In: Computer Science
Write the body of the function getFileSize to return the size of an opened file.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
long getFileSize (FILE * f)
{
} int main () { FILE * file = fopen (“myfile.txt”,”r”); long fsize = getFileSize(file); printf ("File Size : %lu\n",fsize); return 0;}
C Program :
_____________________________
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
long getFileSize (FILE * f)
{
fseek(f, 0L, SEEK_END) ; // fseek to move file
pointer byte by byte
long res = ftell(f); //
ftell gives current position of file pointer
fclose(f);
// close file pointer
return
res;
// return the result
}
int main()
{
FILE *file = fopen ("myfile.txt","r");
long fsize = getFileSize(file);
printf ("File Size : %lu\n",fsize);
return 0;
}
_____________________________
Explanation :
fseek() function format is : int fseek(FILE *pointer, long int offset, int origin)
where pointer is the file pointer
offset is number of characters to shift the position relative to origin
origin is the position to which offset is added.
ftell() format is : long ftell(FILE *pointer) , ftell takes file pointer as input and returns the current position of file pointer with respect to beginning of the file.
_____________________________
SCREENSHOTS :
My "myfile.txt" looked like this
The output of program is :
To confirm that the result was correct,I checked for file size using file properties in windows
You can see that the file size is same as returned by the program(in bytes).
_________________________________
Please comment in case you have any doubt.