Linux下实现删除目录注意事项

目的:用c实现rm删除文件/目录,无参数

函数选择:unlink,remove,本文选择remove(不同头文件可用man 查询)

代码实现:

#include<stdio.h>
#include <unistd.h>
#include<sys/stat.h>
#include <sys/types.h>
#include<string.h>
#include<dirent.h>
#include<stdlib.h>
int Delete(char *dest)  
{  
  
    DIR *dp;  
    struct dirent *entry;  
    struct stat statbuf;
    stat(dest,&statbuf);
    if(S_ISDIR(statbuf.st_mode)){  
    if ((dp = opendir(dest)) == NULL)  
    {  
        fprintf(stderr, "cannot open directory: %s\n", dest);  
        return -1;  
    }  
    chdir(dest);
    while ((entry = readdir(dp)) != NULL)  
    {  
      Delete(entry->d_name);
    }
   chdir("..");
    remove(dest);
    closedir(dp);
}
else
   remove(dest);
    return 0; 
 }
void main(){
char command[100],a[100];
scanf("%s",command);
if(!strcmp("rm",command)){
scanf("%s",a);
  Delete(a);}

}

结果:除了我执行文件所在目录,其他的目录,有删除权限的删的都差不多了。。

修改:

  while ((entry = readdir(dp)) != NULL)    

 { if(strcmp(".",entry->d_name)&&strcmp("..",entry->d_name)) ;每个目录下都有当前目录和上级目录“.”和“..”。要避开删除

       Delete(entry->d_name);

     }

结果:正常删除文件及目录。

*个人看法,另外对整个Linux不是完全了解,有异议或者错误之处望各位道友指出。

猜你喜欢

转载自blog.csdn.net/Liu0000Jian/article/details/80374810