我试图将一些字节附加到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
答案 0 :(得分:1)
基于WriteFileEx
文件句柄的msdn网站,可以使用FILE_FLAG_OVERLAPPED
标志打开任何内容(在您的代码中不是这种情况)。
将此功能更改为WriteFile
就像魅力一样。
有关详细信息,请参阅此处:WriteFileEx MSDN
答案 1 :(得分:0)
我猜它崩溃了,因为内存没有分配给buf,buf在不分配内存的情况下使用。