文本文件I/O与fstream和ifstream
Text file I/O with fstream and ifstream
#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");
对我来说,它不是空白的,而是一些额外的附加字符。这是因为在检查eof()之前,您正在将从旧文件中获得的字符写入新文件。
从一个文件写入到另一个文件的代码应该更改为while (1)
{
ch = is.get();
if (is.eof())
break;
outfile.put(ch);
cout << ch; //this shows
}
相关文章:
- ifstream什么都没读
- 在fstream期间忽略空行
- 使用fstream对txt文件中的数字进行循环
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- ifstream文件在从行中读取时被清除
- 使 std::fstream 写入文件末尾,但从头开始读取
- fstream / ifstream / ofstream 对象如何转换为布尔值
- Using ifstream, ofstream and fstream
- 无法使用 fstream 和 ifstream 读取 NDK C++中的文件
- fstream、ifstream和ofstream的开放模式行为
- 为什么'ifstream'和'ofstream'被添加到"std",而'fstream'可以同时达到这两个目的?
- Xcode 5 c++ fstream(ifstream 和 ofstream)不起作用
- 在 ifstream 预期的地方传递 fstream
- Fstream包含了ofstream和ifstream的所有内容
- 包括 fstream,但"ifstream not found"和"identifier is undefined"
- 文本文件I/O与fstream和ifstream
- 在fstream/ifstream文件中使用多个函数
- 为什么包含fstream允许访问ofstream和ifstream ?
- 在c++头文件中包含fstream或ifstream