判断目录是否存在

判断目录是否存在

       写日志时,经常可能需要用到log这样的目录,通过调用

    DIR *opendir(const char * p a t h n a m e) ;

       这个函数来判断指定目录是否存在,不存在则使用

    int mkdir(const char * p a t h n a m e, mode_t m o d e)

    来创建该目录。下面一个小程序便是对目录操作的一个例子:

 

#include <sys/types.h>

#include <sys/stat.h>

#include <dirent.h>

#include <stdio.h>

#include <stdlib.h>

 

int main(int argc, char *argv[])

{

    if(argc != 2)

    {

        fprintf(stderr, "usage: dir director/n");

        return -1;

    }

   

    DIR *dir = opendir(argv[1]);

    if(dir == NULL)

    {

        printf("%s is not director/n", argv[1]);

        //creae a director

        mkdir(argv[1], S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

        printf("make director %s/n", argv[1]);

        return -1;

    }

   

    printf("%s is exist./n", argv[1]);

    closedir(dir);

    return 0;

}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在shell中判断目录是否存在可以使用test命令或者[]符号来进行判断,具体如下: 使用test命令: ``` if test -d "/path/to/directory"; then echo "directory exists" else echo "directory does not exist" fi ``` 使用[]符号: ``` if [ -d "/path/to/directory" ]; then echo "directory exists" else echo "directory does not exist" fi ``` 其中,-d选项表示判断是否存在目录,如果存在则返回true,否则返回false。 ### 回答2: 在shell脚本中,我们可以使用`test`命令或者`[ ]`来判断一个目录是否存在。 使用`test`命令: ```shell if test -d 目录路径; then echo "目录存在" else echo "目录不存在" fi ``` 使用`[ ]`: ```shell if [ -d 目录路径 ]; then echo "目录存在" else echo "目录不存在" fi ``` 其中,`-d`表示是一个目录。如果目录存在,则返回真(0),否则返回假(非0)。 在脚本中,我们可以根据返回值来判断目录是否存在,然后进行相应的操作。以上示例中,如果目录存在,会输出"目录存在",否则输出"目录不存在"。 ### 回答3: 在Shell脚本中,可以使用`-d`选项来判断一个目录是否存在。 以下是一个示例代码: ```shell #!/bin/bash # 定义目录路径 dir="/path/to/directory" # 使用条件判断语句,判断目录是否存在 if [ -d "$dir" ]; then echo "目录存在" else echo "目录不存在" fi ``` 在上述代码中,我们通过`-d`选项来判断变量`$dir`所表示的目录是否存在。如果目录存在,则打印出"目录存在";如果目录不存在,则打印出"目录不存在"。 需要注意的是,`-d`选项只能判断目录是否存在。如果需要判断文件是否存在,可以使用`-f`选项。此外,`-e`选项可以同时判断文件或目录是否存在
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值