V
V
Vlad_beg2019-03-31 18:14:14
C++ / C#
Vlad_beg, 2019-03-31 18:14:14

How to correctly read a file using the WIN API?

It is necessary to create a file using the WIN API, write a structure to it, and then display the contents of the file on the screen. The file is created, the data is also written, but the contents of the file are not displayed on the console, there are no errors. Doesn't specifically fit into a while loop.

LPCSTR fileName = "file.dat";
DWORD fielAttr = GetFileAttributesA(dir);
HANDLE hFile;
string fileDir = string(dir).append(fileName);

  if (fielAttr == FILE_ATTRIBUTE_DIRECTORY)
  {

    hFile = CreateFile(fileDir.c_str(), GENERIC_WRITE | GENERIC_READ, 0, NULL,
               OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    if (hFile != INVALID_HANDLE_VALUE) {

      cout << "File created...\n\n";
      struct Student st[3];

      cout << "Name: ";
      cin.getline(st[0].name, 40);
      cout << "Surname: ";
      cin >> st[0].surname;
      cout << "Average mark: ";
      cin >> st[0].averageMark;
      cout << "\n\n";

      DWORD dwBytesWritten;
      BOOL writeFile = WriteFile(hFile, &st, sizeof(st), &dwBytesWritten, NULL);

      if (writeFile) {
        cout << "Data has been written to a file!\n\n";
      }
      else {
        cout << "Failed to write data to file! Error code: " << GetLastError() << endl;
        return;
      }
  
    }
    else {
      cout << "Failed to create file. Error code: " << GetLastError() << endl;
      return;
    }
  }
  
  DWORD numberOfBytesToRead;
  char buff[255];
  BOOL readFile = ReadFile(hFile, &buff, sizeof(buff), &numberOfBytesToRead, NULL);
  
  if (readFile != NULL) {

    while (numberOfBytesToRead != 0) {
      cout << buff << endl;
    }
  }
  else {
    cout << "Failed to read file. Error code: " << GetLastError() << endl;
    return;
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2019-03-31
@SaNNy32

https://docs.microsoft.com/en-us/windows/desktop/a...
If the function succeeds, the return value is nonzero (TRUE).
If the function fails, or is completing asynchronously, the return value is zero (FALSE). To get extended error information, call the GetLastError function.
Check what the ReadFile function returns and if FALSE, then use GetLastError to see the error code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question