简体   繁体   中英

Trouble using ReadFile() to read a string from a text file

How can I make the code below to read correct text. In my text file has Hello welcome to C++, however at the end of the text, it has a new line. With the code below, my readBuffer always contains extra characters.

DWORD byteWritten;
int fileSize = 0;

//Use CreateFile to check if the file exists or not.
HANDLE hFile = CreateFile(myFile, GENERIC_READ, FILE_SHARE_READ, NULL, 
                            OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

if(hFile != INVALID_HANDLE_VALUE)
{
    BOOL readSuccess;
    DWORD byteReading;
    char readBuffer[256];
    readSuccess = ReadFile(hFile, readBuffer, byteReading, &byteReading, NULL);

    if(readSuccess == TRUE)
    {
        TCHAR myBuffer[256];
        mbstowcs(myBuffer, readBuffer, 256);

        if(_tcscmp(myBuffer, TEXT("Hello welcome to C++")) == 0)
        {
            FindClose(hFile);
            CloseHandle(hFile);

            WriteResultFile(TRUE, TEXT("success!"));
        }
    }
}

Thanks,

There are a few problems:

  • You're passing uninitialized data (byteReading) as the "# of bytes to read" parameter to ReadFile().
  • Depending on how you created the file, the file's contents may not have a terminating 0 byte. The code assumes that the terminator is present.
  • FindClose(hFile) doesn't make sense. CloseHandle(hFile) is all you need.
  • You need to call CloseHandle if CreateFile() succeeds. Currently, you call it only if you find the string you're looking for.

This isn't a bug, but it's helpful to zero-initialize your buffers. That makes it easier to see in the debugger exactly how much data is being read.

  HANDLE hFile = CreateFile(myfile, GENERIC_READ, FILE_SHARE_READ, NULL, 
    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

  if(hFile != INVALID_HANDLE_VALUE)
  {
    BOOL readSuccess;
    DWORD byteReading = 255;
    char readBuffer[256];
    readSuccess = ReadFile(hFile, readBuffer, byteReading, &byteReading, NULL);
    readBuffer[byteReading] = 0;
    if(readSuccess == TRUE)
    {
      TCHAR myBuffer[256];
      mbstowcs(myBuffer, readBuffer, 256);

      if(_tcscmp(myBuffer, TEXT("Hello welcome to C++")) == 0)
      {
        rv = 0;
      }
    }
    CloseHandle(hFile);
  }

I see two things:

  • byteReading isn't initialized
  • you are reading bytes so you have to terminate the string by 0.
  • CloseHandle is sufficient

从文件中删除换行符,或使用_tcsstr检查字符串“ Hello Welcome to C ++”的存在。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM