Get File Size

Sep 4, 2009 at 5:06pm
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.
Sep 4, 2009 at 5:13pm
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?
Sep 4, 2009 at 5:40pm
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 :\ ...
Sep 4, 2009 at 7:44pm
Open the file using CreateFile(). CreateFile() returns the needed handle.

http://msdn.microsoft.com/en-us/library/aa363858%28VS.85%29.aspx
Sep 4, 2009 at 8:30pm
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);
}
Sep 5, 2009 at 3:07pm
Don't use both standard handles and Win32 handles.
Sep 5, 2009 at 9:11pm
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...
Sep 5, 2009 at 11:28pm
Perhaps I'm missing something, but if he wants a Win32 handle, why doesn't he just use the Win32 method, i.e., CreateFile()?
Sep 6, 2009 at 12:02am
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.
Sep 6, 2009 at 12:46am
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.
Sep 6, 2009 at 1:03am
You can seek and tell...
Sep 6, 2009 at 2:52am
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 Sep 6, 2009 at 2:52am
Topic archived. No new replies allowed.