1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include <windows.h> #include <tchar.h> #include <iostream> using namespace std;
struct Student { int age; char sex; char name[32]; };
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { HANDLE hFile = CreateFile(_T("D:\\VC驿站ok.txt"), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { MessageBox(NULL, _T("文件打开失败!"), _T("Tip"), MB_OK); return -1; }
int num = 123; DWORD dwRealWrite = 0; BOOL bRet = WriteFile(hFile, &num, sizeof(int), &dwRealWrite, NULL);
char ch = 'q'; bRet = WriteFile(hFile, &ch, sizeof(char), &dwRealWrite, NULL);
char szText[32] = "我是VC驿站的粉丝!"; bRet = WriteFile(hFile, szText, sizeof(szText), &dwRealWrite, NULL);
Student stud; stud.age = 20; stud.sex = 'm'; strcpy(stud.name, "zhangsan");
bRet = WriteFile(hFile, &stud, sizeof(stud), &dwRealWrite, NULL); if (bRet) { MessageBox(NULL, _T("数据写入成功!"), _T("Tip"), MB_OK); } else { MessageBox(NULL, _T("数据写入失败!"), _T("Tip"), MB_OK); }
CloseHandle(hFile);
hFile = CreateFile(_T("D:\\VC驿站ok.txt"), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { MessageBox(NULL, _T("文件打开失败!"), _T("Tip"), MB_OK); return -1; }
int ret_num = 0; DWORD dwRealRead = 0; bRet = ReadFile(hFile, &ret_num, sizeof(ret_num), &dwRealRead, NULL);
char cha = 0; bRet = ReadFile(hFile, &cha, sizeof(cha), &dwRealRead, NULL);
char szTextRet[32] = { 0 }; bRet = ReadFile(hFile, szTextRet, sizeof(szTextRet), &dwRealRead, NULL);
Student stud2; bRet = ReadFile(hFile, &stud2, sizeof(Student), &dwRealRead, NULL); if (bRet) { MessageBox(NULL, _T("数据读取成功!"), _T("Tip"), MB_OK); } else { MessageBox(NULL, _T("数据读取失败!"), _T("Tip"), MB_OK); }
CloseHandle(hFile); return 0; }
|