1. 程式人生 > >C++ 將資料寫入txt檔案WriteFile的使用

C++ 將資料寫入txt檔案WriteFile的使用

寫檔案操作WriteFile在開發中經常使用到,對檔案的操作。關於這個API我就不介紹了,編譯器裡面按F1會有詳細的解釋,x_O雖然都是英文,呃呃呃。因為經常使用,久而久之不實用又會忘記,所以乾脆記錄下來。整理了一下程式碼如下:

#include "stdafx.h"
#include <string>
#include <Windows.h>
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
using namespace std;


bool myWriteFile(const TCHAR* pathFile, const TCHAR* data);

int _tmain(int argc, _TCHAR* argv[])
{
	TCHAR szModule[MAX_PATH] = {0};
	::GetModuleFileName(NULL, szModule, MAX_PATH);
	::PathRemoveFileSpec(szModule);
	_stprintf(szModule + _tcslen(szModule), _T("\\%s"), _T("weishao.txt"));

	TCHAR* pdata=_T("徹底怒了 x_O");

	myWriteFile(szModule, pdata);

	system("pause");

	return 0;
}

bool myWriteFile(const TCHAR* pathFile, const TCHAR* data)
{
	if (NULL == pathFile || NULL == data)
	{
		return false;
	}

	//先檢測性檔案存在與否
	if (!PathFileExists(pathFile))
	{
		//不存在則建立
		HANDLE hFile = CreateFile(pathFile, GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (INVALID_HANDLE_VALUE != hFile)
		{
			//關閉
			CloseHandle(hFile);
		}
	}

	//直接開啟
	HANDLE hFile = CreateFile(pathFile, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (INVALID_HANDLE_VALUE != hFile)
	{
		//將資料轉成Ansi(當然也可以直接unicode)
		//SetFilePointer(hFile, 0, 0, FILE_END);
		DWORD len = WideCharToMultiByte(CP_ACP, NULL, data, -1, NULL, NULL, NULL, FALSE);
		if (len <= 0) return false;
		char* pBuffer = new char[len];
		WideCharToMultiByte(CP_ACP, NULL, data, -1, pBuffer, len, NULL, FALSE);
		DWORD dwWrite = 0;
		int size =  strlen(pBuffer);
		WriteFile(hFile, pBuffer, strlen(pBuffer), &dwWrite, NULL);
		delete[] pBuffer;
		CloseHandle(hFile);
		return true;
	}

	return false;
}