打开功能:如何防止目录打开?

时间:2016-03-02 19:46:40

标签: c

我在我的文件中使用这样的open函数来从文件中获取一些坐标:

t_coo       *get_buffer(char **av, t_coo **head)
{
    int     ret;
    int     fd;
    char    *line;
    int     y;
    t_coo   *cur;

    cur = NULL;
    *head = NULL;
    y = 0;
    ret = 0;
    fd = open(av[1], O_RDONLY);
    while ((ret = get_next_line(fd, &line) > 0))
    {
        head = get_map(line, head, y);
        y++;
    }
    close(fd);
    cur = *head;
    return (cur);
}

它工作正常,但问题是当我尝试打开目录时,我的程序会出现段错误。我希望保护它免受目录打开,这样我就不再需要了。我试着看看互联网上的旗帜并尝试了很多但我找不到这个。谁能告诉我它是哪一个?谢谢。

2 个答案:

答案 0 :(得分:1)

您需要使用lstat函数告诉您给定的文件名是代表常规文件还是目录。

struct stat statbuf;
int rval;

rval = lstat(argv[1], &statbuf);
if (rval == -1) {
    perror("error getting file status");
    exit(1);
}

if (S_ISREG(statbuf.st_mode)) {
    printf("%s is a regular file\n", argv[1]);
} else if (S_ISDIR(statbuf.st_mode)) {
    printf("%s is a directory\n", argv[1]);
} else {
    printf("%s is something else\n", argv[1]);
}

答案 1 :(得分:1)

我建议open文件(可以是目录),所以获取文件描述符,然后在该文件描述符上使用fstat(2)(并检查fstat的结果使用statresult.st_mode & S_IFMT == S_IFDIR ...)

这可以避免使用lstat(或stat)然后open方法(Dbush's answer中建议)的(不可能的)竞争条件:某些其他进程可能(与非常糟糕的运气)在这两个系统调用之间删除或重命名文件。您可能还opendiropen(但也会遇到类似的竞争条件)。

PS。我在这里建议的竞争条件是如此不可能,我们通常可以忽略它们......但它们可能是一个安全漏洞(比攻击者可以使用的)

相关问题