2013-04-07 2 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

정확히 "작동하지 않는"것은 무엇입니까? –

+0

오류를 재현 할 수 없습니다. – Beta

+0

프로그램을 실행할 때 두 번째 텍스트 파일을 열고 싶지 않습니다. 제대로 실행되면 두 번째 텍스트 파일이 열리지 않습니다. – Busch

답변

0

파일을 사용한 후에 표준 절차대로 close() 호출을 추가하는 것이 좋습니다. 이전 실행에서 제대로 닫히지 않은 경우 파일을 다시 열 때 문제가 발생하는 경우가 있습니다.

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

또한 릴리스되지 않은 느린 파일 핸들이있는 경우 컴퓨터를 다시 시작할 수 있습니다.