天天看點

C++ 檔案的複制、删除、重命名

一、檔案的複制

#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;

else//複制檔案

   out<<in.rdbuf();

   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;

cin.get();

C++ 檔案的複制、删除、重命名

二、檔案的删除

#include <iostream.h>

#include <windows.h>

#include <io.h>

char source[256];//檔案路徑

cout<<"請輸入要删除的檔案路徑:"<<endl;

/* _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;

三 檔案的重命名

char newname[256];

cout<<"請輸入要重命名的檔案路徑:"<<endl;

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;

cout<<source<<" 不存在,無法重命名."<<endl;