In my 1st year of programming, I've been asked to write a program to mimic a shell in c, with some basic commands.
At some point, I've tried to implement the "cd" command to switch directories, and I had a question about the size I had to give to the "getcwd" function.
In the man page, it's written that "getcwd" has to be given a path and a size to know where to store the path and on how many bytes.
I've tried to get the size depending on the length of the path and the bytes of a character and it worked quite well in the beginning, but at some point, I had some issues with an existing bigger path than my current path I was trying to go to.
For example, I was in /home/$username/..... and I tried to go to "/another_directory" inside of "/home/$username/", but without typing the path from the beginning, causing it not to know the full length of the directory but only my input, and not working.
A friend of mine helped me out telling me I could use "size_t" (as shown in the "man" page too)
I'd like to know how "size_t" works in this case because it's just allocating a big enough size making everything working fine without even malloc-ing it myself.
Here's the code :
{
size_t len;
char *path = NULL;
if (buffarg == 1) {
chdir("/home/cyprien"); //TODO modify cyprien to $NAME
my_putstr("/home/cyprien\n");
} else if (buffarg == 2) {
path = malloc(len);
if (chdir(buffarray[1]) == 0) {
getcwd(path, len);
my_putstr(path);
my_putstr("\n");
} else {
my_putstr("cd: no such file or directory: ");
my_putstr(buffarray[1]);
my_putstr("\n");
}
}
free(path);
}
I initialized size_t len;
and used it in getcwd(path, len)
and it always finds the right size. My older code was something like this :
{
int len = 0;
char *path = NULL;
if (buffarg == 1) {
chdir("/home/cyprien"); //TODO modify cyprien to $NAME
my_putstr("/home/cyprien\n");
} else if (buffarg == 2) {
path = malloc(len);
if (chdir(buffarray[1]) == 0) {
len += my_strlen(buffarray[1]);
getcwd(path, len);
my_putstr(path);
my_putstr("\n");
} else {
my_putstr("cd: no such file or directory: ");
my_putstr(buffarray[1]);
my_putstr("\n");
}
}
free(path);
}
I was initializing len as an int to 0, and trying to get the length of my input to add to size in order to store my buffer in the path
string.
Does anyone knows how size_t
works in this case ? I was really thinking about this since yesterday and I'd like to know more about that.
Sorry for such long text for a such small "problem"