开发者

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

开发者 https://www.devze.com 2023-01-13 18:37 出处:网络
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 s开发者_Python百科traightforward, but extra lo

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 s开发者_Python百科traightforward, 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.


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


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;
    }
   
    if (dwBytesRead > 0 && dwBytesRead <= BUFFERSIZE-1)
    {
        ReadBuffer[dwBytesRead]=L'\0'; // NULL character

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

       
    CloseHandle(hFile);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号