How to read a file using WIN API?

You must use the WIN API sozdal file, write the structure and then display the file on screen. The file is created but the data is also written to the console the contents of the file will not be displayed errors auger no. Not specifically zahodit in 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;
 }
March 19th 20 at 09:25
1 answer
March 19th 20 at 09:27
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 that it returns the function ReadFile, and if FALSE, then GetLastError see the error code.
The Readfile function is executed successfully but in the while loop nezahodil - dayna.Co commented on March 19th 20 at 09:30
@dayna.Co, ReadFile returns TRUE? - hailee1 commented on March 19th 20 at 09:33
Yes - dayna.Co commented on March 19th 20 at 09:36
numberBytesToRead after the function, what is? - hailee1 commented on March 19th 20 at 09:39
Add close file after write and re-opening it before reading. - hailee1 commented on March 19th 20 at 09:42
like tepr reads, the only problem with the encoding. In the end, wrote
if (readFile != 0) {
 cout << buff << endl;
}
- dayna.Co commented on March 19th 20 at 09:45
@dayna.Co, setlocale(LC_ALL, "Russian") - hailee1 commented on March 19th 20 at 09:48
write text latinitas - dayna.Co commented on March 19th 20 at 09:51

Find more questions by tags C++