【问题标题】:Can opendir(pathname) change the value of the input pathname?opendir(pathname) 可以改变输入路径名的值吗?
【发布时间】:2012-04-01 14:58:09
【问题描述】:

我在使用opendir() 时收到了一些奇怪的结果:

int dtw(char *path) {

    struct stat statbuf;

    ...

    else if (S_ISDIR(statbuf.st_mode)) {
            printf("Path is: %s\n", path);

            struct dirent *dirent;
            DIR *dirp;

            if ((dirp = opendir(path)) == NULL) {
                puts("Can't open directory.");
                return -1;
            }

            printf("Path is: %s\n", path);
    }

    ...
}

结果:

Path is: /home/.../etc
Path is:

这里唯一会影响path 的是opendir()。它有我没有看到的副作用吗?还是有其他事情在起作用?

【问题讨论】:

  • 你是如何声明和初始化path的?
  • path从命令行解析,最终从main()传入相关函数。已编辑问题以反映这一点。

标签: c directory-structure opendir


【解决方案1】:

不允许更改; opendir()的定义是:

DIR *opendir(const char *dirname);

constopendir() 并没有改变它。

我想知道您的path 是否是指向已释放内存的指针?在这种情况下,内存可能已分配给opendir(),而您正在看到更改,因为您使用了指向您不应该查看的内存的悬空指针?

【讨论】:

  • 啊,就是这样。这是我从 Java 切换到 C 以来第一次遇到这种问题。非常感谢。
猜你喜欢
  • 2011-09-04
  • 2022-11-18
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多