1. 程式人生 > 其它 >計算檔案大小:lseek、ftell、stat

計算檔案大小:lseek、ftell、stat

計算檔案大小:

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

#include <stdio.h>

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

//核心lseek
int FileSize_1(char
*buf) { int n = -1; int fd = open(buf, O_RDONLY); if(-1 == fd) { printf("open error"); return -1; } //lseek函式的返回值就是距離檔案首位多少位元組 n = lseek(fd, 0, SEEK_END); close(fd); return n; } //核心ftell int FileSize_2(char *buf) { int n = -1; FILE *fd = fopen(buf, "
r"); if(NULL == fd) { printf("fopen error"); return -1; } //將指標指向檔案末尾 int ret = fseek(fd, 0, SEEK_END); if(0 != ret) { printf("fopen error"); return -1; } //讀取當前指標距離檔案開頭多少位元組 n = ftell(fd); fclose(fd); return n; } //核心stat int FileSize_3(char
*buf) { int n = -1; struct stat str; stat(buf, &str); n = str.st_size; return n; } int main() { int size = 0; size = FileSize_1("LF.jpg"); printf("%d\n",size); size = FileSize_2("LF.jpg"); printf("%d\n",size); size = FileSize_3("LF.jpg"); printf("%d\n",size); }