Re: Reading whole text files

From: jacob navia (jacob_at_jacob.remcomp.fr)
Date: 02/10/05


Date: Thu, 10 Feb 2005 19:14:20 +0100

CBFalconer wrote:

>
jacob wrote:
>
>>What about this?
>>
>>#include <stdio.h>
>>#include <stdlib.h>
>>#include <string.h>
>>char *ReadFileIntoRam(char *fname,int *plen)
>>{
>> FILE *infile;
>> char *contents;
>> int actualBytesRead=0;
>> unsigned int len;
>>
>> infile = fopen(fname,"rb");
>> if (infile == NULL) {
>> fprintf(stderr,"impossible to open %s\n",fname);
>> return NULL;
>> }
>> fseek(infile,0,SEEK_END);
>> len = ftell(infile);
>> fseek(infile,0,SEEK_SET);
>> contents = calloc(len+1,1);
>> if (contents) {
>> actualBytesRead = fread(contents,1,len,infile);
>> }
>> else {
>> fprintf(stderr,"Can't allocate memory to read the file\n");
>> }
>> fclose(infile);
>> *plen = actualBytesRead;
>> return contents;
>>}
>
>
> No good.

Please Chuck, it was a program written in a few minutes!

Note that ftell is meaningless for text files.

That's why I opened in binary mode

It also
> returns a long, not an int.

OK

You haven't even tested for failure
> (which it will on input from a keyboard).
The function receives a file name Chuck. There is NO
keyboard input...

Even if everything works
> use of calloc is silly, why zero what you are about to fill.

No. This dispenses with the zeroing of the last byte,
maybe inefficient but it is an habit...

> Any attempt to pre-allocate a buffer for the whole file is doomed,
> because you cannot reliably tell how big that buffer should be.

If you open it in binary mode yes, you can...



Relevant Pages

  • Re: Space Insertion Following Colon or Semicolon
    ... Thanks for your comments, Chuck! ... keyboard, but there a few things I don't like about it, so I might just take ... suspect your keyboard. ... A new one, at least here in Dallas, is less ...
    (microsoft.public.word.general)
  • Re: Thank You Winners Bank200
    ... >Chuck who? ... Andrew <-- is it SEPTEMBER yet? ... "Keeping my grammar up is real important to me." ... "My hands move faster on the keyboard than my brain a lot." ...
    (alt.vacation.las-vegas)
  • Re: OT: Well, well, well...
    ... have to 'splain EVERYTHING to your dumn ass???? ... Chuck for about an hour. ... "My hands move faster on the keyboard than my brain a lot." ...
    (alt.vacation.las-vegas)
  • How do I skip through videos in Myst V?
    ... hitting some combination of keys on the keyboard)? ... Chuck ...
    (comp.sys.ibm.pc.games.adventure)