试图在Ubuntu中打开相对路径不起作用

JAN*_*JAN 1 c io ubuntu file

我正在尝试在Ubuntu中打开一个相对路径,但在打开第一个文件夹后 - 调用14- 代码无法打开里面的文件夹 - 调用15:

int pathsCtr; // number of folders in RelativeArray

char ** RelativeArray; // the folders in the relative path, currently: 

RelativeArray[0] = "14";

RelativeArray[1] = "15";
// some code before 

if (pathsCtr > 0 && flag == TRUE) // then we have a relative path
{
    int j = 0;
    while (j < pathsCtr)  // run until the last path and open every one
    {
        printf("\n%s\n" , RelativeArray[j]);
        dirp = opendir(RelativeArray[j]);  // open all directories until the last one
        if (dirp == NULL)
                return -1;
        j++; // proceed to the next directory
    }

    flag = FALSE; // turn off the flag , we'll never go near this again
}
Run Code Online (Sandbox Code Playgroud)

j == 0这一行:dirp = opendir(RelativeArray[j]);工作而dirp不是NULL.

但是,当j == 1该行dirp = opendir(RelativeArray[j]);失败,dirpNULL.

我究竟做错了什么?

编辑:

假设我RelativeArray在上面的代码之前做了malloc .

Chr*_*ton 6

opendir()打开一个用于读取其内容的目录,但它不会更改进程的工作目录.

要访问子目录,您必须通过相对于当前工作目录的完整路径(或其绝对路径)来指定它.

您可以通过将字符串与适当的分隔符连接来实现.

由于你似乎没有对opendir()返回的目录流指针做任何事情,除了检查它是非空的,因此很可能这不是你想要使用的函数.您可能想要查看chdir()而不是(man 2 chdir),但要考虑任何不良后果.