读取文件内存的问题

C++语言 码拜 8年前 (2016-09-27) 1269次浏览
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	filebuf *pbuf;
	ifstream fileStr;
	long size;
	char *buffer;
	//采用二进制模式打开
	fileStr.open("D:\Notepad++\notepad2++.exe", ios::binary);
	//获取fileStr对应buffer对象的指针
	pbuf = fileStr.rdbuf();
	// 调用buffer对象方法获取文件大小  
	size = pbuf->pubseekoff(0, ios::end, ios::in);
	pbuf->pubseekpos(0, ios::in);
	// 分配内存空间  
	buffer = new char[size];
	// 获取文件内容  
	pbuf->sgetn(buffer, size);
	fileStr.close();
	ofstream out("D:\Notepad++\复制.exe",ios::binary);

	out.write(buffer, size);
	out.close();
	delete[]buffer;
	return 0;
}

这样写为什么生成的文件比源文件大,不符合PE规范 不能运行。
读取文件内存的问题读取文件内存的问题

解决方案

20

int main () {
	filebuf *pbuf;
	ifstream fileStr;
	std::streamsize size;
	char *buffer;
	//采用二进制模式打开
	fileStr.open ("C:\Windows\notepad.exe" ,ios::binary);
	//获取fileStr对应buffer对象的指针
	pbuf = fileStr.rdbuf ();
	// 调用buffer对象方法获取文件大小  
	size = pbuf->pubseekoff (0 ,ios::end);
	pbuf->pubseekpos (0 ,fileStr.beg);
	// 分配内存空间  
	buffer = new char[size];
	// 获取文件内容  
	pbuf->sgetn (buffer ,size);
	fileStr.close ();
	ofstream out ("D:\notepad.exe" ,ios::binary);
	out.write (buffer ,size);
	out.close ();
	delete[]buffer;
	return 0;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明读取文件内存的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)