⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test.cpp

📁 内存映射
💻 CPP
字号:
// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <time.h>
#include <fstream>
#include <string>
using namespace std;
#define DATA_COUNT 1000000
const int size = 10;

static char filepath[]="random.txt1\0";
static char sortpath[]="QuickSort_multi_thread.exe \0";

void GenerateData2(const char * pFilePath);//wzh
void GenerateData(const char * pFilePath);

int main(int argc, char* argv[])
{	
	char modulepath[MAX_PATH];
	GetModuleFileName(NULL,modulepath,MAX_PATH);//初始化地址//
	char *pdest = strrchr(modulepath,'\\');
	strncpy(pdest+1,filepath,sizeof(filepath));	
	//GenerateData(modulepath);
	GenerateData2(modulepath);
	//退出
	cout<<"Exit :x/X "<<endl;
	char x;	
	do
	{
		cin>>x;
	}while( x!='x'&& x!='X');
	return 0;
}

void GenerateData(const char * pFilePath)
{
	time_t startTm;
	time(&startTm);

	int j;
//	string s(ss);
	fstream fio(pFilePath,ios_base::out | ios_base::binary | ios_base::trunc);
//	FILE *fp = fopen("random.txt","w");
//	if(fp)
	if(fio.is_open())
	{
		srand( GetTickCount());
		for (int i = 0; i < DATA_COUNT; i ++)
		{

			j = rand();
			j *= rand();
			fio.write((char*)&j,sizeof(j));
			cout << j << " ";
		}
		fio.flush();
		cout << flush;
	}

	time_t endTm;
	time(&endTm);
	cout <<"用时间: "<< endTm - startTm <<endl;

}

void GenerateData2(const char * pFilePath)
{
	time_t startTm;
	time(&startTm);
	
	HANDLE hFile = CreateFile(pFilePath,GENERIC_WRITE|GENERIC_READ,0,NULL
		,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	if(hFile == INVALID_HANDLE_VALUE)
	{
		printf("File could not be opened.");
		return ;
	}
	
	DWORD dwFileSize = GetFileSize(hFile,NULL);
	
	HANDLE hFileMap = CreateFileMapping(hFile,NULL,PAGE_READWRITE,0,
		DATA_COUNT*sizeof(int),NULL);
	
	if(hFileMap == NULL){
		CloseHandle(hFile);
		return ;
	}
	
	int *pIntFile = (int *)MapViewOfFile(hFileMap,FILE_MAP_WRITE,0,0,0);
	
	if(pIntFile == NULL){
		CloseHandle(hFileMap);
		CloseHandle(hFile);
		return ;
	}
	srand( GetTickCount());
	for (int i(0); i < DATA_COUNT; i ++)
	{
		pIntFile[i] = rand();
		pIntFile[i] *= rand();
		cout<<pIntFile[i]<< " ";
	}
	UnmapViewOfFile(pIntFile);
	CloseHandle(hFileMap);
	
	SetFilePointer(hFile,DATA_COUNT*sizeof(int),NULL,FILE_BEGIN);
	SetEndOfFile(hFile);//实际上不需要写入了。
	CloseHandle(hFile);

	time_t endTm;
	time(&endTm);
	cout <<"用时间: "<< endTm - startTm <<"s"<<endl;

	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -