c++中没找到直接判断文件夹是否存在的函数,只好自己写一个。。
bool dir_file_exists(string dir, bool mkdir_flag)
{
char des_dir[255];
str2char(dir, des_dir); // 将string 写入到字符数组中
int state = access(des_dir, R_OK|W_OK); // 头文件 #include <unistd.h>
if (state==0) {
cout<<"file exist"<<endl;
return true;
}
else if (mkdir_flag)
{
dir = "mkdir " + dir;
str2char(dir, des_dir);
cout<<des_dir<<endl;
system(des_dir); // 调用linux系统命令创建文件
return true;
}
else
{
return false;
}
}
int str2char(string s, char c[])
{
size_t l = s.length();
int i;
for(i = 0; i < l; i++)
c[i] = s[i];
c[i] = '\0';
return i;
}
关于access的解释:
NAME
access -- check access permissions of a file or pathname
SYNOPSIS
#include <unistd.h>
int
access(const char *path, int amode);
DESCRIPTION
The access() function checks the accessibility of the file named by path for the access permissions
indicated by amode. The value of amode is the bitwise inclusive OR of the access permissions to be
checked (R_OK for read permission, W_OK for write permission and X_OK for execute/search permission) or
the existence test, F_OK. All components of the pathname path are checked for access permissions
(including F_OK).
The real user ID is used in place of the effective user ID and the real group access list (including
the real group ID) are used in place of the effective ID for verifying permission.
Even if a process has appropriate privileges and indicates success for X_OK, the file may not actually
have execute permission bits set. Likewise for R_OK and W_OK.
RETURN VALUES
If path cannot be found or if any of the desired access modes would not be granted, then a -1 value is
returned and the global integer variable errno is set to indicate the error. Otherwise, a 0 value is
returned.
这次用到的点:
读写权限: R_OK|W_OK
权限存在返回值:0