Hi, I'm trying to write a script to read from a file and I never had problems before reading/writing to a file, but with the last few times ifstream just won't work for some or other reason. The file is in the right directory and everything and still it won't open the file. Any help?
EDIT: Looks like I'm wrong. txtIN.open("Numbers.txt"); and txtIN.close(); is not the best or only way to open and close a file. I always learned to do it that way but I guess jib's way is better.
you need to open the file like this txtIN.open("Numbers.txt"); and then close it at the end with txtIN.close();
Wrong on both points, using the constructor is the preferred way of opening files, and unless you want to re-use the stream you don't need to actually close the file, just let the destructor do it's job when the class goes out of scope.
but with the last few times ifstream just won't work for some or other reason.
You should check to insure the file opened properly, then if it doesn't you can try to use perror() to help determine why it didn't open.
Here is an example of using perror(), you would probably want to take some action, like exiting the program or retrying to get a valid file name. Remember with the ifstream and the default open mode the file must exist.
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <fstream>
#include <cstdio>
int main()
{
std::ifstream fin("SOMEBADBOY.TXT");
if(!fin)
perror ( "Stream Failed to open because: " );
return(0);
}
I ran the script with the perror() included and it printed "No error". I then used the debugger and the watches window and txtIN's value was "<incomplete type>". I made sure the file was readable and accessible. Anything else I can try? Can it maybe be an error in the compiler or IDE? (I'm using CodeBlocks and GCC)
I ran the script with the perror() included and it printed "No error".
Did you include the if statement? if(!fin)
That would mean the file could not be opened for some reason. Make sure the file exists and is not locked by any other program. If you are not sure if the file path is correct you could specify the absolute file path just to see that it works.
And the "Numbers.txt" was created fine, but the ifstream still wouldn't read it. (Still got the "<incomplete type>" error in the watches window). I am 100% certain that the file is readable and not locked.