i want to know how to check if the file already exists before creating the file?

puts("please enter a file name to create:\n");
scanf("%s", &file_name);
create_pointer = fopen( file_name, "ab");
if( create_pointer == NULL)	
//create file//
else
{
//file already exist// how would you check if the file already exists ?? 
}

Recommended Answers

All 8 Replies

Try to open it for reading. If it opens, it exists.

do you mean something like this ?

puts("please enter a file name to create:\n");
scanf("%s", &file_name);

if( create_pointer = fopen(file_name. "r"); 
printf("file already exist"); 
else
{
if(create_pointer != fopen(file_name"r"); 
create_pointer = fopen( file_name, "ab");
}

> Try to open it for reading. If it opens, it exists.

This approach suffers an inherent race condition. Moreover, in most cases (including this) such test is redundant. Both windows and posix systems provide an atomic solution to the OP problem.
For windows it is CreateFile with the disposition CREATE_NEW. For posix, it is open with flags O_CREAT | O_EXCL .

Your suggestion is no different than Narue's. CreateFile() with CREATE_NEW will fail if the file already exists. Same, but opposite, behavior that Narue suggested.

puts("please enter a file name to create:\n");
scanf("%s", &file_name);    // Never use scanf() to read a string.  It's dangerous. Use fgets()

if( create_pointer = fopen(file_name. "r"); 
printf("file already exist"); 
else
{
if(create_pointer != fopen(file_name"r");   // Didn't the previous fopen already check for this?
create_pointer = fopen( file_name, "ab");
}

You'd want to:

open file for read
If opened
    close it
    set flag to 'exist'
  else
    set flag to 'not exist'
endif
--continue--

But, based on your examples, if you are opening the file for append ("ab") why does it matter? The file will be created if it doesn't exist.

> Your suggestion is no different than Narue's.

No. Consider a scenario:

1. Open file for read - open succeeds; presume that the file didn't exist
2. Open file for write to do an actual job
So far so good, until another process creates the file right between step 1 and step 2. This is what is bad when test and use are separate.

CreateFile does it atomically, thus avoiding the race.

thanks for the help guys i have sorted out by checking if is able to be read if not and is not = to NULL then print file exists or else ask for another file name

Why would a new programmer that barely knows the language be concerned with race conditions? Let them learn to program before you get into high level concepts.

And CreateFile is not a standard C function. Therefore it's not portable and should not be taught at the beginning level programming.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.