文件(fstream)"/>
初识c++(16)之c++中的读写文件(fstream)
先上代码:
#include<iostream>
#include<fstream>using namespace std;int main(){string str;int n;int m;ofstream outfile("my_file.txt");if(outfile){outfile << "helloworld!" << " " << 1 << " " << 2 << endl;outfile << "hello!" << " " << 3 << " " << 4 << endl;outfile << "world!" << " " << 5 << " " << 6 << endl;}else{cout << "error:failed to open file!" << endl;}ifstream infile("my_file.txt");while(infile >> str){infile >> n;infile >> m;cout << str << " " << n << " " << m << endl;}return 0;
}
结果:
helloworld! 1 2
hello! 3 4
world! 5 6
解释:
上面的代码主要用了两个类,ofstream和ifstream,都存在头文件#include<fstream>里。
ofstream outfile("my_file.txt");
这句话的作用就是,定义一个名叫outfile的对象,并打开“my_file。txt”文件,如果程序找不到这个文件就会新建这个文件,这种打开文件的方式会将文件之前的内容给全部清空,如果想要保留文件的内容,并且添加新的内容,就需要用append模式,应该这样写:
ofstream outfile("my_file.txt",ios_base::app);
如果成功打开文件,outfile = true,如果打开失败,outfile = flase.写文件的操作类似于std::cout的操作。
值得注意的是,endl,会插入一个换行。
if(outfile){outfile << "helloworld!" << " " << 1 << " " << 2 << endl;outfile << "hello!" << " " << 3 << " " << 4 << endl;outfile << "world!" << " " << 5 << " " << 6 << endl;}else{cout << "error:failed to open file!" << endl;}
对于读文件,;类似于std::cin的操作,值得注意的是,infile >> str ,返回的是写入的字符,文档结尾为0,返回的也是0
ifstream infile("my_file.txt");while(infile >> str){infile >> n;infile >> m;cout << str << " " << n << " " << m << endl;}
更多推荐
初识c++(16)之c++中的读写文件(fstream)
发布评论