今天面試,面試官問我c語言裏面有木有函數計算一個文件的大小,是哪一個?
我糾結了一小會兒,我想有嗎?當時也沒回答出來,回來查才知道,用的是用lseek和ftell結合使用實現的。
The ftell() function returns the current position in an open file.
ftell()函數的作用是:返回文件指針當前的讀/寫的位置。
Returns the current file pointer position, or FALSE on failure.
如果函數執行成功,將返回當前的指針位置;如果執行失敗,將返回False。
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
long fileSize = 0;
FILE *pFile = fopen("t2.c","r");
if( pFile == NULL)
{
printf("Open File Error /n");
}
else
{
fseek(pFile, 0, SEEK_END);//移向END
fileSize = ftell(pFile);
printf("file size:%ld \n", fileSize);
}
fclose(pFile);
}
使用ls -l 或者ll查看,很準確。