PDA

Click to See Complete Forum and Search --> : Test if file exists?


Wynd
Jan 11th, 2002, 06:40 PM
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 :)

Zaei
Jan 11th, 2002, 06:43 PM
use fopen(), using an open only flag. If your pointer comes back as NULL, the file doesnt exist.

Z.

Wynd
Jan 11th, 2002, 07:39 PM
What is an open only flag? I am doing this right now and it tells me it exists no matter what.
FILE* pFile = fopen(fname, "r");
if (pFile == NULL)
{
printf("File %s already exists ", fname);
}

Zaei
Jan 11th, 2002, 09:41 PM
The file would exist if the pointer is NOT NULL. Try this:

FILE* f = NULL, fopen(fname, "r");
if(f)
{
// file exists
}


Z.

CornedBee
Jan 12th, 2002, 05:26 AM
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.

Wynd
Jan 12th, 2002, 11:35 AM
Ok, I see now :o

Thanks for the help :)

Chris
Jan 13th, 2002, 07:27 PM
How about this?


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;