本文介绍了在ReadFile&中使用结构WriteFile函数用于读取和写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您能否让我知道如何通过Win32 Apis使用C中的数据结构从文件中写入和检索信息.
以下是示例代码,供您参考.
请让我知道我如何实现它.
Hi,
Can you please let me know how do i write and retrieve information from a file using data structures in C through Win32 Apis.
Below is the sample code for your reference.
Please let me know how do i achieve it.
#include <windows.h>
struct emp {
int emp_id;
char emp_name;
int salary;
};
int main() {
HANDLE hInfile = INVALID_HANDLE_VALUE;
HANDLE hOutfile = INVALID_HANDLE_VALUE;
const char* Infile = "c:\\test.dat";
struct emp AnEmployee;
/* Step1: Open test.dat for writing */
hOutfile = CreateFile(Outfile, /* file to open */
GENERIC_WRITE, /* open for writing */
0, /* share for reading */
NULL, /* default security */
CREATE_NEW, /* existing file only */
FILE_ATTRIBUTE_NORMAL, /* normal file */
NULL); /* no att. template
if(hOutfile == INVALID_HANDLE_VALUE) {
fprintf(stderr, "Wrong file to open\n");
return 0;
}
/* Step2: take input for user for employee details */
/* Step3: write the data existing in structure to handle hOutfile */
/* Step4: close hOutfile */
/* Step5: open the test.dat for reading */
hInfile = CreateFile(Infile, /* file to open */
GENERIC_READ, /* open for reading */
FILE_SHARE_READ, /* share for reading */
NULL, /* default security */
OPEN_EXISTING, /* existing file only */
FILE_ATTRIBUTE_NORMAL, /* normal file */
NULL); /* no att. template
if(hInfile == INVALID_HANDLE_VALUE) {
fprintf(stderr, "Wrong file to open\n");
return 0;
}
/* Step6: read each record and then display emp_id, emp_name, salary to the user */
/* Step7: print the output to the screen */
/* Step8: close hInfile */
return 0;
}
推荐答案
int nWritten;
BOOL bResult = WriteFile(hOutfile, &AnEmployee, sizeof AnEmployee, &nWritten, NULL);
要读回它,您可以使用 ReadFile()
进行类似的操作 [ ^ ].
To read it back you do a similar operation using ReadFile()
[^].
这篇关于在ReadFile&中使用结构WriteFile函数用于读取和写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!