#include<Windows.h>
#include<iostream>
using namespace std;
int main() {
HANDLE f = CreateFile(TEXT("F:\\111.bin"), //创建句柄
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL ,
NULL
);
if (f == INVALID_HANDLE_VALUE) //创建文件失败
cout << "failed to create handle, error code is " << GetLastError() << endl;
if (GetLastError() == ERROR_ALREADY_EXISTS) //OPEN_ALWAYS和CREATE_ALWAYS创建成功时返回
cout << "file already exists" << endl;
cout<<endl;
/*
注意:如果文件本来存在,且打开文件时文件指针在文件首,写入字节数小于文件大小
则相当于在复写指定字节数空间中的内容
*/
#define Size 50 * 1024
char *buff = new char[Size]; //设置缓冲区
memset(buff, 65, Size); //缓冲区数据初始化
DWORD bytes_to_write = Size; //待写字节数
LPDWORD written_bytes = new DWORD(0); //已写字节数指针
bool write = WriteFile(f, buff, bytes_to_write, written_bytes, NULL); //同步读文件
if(write == 0)
cout << "Writing to a file is abnormal. error code is " << GetLastError() << endl;
else
cout << "Writing to a file is normal. written_bytes = " << *written_bytes <<endl;
cout<<endl;
/*
此时文件偏移量已到50KB处,因为文件此前为空,即现在已处于文件尾,所以读取结果为0;
重新将指针挪到文件首可以使用SetFilePointer()函数
*/
DWORD bytes_to_read = Size; //待读字节数
LPDWORD readed_bytes = new DWORD(0); //已读字节数指针
bool read = ReadFile(f, buff, bytes_to_read, readed_bytes, NULL); //同步写文件,TRUE表示读文件成功
if (read == 0)
cout << "Reading the file is abnormal. error code is " << GetLastError() << endl;
else
cout << "Reading the file is normal. readed_bytes = " << *readed_bytes << endl;
delete written_bytes;
delete readed_bytes;
delete buff;
CloseHandle(f);
return 0;
}
单线程同步读写(Vistual Studio版)
最新推荐文章于 2022-12-27 01:09:51 发布