读取unicode文件

时间:2012-10-28 16:54:41

标签: c++ c

为什么下一个代码会出错?看代码和图片。如何解决它 enter image description here

wchar_t *GetLine(wchar_t *fileName=L"indexing.xml", wchar_t endSymbol = '\n')
{
    FILE *file = NULL;
    int sz;
    _wfopen_s(&file, fileName, L"r");
    std::wifstream fs (file);
    int size;
    wchar_t wchr[1];
    size = 0;
    do
    {
        sz = fread(&wchr,sizeof(wchar_t),1,file);
        if(!sz)
        {
            break;
        }
        tempGetLine[size] = wchr[0];
        size++;
    }while(wchr[0] != endSymbol);
    tempGetLine[size] = '\0';
    position += (size);
    fs.close();
    return tempGetLine;
}

但是这项工作正确

wchar_t *GetLine(wchar_t *fileName=L"indexing.xml", wchar_t endSymbol = '\n')
{
    hReadFile = CreateFileW(L"indexing.xml",GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ |FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    SetFilePointer(hReadFile,sizeof(wchar_t) * position, NULL, FILE_BEGIN);
    int size;
    wchar_t wchr[1];
    DWORD dw;
    size = 0;
    do
    {
        ReadFile(hReadFile, wchr, sizeof(wchar_t), &dw, NULL);
        if(!dw)
        {
            break;
        }
        tempGetLine[size] = wchr[0];
        size++;
    }while(wchr[0] != endSymbol);
    tempGetLine[size] = '\0';
    position += (size);
    return tempGetLine;
}

enter image description here 完整代码

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <Windows.h>
int position = 0;
wchar_t tempGetLine[500];
wchar_t *GetLine(wchar_t *fileName=L"indexing.xml", wchar_t endSymbol = '\n')
{
    FILE *file = NULL;
    int sz;
    _wfopen_s(&file, L"C:\\indexing.xml", L"r");
    std::wifstream fs (file);
    int x = GetLastError();
    fseek(file,sizeof(wchar_t) * position,SEEK_SET);
    int size;
    wchar_t wchr[1];
    size = 0;
    do
    {
        sz = fread(&wchr,sizeof(wchar_t),1,file);
        if(!sz)
        {
            break;
        }
        if(wchr[0] >= L'А')continue;            //Only for console application
        tempGetLine[size] = wchr[0];
        size++;
    }while(wchr[0] != endSymbol);
    tempGetLine[size] = '\0';
    position += (size);
    fs.close();
    return tempGetLine;
}

2 个答案:

答案 0 :(得分:1)

由于某种原因,您的文件无法打开,file为NULL。 始终检查文件是否已打开。

还想知道你对fs的看法。

答案 1 :(得分:0)

您正在当前目录中查找文件indexing.xml

VC项目的默认设置是设置为exe文件2012\Projects\FindPattern\Debug目录的当前目录。该文件不存在,它是一个文件夹。