-
判断文件是否存在
https://blog.csdn.net/venciliu/article/details/117201180#include <string> #include <io.h> //在c++中判断文件是否存在,如存在将其删除 int main() { std::string rmseFile = "rmse.txt"; if (_access(rmseFile.c_str(), 0) == 0) //文件存在 { if (remove(rmseFile.c_str()) == 0) { printf("删除成功"); } else { printf("删除失败"); } } else { printf("没有该文件"); } }
-
提取文件路径或者文件名
初始化是不正确的,因为需要转义反斜杠: string filename = "C:\\MyDirectory\\MyFile.bat"; 如果存在,则提取目录: string directory; const size_t last_slash_idx = filename.rfind('\\'); if (std::string::npos != last_slash_idx) { directory = filename.substr(0, last_slash_idx); }
-
创建、修改、删除文件
https://blog.csdn.net/YT21198/article/details/131115345
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
int _sysmkdir(const std::string& dir)
{
int ret = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (ret && errno == EEXIST)
{
printf("dir[%s] already exist.\n",dir.c_str());
}
else if (ret)
{
printf("create dir[%s] error: %d %s\n" ,dir.c_str(),ret ,strerror(errno));
return -1;
}
else
{
printf("create dir[%s] success.\n", dir.c_str());
}
return 0;
}
std::string __getParentDir(const std::string& dir)
{
std::string pdir = dir;
if(pdir.length() < 1 || (pdir[0] != '/')){
return "";
}
while(pdir.length() > 1 && (pdir[pdir.length() -1] == '/')) pdir = pdir.substr(0,pdir.length() -1);
pdir = pdir.substr(0,pdir.find_last_of('/'));
return pdir;
}
int _sysmkdirs(const std::string& dir)
{
int ret = 0;
if(dir.empty())
return -1;
std::string pdir;
if((ret = _sysmkdir(dir)) == -1){
pdir = __getParentDir(dir);
if((ret = _sysmkdirs(pdir)) == 0){
ret = _sysmkdirs(dir);
}
}
return ret;
}
0 条评论