文本文件I/O与fstream和ifstream

Text file I/O with fstream and ifstream

本文关键字:fstream ifstream 文件 文本      更新时间:2023-10-16
#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
    }