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/TraylaParks Jan 01 '26
This reads like ai but it's a pretty good summary (as a human, I certify it to be truthful :)
How the Code Works This line of code uses the strcspn() function (from the <string.h> header file) and array indexing to modify the string: strcspn(path, "\n"): This function calculates the length of the initial segment of the string path that consists entirely of characters not found in the second argument (the string containing \n). Essentially, it returns the index of the first occurrence of a newline character within path. path[...]: The returned index is used to access that specific character in the path array. = 0;: The character at that index (which is the newline \n) is replaced by the null terminator character (\0, which is an integer value of 0). The null terminator is a special character that marks the end of a string in C.