1. 程式人生 > >win32 檔案寫入(包括追加到檔案尾)WriteFile CreateFile

win32 檔案寫入(包括追加到檔案尾)WriteFile CreateFile

自定義函式

<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;
}