本文共 1944 字,大约阅读时间需要 6 分钟。
转自: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;
-
-
-
-
-
-
-
-
-
- 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;
- }
- }