Get File Size

Hello. I'm writing a program using M$ Visual C++. Is there a simple API for getting the file size? Something like GetFileSize? :) I'm trying to read out bytes from a binary file, and I think it's prematurely reading out an EOF character. So, I need to query the filesize from the OS. Thanks.
Yes, and the function name is GetFileSize(). http://msdn.microsoft.com/en-us/library/aa364955%28VS.85%29.aspx.

It is the first result from a Google search. :-S Let's try and use it more often, shall we?
Thanks, Jose. I've seen that, but how do I get the HANDLE value that needs to be passed? I can initialize a FILE type variable without any problem, but how do I get the HANDLE? Thank you for your patience. Most of my experience is in writing embedded firmware; I haven't touched this Windows stuff in years :\ ...
Open the file using CreateFile(). CreateFile() returns the needed handle.

http://msdn.microsoft.com/en-us/library/aa363858%28VS.85%29.aspx
Thanks for the help, Jose. I think my problem is solved:

1
2
3
4
5
6
7
FILE* pFile = fopen();
if (pFile)
{
    int fileNum = _fileno(pFile);
    HANDLE hFile = (HANDLE) _get_osfhandle(fileNum);
    GetFileSize(hFile);
}
Don't use both standard handles and Win32 handles.
So what is he supposed to do then?

The _get_osfhandle() function exists in Win32 for this very purpose: convert a standard C handle to a Win32 handle, so you can do cool Win32 stuff with it, like GetFileSize().

It is true that you shouldn't use both the HANDLE and the FILE* at the same time...
Perhaps I'm missing something, but if he wants a Win32 handle, why doesn't he just use the Win32 method, i.e., CreateFile()?
We don't know.

It seems that he is writing in C, and just using the Win32 functions to check the file size as a debug measure. There is nothing wrong with that.
Is there not an easier way to get the filesize if he just wants to stay in the stream functions? I don't really know, as I program almost entirely in C/Win32 API, but I seem to recall in going through my C/C++ books that there is the capability to get the file size without having to resort to the Win32 API.
You can seek and tell...
Further to Duoas' recommendation, to use "seek" and "tell", the reference has something very good:
1
2
3
4
        /* Get size of file: */
        fseek(f, 0, SEEK_END);
        fSize = ftell(f);
        rewind(f);


Note that that's my rewrite of the code and that fSize is a long integer. I think that's what he meant. I'm not sure if there's some C++ way of doing it, but that would be the C way...
Last edited on
Topic archived. No new replies allowed.