BitTickler
BitTickler

Reputation: 11885

Win32 File IO works but fopen et. al. fails. What is going on here?

Never had that before. If I use the fopen() etc. functions for reading a file from disk, fopen succeeds, but the FILE * content looks a bit NULL-ish. Then I try fseek(SEEK_END) and it reports that the file is of size 0 bytes.

If I do the same with CreateFile(), GetFileSize(), ReadFile(), it works. Same function, same path...

VS2013 Community Edition, Win7 x64, 64bit compile. Files I tested with were small (never more than 400 bytes). They are located on E: drive (E:\temp), which is a local partition.

Any ideas where I need to solder my computer to fix that? :)

static void LoadFile(const std::string &path, std::string& target)
{
#if 1
    HANDLE hFile = ::CreateFileA(path.c_str(), FILE_READ_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
    finally finallyClose([&hFile](){ ::CloseHandle(hFile); });
    if (INVALID_HANDLE_VALUE != hFile)
    {
        DWORD fileSize = ::GetFileSize(hFile, NULL);
        target.resize(fileSize);
        DWORD bytesRead = 0UL;
        BOOL success = ::ReadFile(hFile, &target[0], fileSize, &bytesRead, NULL);
    }
    else
    {
        std::cout << "Could not load file: " << path << std::endl;
    }

#else
    FILE * inFile = NULL;
    errno_t err = fopen_s(&inFile, path.c_str(), "rb");

    if (NULL != inFile)
    {
        finally finallyClose([&inFile](){ fclose(inFile); });

        int fileSize = fseek(inFile, 0, SEEK_END);
        fseek(inFile, 0, SEEK_SET);
        target.resize(fileSize);
        fread(&target[0], sizeof(char), fileSize, inFile);
    }
    else
    {
        std::cout << "Could not load file: " << path << std::endl;
    }
#endif
}

Upvotes: 1

Views: 234

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

The fseek function returns 0 on success. It does not return the number of bytes the file pointer has moved.

http://en.cppreference.com/w/c/io/fseek

You need to call ftell to get back the file size.

http://en.cppreference.com/w/c/io/ftell

fseek(inFile, 0, SEEK_END);
int filesize = ftell(inFile);
target.resize(filesize);

Upvotes: 3

Related Questions