r/cprogramming • u/yahia-gaming • Dec 19 '25
Why doesn't this code work
So I wrote this code in C (see below), When I run ./vd ~/Desktop it segfaults but when I run ./vd -a ~/Desktop it works and prints hidden files. I would appreciate any help. (Sorry if the code isn't formatted correctly)
Code:
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
void print_normally(DIR *d, struct dirent *dir) {
while ((dir = readdir(d)) != NULL) {
if (dir->d_name[0] != '.') {
printf("%s\n", dir->d_name);
}
}
}
void show_hidden_files(DIR *d, struct dirent *dir) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
}
int main(int argc, char *argv[]) {
char *directory = argv[2];
DIR *d = opendir(directory);
struct dirent *dir;
if (argc == 2) { // The command at argv[0] and the options at argv[1] and the directory at argv[2]
print_normally(d, dir); // Will call a function that doesn't print hidden files
}
if (argc == 3) { // the command, options, directory
char *options = argv[1];
if (strcmp(options, "-a") == 0) {
show_hidden_files(d, dir);
}
}
else {
printf("USAGE: %s <path-to-directory>", argv[0]);
return 1;
}
} ```
5
Upvotes
16
u/EddieBreeg33 Dec 19 '25
One thing I can immediately tell you: argc tells you the actual number of items in the argv array. So if argc == 2, argv[2] is not valid (and will most likely be NULL, at least that would be the case on linux).
6
u/richardxday Dec 19 '25
Others have highlighted the likely cause of the segfault but some other parts of the code don't make sense.
For example:
What is the intention of the
struct dirent *dirparameter? Its value get immediately overwritten by the return from thereaddir(d)call. So there's no point to passing thedirparameter at all.Instead, you can do this:
Generally the handling of arguments to the file isn't great, I usually do something like this:
Note how this approach prevents accesses outside
argv[], how the directory is opened and closed properly (with the close guaranteed if the open succeeds), how it handles the failure of the directory opening.Learning to handle failures is incredibly important for programming in C, never assume any call succeeds, especially those that are based on user input, file access or memory allocation.
3
u/Axman6 Dec 19 '25
To elaborate on the other answer, the program works when you pass
-abecauseargvactually has three arguments then - the program name atargv[0], the-aatargv[1]and the directory atargv[2]. You should check a) how many args you have using argc and b) that if you have three args,argv[1]is equal to”-a”.Or use a command line argument parsing library.
1
u/dcpugalaxy Dec 19 '25
Are you compiling and running with address sanitiser enabled? If not why not
1
u/spongedevguy Dec 22 '25
i recommend you use getopt it'll be easier