使用 C++ 可以通过以下步骤生成文本文件:

  1. 引入文件流头文件:#include <fstream>

  2. 创建一个 ofstream 对象:ofstream outfile;

  3. 打开文件并指定文件名:outfile.open('filename.txt');

  4. 将数据写入文件:outfile << 'Hello, world!';

  5. 关闭文件:outfile.close();

完整代码示例:

#include <fstream>
using namespace std;

int main() {
    ofstream outfile;
    outfile.open("example.txt");
    outfile << "This is a text file." << endl;
    outfile.close();
    return 0;
}

执行上述代码后,将会在程序所在目录下生成一个名为 example.txt 的文本文件,并将字符串 'This is a text file.' 写入该文件中。

C++ 文件操作:如何创建文本文件

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

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