2013-04-07 93 views
2

我正在写一个简单的程序来获取两个文件。终端命令行看起来像这样。C++ fstream多输入文件

./fileIO foo.code foo.encode 

当它运行时,第二个文件是不能读取。当我进入

./fileIO foo.code foo.code 

它的工作原理。我似乎无法弄清楚为什么第二个不开放。有任何想法吗?谢谢!

#include <fstream> 
#include <iostream> 
#include <queue> 
#include <iomanip> 
#include <map> 
#include <string> 
#include <cassert> 
using namespace std; 

int main(int argc, char *argv[]) 
{ 
    // convert the C-style command line parameter to a C++-style string, 
    // so that we can do concatenation on it 
    assert(argc == 3); 
    const string code = argv[1]; 
    const string encode = argv[2]; 
    string firstTextFile = code; 
    string secondTextFile = encode; 

    //manipulate the first infile 
    ifstream firstFile(firstTextFile.c_str(), ios::in); 
    if(!firstFile) 
    { 
    cerr << "Cannot open text file for input" << endl; 
    return 1; 
    } 

    string lineIn; 
    string codeSubstring; 
    string hexSubstring; 
    while(getline(firstFile, lineIn)) 
    { 
    hexSubstring = lineIn.substr(0, 2); 
    codeSubstring = lineIn.substr(4, lineIn.length()); 
    cout << hexSubstring << ", " << codeSubstring << endl; 
    } 

    //manipulate the second infile 
    ifstream secondFile(secondTextFile.c_str(), ios::in); 
    if(!secondFile) 
    { 
    cerr << "Cannot open text file for input" << endl; 
    return 1; 
    } 

    char characterIn; 
    while(secondFile.get(characterIn)) 
    { 
    cout << characterIn << endl; 
    } 


    return 0; 
} 
+2

什么“不起作用”? – 2013-04-07 19:39:12

+0

我无法重现错误。 – Beta 2013-04-07 19:43:37

+0

当我运行该程序时,它似乎不想打开第二个文本文件。它运行正常,它只是不会打开我的第二个文本文件。 – Busch 2013-04-07 19:50:51

回答

0

您可能想要尝试的一件事是在完成使用文件后,按照标准过程添加close()调用。有时如果在前一次运行中没有正确关闭文件,重新打开文件会出现问题。

firstFile.close(); 
secondFile.close(); 

此外,如果有一些尚未发布的延迟文件句柄,您可以尝试重新启动计算机。