c - Windows 函数 ReadFile 一直返回 FALSE,不知道为什么

标签 c windows

这是一个非常简单的 C 代码来读取文件文本,我以前也这样做过,但不知道为什么现在 ReadFile 函数一直返回 FALSE,这意味着它失败了。

显然文本文件 input.txt 存在并且 CreateFile 函数成功(或者至少不返回 INVALID_HANDLE_VALUE

#include <stdio.h>
#include <windows.h>

int main(int argc, char *argv[])
{
    char ReadBuffer[256] = {0};
    HANDLE hFile1;
    int n = 0;
    DWORD bytesread = 5;

    printf("Press enter to read the file 'input.txt' ... ");
    getch();

    if ( (hFile1 = CreateFile(TEXT("input.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL) == INVALID_HANDLE_VALUE))
    {
        printf("INVALID_HANDLE_VALUE");
        return -1;
    }

    if ( ReadFile(hFile1, ReadBuffer, bytesread, &bytesread, NULL) == FALSE )
    {
        printf("ReadFile ERROR");
        CloseHandle(hFile1);
        return -2;
    }

    printf("\n\nRead bytes: %d \n\n", bytesread);


    CloseHandle(hFile1);
    return 0;
}

最佳答案

错误是括号的简单错位。

if ( (hFile1 = CreateFile(TEXT("input.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)

关于c - Windows 函数 ReadFile 一直返回 FALSE,不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3925779/

相关文章:

C中的字符函数不输出任何内容

c - 在 C 中制作 shell,但无法让 chdir 工作?

c++ - 链接错误,即使一切都在那里

linux - Vagrant + Composer + Windows/nfs/git 错误

windows - Microsoft SysVAD虚拟音频设备驱动程序(SYSVAD)无法工作

windows - 是否有在 Flutter Desktop for Windows 上使用 sqlite 的解决方案?

c++ - g++ 在不使用 -Wconversion 的情况下将 double/float 转换为无符号整数时发出警告

c++ - linux中的pthread_mutex_t是否可重入(如果一个线程试图获取它已经持有的锁,则请求成功)

windows - 在允许的进程之间传递 Windows 安全 token

node.js - 即使在 PATH 中也无法识别 Node