64文件流

基本概念

输入流 ifstream 输出流 ostream 输入输出流 fstream

文件打开方式,如:ios:: out、app、bin、tru、ate

文件流的状态,如:good、is_open、fail、bad、eof

定位:依靠文件指针(输入指针、输出指针)

文件类型:文本文件 & 二进制文件

示例代码

demo1

#include <iostream>
#include <fstream>  //文件流头文件

using namespace std;

int main()
{
    char fileName[255] = "./a.txt"; //当前目录
    cout << "Hello World!" << endl;

    ofstream fout(fileName);       //打开文件,可选参数ios::out、app、bIn、tru、ate

    fout << "Hello World!\n" << endl;

    fout.close();   //关闭

    cout << "写文件成功!" << endl;
    cout << endl;

    ifstream fin(fileName);      //读文件
    char ch;
    cout << "下面是读到的文件的内容:" << endl;
    while(fin.get(ch))      //每次读一个字符
        cout << ch;

    fin.close();            //关闭流
    cout << "读文件成功!" << endl;

    return 0;
}

demo2

#include <iostream>
#include <fstream>  //文件流头文件

using namespace std;

int main()
{
    char buffer[255];
    char fileName[80];

    cout << "请输入一个文件名:";
    cin.getline(fileName, 80);  //cin的话会有一个\n储存在缓冲区

    ofstream fout(fileName, ios::app);          //在文件尾继续写文件
    fout << "This line written directly to the file...\n";
    fout << "这一行也是直接写到文件里的\n";
//    cin.ignore(1, '\n');
    cin.getline(buffer, 255);
    fout << buffer << endl;
    fout.close();

    ifstream fin(fileName);
    cout << "Here's the content of the file: \n";
    char ch;
    while(fin.get(ch))
        cout << ch;

    cout << "End of the file." << endl;
    fin.close();


    return 0;
}

发布了59 篇原创文章 · 获赞 3 · 访问量 1821

猜你喜欢

转载自blog.csdn.net/Felix_hyfy/article/details/98476011