43 C++基础-文件读写操作

1.输入输出流 iostream

istream 输入流类, ostream 输出流类

2. 文件流

c++在头文件 fstream.h 定义了文件流体系

文件可以分为两大类:文本文件、二进制文件

2.1 定义文件类对象

  • fstream file; // 可读可写

  • ifstream infile; // 可读不可写

  • ofstream outfile; // 可写不可读

2.2 打开文件

    ifstream infile;
    ofstream outfile;

    infile.open("D:\\test.txt");
    outfile.open("D:\\test_copy.txt");

2.3 读写文件

    char ch;
    while(infile.get(ch)) {
        cout<<ch;
        outfile.put(ch);
    }

2.4 关闭文件

    infile.close();
    outfile.close();

2.5 demo

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    ifstream infile;
    ofstream outfile;

    infile.open("D:\\test.txt");
    outfile.open("D:\\test_copy.txt");

    if(!infile || !outfile) {
        cout<<"open file failed!"<<endl;
    }

    char ch;
    while(infile.get(ch)) {
        cout<<ch;
        outfile.put(ch);
    }

    infile.close();
    outfile.close();

    return 0;
}

3. 二进制文件

3.1 打开文件

    // 读取二进制文件
    fstream infile;
    // 写入二进制文件
    fstream outfile;

    // 打开文件方式。指定类型为二进制
    infile.open("D:\\test.txt", ios::in | ios::binary);
    outfile.open("D:\\testb_copy.txt", ios::out | ios::binary);

    if(!infile || !outfile) {
        cout<<"open file fialed"<<endl;
        return 0;
    }

3.2 读写文件

    // 读取缓冲区
    char buff[1024];

    // 文件末尾判断
    while(!infile.eof()) {
        // 读取数据
        infile.read(buff, 1024);
        // 文件实际读取的长度
        int len = infile.gcount();
        // 写入数据
        outfile.write(buff, len);
    }

3.3 关闭文件

    // 关闭文件
    infile.close();
    outfile.close();

3.4 demo

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    // 读取二进制文件
    fstream infile;
    // 写入二进制文件
    fstream outfile;

    // 打开文件方式。指定类型为二进制
    infile.open("D:\\test.txt", ios::in | ios::binary);
    outfile.open("D:\\testb_copy.txt", ios::out | ios::binary);

    if(!infile || !outfile) {
        cout<<"open file fialed"<<endl;
        return 0;
    }

    // 读取缓冲区
    char buff[1024];

    // 文件末尾判断
    while(!infile.eof()) {
        // 读取数据
        infile.read(buff, 1024);
        // 文件实际读取的长度
        int len = infile.gcount();
        // 写入数据
        outfile.write(buff, len);
    }

    // 关闭文件
    infile.close();
    outfile.close();

    cout<<"copy success"<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/su749520/article/details/80375734
43