#include <fstream> #include <iostream> int main(){
std::fstream file;
file.open("example.txt", std::ios::out);// 以输出模式打开文件 if(!file){
std::cerr<<"Unable to open file!"<< std::endl; return1;// 文件打开失败 }
file <<"Hello, World!"<< std::endl;// 写入文本
file.close();// 关闭文件 return0; }
在当前目录下创建一个名为example.txt的文件,文件内容为:
Hello,World!
读取文本文件
#include <fstream> #include <iostream> #include <string> int main(){
std::fstream file;
file.open("example.txt", std::ios::in);// 以输入模式打开文件 if(!file){
std::cerr<<"Unable to open file!"<< std::endl; return1;// 文件打开失败 }
std::string line; while(getline(file, line)){// 逐行读取
std::cout<< line << std::endl; }
file.close();// 关闭文件 return0; }
如果 example.txt 文件包含以下内容:
Hello,World!Thisis a test file.
则程序将输出:
Hello,World!Thisis a test file.
追加到文件:
#include <fstream> #include <iostream> int main(){
std::fstream file;
file.open("example.txt", std::ios::app);// 以追加模式打开文件 if(!file){
std::cerr<<"Unable to open file!"<< std::endl; return1;// 文件打开失败 }
file <<"Appending this line to the file."<< std::endl;// 追加文本
file.close();// 关闭文件 return0; }
example.txt 文件原本包含以下内容:
Hello,World!Thisis a test file.
执行上述程序后,文件内容将变为:
Hello,World!Thisis a test file.Appendingthis line to the file.