【问题标题】:Text file I/O with fstream and ifstream使用 fstream 和 ifstream 的文本文件 I/O
【发布时间】:2013-05-22 17:58:59
【问题描述】:
#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 由于某种原因仍然为空?

【问题讨论】:

    标签: c++ file-io ifstream ofstream


    【解决方案1】:

    请检查流状态,不仅要检查 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");
    

    【讨论】:

    • 程序在 Visual Studio 中运行良好,但没有使用 gcc。它抛出“这个程序不能在 DOS 模式下运行”
    • 你说的是哪个程序?
    • @Alex 代码替换为我的 sn-p。见stackoverflow.com/questions/16700102/…
    • Saksham,请检查您的回复地点和对象,我猜您的意思并不是要在我的回答中显示您的信息,而是在问题或您的回答中显示。
    • 好吧,那只能做一个假设,为什么我在 test.txt 中的任何内容都没有复制到 test2.txt 中,尽管程序似乎在 cmd 上运行良好并且它也输出它?
    【解决方案2】:

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

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

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

    【讨论】:

    • 同样的事情发生在我身上...... test2.txt 中没有任何内容
    • 将索引从 argv[1], argv[2] 更改为 argv[0], argv[1] 以及上面建议的代码更改
    • 我传递的参数必须在 argv[1] 和 argv[2] 对吗?
    • 不是 argv[0] 用于程序名称或类似名称吗?
    • 好吧好吧。我通常在 Visual Studio 上工作,并且通过用硬编码文件名替换参数来正常工作
    猜你喜欢
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多