|
-
Jan 11th, 2002, 07:40 PM
#1
Thread Starter
Fanatic Member
Test if file exists?
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
Alcohol & calculus don't mix.
Never drink & derive.
-
Jan 11th, 2002, 07:43 PM
#2
use fopen(), using an open only flag. If your pointer comes back as NULL, the file doesnt exist.
Z.
-
Jan 11th, 2002, 08:39 PM
#3
Thread Starter
Fanatic Member
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);
}
Alcohol & calculus don't mix.
Never drink & derive.
-
Jan 11th, 2002, 10:41 PM
#4
The file would exist if the pointer is NOT NULL. Try this:
Code:
FILE* f = NULL, fopen(fname, "r");
if(f)
{
// file exists
}
Z.
-
Jan 12th, 2002, 06:26 AM
#5
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.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Jan 12th, 2002, 12:35 PM
#6
Thread Starter
Fanatic Member
Ok, I see now
Thanks for the help
Alcohol & calculus don't mix.
Never drink & derive.
-
Jan 13th, 2002, 08:27 PM
#7
PowerPoster
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;
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|