WriteFile与ReadFile实例(实用)

Posted mktest123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WriteFile与ReadFile实例(实用)相关的知识,希望对你有一定的参考价值。

不多说,上代码:

 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实例(实用)的主要内容,如果未能解决你的问题,请参考以下文章

使用 ReadFile 和 WriteFile 时出现死锁

28-Jenkins-Pipeline-Pipeline Basic Steps插件之readFile和writeFile方法

Windows API一日一练(54)WriteFile和ReadFile函数

WriteFile 返回错误代码 995

同步I/O 和 异步I/O

node 之 fs流读写