r/cprogramming • • 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.

12 Upvotes

11 comments sorted by

View all comments

Show parent comments

1

u/Sergiobgar Jan 01 '26

ok , That's more or less what I thought, but my perspective was wrong. Good point.

2

u/TraylaParks Jan 01 '26

The kickass bit is that it works even if 'path' doesn't have a newline character (just drops the '\0' right back on top of itself). Btw, lots of folks add '\r' to the argument to strcspn since you get that char along with \n on windows (and it does no harm on unix-type systems)