自定义函数
<pre name="code" class="cpp">void writeFile(LPCWSTR filePath,LPCVOID content, int size)
{
//创建文件
HANDLE hFile = CreateFile(filePath, //创建文件的名称。
GENERIC_WRITE | GENERIC_READ, // 写和读文件。
0, // 不共享读写。
NULL, // 缺省安全属性。
OPEN_EXISTING, // CREATE_ALWAYS 覆盖文件(不存在则创建) OPEN_EXISTING 打开文件(不存在则报错)
FILE_ATTRIBUTE_NORMAL, // 一般的文件。
NULL); // 模板文件为空。
if (hFile == INVALID_HANDLE_VALUE)
{
OutputDebugString(TEXT("CreateFile fail!\r\n"));
}
//设置偏移量 到文件尾部 配合OPEN_EXISTING使用 可实现追加写入文件
//SetFilePointer(hFile, NULL, NULL, FILE_END);
//写文件
//const int BUFSIZE = 8192;//如果缓冲区不够可增加
//char chBuffer[BUFSIZE];
//memcpy(chBuffer, content, size);//也可使用strcpy
DWORD dwWritenSize = 0;
BOOL bRet = WriteFile(hFile, content, size, &dwWritenSize, NULL);
if (bRet)
{
OutputDebugString(TEXT("WriteFile 写文件成功\r\n"));
}
//刷新文件缓冲区
FlushFileBuffers(hFile);
}
函数调用
int _tmain(int argc, _TCHAR* argv[])
{
writeFile(L"c:/test2.txt", "1234\r\n56789", 11);
return 0;
}