Linux下用C语言删除文件/(非空)目录


=Start=

缘由:

学习需要

正文:

参考解答:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
// int rc = unlink(LOCKFILE);
// if (rc == -1) {
//  fprintf(stderr, "Failed to delete current pid file.\n");
//  return -1;
// }
int remove_directory(const char *path)
{
    DIR *d = opendir(path);
    size_t path_len = strlen(path);
    int r = -1;
    if (d)
    {
        struct dirent *p;
        r = 0;
        while (!r && (p = readdir(d)))
        {
            int r2 = -1;
            char *buf;
            size_t len;
            /* Skip the names "." and ".." as we don't want to recurse on them. */
            if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
            {
                continue;
            }
            len = path_len + strlen(p->d_name) + 2;
            buf = malloc(len);
            if (buf)
            {
                struct stat statbuf;
                snprintf(buf, len, "%s/%s", path, p->d_name);
                if (!stat(buf, &statbuf))
                {
                    if (S_ISDIR(statbuf.st_mode))
                    {
                        r2 = remove_directory(buf);
                    }
                    else
                    {
                        r2 = unlink(buf);
                    }
                }
                free(buf);
            }
            r = r2;
        }
        closedir(d);
    }
    if (!r)
    {
        r = rmdir(path);
    }
    return r;
}
int main(int argc, char const *argv[])
{
    if(argc < 2) {
        return 1;
    }
    int rc = remove_directory(argv[1]);
    if (rc == -1) {
        fprintf(stderr, "Failed to delete file/directory: '%s'.\n", argv[1]);
        return 1;
    }
  return 0;
}

 

参考链接:

Linux下用C语言删除文件/目录
https://linux.die.net/man/3/remove
http://man7.org/linux/man-pages/man2/unlink.2.html # delete a name and possibly the file it refers to
http://man7.org/linux/man-pages/man2/rmdir.2.html # deletes a directory, which must be empty
http://c.biancheng.net/cpp/html/322.html

在C语言中如何删除一个非空目录?
https://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c
https://stackoverflow.com/questions/5467725/how-to-delete-a-directory-and-its-contents-in-posix-c

=END=

, ,

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注