I am writing a simple c program which outputs all the contents within a given directory. Files are printed in green, executables are printed in red, and directories are printed in blue. Files and executables have their size printed as well. The code works properly when I open the current directory with either a relative path (".") or an absolute path. However, when I open other directories, all contents are identified as directories and printed in blue. I am unsure why the behavior changes when opening different directories.
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[]){
DIR* dir;
struct dirent* sd;
dir = opendir(".");
if(dir == NULL){
exit(1);
}
int fd;
int size;
while((sd=readdir(dir)) != NULL){
struct stat statstruct;
stat(sd->d_name, &statstruct);
if(S_ISREG(statstruct.st_mode)){
fd = open(sd->d_name, O_RDONLY);
size = lseek(fd, 0, SEEK_END);
if(statstruct.st_mode & S_IXUSR){
printf("\033[1;31m%s %d bytes\n\033[0m", sd->d_name, size);
}
else{
printf("\033[0;32m%s %d bytes\n\033[0m", sd->d_name, size);
}
}
else if(S_ISDIR(statstruct.st_mode)){
printf("\033[0;34m./%s\n\033[0m", sd->d_name);
}
}
closedir(dir);
}