C++ 将数据写入txt文件WriteFile的使用

来源:互联网 发布:阿里云cdn添加域名 编辑:程序博客网 时间:2024/06/11 06:23

写文件操作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;}


原创粉丝点击