C++文件的創建、刪除、更改文件名操作(代碼)


#pragma once

#ifndef __FileOperation_H__
#define __FileOperation_H__

#include <string>
using namespace std;

class FileOperation
{
public:
    // 構造函數,dir為文件夾名稱:標注、書簽、試題、模型及動畫、media、界面等
    FileOperation( string dir );
    ~FileOperation(void);

    // 創建一個文件名為filename的文件
    bool CreateFile( string filename );

    // 刪除一個文件名為filename的文件
    bool DeleteFile( string filename );

    // 將一個文件名為filename的文件更名為newname
    bool AlterFileName( string filename, string newname );

protected:
    // 判斷目錄path是否存在
    bool IsExisteDirectory( string path );

    // 工作目錄
    string m_strPath;
};

#endif  // #ifndef __CFileOperation_H__
#include "FileOperation.h"

#include <fstream>
#include <io.h>

FileOperation::FileOperation( string dir )
{
    // 給m_strPath賦初值
    string path = _pgmptr;  // exe文件所在目錄,帶*.exe
    m_strPath = path.substr(0, path.find_last_of('\\') + 1 );
    m_strPath += dir;

    if (!IsExisteDirectory(m_strPath))
    {
        string str = "md \"" + m_strPath + "\"";
        system( str.c_str() );
    }
}


FileOperation::~FileOperation(void)
{
}


bool FileOperation::CreateFile( string filename )
{
    string path = m_strPath + '\\' + filename;
    fstream file;
    file.open( path, ios::out );
    if (!file)
    {
        return false;
    }
    file.close();

    return true;
}


bool FileOperation::DeleteFile( string filename )
{
    string path = m_strPath + '\\' + filename;
    // int remove(char *filename);
    // 刪除文件,成功返回0,否則返回-1
    if (-1 == remove(path.c_str()))
    {
        return false;
    }

    return true;
}


bool FileOperation::AlterFileName( string filename, string newname )
{
    string path = m_strPath + '\\' + filename;
    newname = m_strPath + '\\' + newname;
    // int rename(char *oldname, char *newname);
    // 更改文件名,成功返回0,否則返回-1
    if (-1 == rename(path.c_str(), newname.c_str()))
    {
        return false;
    }

    return true;
}

bool FileOperation::IsExisteDirectory( string path )
{
    if (-1 != _access(path.c_str(), 0))
    {
        return true;
    }
    return false;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM