Add copy_file_with_lines.cpp

main
p68710245 1 year ago
parent e639f1387c
commit bbd60714c6

@ -0,0 +1,29 @@
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream ifile("hello.txt");
std::ofstream ofile("hello_copy.txt");
char temp[81];
// 忽略文件对象判断的过程
do
{
ifile.getline(temp, 81);
if (ifile.rdstate() == std::ios::goodbit) // 正常结束
ofile << temp << '\n';
else if (ifile.rdstate() == std::ios::failbit) // 读取长度超限进入fail状态
{
ifile.clear(); // 恢复流状态
ofile << temp; // 注意没有换行
}
else // 文件读取结束进入fail+eof状态
{
ofile << temp;
break;
}
} while (1);
ifile.close(); // 如没有这两个函数析构函数也可关闭,但建议显式书写
ofile.close();
return 0;
}
Loading…
Cancel
Save