C++ 文件的I/O

(出处:C++ Primer Plus  第6版  中文版_  17.4  文件输入和输出)

一,写入文件

要让程序写入文件,必须这样做:

1,创建一个ofstream对象来管理输入流;

2,将该对象与特定的文件关联起来;

3,以使用cout的方式使用该对象,唯一的区别是将进入文件,而不是屏幕。

要完成以上任务,首先应该包含头文件fstream。对于大多数实现来说,包含该头文件便自动包括iostream文件。

例:

ofstream fout;

fout.open("xxx.txt");

或者:

ofstream fout("xxx.txt");

然后,以使用cout的方式使用fout.

fout<<"AAAAAAAA";//将“AAAAAAAA”放到文件中。


二,读取文件

读取文件的要求与写入文件相似:

1,创建一个ifstream对象来管理输入流;

2,将该对象与特定的文件管理起来;

3,使用cin的方式使用该对象。

读文件类似与写文件,首先要包含头文件fstream。然后声明一个ifstream对象,将它与文件名关联起来。

例:

ifstream fin;

fin.open("xxx.txt");//打开xxx.txt文件

或者:

ifstream fin.open("xxx.txt");


三,示例

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>


int main()
{
    using namespace std;
    string filename("20180921-1.txt");

    ofstream fout(filename.c_str());

    fout << "AAAAAAA";
    fout.close();

    ifstream fin(filename.c_str());
    char ch;
    while (fin.get(ch))
    {
        cout << ch;
    }
    cout << "Done\n";
    fin.close();
    return 0;
}

四,结果

猜你喜欢

转载自blog.csdn.net/csdn_RL/article/details/82799424