c++ - 如何解决Readfile权限错误?

标签 c++ winapi assembly

有一个任务使用WiAPI函数和ASM嵌套到C++中处理文本文件。
当我试图调用readfile时,我得到了一个错误
0x7692DEB5(kernelbase.dll)处的未处理异常;b xxx.exe:
0xc000005:写入0x00000000时侵犯访问权限

#include "stdafx.h"
#include <Windows.h>
#include <fileapi.h>
#include <string> 
#include <iostream> 
#include <iomanip>

using namespace std;

int main() 
{
    char filename[256] = "text.txt"; //name of file with text
    OFSTRUCT buffer;
    HFILE pfile; 
    DWORD filesize; //size of file
    BYTE * pbuf;

    setlocale(0, "");
__asm
    {
        //File opening
        push OF_READ
        lea eax, buffer
        push eax
        lea eax, filename
        push eax
        call DWORD PTR OpenFile
        cmp eax, -1
        je fopen_error
        mov pfile, eax

        //Getting file size
        push NULL
        push pfile 
        call GetFileSize //executing function which calculates file size, result goes to ax
        mov filesize, eax  //Saving into variable

        //Reserving memory for file reading into buffer
        mov eax, filesize
        inc eax
        push eax
        call malloc
        mov pbuf, eax
        add esp, 4

        //Reading into buffer
        push NULL
        push NULL
        PUSH filesize
        push pbuf
        push pfile
        call ReadFile  // At this point I'm getting an error

它在我的朋友PC上运行良好(Win10和VS2017),我在Win7和2017上运行,我得到了这个例外。另外,我们尝试用相同的代码启动相同的exe文件,它在我朋友的电脑上运行良好,而在我的电脑上运行不好。
你能检查一下并告诉我哪里错了吗?

最佳答案

我想,一定是这样的:

char filename[256] = "text.txt"; //name with text
    OFSTRUCT buffer;
    HFILE pfile; 
    DWORD filesize; //file size
    BYTE * pbuf;

    DWORD dwBytesRead; /* error because of absent link */

    setlocale(0, "");
__asm
    {
        //opening file
        push OF_READ
        lea eax, buffer
        push eax
        lea eax, filename
        push eax
        call DWORD PTR OpenFile
        cmp eax, -1
        je fopen_error
        mov pfile, eax

        //Getting full size
        push NULL
        push pfile
        call DWORD PTR GetFileSize //calling function via checking size
        mov filesize, eax  //recording

        //storaging memory for reading
        mov eax, filesize
        inc eax
        push eax
        call DWORD PTR malloc
        mov pbuf, eax
        add esp, 4

       //Reading into buffer
        push NULL
        lea eax,[dwBytesRead]
        push eax
        PUSH filesize
        push pbuf
        push pfile
        call DWORD PTR ReadFile

关于c++ - 如何解决Readfile权限错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57871778/

相关文章:

c++ - 什么 API 会启动 FTP 传输并向 GUI 报告状态?

c++ - 上次运行进程 win32 的句柄

程序集弹出空堆栈

c++ - 我应该为我正在包装的结构使用转换运算符吗?

c++ - std::atomic<T>::wait 的 std::memory_order

c++ - MIPS 32 位上缺少 __sync_fetch_and_add_8 的替代方法

c++ - 如何有效地选择符合特定条件的 QTableView 行的子集?

c++ - Visual C++ 和 *nix 环境下的编译差异

assembly - 如何执行机器代码(学习汇编)

linux - 基本而全面的组装教程(Linux)?