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: Just eaten......
    ... Rabbit burst on the scene, ... I will not accept responsibility if you chuck up over your ... keyboard :-) ...
    (uk.people.silversurfers)
  • Re: OT: Man-Child up to old and new tricks again.
    ... He's a real magician with his keyboard. ... seems his new gimmick there days is to spoof mine and other peoples IP ... Give Chuck an inch of crazy and he takes a mile. ...
    (alt.vacation.las-vegas)
  • Re: OT: Man-Child up to old and new tricks again.
    ... He's a real magician with his keyboard. ... Give Chuck an inch of crazy and he takes a mile. ... insects buzzing around. ...
    (alt.vacation.las-vegas)
  • Re: Just eaten......
    ... I will not accept responsibility if you chuck up over your ... keyboard :-) ... it definitely needs full screen for the whole thrill :-) ...
    (uk.people.silversurfers)