Linux C_純C/C++ 確認檔案是否存在和抓取檔案大小

Linux C_純C/C++ 確認檔案是否存在和抓取檔案大小

Linux C_純C/C++ 確認檔案是否存在和抓取檔案大小


GITHUB: https://github.com/jash-git/Jash_LinuxC/tree/master/%E7%B4%94C%E7%A2%BA%E8%AA%8D%E6%AA%94%E6%A1%88%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8%E5%92%8C%E6%8A%93%E5%8F%96%E6%AA%94%E6%A1%88%E5%A4%A7%E5%B0%8F


code:

#include <stdio.h>   // FILE...

// get the file size.
long getfilesize(FILE *pFile)
{
        // check FILE*.
        if( pFile == NULL)
        {
                return -1;
        }

        // get current file pointer offset.
        long cur_pos = ftell(pFile);
        if(cur_pos == -1)
        {
                return -1;
        }

        // fseek to the position of file end.
        if(fseek(pFile, 0L, SEEK_END) == -1)
        {
                return -1;
        }

        // get file size.
        long size = ftell(pFile);

        // fseek back to previous pos.
        if(fseek(pFile, cur_pos, SEEK_SET) == -1)
        {
                return -1;
        }

        // deal returns.
        return size;
}
int main()
{
        // open a file.
        FILE *pFile = fopen("c:\\123.bat", "r");
        if(pFile == NULL)
        {
                printf("error.\n");
                return 0;
        }

        // get the file size.
        printf("the file size: %ld bytes\n", getfilesize(pFile));

        // close the file.
        fclose(pFile);

        return 0;
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *