Your cwd[1] != 0
or cwd[1] != '\0'
is an okay way to do it. There’s no need to cast that to an int.
You could also use strcmp(cwd, "https://stackoverflow.com/")
, which makes it slightly more clear what you are doing. This will be zero at the root directory on a UNIX or Linux system.
For a more portable solution, you can compare the current directory name with the previous directory name, something like this:
char cwd[1024];
char parent[1024];
getcwd(cwd, sizeof(cwd));
and inside the loop:
chdir("..");
getcwd(parent, sizeof(parent));
if (strcmp(cwd, parent) == 0)
break;
strcpy(cwd, parent);
On a POSIX system, you can check if the current directory is the root without using getcwd()
, using code like this:
int cwd_is_root(void)
{
struct stat cwd, parent;
if (stat(".", &cwd) < 0)
return -1;
if (stat("..", &parent) < 0)
return -1;
return cwd.st_ino == parent.st_ino && cwd.st_dev == parent.st_dev;
}
It is simpler and better just to use getcwd
as you did, unless you are writing your own libc! getcwd
is a system call on Linux.
1
solved C – list all files in current directory then move in directory above, list files, and so on until root directory is reached [closed]