fseeko64() and ftello64() for deal with large files (eg. file dimension)

AuSsIeStOnE 2 Tallied Votes 501 Views Share

fseek() and ftell() work only for files < 2,147,483,647 bytes

fseeko64() and ftello64() from <stdio.h> can deal with files up to 18,446,744,073,709,552,000 bytes

the printf format for unsigned long long val is %I64d

eg. Obtaining the file dimension (this code was tested with GNU GCC compiler (MinGW/Cygwin) from code::blocks)

#include <stdio.h>
#include <conio.h>

int main ()
{

    FILE * pFile;

    unsigned long long file_dim = 0;
    char file_name[260] = "";

/////////////////////////////////////////////////////////

    printf("ENTER [path] file name.ext:\n");
    gets(file_name);

    pFile = fopen (file_name,"rb");

    if (pFile==NULL)
        perror ("Error opening file");
    else
    {
        fseeko64 (pFile, 0, SEEK_END);
        file_dim = ftello64 (pFile);
        fclose (pFile);
        printf ("File:\n%s\ncontains %I64d bytes:\n", file_name, file_dim);
    }

    printf("Press any key to exit");
    getch();

    return 0;
}

Dani AI

Generated

Good point from — the classic 32-bit fseek/ftell limits still bite on some toolchains. On Unix-like systems prefer the off_t-based interfaces (use fseeko/ftello or enable large-file support with _FILE_OFFSET_BITS=64) so offsets become 64-bit. On Windows use the CRT helpers (_fseeki64/_ftelli64) or the Win32 API (GetFileSizeEx) for unambiguous 64-bit file sizes. (man7.org)

A practical, portable recipe: on POSIX build with -D_FILE_OFFSET_BITS=64 (or explicitly use the *64 variants where available), or simply query the filesystem with stat()/fstat() and read st_size. On Windows, call _fseeki64/_ftelli64 or GetFileSizeEx. Check your compiler/CRT: Cygwin, MinGW and MSVC expose different symbols and behaviours, so test the exact function names in your environment. (man7.org)

A short, safe pattern (uses stat() and the standard printf macros) — this avoids fseek/ftell portability issues:

#include <sys/stat.h>
#include <inttypes.h>
#include <stdio.h>

int main(void) {
    struct stat st;
    if (stat("path/to/file", &st) == 0) {
        printf("size: %" PRIuMAX " bytes\n", (uintmax_t)st.st_size);
    } else {
        perror("stat");
    }
}

stat() exposes st_size (the file size) and printing with the <inttypes.h> macros is portable across platforms. (man7.org)

Quick safety notes and troubleshooting: remove gets() (it was removed from the C standard; use fgets or getline instead). Check binary vs text mode — text-mode translations can make ftell/fseek results unreliable near line endings on some systems. Always test compiled symbols on the target toolchain (MinGW vs MinGW‑w64 vs MSVC vs Cygwin behave differently) and check return values for errors. (stackoverflow.com)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.