以下是C++中保存文件和读取文件的完整代码示例:

保存文件:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ofstream file;
    file.open("example.txt");
    if (!file) {
        cout << "Failed to create file." << endl;
        return 1;
    }
    file << "This is an example file." << endl;
    file << "This is the second line of the file." << endl;
    file.close();
    cout << "The file has been saved." << endl;
    return 0;
}

读取文件:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ifstream file;
    string line;
    file.open("example.txt");
    if (!file) {
        cout << "Failed to open file." << endl;
        return 1;
    }
    while (getline(file, line)) {
        cout << line << endl;
    }
    file.close();
    return 0;
}

以上代码示例中,首先通过 ofstreamifstream 类创建文件流对象。然后使用 open() 方法打开文件, ofstream 中使用 << 运算符将数据写入文件, ifstream 中使用 getline() 方法读取文件内容。最后使用 close() 方法关闭文件流对象

c++保存文件读取文件怎么写完整代码

原文地址: http://www.cveoy.top/t/topic/f26D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录