0

我正在尝试将一些字节附加到 Visual C++ 中的二进制文件

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <iostream>
#include <string>

//  Forward declarations:
void append(LPCTSTR);

int main()
{
    LPCTSTR fn = L"C:/kaiyin/kybig.out"; 
    append(fn);

    printf("hello world\n");
    std::string s = "";
    std::getline(std::cin, s);
    return 0;
}

void append(LPCTSTR filename) {
    LARGE_INTEGER size;
    size.QuadPart = 0;
    HANDLE fh = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    GetFileSizeEx(fh, &size);
    LPCVOID buf = "abc";
    SetFilePointerEx(fh, size, NULL, FILE_BEGIN);
    WriteFileEx(fh, buf, 3, NULL, NULL);
    CloseHandle(fh);
}

我收到一个错误:

First-chance exception at 0x76AB8833 (KernelBase.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0x00000008.

If there is a handler for this exception, the program may be safely continued.

什么地方出了错?


更新

如果我在没有调试的情况下运行它,我会得到如下的崩溃报告:

Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: ConsoleApplication1.exe
  Application Version:  0.0.0.0
  Application Timestamp:    560255b2
  Fault Module Name:    KERNELBASE.dll
  Fault Module Version: 6.3.9600.17415
  Fault Module Timestamp:   54504ade
  Exception Code:   c0000005
  Exception Offset: 000b8833
  OS Version:   6.3.9600.2.0.0.256.48
  Locale ID:    1033
  Additional Information 1: 5861
  Additional Information 2: 5861822e1919d7c014bbb064c64908b2
  Additional Information 3: a10f
  Additional Information 4: a10ff7d2bb2516fdc753f9c34fc3b069

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=280262

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt
4

2 回答 2

1

基于 msdn 网站,使用的WriteFileEx文件句柄可以是任何用FILE_FLAG_OVERLAPPED标志打开的东西(在您的代码中不是这种情况)。将此功能更改为WriteFile像魅力一样工作。有关更多信息,请参见此处:WriteFileEx MSDN

于 2015-09-23T07:55:55.580 回答
0

我猜它崩溃了,因为内存没有分配给 buf,buf 被使用而不分配内存。

于 2015-09-23T08:56:45.190 回答