我一直在編寫一個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中添加第二個反斜槓以進行正確的解析),但最終沒有運氣。
你們有什麼想法我可以解決這種情況嗎?
謝謝!
您正在使用哪個平臺? – FailedDev
Windows 7 64位。 –
然後我的解決方案應該工作:) – FailedDev