2013-04-07 69 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(); 

此外,如果有一些尚未發佈的延遲文件句柄,您可以嘗試重新啓動計算機。