Hello,
I am very new to C++, as such I am having difficulties with the settings. I tried for several hours last night to create a simple program opening a file manipulating the data and outputting it, formatted, to another file. I never could get the input file to read into the program yet I had no errors when I compiled. I transferred the program to my laptop and it worked flawless. Exactly as written. I am sure the problem is a setting in application but I cannot find any information on troubleshooting this aspect. Any help would be greatly appreciated. Thanks in advance.
Hello David. I certainly understand how frustrating computers can be. I suspect that before you moved to the laptop, the input file was not in the correct location for your program. This can easily happen if you run your program from a development environment, like Visual Studio. When you moved to the laptop, you probably put both the program and the input file in the same directory so the program was able to find it. There are a number of things you can try.
1) Try running the program on the original machine but provide the full path to the input file.
2) It can be instructive to place this code into your main function to show you what folder the program is running in. It will show you where the program will look for the input file if you don't supply the full path to the file.
char wd[MAX_PATH]; _getcwd(wd, MAX_PATH); cout << "working directory is " << wd << endl;
You will need these headers
using namespace std;
3) You can get the reason for the failure to open the file using code from the sample below. It is good to tell the user why something is not working. There are 2 methods for getting an error message, the strerror function, or the GetLastError and FormatMessage functions. The first method is standard C. The second method is Windows specific. You can see how they are used below.
using namespace std;
const char* GetLastErrorMessage(void) {
static char result[128]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, result, sizeof(result), NULL); return result;
}
int main(void) {
char wd[MAX_PATH]; _getcwd(wd, MAX_PATH); cout << "working directory is " << wd << endl;
ifstream inf; inf.open("foo.txt"); if (!inf) { cout << "Cannot Open ->" << GetLastErrorMessage() << endl; cout << "Cannot open ->" << strerror(errno) << endl; }
}
Advertisement