LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   C: fread to read a file line by line until the end (http://www.linuxquestions.org/questions/programming-9/c-fread-to-read-a-file-line-by-line-until-the-end-299446/)

Blue_muppet 03-09-2005 12:05 AM

C: fread to read a file line by line until the end
 
Hey there,
Im having trouble getting fread to work the way i want it to. I have a long text file 500,000+ lines of text, that i want to read in line by line, until the end of the file. At the moment, my code looks kinda like this

char *buffer[somebignumber];
fread(buffer, sizeof(buffer), 1, dataFile);

dataFile is correctly opened.
Basically the problem i get is that it will read in the first 35,000 lines or so, and then stop, like it has run out of memory space or something.
there are 122 characters on each line of the text file.
Can anybody help me with this?

also, how would i go about telling fread to only read in say, the first 5,000 lines? would it just be a matter of keeping track of an incrementing int in a loop?

thanks.

itsme86 03-09-2005 03:03 AM

You can't use fread() to read in a line of text. fread() works on number of bytes. I think fgets() will do what you're looking for.

yodasoda 09-19-2008 09:42 AM

Quote:

Originally Posted by Blue_muppet (Post 1518736)
Hey there,
Im having trouble getting fread to work the way i want it to. I have a long text file 500,000+ lines of text, that i want to read in line by line, until the end of the file. At the moment, my code looks kinda like this

char *buffer[somebignumber];
fread(buffer, sizeof(buffer), 1, dataFile);

dataFile is correctly opened.
Basically the problem i get is that it will read in the first 35,000 lines or so, and then stop, like it has run out of memory space or something.
there are 122 characters on each line of the text file.
Can anybody help me with this?

also, how would i go about telling fread to only read in say, the first 5,000 lines? would it just be a matter of keeping track of an incrementing int in a loop?

thanks.

That is because it has run out of space. I had a similar problem on an embedded system (TI DSP) and I think this may be the same case for you. I had a really big array to compute with and I had declared it in my main but what that did was to saturate the stack of my main. So what I then did was to declare the big array outside of my main as a global variable and the problem disapeared. remember also that each time you call a function the computer has to save the current process in the stack so your array would bust the stack.


All times are GMT -5. The time now is 10:53 AM.