#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile("1.txt", ios::in); //以文本模式打开1.txt备读
if (!inFile) { //打开失败
perror("error opening source file.");
exit(1);
}
//可以像用cin那样用ifstream对象
string string, str;
cout<<"-----------------------------"<<endl;
string = "", str = "";
//以空格和换行符为界,读入字符(不读入空格与换行符)
while (inFile >> str) {
string += str + "\n";
}
cout<<string;
cout<<endl<<endl;
cout<<"-----------------------------"<<endl;
//文件流指针回到文件头
inFile.clear();
inFile.seekg(0, ios::beg);
string = "", str = "";
//按行读取字符串(不读入换行符)
while (getline(inFile, str))
{
string += str + "\n";
}
cout<<string;
cout<<endl<<endl;
inFile.close();
return 0;
}
C++ 读写文件
于 2022-04-06 09:33:28 首次发布