Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue on file existence in C

Tags:

c

file

cygwin

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

like image 996
name_masked Avatar asked Feb 01 '26 04:02

name_masked


1 Answers

Just because the call to access() fails does not mean that the file does not exist. The call could fail for other reasons.

Use printf("error:%s\n", strerror(errno)); to print out the text of the error message.

Also you are still incorrectly appending to "path" received from getcwd as you were in your previous question. Even though it is not crashing, it is still not correct and could cause you problems... possibly even the problem you have now.

getcwd() allocates a buffer for your path, but that buffer is only sized to fit the path. you are appending to that buffer, going past the end. That's bad, you can't do that. It will cause problems, and occasionally crashes. you need to pause and understand how this getcwd function works and how to properly use it.

like image 74
SoapBox Avatar answered Feb 03 '26 23:02

SoapBox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!