1. 程式人生 > >Linux 下程式設計(C語言)獲取檔案大小

Linux 下程式設計(C語言)獲取檔案大小

程式碼:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc,char *argv[])
{
	if(argc < 1)
	{
		printf("no file \n");
		return 0;
	}
	int fd = open(argv[1],O_RDONLY);
	if(fd < 0)
	{
		perror("open ");
		return 0;
	}
	long int size = lseek(fd,0,SEEK_END);
	printf("%s size is %ld\n",argv[1],size);

	return 0;
}

以上程式碼檔名為fsize.c
gcc fsize.c -o fsize
./fsize hello.c
在終端執行上述語句,即可獲取hello.c檔案的大小
可以通過 ll (即 ls -l)命令檢視hello.c的檔案大小是否和程式獲取的一樣來檢驗程式