Cでファイルのサイズを取得するにはどうすればよいですか?

ファイルの最後までシークしてから、その位置を尋ねる必要があります:

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

その後、次のようにシークバックできます:

fseek(fp, 0L, SEEK_SET);

または (先頭に移動する場合)

rewind(fp);

標準ライブラリの使用:

実装が意味のある SEEK_END をサポートしていると仮定します:

fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file

Linux/POSIX:

stat を使用できます (ファイル名がわかっている場合)、または fstat (ファイル記述子がある場合)

以下は統計の例です:

#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;

Win32:

GetFileSize または GetFileSizeEx を使用できます。


ファイル記述子 fstat() がある場合 ファイルサイズを含む stat 構造体を返します。

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

// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.
struct stat buf;
fstat(fd, &buf);
off_t size = buf.st_size;