473,758 Members | 2,401 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Checking if a file exists

Is this a good way to check wheter a file already exists?

#include <stdio.h>
#include <stdlib.h>
int ask(const char *prompt);
typedef char filename[FILENAME_MAX];

int main(int argc, char *argv[])
{
FILE *in, *out;
filename in_name, out_name;
int overwrite = 0;
/* get filenames */
out = fopen(out_name, "r")
if (out != NULL) {
fclose(out);
printf("File %s already exists. ", out_name);
if (ask("Do you want to overwrite it?") == 1)
overwrite++;
else
exit(EXIT_FAILU RE);
}
/* etc... */
}

--
#include <stdio.h>
#include <stdlib.h>
int main(void) /* Don't try this at home */ {
const size_t dim = 256; int i;
for (i=0; malloc(dim); i++) /*nothing*/ ;
printf("You're done! %zu\n", i*dim);
puts("\n\n--Army1987"); return 0;
}
Apr 7 '07 #1
26 4956
Army1987 said:
Is this a good way to check wheter a file already exists?

#include <stdio.h>
#include <stdlib.h>
int ask(const char *prompt);
typedef char filename[FILENAME_MAX];

int main(int argc, char *argv[])
{
FILE *in, *out;
filename in_name, out_name;
int overwrite = 0;
/* get filenames */
out = fopen(out_name, "r")
if (out != NULL) {
fclose(out);
printf("File %s already exists. ", out_name);
if (ask("Do you want to overwrite it?") == 1)
overwrite++;
else
exit(EXIT_FAILU RE);
}
/* etc... */
}
It's about as good as you're going to get under ISO C, but it's not
reliable. The open might fail for other reasons than the non-existence
of the file (e.g. disk error, no read permission, etc). And there is no
guarantee that the file will continue to exist after the fclose, or
that it will continue not to exist (if indeed it did not exist) after
the fopen failure.

Abstract this functionality into your "non-portable stuff" module, and
consult your implementation' s documentation for details of how to solve
this problem (if indeed there is a solution) on the platform that it
targets.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 7 '07 #2
Army1987 <pl********@for .itwrote:
Is this a good way to check wheter a file already exists?
out = fopen(out_name, "r")
if (out != NULL) {
fclose(out);
printf("File %s already exists. ", out_name);
if (ask("Do you want to overwrite it?") == 1)
overwrite++;
No, that's not a good idea. There could be lots of other reasons
why the fopen() failed, starting from missing permission to open
it for reading up to e.g. having run out of file descriptors. So
you shouldn't blindly assume that the file does not already exist
just because fopen() in read mode failed (and, by the way, it is
also possible on a multitasking system that the file gets created
by another process between the time you did the test and the time
you open the it). If you want to avoid overwriting data in the
file if it already exists fopen it in append mode and check if
with ftell() if you're at the very start of the file (but that
still will not allow to distinguish the cases of the file not
existing at all and the file existing but being empty).

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Apr 7 '07 #3
At about the time of 4/7/2007 6:51 AM, Army1987 stated the following:
Is this a good way to check wheter a file already exists?

#include <stdio.h>
#include <stdlib.h>
int ask(const char *prompt);
typedef char filename[FILENAME_MAX];

int main(int argc, char *argv[])
{
FILE *in, *out;
filename in_name, out_name;
int overwrite = 0;
/* get filenames */
out = fopen(out_name, "r")
if (out != NULL) {
fclose(out);
printf("File %s already exists. ", out_name);
if (ask("Do you want to overwrite it?") == 1)
overwrite++;
else
exit(EXIT_FAILU RE);
}
/* etc... */
}
I think that Microsoft implements a file exists call. On Unix systems,
you can stat(2) the file and check if errno = ENOENT. Granted, this is
not portable, but it works.
--
Daniel Rudy

Email address has been base64 encoded to reduce spam
Decode email address using b64decode or uudecode -m

Why geeks like computers: look chat date touch grep make unzip
strip view finger mount fcsk more fcsk yes spray umount sleep
Apr 7 '07 #4
"Army1987" <pl********@for .itwrites:
Is this a good way to check wheter a file already exists?
[snip]

Testing whether a file exists often (not always, but often) means
you're asking the wrong question.

Why do you want to know whether the file exists? If it's so you can
decide whether to attempt some operation (e.g., reading from the file
if it does exist, or creating it if it doesn't), it's often better to
just go ahead and attempt the operation, and handle the error if it
fails. (This can be difficult in standard C if you're trying to
create a file; if I recall correctly, it's implementation-defined
whether attempting to create an existing file will clobber the file or
fail, but there are often system-specific ways to control this
behavior.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 7 '07 #5
Keith Thompson wrote:
"Army1987" <pl********@for .itwrites:
>Is this a good way to check wheter a file already exists?
[snip]

Testing whether a file exists often (not always, but often) means
you're asking the wrong question.

Why do you want to know whether the file exists? If it's so you can
decide whether to attempt some operation (e.g., reading from the file
if it does exist, or creating it if it doesn't), it's often better to
just go ahead and attempt the operation, and handle the error if it
fails. (This can be difficult in standard C if you're trying to
create a file; if I recall correctly, it's implementation-defined
whether attempting to create an existing file will clobber the file or
fail, but there are often system-specific ways to control this
behavior.)
I would prefer to see "File IRREPLACABLE.DA T exists.
Overwrite?" than to regret it at leisure ...

This is what you allude to in "system-specific ways," but
unfortunately Standard C's I/O is too diluted to do the job
unaided.

--
Eric Sosman
es*****@acm-dot-org.invalid
Apr 7 '07 #6
"Richard Heathfield" <rj*@see.sig.in validha scritto nel messaggio
news:tM******** *************** *******@bt.com. ..
Army1987 said:
>Is this a good way to check wheter a file already exists?

#include <stdio.h>
#include <stdlib.h>
int ask(const char *prompt);
typedef char filename[FILENAME_MAX];

int main(int argc, char *argv[])
{
FILE *in, *out;
filename in_name, out_name;
int overwrite = 0;
/* get filenames */
out = fopen(out_name, "r")
if (out != NULL) {
fclose(out);
printf("File %s already exists. ", out_name);
if (ask("Do you want to overwrite it?") == 1)
overwrite++;
else
exit(EXIT_FAILU RE);
}
/* etc... */
}

And there is no
guarantee that the file will continue to exist after the fclose.
That's the problem. If the file couldn't be opened for some other reason
other than not existing, I would expect the fopen(out_name, "w") later in
the program to fail (unless the user has permission -w- on the file, in
which case I think he (or its owner) *deserves* to lose it, or some other
problem which I can't imagine).

Now if it is possible that out = fopen(out_name, "r"); fclose(out); deletes
the file, I'd better find another way...
Apr 8 '07 #7
"Keith Thompson" <ks***@mib.orgh a scritto nel messaggio
news:ln******** ****@nuthaus.mi b.org...
"Army1987" <pl********@for .itwrites:
>Is this a good way to check wheter a file already exists?
[snip]

Testing whether a file exists often (not always, but often) means
you're asking the wrong question.

Why do you want to know whether the file exists? If it's so you can
decide whether to attempt some operation (e.g., reading from the file
if it does exist, or creating it if it doesn't), it's often better to
just go ahead and attempt the operation, and handle the error if it
fails.
7.19.5.3.3 says that fopen(name, "w") "truncate[s] to zero length or
create[s] text file for writing".
Simply opening the file for writing loses its contents if it already exists.
Apr 8 '07 #8
Army1987 said:

<snip>
Now if it is possible that out = fopen(out_name, "r"); fclose(out);
deletes the file, I'd better find another way...
Well, I wouldn't expect that to happen! But I would not be surprised by
the following sequence of events:

1) you open the file read-only
2) you close the file
3) another process deletes the file
4) you act on your belief that the file exists

Multi-user / multi-process systems can be tricky, can't they?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 8 '07 #9
Army1987 <pl********@for .itwrote:
"Keith Thompson" <ks***@mib.orgh a scritto nel messaggio
news:ln******** ****@nuthaus.mi b.org...
"Army1987" <pl********@for .itwrites:
Is this a good way to check wheter a file already exists?
[snip]

Testing whether a file exists often (not always, but often) means
you're asking the wrong question.

Why do you want to know whether the file exists? If it's so you can
decide whether to attempt some operation (e.g., reading from the file
if it does exist, or creating it if it doesn't), it's often better to
just go ahead and attempt the operation, and handle the error if it
fails.
7.19.5.3.3 says that fopen(name, "w") "truncate[s] to zero length or
create[s] text file for writing".
Simply opening the file for writing loses its contents if it already exists.
In order to avoid just that there's the "a" or "a+" mode you can
pass to fopen() instead of "w" to open it in append mode. Then an
already existing file won't get truncated and you're positioned
at the end of the file while, if the file doesn't exist, it be-
haves as if you had used "w".
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Apr 8 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1756
by: Phil Lamey | last post by:
Hi Folks, I have run into a bit of an issue with checking for files. Some files reside on Server X and some on Server Y. The page with all the links is on Server X. If the file exists we display a link, if it does not then we display "sorry not yet available". For the files on server X it is no problem I use an FSO and don't have a problem. For files on server Y I am having a big problem.
15
114212
by: Geiregat Jonas | last post by:
is using if(open("file",O_EXCL) != -1){ printf("File does exists")}else{printf("file does not exists"); } a good way of checking if a file exists or not, if not how should I do it ?
11
16843
by: Daz | last post by:
Would anyone know of a way to check whether or not a particular path is a directory? If I have to go down the route of using _findfirst and _findnext (windows specific), then so be it. However, I don't think it should be that difficult to check. My original idea was to check to see if the path can be opened with fstream, but this can give false results if the path is a filename, and the file cannot be opened. I am using boost, and can't...
13
24195
by: darkslide | last post by:
Hi, I'm checking if a file exists with the following code; If System.IO.File.Exists("C:\test.txt") = True Then MsgBox("File Exists") Else MsgBox("File Does Not Exist") End If For some reason it always returns false even though the file does exist. Any suggestions? Could this be a security issue?
7
19112
by: sprash | last post by:
Newbie question: I'm trying to determine if a file physically exists regardless of the permissions on it Using File.Exists() returns false if it physically exists but the process does not have the necessary permissions. One hack could be to check for length and that would throw a FileNotFoundException ...but there is got to be a better way!
1
2933
by: mengesb | last post by:
I'm looking to utilize something to the effect of this code: ps -ef | grep sc_serv | grep -v grep | awk '{print $2}' > sc_serv.pid cat sc_serv.pid 3447 3449 The first id it spits out is the screen process that I run the sc_serv command under, and that's fine, because killing that process is really what I want. Killing the second will just produce nothing. What I'd really like is for when this system boots up, it will check for the...
1
3238
by: timexsinclair2068 | last post by:
This is a very simple question. Is there a simple,short way of checking if the application's App.Config file exists? Thanks!
4
2686
by: winningElevent | last post by:
Hi everyone, I have a question would like to ask. So far I know how to retrieve files from device, but sometimes device takes so long to produce file so I want my desktop to keep checking every 3seconds to see if file exist. Here is the conditions. 1- if file exists after checking for exisitng is True, then desktop application will continue to do other stuff. 2- if file doesn't exist after three times of checking, then desktop sends...
4
14987
by: ndedhia1 | last post by:
Hi. I am writing a java program in which I want to ftp a file to another unix box. First I have to check if the directory exists in which I am ftping into and if it does not exist, I have to create it: this is the code that I am using that is not working properly: System.out.println("YOU ARE IN UPLOAD"); System.out.println("THIS IS THE HOST: " + host); SshClient ssh = new SshClient();
0
9492
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9299
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10076
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9740
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8744
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7287
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5332
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2702
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.