Reading a Text File w/ WIN32

2

I'm trying to parse a text file with a win32 program in c++. Is there a simple method of reading a text file line by line? My text file consists of strings that I would like to store in a char array(const char* cArray[67]). Here is what I have so far. I am using CreateFile and ReadFile. I get an access violation error(0x000003e6) from readfile:

CDECK::CDECK():filename(".\\Deck/list.txt")
{
    LPVOID data = NULL;
    hFile = CreateFileA(filename, GENERIC_READ,FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if(hFile == INVALID_HANDLE_VALUE)
        MessageBox(NULL, L"Failed to CreateFile - 'hFile'", L"CDECK::CDECK()", MB_OK);

    DWORD fileSize = GetFileSize(hFile, &fileSize);
    DWORD read = -1;
    if(!ReadFile(hFile, data, fileSize, &read, NULL))
    {
        DWORD err = GetLastError();
        MessageBox(NULL, L"Failed to ReadFile - 'hFile'", L"CDECK::CDECK()", MB_OK);
    }
    return;
}
c++
winapi
file-io
asked on Stack Overflow May 18, 2012 by P. Avery

4 Answers

10

Is there a simple method of reading a text file line by line?

Yes:

{
  std::ifstream hFile(filename);

  std::vector<std::string> lines;
  std::string line;
  while(std::getline(hFile, line))
    lines.push_back(line);

  return lines;
}
answered on Stack Overflow May 18, 2012 by Robᵩ • edited May 18, 2012 by Robᵩ
6

Consider this code:

LPVOID data = NULL;
if(!ReadFile(hFile, data, fileSize, &read, NULL))

Here data is null, and the following argument is the size of the entire file. You are supposed to allocate a buffer, and then pass a pointer to such buffer and its size to it. There is where the ReadFile function will write the readed bytes.

Here is a simple way of getting it to work with a statically sized buffer:

char data[4096] = {};
if(!ReadFile(hFile, static_cast< LPVOID >( &data ), 4096, &read, NULL))
answered on Stack Overflow May 18, 2012 by K-ballo
0

Your problem is that you are reading the bytes of the file, to read the string you need to alloc a string location using SysAllocStringByteLen and then use the ReadFile

answered on Stack Overflow May 20, 2012 by João Marcelo Brito
0

You forgot to allocate a buffer space before reading your data : LPVOID data = NULL;

Before reading you must allocate a fileSize buffer space : data = malloc(fileSize);

And probably must also declare your data variable as char* instead of void*

answered on Stack Overflow Nov 18, 2018 by (unknown user)

User contributions licensed under CC BY-SA 3.0