牛骨文教育服务平台(让学习变的简单)
博文笔记

Win32 复制文件

创建时间:2011-08-06 投稿人: 浏览次数:2587

第一种方法:

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>

#define BUF_SIZE 256


int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE hIn,hOut;
	DWORD nIn,nOut;
	CHAR Buffer[BUF_SIZE];

	if (argc!=3)
	{
		printf("Usage: cpW file1 file2
");
		return 1;
	}
	hIn=CreateFile(argv[1],GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
	if (hIn==INVALID_HANDLE_VALUE)
	{
		printf("Cannot open input file. Error:%x
",GetLastError());
		return 2;
	}
	hOut=CreateFile(argv[2],GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	if (hOut==INVALID_HANDLE_VALUE)
	{
		printf("Cannot open output file. Error:%x
",GetLastError());
		return 3;
	}
	while (ReadFile(hIn,Buffer,BUF_SIZE,&nIn,NULL)&&nIn>0)
	{
		WriteFile(hOut,Buffer,nIn,&nOut,NULL);
		if (nIn!=nOut)
		{
			printf("Fatal write error:%x
",GetLastError());
			return 4;
		}
	}
	CloseHandle(hIn);
	CloseHandle(hOut);
	return 0;
}

第二种方法: 用win32便利函数

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{

	if (argc!=3)
	{
		printf("Usage: cpW file1 file2
");
		return 1;
	}
	
	if (!CopyFile(argv[1],argv[2],false))
	{
		printf("copy file Error:%x
",GetLastError());
		return 2;
	}
	return 0;
}

程序运行,dos下,3个参数。

*.exe "源文件名称" "目标文件名称"

三个文件在同一目录下

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。