C++读写文件

Posted zoey686

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++读写文件相关的知识,希望对你有一定的参考价值。

使用ifstream 然后对C++进行文件的读取

头文件

>#include<cstdio>
>#include<cmath>
>#include<cstring>
>#include<cstdlib>
>#include<algorithm>
>#include<iostream>
>#include<string>
>#include<fstream>
>using namespace std;

读取代码段

int main() 
    string buffer, filepath = "test.txt";
    ifstream myfile(filepath.c_str());
    //等同于 ifstream myfile("test.txt");

    while(getline(myfile, buffer)) 
        cout << buffer << endl;
    
    myfile.close();
    return 0;

写入代码段

int main() 
    string filepath = "test.txt";
    //ofstream myfile("test.txt");
    ofstream myfile(filepath.c_str());

    myfile << "hbhh" << endl;
    myfile << "aaaaa" << endl;
    myfile.close();
    return 0;

以上是关于C++读写文件的主要内容,如果未能解决你的问题,请参考以下文章