-
Reading from files
Hi, I was wondering how to read from files in c++ in a way that lets me know if there are any problems. I need this because when I load somthing like a level file, if the file isn't exactly right I want it to know and stop instead of carrying on and doing somthing upredictable.
I used to use sscanf in c like this.
Code:
char buffer[100];
int x, y;
fgets(buffer,sizeof(buffer),fp);
if (sscanf(buffer, "x: %d, y: %d", &x, &y) < 2)
printf("Woops\n");
What is the best way to do this in c++? Thanks
-
I would do it almost the same way
Code:
int x, y;
std::string buffer;
std::ifstream in("file");
while( std::getline(in,buffer) )
{
if (sscanf(buffer.c_str(),"x: %d, y: %d", &x, &y) < 2)
std::cout << "Woops\n";
}
-
One of the simplest ways to do that is to save each field on a separate line and use ifstream::getline() to read one at a time, and if you read fewer lines than expected or any line contains something it shouldn't, you know you have an error on your hands. One better way to accomplish your goals would be to save all of your data in a struct and write the entire thing to a file. Then, when you intend to load it, you can insure that a) the file contains exactly the size of your struct and b) each data field contains valid information.
-
If using istream's check the status using
Code:
// do a read operation from the_stream
if (the_stream) no_error_has_occurred();
if (!the_stream) an_error_has_occurred();
Most of the reading operators (eg operator >>(), getline()) will set status of the stream so that the above tests work. Some of the member functions return the number of bytes actually read: if this number is different from what is expected (eg you expect more than one byte to be read, and none are) it can also be used by your program as a primitive indication of an error.
I seem to recall reading somewhere that some of the operations on streams throw exceptions in some cases if an error is encountered, but that may just be my foggy early morning memory.
-
The stream class provides plenty of functions for checking for errors after opening.
Code:
ifstream inFile;
inFile.open("text.txt", ios::in);
if(inFile.is_open())
{ while(!inFile.fail())
{ // read from file
}
}
inFile.close();
-
Code:
while(!inFile.fail())
Isn't that kind of like this?
If it is, you should read the FAQ . . . .