C++ 获取系统目录,自身目录,临时目录,文件读写

本文详细介绍了在Windows环境下,如何使用CreateFile、ReadFile、WriteFile等API进行文件的读写操作,包括获取系统目录、自身绝对路径及当前进程号等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include <stdlib.h> 
#include <stdio.h>
#include <iostream.h>
#include <windows.h>
#include <memory.h>
#include <string.h>
int WriteFile();

int main(int argc, char* argv[])
{
	//获取系统temp目录
	char	strTmpPath[MAX_PATH];
	GetTempPath(sizeof(strTmpPath), strTmpPath);
	printf("获取系统temp目录:%s\n",strTmpPath);
	
	// 获取自身的绝对路径
	char	strSelf[MAX_PATH];
	memset(strSelf, 0, sizeof(strSelf));
	GetModuleFileName(NULL, strSelf, sizeof(strSelf));
	printf("获取自身的绝对路径:%s\n", strSelf);
	
	//获取当前进程号
	printf("获取当前进程号:%d\n",GetCurrentThreadId());

	// 获取系统目录
	char strSysDir[100];
	GetSystemDirectory(strSysDir, sizeof(strSysDir));
	// char *bin = "%SystemRoot%\\System32\\svchost.exe -k netsvcs";
	printf("系统目录:%s\n",strSysDir);

	//采用:CreateFile、ReadFile、WriteFile读写文件
	WriteFile();
	//采用fread、fwrite
	system("pause");
	return 0;
}


int WriteFile()
{
  
DWORD dwFileSize = 0;
 
	BYTE* buffer = NULL;
 
	HANDLE hFile = INVALID_HANDLE_VALUE;
 
	hFile = CreateFile("E:\\123.txt",GENERIC_READ,
		               FILE_SHARE_READ,NULL,OPEN_EXISTING,
					   FILE_ATTRIBUTE_NORMAL,NULL);
 
	if (hFile == INVALID_HANDLE_VALUE)
	{
		CloseHandle(hFile);
 
		printf("Create File Failed !\n");
		return 0;
	} 
	else
	{
		dwFileSize = GetFileSize(hFile,NULL);
		//LARGE_INTEGER lFileSize;
		//GetFileSizeEx(hFile,&lFileSize);//若文件长度超过0xFFFFFFFF,使用GetFileSizeEx。
		printf("%d\n",dwFileSize);

		buffer = new BYTE[dwFileSize];
		if (buffer == NULL)
		{
	        printf("Create buffer error !\n");
	        return 0;
		}
		ZeroMemory(buffer,dwFileSize);

		DWORD dwReadSize = 0,dwReadTotal = 0;

		while (dwReadTotal < dwFileSize)
		{
			ReadFile(hFile,buffer + dwReadTotal,dwFileSize - dwReadSize,&dwReadSize,NULL);
			dwReadTotal += dwReadSize;
		}
		printf("总共读取的文件大小:%d\n:",dwReadTotal);
	}
	
	hFile = CreateFile("E:\\方式一.txt",GENERIC_WRITE,0,NULL,               
		CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		CloseHandle(hFile);
		printf("Create File Failed -2 !\n");
		delete []buffer;
		buffer = NULL;
		return 0;
	} 
	else
	{
		DWORD dwWriteTotal = 0,dwWriteSize = 0;
		while (dwWriteTotal < dwFileSize)
		{
			WriteFile(hFile,buffer + dwWriteTotal,dwFileSize,&dwWriteSize,NULL);
			dwWriteTotal += dwWriteSize;
		}
	}
	delete []buffer;
	buffer = NULL;
	CloseHandle(hFile);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值