C++文件的创建、删除、更改文件名操作

C++文件的创建、删除、更改文件名操作(代码)<转载>

#pragma once

#ifndef FileOperation_H
#define FileOperation_H

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值