1 #include <Windows.h> 2 #include <stdio.h> 3 4 DWORD ReadFileContent(LPSTR szFilePath) 5 { 6 HANDLE hFileRead; 7 LARGE_INTEGER liFileSize; 8 DWORD dwReadedSize; 9 LONGLONG liTotalRead =0; 10 BYTE lpFileDataBuffer[32]; 11 12 hFileRead = CreateFile(szFilePath, 13 GENERIC_READ, 14 FILE_SHARE_READ, 15 NULL, 16 OPEN_EXISTING, 17 FILE_ATTRIBUTE_NORMAL, 18 NULL); 19 20 if(hFileRead == INVALID_HANDLE_VALUE) 21 { 22 printf("Open file failed:%d\n",GetLastError()); 23 } 24 if(!GetFileSizeEx(hFileRead,&liFileSize)) 25 { 26 printf("Get file size failed: %d\n",GetLastError()); 27 } 28 else 29 { 30 printf("File size is:%d\n",liFileSize.QuadPart); 31 } 32 33 while(TRUE) 34 { 35 DWORD i; 36 if(!ReadFile(hFileRead, 37 lpFileDataBuffer, 38 32, 39 &dwReadedSize, 40 NULL)) 41 { 42 printf("Read file error:%d\n",GetLastError()); 43 break; 44 } 45 printf("Readed %d byte,file content is: ",dwReadedSize); 46 for(i = 0; i < dwReadedSize; i++) 47 { 48 printf("0x%x ",lpFileDataBuffer[i]); 49 } 50 printf("\n"); 51 liTotalRead += dwReadedSize; 52 if(liTotalRead == liFileSize.QuadPart) 53 { 54 printf("Read file end!\n"); 55 break; 56 } 57 } 58 CloseHandle(hFileRead); 59 return 0; 60 } 61 62 DWORD SaveDataToFile( 63 LPSTR szFilePath, 64 LPVOID lpData, 65 DWORD dwDataSize) 66 { 67 HANDLE hFileWrite; 68 DWORD dwWritedDateSize; 69 hFileWrite = CreateFile(szFilePath, 70 GENERIC_WRITE, 71 0, 72 NULL, 73 OPEN_ALWAYS, 74 FILE_ATTRIBUTE_NORMAL, 75 NULL); 76 77 78 if(hFileWrite == INVALID_HANDLE_VALUE) 79 { 80 printf("Open file failed: %d\n",GetLastError()); 81 } 82 SetFilePointer(hFileWrite,0,0,FILE_END); 83 if(!WriteFile(hFileWrite, lpData, dwDataSize, &dwWritedDateSize, NULL)) 84 printf("Write file failed: %d\n",GetLastError()); 85 else 86 printf("Write file sucess!,write %d bytes.\n",dwWritedDateSize); 87 CloseHandle(hFileWrite); 88 return 0; 89 } 90 91 int main(void) 92 { 93 LPSTR szFileData = "this is my first sample!"; 94 SaveDataToFile("D:\\show.txt",szFileData,lstrlen(szFileData)); 95 ReadFileContent("D:\\show.txt"); 96 return 0; 97 }