c++判断文件夹是否存在,若不存在,调用linux命令创建它

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值