- C++文本文件读写程序(基本方式)
//C++ code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class file{
public:
//按行读数据,不分行写入另外一个文件
bool fromShortToLong(string s_path,string d_path){
string buffer;
fstream infile(s_path);
fstream outfile(d_path);
if(!infile){
cout << "Unable to open infile";
exit(1); // terminate with error
}
if(!outfile){
cout << "Unable to open outfile";
exit(1); // terminate with error
}do{
outfile<<buffer;
}while (getline(infile,buffer));
cout<<"读写完成。"<<endl;
system("pause");
outfile.close();
infile.close();
}
};
void main(){
file test;
test.fromShortToLong("D://test_read.txt","D://test_write.txt");
}
- 使用缓冲的读写程序
bool fromShortToLong(string s_path,string d_path)
{
string buffer;
ifstream infile(s_path.c_str());
ofstream outfile(d_path.c_str());
if(!infile)
{
cout << "Unable to open infile";
exit(1); // terminate with error
}
if(!outfile)
{
cout << "Unable to open outfile";
exit(1); // terminate with error
}
buffer.assign(istreambuf_iterator<char>(infile),istreambuf_iterator<char>());
stringstream strStr;
strStr.str(buffer);
string linestr;
do
{
outfile<<linestr;
}
while (getline(strStr,linestr));
cout<<"读写完成。"<<endl;
return true;
}
后者比前者的读写速度要快很多倍。主要原因就是后者的文件IO次数远远少于前者。
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询