Reputation: 34533
char *loadTextFile(const char *filename)
{
FILE *fileh;
char *text = 0;
long filelength;
if((fileh=fopen(filename,"rb"))== 0)
printf("loadTextFile() - could not open file");
else
{
fseek(fileh, 0, SEEK_END);
filelength = ftell(fileh);
rewind(fileh);
text=(char *) smartmalloc((int)filelength + 1);
fread(text,(int)filelength, 1, fileh);
fclose(fileh);
text[filelength]=0;
}
printf(text);
return(text);
}
This function only returns partial data of a txt file. It is also inconsistent...soemtimes gives me 100 characters of the file some times 20. I don't see anything wrong with it. Thought I might get another pair of eyes on it. Thanks.
Upvotes: 1
Views: 333
Reputation: 202505
fread
is not guaranteed to return as many characters as you ask for. You need to check its return value and use it in a loop.
Example loop (not tested):
char *p = text;
do {
size_t n = fread(p,1,(size_t)filelength, fileh);
if (n == 0) {
*p = '\0';
break;
}
filelength -= n;
p += n;
} while (filelength > 0);
The test for n==0
catches the case where some other process truncates the file as you are trying to read it.
Upvotes: 3
Reputation: 118128
Here is a slightly better version of your code. You need more error checking with the IO function calls. Also, there is the annoying long
to size_t
implicit conversions which I would recommend dealing with properly in production code.
char* loadTextFile(const char *filename) {
char *text;
long length;
FILE *fileh = fopen(filename, "rb");
if ( !fileh ) {
return NULL;
}
fseek(fileh, 0, SEEK_END);
length = ftell(fileh);
rewind(fileh);
text = malloc(length + 1);
if ( !text ) {
return NULL;
}
fread(text, 1, length, fileh);
text[length] = 0;
fclose(fileh);
return text;
}
Note that, John R. Strohm is right: If your assessment of what has been read is based on what printf
prints, then you are likely being misled by embedded nul
s.
Upvotes: 3
Reputation: 7667
Obvious things to check:
What did ftell(fileh) give you?
Can there be embedded NUL characters in the file? That would cause printf(text) to stop prematurely.
Upvotes: 4