首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

Windows API 文本文件的读写、换行解决方法

2013-09-25 
Windows API 文本文件的读写、换行#include windows.h#include iostream#include sstream#include s

Windows API 文本文件的读写、换行

#include <windows.h>
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
char rBuffer[64] = {0};
DWORD dwRead = 0;
DWORD dwWrite = 0;
HANDLE hFile = CreateFile("D:\\TEXT.txt", GENERIC_WRITE | GENERIC_READ, 0, 
NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("CreateFile failed!");
CloseHandle(hFile);

return -1;
}
WriteFile(hFile, "shanghai\r\n", sizeof("shanghai\r\n"), &dwWrite, NULL);
WriteFile(hFile, "beijing\r\n", sizeof("beijing\r\n"), &dwWrite, NULL);
WriteFile(hFile, "shenzhen\r\n", sizeof("shenzhen\r\n"), &dwWrite, NULL);
WriteFile(hFile, "nanning\r\n", sizeof("nanning\r\n"), &dwWrite, NULL);

DWORD fileSize = GetFileSize(hFile, NULL);
ReadFile(hFile, rBuffer, fileSize, &dwRead, NULL);
rBuffer[fileSize] = 0;

CloseHandle(hFile);

return 0;
}


读写文件的API不是很熟悉,自己编写上面这段代码,测试了一下。WriteFile的时候我都加了\r\n,但是到目录下去看文件的时候除了第一行左顶格之外其他行都空一格,这是为什么?然后我要把这个文件逐行读取到变量中应该怎么做?
[解决办法]
引用:
或者用fstream类也可以,之前写过MFC的CStdioFile写过,windows API 写的觉得没那么顺手!


多写了一个'\0' -->这个就是那个空格了。

改成
WriteFile(hFile, "shanghai\r\n", strlen("shanghai\r\n"), &dwWrite, NULL); 
应该就没有空格了。
PS:
用二进制方式,写文本文件,当然不那么顺手了。

热点排行