Re: Reading whole text files
From: jacob navia (jacob_at_jacob.remcomp.fr)
Date: 02/10/05
- Next message: Michael Wojcik: "Re: Are C pitfalls the mistake of standard or that of implementations?"
- Previous message: Ben Pfaff: "Re: Is "scope" different from "visibility" ?"
- In reply to: CBFalconer: "Re: Reading whole text files"
- Next in thread: Chris Torek: "Re: Reading whole text files"
- Reply: Chris Torek: "Re: Reading whole text files"
- Reply: Flash Gordon: "Re: Reading whole text files"
- Reply: CBFalconer: "Re: Reading whole text files"
- Reply: Eric Sosman: "Re: Reading whole text files"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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...
- Next message: Michael Wojcik: "Re: Are C pitfalls the mistake of standard or that of implementations?"
- Previous message: Ben Pfaff: "Re: Is "scope" different from "visibility" ?"
- In reply to: CBFalconer: "Re: Reading whole text files"
- Next in thread: Chris Torek: "Re: Reading whole text files"
- Reply: Chris Torek: "Re: Reading whole text files"
- Reply: Flash Gordon: "Re: Reading whole text files"
- Reply: CBFalconer: "Re: Reading whole text files"
- Reply: Eric Sosman: "Re: Reading whole text files"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|