C++ 文件操作:如何创建文本文件
使用 C++ 可以通过以下步骤生成文本文件:
-
引入文件流头文件:
#include <fstream> -
创建一个
ofstream对象:ofstream outfile; -
打开文件并指定文件名:
outfile.open('filename.txt'); -
将数据写入文件:
outfile << 'Hello, world!'; -
关闭文件:
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.' 写入该文件中。
原文地址: http://www.cveoy.top/t/topic/olih 著作权归作者所有。请勿转载和采集!