Issue on file existence in C

Posted by darkie15 on Stack Overflow See other posts from Stack Overflow or by darkie15
Published on 2010-04-01T00:16:05Z Indexed on 2010/04/01 0:23 UTC
Read the original article Hit count: 695

Filed under:
|
|

Hi All,

Here is my code which checks if the file exists :

#include<stdio.h>
#include<zlib.h>
#include<unistd.h>
#include<string.h>


int main(int argc, char *argv[])
{
   char *path=NULL;
   FILE *file = NULL;
   char *fileSeparator = "/";
   size_t size=100;
   int index ;
   printf("\nArgument count is = %d", argc);

   if (argc <= 1)
   {
      printf("\nUsage: ./output filename1 filename2 ...");
      printf("\n The program will display human readable information about the PNG file provided");
   }
   else if (argc > 1)
   {
      for (index = 1; index < argc;index++)
      {
            path = getcwd(path, size);
            strcat(path, fileSeparator);
            printf("\n File name entered is = %s", argv[index]);
            strcat(path,argv[index]);
            printf("\n The complete path of the file name is = %s", path);
            if (access(path, F_OK) != -1)
            {
                  printf("File does exist");
            }
            else
            {
                  printf("File does not exist");
            }
            path=NULL;
      }
   }
   return 0;
}

On running the command ./output test.txt test2.txt The output is:

$ ./output test.txt test2.txt

Argument count is = 3
 File name entered is = test.txt
 The complete path of the file name is = /home/welcomeuser/test.txt
 File does not exist
 File name entered is = test2.txt
 The complete path of the file name is = /home/welcomeuser/test2.txt
 File does not exist

Now test.txt does exist on the system:

$ ls
assignment.c  output.exe  output.exe.stackdump  test.txt

and yet test.txt is shown as a file not existing.

Please help me understand the issue here. Also, please feel free to post any suggestions to improve the code/avoid a bug.

Regards, darkie

© Stack Overflow or respective owner

Related posts about file

Related posts about c