一直打不起精神,直到前几个月开始时间emacs 和 vim,两款在神左右相伴的编辑器,很强大,很舒服,相见恨晚。
程序是小程序,是《Understanding Unix/Linux Programming - A Guide to Theory and Practice》这本书中4.15的习题。题目是这样的:
Unix 命令 mkdir 接受选项 -p。编写一种支持这个选项的 mkdir 命令版本
题目不是很难,查看 man mkdir 可知如下:
-p, --parents
no error if existing, make parent directories as needed
好,根据功能描述开始实现吧~代码如下:
/*
* =====================================================================================
*
* Filename: mkdir.c
*
* Description: mkdir
*
* Version: 1.0
* Created: 2012年09月02日 16时11分17秒
* Revision: none
* Compiler: gcc
*
* Author: Guotf(), tfguo369@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include "debug.h"
#include "error.h"
#define DIR_MODE 0777
#define ARRAY_LENGTH 1000
int checkPath(char *, char *);
int is_dir_exist(char *);
void deal_dir(char *);
/*
checkPath 这个函数写的不好,循坏的控制很差,希望大牛指正批评。
*/
int checkPath(char *path, char *spath){
memset(path, 0, ARRAY_LENGTH);
int i = 0;
char c;
char *originp = spath;
#ifdef DEBUG
printf("av[1] is %s\n", spath);
#endif
while(c)
{
#ifdef DEBUG
printf("c is %c , ", c);
printf("i is %d\n", i);
#endif
#ifdef DEBUG
printf("*spath is %c.(out)\n", *spath);
#endif
while((c = *spath++) != '/' && c != '\0'){
i++;
}
if(i == 0){
if(!is_dir_exist("/")){
deal_dir("/");
}
}
else{
memcpy(path, originp, i);
#ifdef DEBUG
printf("debug %s\n", path);
#endif
deal_dir(path);
}
i++;
}
}
int is_dir_exist(char *name){
DIR *d = opendir(name);
return d == NULL ? 0 : 1;
}
void deal_dir(char *name){
#ifdef DEBUG
printf("debug %s\n", name);
#endif
if(!is_dir_exist(name)){
if(mkdir(name, DIR_MODE) == -1){
perror("Error");
exit(1);
}
}
}
int main(int ac, char *av[]){
char path[ARRAY_LENGTH];
if(ac != 2){
error(stderr, "dir is invalid.");
}
else{
checkPath(path, av[1]);
}
}
目前测试没有bug,但以我的性格,虽然经过测试,但此程序难免会漏洞百出滴!
好了,给自己打打气,明天继续埋头~
本文介绍了一个简单的自制mkdir命令的实现过程,该命令支持-p选项,能够递归创建目录及其父目录。通过对《Understanding Unix/Linux Programming》一书中习题的解答,作者分享了具体的代码实现和调试经验。
1292

被折叠的 条评论
为什么被折叠?



