From bbd60714c6fcf60601c7746ba45137f71b10c832 Mon Sep 17 00:00:00 2001 From: p68710245 Date: Sun, 28 Apr 2024 20:02:59 +0800 Subject: [PATCH] Add copy_file_with_lines.cpp --- copy_file_with_lines.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 copy_file_with_lines.cpp diff --git a/copy_file_with_lines.cpp b/copy_file_with_lines.cpp new file mode 100644 index 0000000..7310fdc --- /dev/null +++ b/copy_file_with_lines.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +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; +} \ No newline at end of file