本文共321个字,预计阅读时间需要1分钟。
7月非常忙,这大概是这个月的第一篇吧。
某高校机试需要从文件中读取数据并将数据写入到文件中。完成这一操作需要用到fstream模块,网上一堆资料,但是乱七八糟的,不能满足一些简单的需求,下面给出从文件中读(一行一行地读出所有字符)和向文件中写入数据(追加写入)的C++代码。
从文件中读(一行一行地读出所有字符)
采用的ifstream类型
注意要使用getline
#include<iostream>#include<fstream>using namespace std;int main(){ifstream inFile; //读取文件使用ifstreaminFile.open("/Users/reacubeth/Desktop/test.txt");string str;while(getline(inFile, str)){cout<<str<<endl;}inFile.close();return 0;}
往文件中写入(追加写入)
采用的ofstream类型,并且在读文件时,要选取ios::app打开文件,这样才能追加。
#include<iostream>#include<fstream>using namespace std;int main(){ofstream outFile;outFile.open("/Users/reacubeth/Desktop/test.txt", ios::app);string str = "cdscs\n dvfsvcdfsvdsfv❤️dfvdfsvdf\n";if(!outFile.fail()){outFile<<str;}outFile.close();return 0;}
最后结束时不要忘记关闭文件哦!
更多内容访问
网站所有代码采用Apache 2.0授权
网站文章采用知识共享许可协议BY-NC-SA4.0授权
© • OmegaXYZ-版权所有 转载请注明出处