gpt4 book ai didi

c++ - 使用 fstream 和 ifstream 的文本文件 I/O

转载 作者:行者123 更新时间:2023-11-28 07:36:24 26 4
gpt4 key购买 nike

#include <iostream> 
#include <fstream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])
{
ifstream is;
is.open(argv[1]);
ofstream outfile;
outfile.open(argv[2]);
char ch;
while (1)
{
ch = is.get(); // this is where test.txt is supposed
outfile.put(ch); // to be copied to test2.txt
if (is.eof())
break;
cout << ch; //this shows
}

is.close();
outfile.close();

ifstream outfile2;
outfile2.open(argv[2]);
char ch2;
while (1)
{
ch2 = outfile2.get();
if (outfile2.eof())
break;
cout << ch2; //this doesnt
}
outfile2.close();

system("PAUSE");
return 0;
}

我通过 cmd 运行它,给它 2 个参数 test.txt test2.txt,它输出我在 cmd 中的 test.txt 中写的内容,但 test2.txt 出于某种原因仍然为空?

最佳答案

请不仅检查 eof() 的流状态,还要检查失败的流状态。此外,在读取最后一个字符后,如果流状态为 EOF,即使该字符已成功读取,也很常见。因此,始终尝试读取一个元素,如果成功,然后才使用该元素:

ifstream in(argv[1]);
ofstream out(argv[2]);
char c;
while(in.get(c))
out.put(c);

要使它真正有效,请使用它:

out << in.rdbuf();

无论如何,检查流状态是否成功:

if(!in.eof())
throw std::runtime_error("failed to read input file");
if(!out.flush())
throw std::runtime_error("failed to write output file");

关于c++ - 使用 fstream 和 ifstream 的文本文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16698611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com