• 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;
       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;
    }
    cin.get();
    cin.get();
    }


    二、文件的删除

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

    cin.get();
    }


    三 文件的重命名

    #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<<" "<<"1. "<<newname<<" 已存在"<<endl
        <<" "<<"2. "<<newname<<" 正在使用,未关闭."<<endl
        <<" "<<"3. "<<"你没有权限重命名此文件."<<endl;
    }
    }
    else//文件不存在
    {
    cout<<source<<" 不存在,无法重命名."<<endl;
    }
    cin.get();
    }

  • 相关阅读:
    [LeetCode] 215. Kth Largest Element in an Array 数组中第k大的元素
    [LeetCode] 23. Merge k Sorted Lists 合并k个有序链表
    [LeetCode] 146. LRU Cache 近期最少使用缓存
    [LeetCode] 381. Insert Delete GetRandom O(1)
    [LeetCode] 380. Insert Delete GetRandom O(1) 插入删除获得随机数O(1)时间
    [LeetCode] 57. Insert Interval 插入区间
    [LeetCode] 56. Merge Intervals 合并区间
    [LeetCode] 155. Min Stack 最小栈
    移动web开发-------meta
    font-family
  • 原文地址:https://www.cnblogs.com/lidabo/p/3324713.html
Copyright © 2020-2023  润新知