码迷,mamicode.com
首页 > 其他好文 > 详细

WriteFile与ReadFile实例(实用)

时间:2020-01-02 18:27:47      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:数字   ESS   tin   结构体   invalid   str   npc   click   string   

不多说,上代码:

 1 struct NPC{
 2     char sex;
 3     int age;
 4     double Blood;
 5 };
 6 //通过WriteFile写入数据
 7 void CWriteFileDlg::OnBnClickedButton1()
 8 {
 9     HANDLE hFile = CreateFile(_T("F:\\123.txt"), GENERIC_WRITE, FILE_SHARE_READ,NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
10     if (hFile== INVALID_HANDLE_VALUE) {
11         MessageBox(_T("出错啦"));
12         return;
13     }
14     //定义各种数据
15     int number = 55567;
16     NPC mk;
17     mk.sex = m;
18     mk.age = 18;
19     mk.Blood = 100.00;
20     char szchar[20] = "你好!世界!!!";
21     DWORD iWrite = 0;
22     //写入各种数据
23     BOOL rRet = WriteFile(hFile, &number, sizeof(number), &iWrite, NULL);
24     rRet = WriteFile(hFile, &mk, sizeof(mk), &iWrite, NULL);
25     rRet = WriteFile(hFile, szchar, sizeof(szchar), &iWrite, NULL);
26     if (rRet) {
27         MessageBox(_T("成功!"));
28     }
29     else {
30         MessageBox(_T("WriteFile失败!"));
31     }
32     CloseHandle(hFile);
33     return;
34 }
35 
36 //使用ReadFile读取数据
37 void CWriteFileDlg::OnBnClickedButton2()
38 {
39     HANDLE hFile = CreateFile(_T("F:\\123.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
40     if (hFile == INVALID_HANDLE_VALUE) {
41         MessageBox(_T("出错啦"));
42         return;
43     }
44     //定义接收数据的变量
45     int number = 0;
46     NPC read = {0};
47     char szStr[20] = "";
48     DWORD iWritten = 0;
49     CString retStr;
50     //读取数字
51     BOOL iRet = ReadFile(hFile, &number, sizeof(number), &iWritten, NULL);
52     if (iRet) {
53         MessageBox(_T("读取成功"));
54         retStr.Format(_T("%d"), number);
55         MessageBox(retStr);
56     }
57     else {
58         MessageBox(_T("读取失败!"));
59     }
60     //读取结构体
61     iRet = ReadFile(hFile, &read, sizeof(read), &iWritten, NULL);
62     if (iRet) {
63         MessageBox(_T("读取成功"));
64     }
65     else {
66         MessageBox(_T("读取失败!"));
67     }
68     //读取字符串
69     iRet = ReadFile(hFile, szStr, sizeof(szStr), &iWritten, NULL);
70     if (iRet) {
71         MessageBox(_T("读取成功"));
72         
73     }
74     else {
75         MessageBox(_T("读取失败!"));
76     }
77     CloseHandle(hFile);
78 }

WriteFile与ReadFile实例(实用)

标签:数字   ESS   tin   结构体   invalid   str   npc   click   string   

原文地址:https://www.cnblogs.com/mktest123/p/12134448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!