2011-12-01 2 views
1

나는 텍스트 파일에서 특정 원하지 않는 서식을 결국 제거 할 C++ 프로그램을 작성했습니다. 불행히도, 나는 아직도이 목표에 미치지 못합니다.C++ 사용자 입력을 사용하여 다른 디렉토리에 파일 열기

현재 문제는 주어진 (사용자가 입력 한) 디렉토리에있는 텍스트 파일을 열 수없는 것 같습니다. 지금까지 어디에 있어요 다음은 대부분의 불필요한 대량의 제거 :

//header, main function, bulk 

//variable definitions 
FILE * pFile; 
//char filePathBuffer [512]; --unused, from older attempts 
string currentLine = "", command = "", commandList = "ct", filePath = "defaultPath"; 
int quotePos = 0, slashPos = 0, bufferLength = 0; 
bool contQuote = true, contSlash = true; 

cout << "> "; 
getline(cin, command); 

//various exit commands 
while(command != "q" && command != "quit" && command != "exit") { 

    //check for valid commands stored in a string 
    //--definitely not the best way to do it, but it's functional 

    if(commandList.find(command) == commandList.npos) { 
     puts("\nPlease enter a valid command.\n"); 
    } 
    else if(command == "t") { 
     puts("\nPlease enter the file path:\n"); 
     cout << "> "; 
     getline(cin, filePath); 

     //rip all quotes out of the entered file path 
     while(contQuote == true) { 
      quotePos = filePath.find("\""); 

      if(quotePos == filePath.npos) 
       contQuote = false; 
      else 
       filePath.erase(quotePos, 1); 
     } 

     pFile = fopen(filePath.c_str(), "r+"); 

     //I've also tried doing countless variations directly in the code, 
     //as opposed to using user-input. No luck. 
     //pFile = fopen("C:\\test.txt", "r+"); 

     if(pFile!=NULL) { 
      cout << "\nFile opened!" << endl << endl; 
      fclose (pFile); 
     } 
     else 
      cerr << "\nFile failed to open!\n\n"; 

    } 

    //reset variables to default values 
    quotePos = -1; 
    slashPos = -1; 
    contQuote = true; 
    contSlash = true; 

    cout << "> "; 
    getline(cin, command); 
} 

내가 입력 문자열은 따옴표 여부를 여부를 사실 잘 모르겠어요 - 내가 그들 중 하나의 방법을 작동시킬 수 없습니다. 또한 filePath.find ('\\')를 사용하여 백 슬래시를 찾으려고 시도 했으므로 (올바른 파싱을 위해 두 번째 백 슬래시를 filePath에 추가 할 수 있도록) 끝에 행운이 없었습니다.

이 상황을 어떻게 해결할 수 있는지 알고 계십니까?

감사합니다.

+0

어떤 플랫폼을 사용하고 있습니까? – FailedDev

+0

Windows 7 64 비트. –

+0

그럼 내 솔루션이 작동해야합니다 :) – FailedDev

답변

1

fopen을 호출 할 때 filePath의 내용을 살펴 보시기 바랍니다. 그렇다면 무엇이 잘못되었는지 보게 될 것입니다.

두 가지 접근 방법 :

  1. 하면 fopen 호출에 당신이

  2. 사용 디버거를 fopen의 호출 직전 값, 장소 중단 인쇄 및

+0

네, 저도 그렇게 생각했습니다. 그리고 저는 그것을 무수히했습니다. C : \ test.txt를 입력하면 C : \ test.txt가 출력됩니다. –

+0

글쎄요. 파일이 존재합니까? – ravenspoint

+0

예, 파일이 존재합니다. 실행 파일과 동일한 디렉토리에있는 파일을 사용하면 코드가 제대로 작동합니다. –

1

나는 당신이 \\로 판단하는 창문에 있다고 생각합니다.

이 기능을 사용해보십시오 :

#include <windows.h> 
bool fileExist(const std::string& fileName_in) 
{ 
    DWORD ftyp = GetFileAttributesA(fileName_in.c_str()); 
    if (ftyp == INVALID_FILE_ATTRIBUTES) 
    return false; 
    if (ftyp & FILE_ATTRIBUTE_DIRECTORY) 
    return false; // this is a directory 
    return true;  // this is a normal file 
} 

이 기능은 입력 문자열을보십시오. false를 반환하면 사용자에게 장님이라고 알립니다.

+0

사실 반환 - 그래서 파일을 볼 수 있습니다. 그렇다면 무엇이 잘못 될지 확실하지 않습니다. :) 편집 : 와우, 얼마나 당황. 실행 파일을 관리자로 실행하는 것을 잊었습니다. 도와 주셔서 감사합니다! –

+0

@ 13ack.Stab 문제 없음 :) .. – FailedDev

0

의 모습 파일 경로의 내용을 검사 허가 문제. 다른 하위 디렉토리에서 해봤습니까? fopen()이 반환 될 때 errno 값을 검사하는 코드를 추가했습니다. 아래의 "Permission Denied"에 유의하십시오.

> t 

Please enter the file path: 

> .\test.cpp 

File opened! 

> t 

Please enter the file path: 

> c:\setup.log 

File failed to open with error: Permission denied 

> t 

Please enter the file path: 

> c:\cygwin\cygwin.bat 

File opened! 

>