【问题标题】:Confustion with realpath() buffer [duplicate]与 realpath() 缓冲区混淆 [重复]
【发布时间】:2015-02-22 14:14:17
【问题描述】:

这是我的函数,它在给定目录中查找常规文件,然后将它们的完整路径存储在列表中。

static my_func(const char *path, Files **list) //list - storage for file names
{
    DIR *d;
    struct dirent *dir;
    char buf[PATH_MAX + 1];

    d = opendir(path);
    if (d) {
        while ((dir = readdir(d)) != NULL) {
            if ((DT_REG == dir->d_type)) {

                realpath(dir->d_name, buf);
                List_push(list, buf);
                printf("%s\n", dir->d_name);
                // memset(buf, 0, PATH_MAX + 1);
            }
        }
    }
    closedir(d);
    return 0;
}
...
...

int main()
{
    // list creation
    // my_func call
    ...
    List_print(...)
}

预期输出:

FILE_1.txt
FILE_2.txt
FILE_3.txt
FILE_4.txt
FILE_5.txt
/home/user/c/FILE_1.txt
/home/user/c/FILE_2.txt
/home/user/c/FILE_3.txt
/home/user/c/FILE_4.txt
/home/user/c/FILE_5.txt

当前输出:

FILE_1.txt
FILE_2.txt
FILE_3.txt
FILE_4.txt
FILE_5.txt
/home/user/c/FILE_1.txt
/home/user/c/FILE_1.txt
/home/user/c/FILE_1.txt
/home/user/c/FILE_1.txt
/home/user/c/FILE_1.txt

它可以与我的链表实现有关吗?它工作得很好,因为我测试了它:

List_push(list, dir->d_name)

并得到了预期的结果。这是 List_push 的实现(文件只是简单的结构,带有 char * 和指向下一个元素的指针):

void List_push(Files **head, char *x)
{
    Files *new;

    new   = malloc(sizeof(Files));

    if (NULL != new) {
        new->next = *head;
        new->text = x;
        *head = new;
    } else {
        printf("malloc error");
    }

}

另外,如您所见,我试图用 memset 清除 buf,但没有成功 - 输出是:

FILE_1.txt
FILE_2.txt
FILE_3.txt
FILE_4.txt
FILE_5.txt






[console]$

是的,空格似乎被归档了一些东西(或者这些只是 List_print 中的 '\n' 符号),所以 list 不是空的。

这里有什么问题?

【问题讨论】:

  • 您必须制作字符串的副本,这样您就不会保留指向不断变化的 buf[] 变量的指针。考虑 strdup()。
  • 也谢谢你,汉斯 :)

标签: c linked-list memset realpath


【解决方案1】:

List_push(list, buf); 中,您将指向buf 的指针存储在列表中。您对每个文件都执行此操作,因此您最终会在列表中获得多个指向同一 buf 的指针。打印列表项时,它将显示buf 的(当前)内容。

为避免这种情况,您需要创建buf 的副本并将其存储,这样当您将buf 用于下一个文件时,存储的数据不会被覆盖。

【讨论】:

  • 好的,我会尝试这样做。谢谢:)
猜你喜欢
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
  • 1970-01-01
  • 2018-12-22
相关资源
最近更新 更多