-1

hi im trying to write a code that will search for file in /bin directory and identify if the file actually exist, my code always turns ERROR and i don't really get why can you give me a clue?

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h> 
#include <sys/types.h>
#include <sys/stat.h>
#define MAX 4096

int main() 
{  
    while(1)
    {
       char input[MAX];
       struct stat buf;
       const char *space=" ";
       fgets(input, MAX, stdin);
       char *token;
       token = strtok(input, space);

            if (!strncmp(token,"/bin/",5))
                {    
                    if (stat(token,&buf)==-1)
                    {
                       perror(token);
                       printf( "ERROR\n");
                    }
                    else
                    {  
                 printf("FILE EXISTS\n");     
                    }  
                 }
    }
 return 0;
}   

here's input and what it returns:

/bin/ls

: No such file or directory
ERROR

DISCLAIMER: i've just corrected question and added more so you guys can understand the problem better dont scream at me.

kaylum
  • 13,833
  • 2
  • 22
  • 31
mxsgd
  • 11
  • 3

1 Answers1

3

From the fgets manual:

If a newline is read, it is stored into the buffer.

That is, the code currently tries to check "/bin/ls\n" rather than "/bin/ls".

Fix by first stripping the trailing newline character. One way:

const char *delim = " \n";
fgets(input, MAX, stdin);
const char *token = strtok(input, delim);
kaylum
  • 13,833
  • 2
  • 22
  • 31