#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
#define FILENAME "test.lod"
int main(void)
{
struct stat statbuf;
FILE *stream;
/* open a file for update */
if ((stream = fopen(FILENAME, "r")) == NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return(1);
}
/* get information about the file */
stat(FILENAME, &statbuf);
fclose(stream);
printf("Size of file in bytes: %ld\n", statbuf.st_size);
printf("Time file last opened: %s\n", ctime(&statbuf.st_ctime));
return 0;
}
上述函数虽然能够获得文件大小,但是仅限于在单线程中,如果在多线程中使用stat函数获得文件大小,偶尔会出现文件大小为0的现象。下面的函数反而实用。
#include <stdio.h>
#include <time.h>
#define FILENAME "test.lod"
int main(void)
{
FILE *stream;
long length;
/* open a file for update */
if ((stream = fopen(FILENAME, "r")) == NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return(1);
}
fseek(stream, 0L, SEEK_END);
length = ftell(stream);
fclose(stream);
printf("Size of file in bytes: %ld\n", length);
return 0;
}