Im rewriting an "ls" command to show my directories in one color and files in another for
easy notice..currently my stat calls are failing, and I dont know why?

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

#define TRUE 1
#define FALSE 0

#define RED 31
#define BLUE 34


typedef struct files{

	char *name;
	int directory;


}FILES;



void printDir(char *path);

int main(int argc, char *args[]){

	//a.out argc = 1
	//args[argc = 1] = null

	int i;

	if(argc == 1){
		printDir(".");
	}

	for(i = 1;i<argc;i++){
		if(argc > 2)
			printf("%s: \n",args[i]);

		printDir(args[i]);

		if(i+1 != argc)
			printf("\n");

	}


	return 0;
}


void printDir(char *path){

	DIR *dir = opendir(path);

	struct dirent *dit;

	while((dit = readdir(dir))!= NULL){

		struct stat buf;

		if(dit->d_name[0] == '.')
			continue;

		printf("%d\n",stat(dit->d_name,&buf));

		if(S_ISDIR(buf.st_mode)){

			printf("\033[%dm%s\033\n[0m",RED,dit->d_name);
		}
		else{

			printf("\033[%dm%s\033\n[0m",BLUE,dit->d_name);
		}

	}//while

	closedir(dir);


}

So when I compile and do "./a.out" works...But when I do "./aout /" it shows the directories,
but stat call fails...Any Ideas?

Just for fun, do touch bin , and then run ./a.out / again. See that stat doesn't fail on bin anymore, yet it is presented as a plain file.
Can you explain this observation?

Member Avatar for Mouche

You can check stat's error using strerror(errno). It takes the error code set by stat and turns it into a string. Seeing the error message will help you troubleshoot your problem.

Example:

#include <errno.h>

...

int result;
result = stat(dit->d_name, &buf);
if (result == -1) {
  printf("Error with stat: %s\n", strerror(errno));
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.