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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值