【转载】windows下的文件复制、删除、重命名操作

本文介绍了如何在Windows环境下使用C++进行文件复制、删除及重命名操作。通过具体的代码示例展示了如何利用C++标准库和Windows API完成这些基本的文件管理任务。

windows下的文件复制、删除、重命名操作,都可以很方便的通过windows.h中的函数来实现

一、文件的复制

#include <iostream>  
#include <fstream>  
using namespace std;  
int CopyFile(char *SourceFile,char *NewFile)  
{  
  ifstream in;  
  ofstream out;  
  in.open(SourceFile,ios::binary);//打开源文件  
  if(in.fail())//打开源文件失败  
  {  
     cout<<"Error 1: Fail to open the source file."<<endl;  
     in.close();  
     out.close();  
     return 0;  
  }  
  out.open(NewFile,ios::binary);//创建目标文件   
  if(out.fail())//创建文件失败  
  {  
     cout<<"Error 2: Fail to create the new file."<<endl;  
     out.close();  
     in.close();  
     return 0;  
  }  
  else//复制文件  
  {  
     out<<in.rdbuf();  
     out.close();  
     in.close();  
     return 1;  
  }  
}  
void main()  
{  
  char source[256],NewFile[256];  
  cout<<"请输入要复制的文件路径:"<<endl;  
  cin>>source;  
  cout<<"请输入新文件的路径:"<<endl;  
  cin>>NewFile;  
  if(CopyFile(source,NewFile))  
  {  
     cout<<"文件已成功复制..."<<endl;  
  }  
  else  
  {  
     cout<<"文件复制失败..."<<endl;  
  }  
}

二、文件的删除

#include <iostream.h>  
#include <windows.h>  
#include <io.h>  
void main()  
{  
  char source[256];//文件路径  
  cout<<"请输入要删除的文件路径:"<<endl;  
  cin>>source;  
/* _access(char *,int) 判断文件是否存在 
存在 返回0;不存在 返回-1. 
_access(const char *path,int mode) 
mode的值: 
00 是否存在 
02 写权限 
04 读权限 
06 读写权限 
*/  
  if(!_access(source,0))//如果文件存在:文件为只读无法删除  
  {  
  //去掉文件只读属性  
  SetFileAttributes(source,0);  
  if(DeleteFile(source))//删除成功  
  {  
     cout<<source<<" 已成功删除."<<endl;  
  }  
  else//无法删除:文件只读或无权限执行删除  
  {  
     cout<<source<<" 无法删除:文件为只读属性或无删除权限."<<endl;  
  }  
  }  
  else//文件不存在  
  {  
    cout<<source<<" 不存在,无法删除."<<endl;  
  }  
}

三 文件的重命名

#include <iostream.h>  
#include <windows.h>  
#include <io.h>  
void main()  
{  
  char source[256];//文件路径  
  char newname[256];  
  cout<<"请输入要重命名的文件路径:"<<endl;  
  cin>>source;  
  cout<<"请输入文件的新名称:"<<endl;  
  cin>>newname;  
  if(!_access(source,0))//如果文件存在:  
  {  
    if(!rename(source,newname))//删除成功  
    {  
       cout<<source<<" 成功重命名为: "<<newname<<endl;  
    }  
    else//无法重命名:文件打开或无权限执行重命名  
    {  
       cout<<"文件无法重命名(可能原因如下):"<<endl;  
       cout<<"\t"<<"1. "<<newname<<" 已存在"<<endl  
         <<"\t"<<"2. "<<newname<<" 正在使用,未关闭."<<endl  
         <<"\t"<<"3. "<<"你没有权限重命名此文件."<<endl;  
    }  
  }  
  else//文件不存在  
  {  
    cout<<source<<" 不存在,无法重命名."<<endl;  
  }  
}


转载于:https://my.oschina.net/mrcamus/blog/150197

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值