Doing an ls in C

Solved
Jayjaynam Posted messages 2 Status Membre -  
Jayjaynam Posted messages 2 Status Membre -
Hello, I'm trying to replicate the functionality of ls in C, but I'm facing an issue. Here is my code:


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char **argv){

DIR* dir = NULL;
struct dirent* fileRead = NULL;
if((dir = opendir("/home/jayjay/projetres")) == NULL){
perror("The file could not be opened");
exit(1);
}

while((fileRead = readdir(dir)) != NULL){
if(strcmp(fileRead->d_name, ".") != 0 && strcmp(fileRead->d_name, "..") != 0 && fileRead->d_name[0] != "."){
printf("%s\n", fileRead->d_name);
}
}
closedir(dir);
}

The problem is in the line where I compare strings. The 3rd comparison is wrong, and I know it, but actually, I just want to compare my string to .* to remove all hidden files from the list that will be displayed like ls does. This is the point where I would like your help because I have no idea how to do that.

Thanks in advance for your answers.
Jayjaynam

2 réponses

[Dal] Posted messages 6205 Registration date   Status Contributeur Last intervention   1 108
 
Hi Jayjaynam,

https://man7.org/linux/man-pages/man3/readdir.3.html

Since the
dirent
structure contains
d_name[256]
, which is a C string, you just need to check that the first character of the d_name array is not a dot.

You can do this simply like this:

if ( (strcmp(fichierLu->d_name, "..") != 0) && (fichierLu->d_name[0] != '.') ) {


This also allows you to remove the test
(strcmp(fichierLu->d_name, ".") != 0)
since this case is anyway covered by the inequality test of the first character with the dot.

Dal
2
Jayjaynam Posted messages 2 Status Membre 1
 
Oh yes, indeed, I completely forgot the basics of the basics... Thanks to you, it's working well and I can continue practicing.
The subject can therefore be closed.

Thank you very much and have a great day.
Jayjaynam.
1