C++读写文件


头文件

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


**读取代码段** ####使用*ifstream* 然后对C++进行文件的读取####
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;
}


使用ofstream 然后对C++进行文件的写入####

写入代码段

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;
}


posted @ 2019-09-18 09:44  test1024  阅读(154)  评论(0)    收藏  举报