-3

How would I know if a file exists in my current directory in C? I'm prompting the user and I'm trying to see if the file they type in already exists or not. Here's what I got:

int a=0;
char ing[100];
FILE * inp;


while (a=0);
{
    printf("Input file name: ");
    scanf("%s", ing);
    inp=fopen(ing , "r");
        if (inp==NULL)
            a=0;
        else
            a=1;
}

Whenever I type in a file that doesn't exist, I get that the cmd isn't responding. Whenever I type something that exists, it works fine, which is good. I just don't know what exactly I would need to put in if NULL doesn't work.

john
  • 139
  • 1
  • 8
  • 6
    `while (a=0);` should be `while (a==0)` – Iłya Bursov Mar 27 '15 at 22:43
  • possible duplicate of [What's the best way to check if a file exists in C? (cross platform)](http://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform) – notadam Mar 27 '15 at 22:44

2 Answers2

1

Replace:

while (a=0)

With:

while (a==0)

And for the check use this:

if( access( ing, F_OK ) != -1 ) {
    // exists
} else {
    // not exist
}
ismaestro
  • 7,561
  • 8
  • 37
  • 50
1

Using a access() function in c , we can get to know the existence of the file and permission allocated for us. for the file.

  if(access(filename,Checking option)==0)
             printf("success\n");
   else
     printf("...\n");

Checking option:

     R_OK - Check for the read operation
     W_OK - check for the write operation
     X_OK - check for the execute operation
     F_OK - check for the existence of the file
Bhuvanesh
  • 1,269
  • 1
  • 15
  • 25