I've been writing a C++ program that will eventually remove certain undesired formatting from text files. Unfortunately, I'm still far from reaching this goal.
My current issue is my seeming inability to open text files that are located in a given (user-inputted) directory. Here is where I'm at so far, stripped of most unneeded bulk:
//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);
}
I'm not actually sure whether the input string should have quotes or not - I couldn't get them to work either way. I also tried to do a filePath.find('\\') to find backslashes (so that I could then add a second backslash into the filePath for proper parsing), but had no luck in the end.
Do you guys have any idea how I can remedy this situation?
Thanks!
I suggest you take a look at what filePath contains when you call fopen. Then you will be able to see what is going wrong.
Two approaches:
Print out the value just before you call fopen
Use debugger, place breakpoint on fopen call and inspect content of filepath