sofr
sofr

Reputation: 5607

Reading from file using fgets() causes "Access Violation reading from address..." c++

I'm Using FILE * F opened in _sfopen () I'm reading from the file in while(!feof(f)) and then fgets(str,1024,f) when running reaches the last line it still goes in the while but then when trying to fgets it flies out with an access violation arror (menwhile I just put a try and catch(...) but I know It's not a good solution ) what shoul I change for fixing the problem?

Plus- if I want to read line by line is it correct just to give the size of 1024 or it might fail -- I had a file where due to the size it read each time from the middle of a line till the middle of next line - is there a better way to read a line because I have no idea how my files will look like (if the have \n at the end etc...)

thanks!

Upvotes: 2

Views: 2086

Answers (2)

Evan Teran
Evan Teran

Reputation: 90422

If you don't read before the while(!feof(f)) then it is broken since the EOF flag does not get set until after a read has been done. Instead do something like this:

char buf[1024];
while(fgets(buf, sizeof(buf), f)) {
    /* process the line */
}

Since fgets is defined to return NULL on either failure to read or EOF.

If you are doing this in c++, then I recommend a similar pattern (but using c++ iostreams instead).

std::ifstream file("filename.txt");
std::string line;
while(std::getline(file, line)) {
    // process the line
}

Upvotes: 3

Emile Vrijdags
Emile Vrijdags

Reputation: 1578

You specified C++ as tag, maybe use a filestream (std::ifstream for input from file) and the global getline() function to get it line by line and put it in a std::string for further analysis/manipulation.

For an example look here (2nd example in the "Text files" paragraph)

Upvotes: 0

Related Questions