zoukankan      html  css  js  c++  java
  • 讨论linux下I/O联级创建目录

           前几天,因为在linux上编程,所以需要使用一些linux下的API。终于体会到了什么叫做“自己动手,丰衣足食”的感觉!C开发果然名不虚传啊,很多以前在net下司空见惯的算法竟然都要自己写,就算是一个小小的建立目录路径功能都是要自己写。咳!

          先来看一下linux下的IO编程中,建立目录功能。如果我们需要建立一个目录,如果路径名为"/app/locker_server/data/log/”(window下可以为”c:/app/locker_server/data/log/”),那么我们如果在net或者java的编程环境中,使用一个API方法就能搞定了,net frame或者jvm会更加目录“联级”的去创建;但是在c下,api函数mkdir只是建立当前目录下的子目录,对于“联级”目录,只能“望洋兴叹”了。所以,对于一般性的程序,一个“级联”创建文件夹是必不可少的,毕竟存储数据文件,log文件都是需要根据配置的文件夹路径创建的,那么这个算法怎么实现呢?其实很简单,还是要靠mkdir,还记得吗?mkdir的功能是创建当前目录的子目录,那么我们只要在创建子目录以后进入创建的子目录,然后再创建子目录就ok了。要注意的地方就是判断要创建的目录是否已经存在,然后怎么根linux下的’/’目录分隔符拆分目录。

    mkdir by cascading
    { int result,length,pointer_postion = 0; char *postion; char *path_temp = path; char cwd[MAX_PATH_SIZE]; char *subfolder; bool is_error = false; if(NULL == getcwd(cwd,sizeof(cwd))) { printf("Error!file:"__FILE__",line:%d.dir path name more than max_path_size %d.\n", __LINE__,MAX_PATH_SIZE); return false; } if(*path_temp == '/') { if(-1 == chdir("/")) { printf("Error!file:"__FILE__",line:%d.change dir to root dir is error.error info is %s.\n", __LINE__,strerror(errno)); return false; } pointer_postion ++; } if(*(path_temp + strlen(path_temp)-1) == '/') { path_temp[strlen(path_temp)-1] ='\0'; } while(pointer_postion -1 != strlen(path_temp)) { do { postion = strchr(path_temp + pointer_postion,'/'); if(0 == postion) { length = strlen(path_temp) - pointer_postion; } else { length = postion - path_temp - pointer_postion; } subfolder = (char *)calloc(length,sizeof(char)); memcpy(subfolder,path_temp+pointer_postion,length); if(is_dir(subfolder)) { if(-1 == chdir(subfolder)) { printf("Error!file:"__FILE__",line:%d.change dir to cwd is error.error info is %s.\n", __LINE__,strerror(errno)); return false; } pointer_postion = pointer_postion + length + 1; break; } if(-1 == mkdir(subfolder,mode)) { printf("Error!file:"__FILE__",line:%d.cascad creating folder is error.error info is %s.\n", __LINE__,strerror(errno)); is_error = true; break; } if(-1 == chdir(subfolder)) { printf("Error!file:"__FILE__",line:%d.change dir to cwd is error.error info is %s.\n", __LINE__,strerror(errno)); return false; } pointer_postion = pointer_postion + length + 1; break; } while(false); if(NULL != subfolder) { free(subfolder); subfolder = NULL; } if(is_error) { break; } } if(-1 == chdir(cwd)) { printf("Error!file:"__FILE__",line:%d.change dir to cwd is error.error info is %s.\n", __LINE__,strerror(errno)); return false; } return true; }

  • 相关阅读:
    Java正则表达式入门
    sql join
    java collection
    JAVA中this用法小结
    SQL Server 触发器
    SQL 存储过程
    123456 所有组合 递归
    sublime plugin & add number to mulitple line .
    重做树莓派系统盘
    制作树莓派系统盘
  • 原文地址:https://www.cnblogs.com/Seapeak/p/1709295.html
Copyright © 2011-2022 走看看