Reading in a file in C, after file read null terminator at strings end gone
Hi
In reading a file into my program using C, i used calloc to allocate and initialize the needed memory. The size of the memory allocated was the size of the file-length + 1, so that the end of the string would house the NULL-terminator. However, after i read in the file using fread and I use while(*cfile) to read the string until reaching the null char the loop becomes an infinite loop (cfile is the name of the pointer to the memory block). Its as if after using fread to read in the file contents the null terminator is gone. I attached my code below. Thanks for any help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
FILE *fp; //file pointer
long int lfilelng; //file length
//open file
if ((fp=fopen("toberead", "rb"))==NULL) {
printf("cannot open file - 'toberead'");
exit(1);
}
if (fseek(fp, 0L, SEEK_END) !=0 ) {
printf("seek error");
exit(1);
}
lfilelng = ftell(fp);
printf("%ld\n", lfilelng);
rewind(fp);
char *cfile;
if ((cfile=calloc(lfilelng+1, sizeof(char)))==NULL) {
printf("insuficient memory to read file");
exit(1);
}
if (fread(cfile, lfilelng, 1, fp) != 1) {
printf("\nread error occured");
exit(1);
}
fclose(fp);
int i=0;
while (*cfile) { //Here is the problem
i++;
printf("\n");
printf("%d",i);
}
free(cfile);
cfile = NULL;
return 0;
}
|