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
Printable View
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
Does this help?Code:#include <stdio.h>
int file_check(char *FileToCheck, char *ManipulateFile)
{
FILE * Existance;
if ( ( Existance = fopen(FileToCheck, "r+") ) == 0)
{
/* file was not found */
}
else
{
fclose(Existance); /* Make sure to close it */
system(ManipulateFile);
}
return 0;
}
int main()
{
file_check("c:\\path\\to\\file\\foo.txt", "c:\\windows\\notepad.exe c:\\path\\to\\file\\foo.txt");
return 0;
}
Except "r+" will create the file if it doesn't exist
Perhaps "r"
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:
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 <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");
}
}
Regards,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)
printf("File has read/write permission\n");
}
}
Monster