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

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

2013-09-28 
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,但是到目录下去看文件的时候除了第一行左顶格之外其他行都空一格,这是为什么?然后我要把这个文件逐行读取到变量中应该怎么做?
[解决办法]
应将sizeof改为strlen
[解决办法]
sizeof("shanghai\r\n")-1 , 你多写了一个NULL进去
[解决办法]
你写文件的时候加了'\n'读的时候肯定也就有了啊!

以什么方式写文件的,就以什么方式读文件就好了!
你自己写进去的,同样以同样的方式读出来就好,write改read而已

热点排行