簡體   English   中英

使用ReadFile()從文本文件讀取字符串時遇到麻煩

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

如何使下面的代碼讀取正確的文本。 在我的文本文件中,您好歡迎使用C ++,但是在文本結尾處,有新的一行。 使用下面的代碼,我的readBuffer總是包含額外的字符。

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!"));
        }
    }
}

謝謝,

有幾個問題:

  • 您要將未初始化的數據(byteReading)作為“要讀取的字節數”參數傳遞給ReadFile()。
  • 根據您創建文件的方式,文件的內容可能沒有終止0字節。 該代碼假定存在終止符。
  • FindClose(hFile)沒有意義。 您只需要CloseHandle(hFile)。
  • 如果CreateFile()成功,則需要調用CloseHandle。 當前,僅在找到要查找的字符串時才調用它。

這不是一個錯誤,但是對緩沖區進行零初始化很有幫助。 這樣可以更輕松地在調試器中查看正在讀取多少數據。

  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);
  }

我看到兩件事:

  • byteReading未初始化
  • 您正在讀取字節,因此必須以0結尾的字符串。
  • CloseHandle就足夠了

從文件中刪除換行符,或使用_tcsstr檢查字符串“ Hello Welcome to C ++”的存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM