獲得檔案的大小(c語言)

Aaron_tj發表於2016-12-04

方法一

使用c的兩個函式:fseek()和seek()。
fseek()函式原型

int fseek(
    FILE *stream,
    long offset,
    int orign
)

引數:
stream:指向FILE結構體的指標;
offset:偏移量,正數表示正向偏移,負數表示負向偏移;
origin:代表從哪個位置開始偏移;
SEEK_CUR ——從當前檔案指標的位置開始偏移
SEEK_END——從檔案結尾的位置開始偏移
SEEK_SET——從檔案開頭的位置開始偏移

ftell()函式原型

long ftell(
    FILE *stream
)

引數:
stream:指向目標檔案的FILE*結構體指標

**

方法二

使用_stat結構體和_stat()函式
st_size:檔案大小
st_atime:最後一次被訪問的時間;
st_ctime:檔案建立的時間
_stat函式原型

int _stat(
    const char *path;
    struct _stat *buffer
)

引數:
path:檔名
buffer:_stat結構體指標
返回值:
成功:0; 失敗:-1;

程式碼實現:

#include <stdio.h>
#include <sys/stat.h>
int main()
{
    char FileName[MAX_PATH] = { 0 };
    //方法一
    long filesize = 0;
    fopen_s(&file, FileName, "r");
    fseek(file, 0, SEEK_END);
    filesize = ftell(file);
    printf("檔案大小\t:%ld\n", filesize);

    //方法二
    struct _stat buf;
    int result = _stat(FileName, &buf);
    if(0 != result)
    {
        return -1;
    }
    printf("檔案大小\t:%ld\n", buf..st_size);
    return 0;
}

相關文章