You are here:

C/fread()

Advertisement


Question
QUESTION:   Hey,

I'm trying to read a file one byte at time but I want the computer to forget each byte by the time I ask it to read the next byte.

   char *r;
   for (i=0; i<verylargenumber; ++i)
    {
     fread(&r, 1, 1, myfile);
     printf("%d", r);
     }   

The above program works fine until the files get large. It looks like I'm running out of memory. Is it possible to "empty the buffer" after each entry is printed and before the newt one is read. Or what am I doing wrong?
Thanks. Andres.
ANSWER: Change:
char *r;
to:
char r;

-Narendra

---------- FOLLOW-UP ----------

QUESTION:  Thanks a lot.

However, when I change "char *r" to "char r" then I am not seeing the correct info anymore. What is the difference between char *r and char r? Is it possible to empty buffer during program run? What's the fifference between
fread(&r,1,1,filename) and fread(r,1,1,filename)?
 Andres  

Answer
First of all, you have not posted the complete code.
I don't know how you have defined myfile and how you opened the file. Also, what are the contents of this file - is this a binary file or a text file?

when you do:
char *r;
You are declaring a pointer of type char and you will also need to assign it a valid address or allocate some space, before using it.

And in the problem that you are talking, you are reading one character at a time. So, you don't need a pointer for this.
It will suffice if you declare a character and use it.

Here below, I am posting the code and the test that I did.
You can see my complete screen dump and also that it is working fine:

googol:temp> cat temp1.c
#include <stdio.h>

int main()
{
       FILE *myfile;
       char r;

       myfile = fopen("temp1.txt", "r");
       while (!feof(myfile))
       {
         fread(&r, 1, 1, myfile);
         printf("%c", r);
       }
       printf("\n");

       return 0;
}
googol:temp> gcc -Wall temp1.c
googol:temp> cat temp1.txt
This is a test file.
First line
2nd Line
1234567890

End of File
googol:temp> ./a.out
This is a test file.
First line
2nd Line
1234567890

End of File
googol:temp>

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.