c++中读写文本文件的操作比较方便,如下:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream *outFile = new ofstream;
outFile->open("duck.txt");
*outFile << "hello duck";// 写文件
outFile->close();
ifstream inFile;
inFile.open("duck.txt");
// cout << "open inFile: " << inFile.is_open() << endl;
char buffer[100];
while (inFile.is_open()
&& !inFile.eof()
&& !inFile.bad()
&& inFile.getline(buffer, 100)) {
cout << buffer; // 文件内容输出
}
cout << endl << "文件读写完成" << endl;
inFile.close();
return 0;
}
output:
hello duck
文件读写完成

本文介绍了一个简单的C++程序示例,演示了如何使用ofstream和ifstream进行文本文件的基本读写操作。程序首先创建并写入一个文本文件,然后读取该文件的内容并输出到控制台。
1万+

被折叠的 条评论
为什么被折叠?



