c++ - 将字节附加到 Visual C++ 中的二进制文件

标签 c++ visual-c++ file-manipulation

我正在尝试将一些字节附加到 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

最佳答案

基于 WriteFileEx 文件句柄的 msdn 网站,使用的文件句柄可以是使用 FILE_FLAG_OVERLAPPED 标志打开的任何内容(在您的代码中不是这种情况)。 将此函数更改为 WriteFile 非常有效。 有关详细信息,请参见此处:WriteFileEx MSDN

关于c++ - 将字节附加到 Visual C++ 中的二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32733289/

相关文章:

c++ - 一种将 std::string 复制到 vector<char> 中的更优雅的方法

c++ - bitshifting unsigned char 和 unsigned long long 出错了

c++ - C++ 中的 4d 映射?

java - 处理/访问磁盘上的文件

c++ - 查找库中的所有动态初始化

c++ - Winsock 发送调用很慢

winapi - XP 通用控制 list : processorArchitecture ='x86' vs. 处理器架构 ='*'

php - 使用 php 替换文本文件中的特定行,同时保留文件的其余部分

linux - 在 Linux 中从包含文件夹名称的多个文件夹复制文件

c++ - 在文本文件中找到最后一行并选择前 10 个字符并打印到新文件?