Reading from file using fgets() causes “Access Violation reading from address…” c?

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.

Up vote 2 down vote favorite share g+ share fb share tw.

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! C++ c file link|improve this question asked May 13 '09 at 22:13sofr4612619 84% accept rate.

6 Please post your code that you're using. – Jon Benedicto May 13 '09 at 22:14 Do you have any particular reason to use FILE instead of std::ifstream? – Jem May 13 '09 at 22:44 char buf1024, *p; while (fgets(buf, sizeof(buf), fp)!

= NULL) { do something... } – sofr May 16 '09 at 18:14 Thanks, Putting the fgets into th while really helpwd the access violation error but still I have twu question 1) critical what if my line is more than 1024 characters? 2) I need to use FILE * although I'm programming in c++ how can I use c++ variables instead of char* inorder to read the line (fgest(...)). – sofr May 16 '09 at 18:17.

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).

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 buf1024; 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 }.

Take a look here - especially the "caveats" section.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions