I am making a program with file I/O. How can I tell if a file exists before I write over it? (preferably non-Windows, but post that if it's the only way)
Thanks :)
Printable View
I am making a program with file I/O. How can I tell if a file exists before I write over it? (preferably non-Windows, but post that if it's the only way)
Thanks :)
use fopen(), using an open only flag. If your pointer comes back as NULL, the file doesnt exist.
Z.
What is an open only flag? I am doing this right now and it tells me it exists no matter what.PHP Code:FILE* pFile = fopen(fname, "r");
if (pFile == NULL)
{
printf("File %s already exists ", fname);
}
The file would exist if the pointer is NOT NULL. Try this:
Z.Code:FILE* f = NULL, fopen(fname, "r");
if(f)
{
// file exists
}
Wynd:
if (pFile == NULL)
{
printf("File %s already exists ", fname);
}
If the file cannot be opened fopen returns NULL. So if pFile is NULL it means that the file couldn't be opened. This is surely not because it already exists, but rather because it doesn't exist. You are drawing the false conclusion from the fact that pFile is NULL. Your program worked all the time, it told you that the file exists only because you told it to say the wrong thing.
Ok, I see now :o
Thanks for the help :)
How about this?
PHP Code:hFile = CreateFile(lpszFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
NULL);
if (hFile == INVALID_HANDLE_VALUE || hFile == NULL)
{
// File does not exist
CloseHandle(hFile);
return 0;
}
else
// File exist
// Set return value
return 1;