初识c++(16)之c++中的读写文件(fstream)

编程入门 行业动态 更新时间:2024-10-11 15:21:45

初识c++(16)之c++中的读写<a href=https://www.elefans.com/category/jswz/34/1771438.html style=文件(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)

本文发布于:2024-03-06 17:49:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1715977.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   fstream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!