您的位置:首页 > 编程语言 > C语言/C++

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

2017-08-03 23:20 706 查看
写文件操作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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  写文件txt WriteFile