Determining the size of a file larger than 4GB
Asked Answered
T

6

8

The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a file > 4GB?

fpos_t currentpos;

sok=fseek(fp,0,SEEK_END);
assert(sok==0,"Seek error!");

fgetpos(fp,&currentpos);
m_filesize=currentpos;
Toothpick answered 22/9, 2008 at 2:34 Comment(2)
Just out of curiosity, are you sure that fgetpos is working correctly if you haven't gotten to the end of the file?Chappell
fpos_t is not an integer type so the last line is invalid.Pringle
L
6

If you're in Windows, you want GetFileSizeEx (MSDN). The return value is a 64bit int.

On linux stat64 (manpage) is correct. fstat if you're working with a FILE*.

Lebna answered 22/9, 2008 at 3:41 Comment(0)
P
9

Ignore all the answers with "64" appearing in them. On Linux, you should add -D_FILE_OFFSET_BITS=64 to your CFLAGS and use the fseeko and ftello functions which take/return off_t values instead of long. These are not part of C but POSIX. Other (non-Linux) POSIX systems may need different options to ensure that off_t is 64-bit; check your documentation.

Pringle answered 3/8, 2010 at 18:16 Comment(2)
Could you provide references?Bernadette
@qed: "Not part of POSIX": See pubs.opengroup.org/onlinepubs/9699919799/functions/… ; Usage of -D_FILE_OFFSET_BITS=64: see man7.org/linux/man-pages/man7/feature_test_macros.7.htmlPringle
L
6

If you're in Windows, you want GetFileSizeEx (MSDN). The return value is a 64bit int.

On linux stat64 (manpage) is correct. fstat if you're working with a FILE*.

Lebna answered 22/9, 2008 at 3:41 Comment(0)
A
3

This code works for me in Linux:

int64_t bigFileSize(const char *path)
{
    struct stat64 S;

    if(-1 == stat64(path, &S))
    {
        printf("Error!\r\n");
        return -1;
    }

    return S.st_size;
}
Animate answered 22/9, 2008 at 2:52 Comment(0)
P
2

(stolen from the glibc manual)

int fgetpos64 (FILE *stream, fpos64_t *position)

This function is similar to fgetpos but the file position is returned in a variable of type fpos64_t to which position points.

If the sources are compiled with _FILE_OFFSET_BITS == 64 on a 32 bits machine this function is available under the name fgetpos and so transparently replaces the old interface.

Penniepenniless answered 22/9, 2008 at 2:42 Comment(0)
D
2

Stat is always better than fseek to determine file size, it will fail safely on things that aren't a file. 64 bit filesizes is an operating specific thing, on gcc you can put "64" on the end of the commands, or you can force it to make all the standard calls 64 by default. See your compiler manual for details.

Diploblastic answered 22/9, 2008 at 2:48 Comment(0)
N
1

On linux, at least, you could use lseek64 instead of fseek.

Norvin answered 22/9, 2008 at 2:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.