使用fstream和ifstream的文本文件I / O.

时间:2013-05-22 17:58:59

标签: c++ file-io ifstream ofstream

#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由于某种原因仍然是空的?

2 个答案:

答案 0 :(得分:1)

请检查streamstate,不仅是eof(),还有失败。此外,在读完最后一个字符后,即使字符被成功读取,如果streamstate是EOF也不常见。因此,总是尝试读取一个元素,如果它成功,那么只使用元素:

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

为了使这个真正有效,请使用它:

out << in.rdbuf();

无论如何,请检查streamstate是否成功:

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

答案 1 :(得分:0)

对我来说它不是空白但有一些额外的附加字符。这是因为在检查eof()之前,您正在将从旧文件中获得的字符写入新文件。

从一个文件写入另一个文件的代码应改为

while (1) 
    { 
         ch = is.get();
         if (is.eof()) 
             break; 
         outfile.put(ch);
         cout << ch;  //this shows
    }