牛骨文教育服务平台(让学习变的简单)
博文笔记

win32 文件写入(包括追加到文件尾)WriteFile CreateFile

创建时间:2016-02-01 投稿人: 浏览次数:4172

自定义函数

<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!
"));
	}

	


	//设置偏移量 到文件尾部 配合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 写文件成功
"));
	}

	//刷新文件缓冲区
	FlushFileBuffers(hFile);
}



函数调用

int _tmain(int argc, _TCHAR* argv[])
{
	writeFile(L"c:/test2.txt", "1234
56789", 11);

	return 0;
}



声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。