Read text file (Unicode) in 'C' using native Win32

亡梦爱人 提交于 2021-01-27 05:42:20

问题


I have a line-oriented text file (Unicode) that was created using CreateFile() and WriteFile().

Reading that file as a binary stream using ReadFile() is straightforward, but extra low-level processing is needed to break it into lines.

Is there a Win32 function that does this for me?

Again, please note that it's in 'C' (not C++) and I don't want to use POSIX/ANSI C functions such as readline().

If the answer to the aforementioned question is negative, what would be the "shortest code" to accomplish reading a line-oriented text file, using native Win32 C functions only? e.g. using ReadFile(), StrChr(), etc.

Thanks.


回答1:


AFAIK there is no win32 function for reading file line by line.




回答2:


Here is a function skeleton that reads an entire file and supports 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);
}


来源:https://stackoverflow.com/questions/3614483/read-text-file-unicode-in-c-using-native-win32

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!