【C++11】文件操作ifstream&ofstream

文章目录

      • 文件输入流
        • 创建ifstream对象
        • 读取文件数据
      • 文件输出流
        • 文件流的打开模式
        • 创建ofstream对象
        • 写入文件数据
      • 文件输入输出示例

文件输入流

创建ifstream对象

使用ifstream类创建ifstream对象,所获取的对象能够像cin一样使用>>运算符从所绑定文件中取数据。

// 创建一个未绑定的文件输入流
ifstream in;

// 绑定文件输入流文件为1.txt
ifstream in("1.txt");

读取文件数据

使用ifstream对象读取文件中的数据:

ifstream in("1.txt");
if(in) { // 检察打开是否成功
    string s;
    while(in >> s) {
        // 将文件中的数据读出并存入s中
        in >> s;
        // 使用标准输出cout进行输出
        cout << s << endl;
    }
}

运行效果:
【C++11】文件操作ifstream&ofstream_第1张图片

文件输出流

文件流的打开模式

模式 含义
in 只读模式(ifstream默认模式)
out 只写模式(只读模式会抛弃文件已有数据,ofstream默认模式)
app append追加,向文件末尾追加数据
ate at the end定位至文件尾
binary 以二进制形式打开文件

创建ofstream对象

使用ofstream类创建ofstream对象,所获取的对象能够像cout一样使用<<运算符向所绑定文件中数据。

// 创建一个未绑定的文件输出流
ofstream out;
// 进行绑定以及打开模式指定
out.open("2.txt", ios::out);

// 绑定文件输入流文件为1.txt
// 并指定打开方式为binary和app(使用|连接多个模式)
ofstream out("2.txt", ios::binary | ios::app);

写入文件数据

使用ofstream向文件中写数据:

ofstream out("1.txt");
if(out) { // 检查是否失败
    for (int i = 0; i < 999; ++i) {
        out << "爱你" << i + 1 << "遍!" << endl;
    }
}
// 注意:关闭的是文件而非输出流对象
// 可以通过out.open()重新绑定文件
out.close();

运行结果:
【C++11】文件操作ifstream&ofstream_第2张图片

文件输入输出示例

一个小实践:使用ifstream对象读取C盘下的一张图片,并使用ofstream将其存入同代码目录下的"3.png"中。

ifstream in("C:/Users/zhizi/Pictures/pic.png", ios::binary);
ofstream out("3.png", ios::app | ios::binary);
string s;
while(getline(in, s)) {
    out << s << endl;
}

运行效果(图片来源网络,侵权联系删除):

你可能感兴趣的:(C++,c++,文件操作,ifstream,ofstream)