7: // The hi score file couldn’t be
7: // The hi score file couldn’t be created, so bail 8: return FALSE; 9: 10: // Write the scores 11: for (int i = 0; i < 5; i++) 12: { 13: // Format each score for writing 14: CHAR cData[6]; 15: wsprintf(cData, "%05d", _iHiScores[i]); 16: 17: // Write the score 18: DWORD dwBytesWritten; 19: if (!WriteFile(hFile, &cData, 5, &dwBytesWritten, NULL)) 20: { 21: // Something went wrong, so close the file handle 22: CloseHandle(hFile); 23: return FALSE; 24: } 25: } 26: 27: // Close the file 28: return CloseHandle(hFile); 29: } Most of this code should look familiar to you because it is very similar to the code you saw earlier in the hour when discussing how to create a new file and write a score using the CreateFile() and WriteFile() functions. A new HiScores.dat file is first created with a call to the CreateFile() function (lines 4 8); even if the file already exists, a new one is created to replace it. After the file is created, the function prepares to write to the file by looping through the high scores (line 11). Each score must be formatted into a five-digit character string before it can be written (lines 14 and 15). The score is then written to the file with a call to the WriteFile() function (line 19). If an error occurs during the write, the file handle is closed with a call to CloseHandle() (line 22). If all goes well and the data is successfully written, the function finishes by closing the file with a call to CloseHandle() (line 28). Not surprisingly, the ReadHiScores() function works similarly to WriteHiScores(), except everything happens in the reverse. Listing 24.5 contains the code for the ReadHiScores() function. Listing 24.5 The ReadHiScores() Function Reads the High Score List from the File HiScores.dat 1: BOOL ReadHiScores() 2: { 3: // Open the hi score file (HiScores.dat) 4: HANDLE hFile = CreateFile(TEXT("HiScores.dat"), GENERIC_READ, 0, NULL, 5: OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL); 6: if (hFile == INVALID_HANDLE_VALUE) 7: { 8: // The hi score file doesn't exist, so initialize the scores to 0 9: for (int i = 0; i < 5; i++) 10: _iHiScores[i] = 0; 11: return FALSE; 12: } 13: 14: // Read the scores 15: for (int i = 0; i < 5; i++) 16: { 17: // Read the score 18: char cData[6]; 19: DWORD dwBytesRead; 20: if (!ReadFile(hFile, &cData, 5, &dwBytesRead, NULL)) 21: { 22: // Something went wrong, so close the file handle 23: CloseHandle(hFile); 24: return FALSE; 25: } 26: 27: // Extract each integer score from the score data
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Cheap Web Hosting services