-2

Im trying to count the types of files inputted into a program. So if you enter echo.c its a C source, echo.h is Header and so on. But if you input a directory, like echo/root it should count as an directory type but right now its counting as a exe type. Ive gotten everything else working, im just trying to figure out how to use stat() to check if the argv is a directory.

Heres what I have so far:

#include <sys/stat.h> 

int main(int argc, char* argv[]){
int cCount = 0;
int cHeadCount = 0;
int dirCount = 0; 


for(int i = 1; i < argc; i++){

    FILE *fi = fopen(argv[i], "r");

    if(!fi){
        fprintf(stderr,"File not found: %s", argv[i]);
    }
    else{

    struct stat directory;
    //if .c extension > cCount++
    //else if .h extension > cHeadCount++

    else if( stat( argv[i], &directory ) == 0 ){
        if( directory.st_mode & S_IFDIR ){
          dirCount++;
        }
     }

    }

   //print values, exit
 }
}
Alonzo Robbe
  • 465
  • 1
  • 8
  • 23
  • 1
    show what you have so far – TheQAGuy Oct 25 '17 at 23:51
  • What is unclear to you in `man 2 stat`? –  Oct 25 '17 at 23:58
  • Have you read `man 2 stat`? – dlmeetei Oct 25 '17 at 23:58
  • Review https://stackoverflow.com/help/mcve. – jwdonahue Oct 26 '17 at 03:27
  • @JackVanier I have added what i have – Alonzo Robbe Oct 26 '17 at 10:08
  • @RobBor Your use of stat() looks fine. You have a few mismatched `if/else` and missing braces in the code - but please, you should rather tell us what issue you are facing - however, if you have a program that compiles, post that code, the code you did post have a lot of other errors so it does not compile. If the issue is that your code does not compile, you should ask about that instead of asking about stat() though. – nos Oct 26 '17 at 10:19
  • @nos sorry about the mismatch braces. They are not the issue. That just happened bc i was quickly trying to type it up. I still have not been able to figure out why its not counting as a `directory`. – Alonzo Robbe Oct 27 '17 at 05:13

1 Answers1

0

Pay close attention to the documentation: stat(2)

I am also unsure why you are opening the file. You don’t appear to need to do that.

#include <stdio.h>

// Please include ALL the files indicated in the manual
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main( int argc, char** argv )
{
  int dirCount = 0;

  for (int i = 1; i < argc; i++)
  {
    struct stat st;
    if (stat( argv[i], &st ) != 0) 
      // If something went wrong, you probably don't care,
      // since you are just looking for directories.
      // (This assumption may not be true. 
      //  Please read through the errors that can be produced on the man page.)
      continue;

    if (S_ISDIR( st.st_mode )) 
      dirCount += 1;
  }

  printf( "Number of directories listed as argument = %d.\n", dirCount );

  return 0;
}
Dúthomhas
  • 8,200
  • 2
  • 17
  • 39