2021年2月26日金曜日

File Size in C

Problem with using fseek/ftell

From cppreference.com - fseek, SEEK_END may not be supported. In this case, ftell doesn't indicates true file size.

Binary streams are not required to support SEEK_END, in particular if additional null bytes are output.

Reliable method

Should use OS specific functions.

Windows

HANDLE file;
LARGE_INTEGER result;
int64_t size = TRUE == GetFileSizeEx(file, &result)? result.QuadPart : 0;

Others

FILE file;
int32_t fd = fileno(file); //If file has not been opened, the result will be undefined.
struct stat64 status;
int64_t size = 0<=fstat64(fd, &status)? status.st_size : 0;

0 件のコメント:

コメントを投稿