From f65d195593c76b98e666f66013746535ffbb63d6 Mon Sep 17 00:00:00 2001 From: p68710245 Date: Sun, 28 Apr 2024 19:59:11 +0800 Subject: [PATCH] Add copy_file_with_lines --- copy_file_with_lines | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 copy_file_with_lines diff --git a/copy_file_with_lines b/copy_file_with_lines new file mode 100644 index 0000000..bddc6e5 --- /dev/null +++ b/copy_file_with_lines @@ -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; +}