Basically, i have a file of an unkown size, with no header etc. to get information from about the size of the file! ...All i need to do is to allocate memory using malloc, creating a pointer to the allocated memory and then read the file char by char into the memory!
Does anyone know the best way to find the length of the file????
I have tried a few different ways, but they don't seem to work! This is what i am doing at the moment, but when i print the memory, it is just blank, no data gets put into it!!!!
Code:
FILE *fp;
char *buffer;
long numbytes;
/* open an existing file for reading NOTE: filename is not the file i am opening, its just for example!*/
fp = fopen("filename", "r");
/* quit if the file does not exist */
if(fp == NULL)
return 1;
/* Get the number of bytes */
fseek(fp, 0L, SEEK_END);
numbytes = ftell(fp);
/* reset the file position indicator to
the beginning of the file */
fseek(fp, 0L, SEEK_SET);
/* grab sufficient memory for the
buffer to hold the text */
buffer = (char*)calloc(numbytes, sizeof(char));
/* memory error */
if(buffer == NULL)
return 1;
/* copy all the text into the buffer */
fread(buffer, sizeof(char), numbytes, fp);
fclose(fp);
/* confirm we have read the file by
outputing it to the console */
printf("contents of file:\n%s", buffer);
/* free the memory we used for the buffer */
free(buffer);