# Checking for file existence

This is a discussion on Checking for file existence within the C Programming forums, part of the General Programming Boards category; Can anyone suggest how I can check for a files existence prior to using it... I have found a code ...

1. ## Checking for file existence

Can anyone suggest how I can check for a files existence prior to using it...

I have found a code called F_OK - but am not sure of the syntax to use it.

many thanks
Sue

2. Code:
#include <stdio.h>

int file_check(char *FileToCheck, char *ManipulateFile)
{
FILE * Existance;
if ( ( Existance = fopen(FileToCheck, "r+") ) == 0)
{
}
else
{
fclose(Existance); /* Make sure to close it */
system(ManipulateFile);
}
return 0;
}

int main()
{
return 0;
}
Does this help?

3. Except "r+" will create the file if it doesn't exist
Perhaps "r"

4. I think the F_OK you found is from the access (or _access) function. I don't know which OS/compiler you are using and if your compiler supports the function but here's an example:
Code:
#include  <io.h>
#include  <stdio.h>
#include  <stdlib.h>

int main()
{
// 0 = check for existence, 2 = check for write permission
// 4 = check for read permission, 6 = check for read/write permission
if(_access( "C:\\file.xt", 0 ) != -1)
{
printf("File exists\n");

if(_access( "C:\\file.txt", 2 ) != -1)
printf("File has write permission\n");
}
}
This (above) is a windows example. If you are using unix/linux and the access function is supported you probably need to include unistd.h and you can use R_OK, W_OK, X_OK and F_OK.
Code:
#include  <unistd.h>
#include  <stdio.h>
#include  <stdlib.h>

int main()
{
if(access("file.xt", F_OK) != -1)
{
printf("File exists\n");

if(access("file.txt", R_OK|W_OK) != -1)
}