转自:http://blog.csdn.net/mmjwung/article/details/8499802
都可以很方便的通过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;
- }
- }
本文介绍了如何在Windows环境下使用C++进行文件复制、删除及重命名的基本方法,并提供了详细的代码示例。
2115

被折叠的 条评论
为什么被折叠?



