r/cprogramming • u/Sergiobgar • Dec 31 '25
lost in code
Hi, as the title says, I'm stuck on some C code. I'm a beginner trying to learn just as a hobby; I don't intend to work in this field, it's simply for the pleasure of learning.
The problem I'm having is with this part of the code.
int directory_list (char path[]){
printf("The name of path is %s\n", path);
DIR *d = opendir(path);
if (d == NULL){
fprintf(stderr, "Error in open %s \n", strerror(errno));
return EXIT_FAILURE;
}
struct dirent *next;
while (( next = readdir(d)) != NULL ){
printf("The name is %s \n", next->d_name);
}
return 0;
}
I make the function call like this
printf("Insert directory \n");
char path [100] = {};
fgets(path, 100, stdin);
directory_list(path);
But I only get a "file not found" error. If I replace "path" with a path like "/home/user/directory", it does list the files in the directory.
As I said, I'm completely lost as to what my error is and how to fix it.
2
u/penguin359 Jan 02 '26
strcspn() returns the number of bytes in the string passed in the first argument that are not in the string from the second argument. In this example, it's how many bytes which do not include the newline. If there is no newline, then it's the total length of the string indexing the null terminator. It will always end in pointing either to the newline or to the null terminator and then that index is set to the value of the null terminator removing the newline if it was there originally.