【问题标题】:Read text file (Unicode) in 'C' using native Win32使用本机 Win32 读取“C”中的文本文件(Unicode)
【发布时间】:2011-04-06 13:57:51
【问题描述】:

我有一个使用 CreateFile() 和 WriteFile() 创建的面向行的文本文件 (Unicode)。

使用 ReadFile() 将该文件作为二进制流读取很简单,但需要额外的低级处理才能将其分成几行。

是否有一个 Win32 函数可以为我做这件事?

再次请注意,它是在“C”(不是 C++)中,我不想使用诸如 readline() 之类的 POSIX/ANSI C 函数。

如果上述问题的答案是否定的,那么仅使用本机 Win32 C 函数来完成读取面向行的文本文件的“最短代码”是什么?例如使用 ReadFile()、StrChr() 等。

谢谢。

【问题讨论】:

  • 呃。 MSVC CRT 支持这一点。 fopen() 模式参数中的“ccs”,然后只是 fgetws()。
  • 汉斯,MSVC CRT 不是“本机 Win32”。
  • 我认为最短的方法是 ReadFile in long chunks 然后 strtok (将最后一部分保留到下一个读取操作中)或 ReadFile 在单个字符(2 个字节)上,直到到达行尾序列.不过,我不确定是否可以用 sn-ps 输入完整的答案。
  • @peachykeen,strtok() 是 MSVC CRT 的一部分,而不是“本机 Win32”。 :)
  • @Android Eve:我可以发誓它在 STL 中,甚至可能包含在 string.h 中。即使它是 CRT 并且不能使用,它也提供了所需的功能,因此可以重写(或找到非 CRT 替代方案)。 :) 我建议这样做的理由是,使用 ReadFile 读取较大的块可能会比小块更快,但是您可能无法读取整个文件并且需要能够中断缓冲区成行。

标签: c winapi readline createfile


【解决方案1】:

AFAIK 没有用于逐行读取文件的 win32 函数。

【讨论】:

【解决方案2】:

这是一个读取整个文件并支持UNICODE的函数骨架:

  void MyReadFile(wchar_t *filename)
  {

    HANDLE hFile; 
    DWORD  dwBytesRead = 0;
    wchar_t   ReadBuffer[BUFFERSIZE] = {0};
    OVERLAPPED ol = {0};


    hFile = CreateFile(filename,
                       GENERIC_READ,          // open for reading
                       FILE_SHARE_READ,       // share for reading
                       NULL,                  // default security
                       OPEN_EXISTING,         // existing file only
                       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file
                       NULL);                 // no attr. template

    if (hFile == INVALID_HANDLE_VALUE) 
    { 

        return; 
    }

    // Read one character less than the buffer size to save room for
    // the terminating NULL character. 

    if( ReadFileEx(hFile, ReadBuffer, BUFFERSIZE-1, &ol, FileIOCompletionRoutine) == FALSE)
    {

        CloseHandle(hFile);
        return;
    }
    SleepEx(5000, TRUE);
    dwBytesRead = g_BytesTransferred;

    if (dwBytesRead > 0 && dwBytesRead <= BUFFERSIZE-1)
    {
        ReadBuffer[dwBytesRead]=L'\0'; // NULL character

    }
    else if (dwBytesRead == 0)
    {
    }
    else
    {
    }


    CloseHandle(hFile);
}

【讨论】:

    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 2017-02-22
    • 2010-11-02
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    相关资源
    最近更新 更多