473,769 Members | 5,570 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
26 4957

"Barry Schwarz" <sc******@doezl .netha scritto nel messaggio
news:p3******** *************** *********@4ax.c om...
> name = overwrite ? tmpnam(NULL) : out;

I assume you meant out_name here.
Yes...
Isn't the test backwards?
No. The next statement opens out_name if overwrite is 0 (i.e. if a file
called that way didn't exist before), and creates a temporary file if a file
called out_name existed and the user answered yes when asked wheter to
overwrite it.
> if (overwrite) {
if (remove(in_name )) {

Didn't you mean out_name throughout this overwrite logic?
Yes... (Luckily enough I didn't test it...)
Apr 10 '07 #21
Eric Sosman <es*****@acm-dot-org.invalidwrot e:
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 ...
So would I, but there are circumstances where that is just not possible.

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.
YM too portable. I don't think there _is_ a way to test for file
existence that would work everywhere <stdio.hdoes.

Richard
Apr 12 '07 #22
Richard Bos wrote:
Eric Sosman <es*****@acm-dot-org.invalidwrot e:
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.

YM too portable. I don't think there _is_ a way to test for file
existence that would work everywhere <stdio.hdoes.
If you mean exactly what you said, that doesn't seem relevant to me.
There's no way to open a file that works everywhere except for
<stdio.h>'s fopen, that's why fopen's there. Similarly, if there's no
way to test for a file's existence that works everywhere, that could
be why <stdio.hshoul d have provided a function for that.

If you mean that some systems supporting <stdio.hfunctio nality don't
provide any way at all to test whether a file exists, could you give
an example? It doesn't have to be a real world example, just a reason
of why a hypothetical implementation might not be able to provide it.
I can understand that media may be damaged, or directories may have
restricted access, so I can understand why a general fexist() that
returns true or false might be unimplementable , but in the specific
context, might any system not be able to reliably answer "if I try to
create file XXX, would I get an error, would I get a new file, or
would I overwrite an existing file"?

Apr 12 '07 #23
Richard Bos wrote:
Eric Sosman <es*****@acm-dot-org.invalidwrot e:
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.

YM too portable. I don't think there _is_ a way to test for file
existence that would work everywhere <stdio.hdoes.
If you mean exactly what you said, that doesn't seem relevant to me.
There's no way to open a file that works everywhere except for
<stdio.h>'s fopen, that's why fopen's there. Similarly, if there's no
way to test for a file's existence that works everywhere, that could
be why <stdio.hshoul d have provided a function for that.

If you mean that some systems supporting <stdio.hfunctio nality don't
provide any way at all to test whether a file exists, could you give
an example? It doesn't have to be a real world example, just a reason
of why a hypothetical implementation might not be able to provide it.
I can understand that media may be damaged, or directories may have
restricted access, so I can understand why a general fexist() that
returns true or false might be unimplementable , but in the specific
context, might any system not be able to reliably answer "if I try to
create file XXX, would I get an error, would I get a new file, or
would I overwrite an existing file"?

Apr 12 '07 #24
Harald van D?k wrote:
[...]
If you mean that some systems supporting <stdio.hfunctio nality don't
provide any way at all to test whether a file exists, could you give
an example? It doesn't have to be a real world example, just a reason
of why a hypothetical implementation might not be able to provide it.
[...]

I seem to recall that someone posted several months back about a
"cryptograp hic filesystem", for which there was no way to test a
file's existence.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Apr 13 '07 #25
In article <46************ ***@spamcop.net >,
Kenneth Brody <ke******@spamc op.netwrote:
>I seem to recall that someone posted several months back about a
"cryptograph ic filesystem", for which there was no way to test a
file's existence.
Michael Wojcik initiated that subthread, discussing
'steganographic "deniable"' (SD) filesystems.

http://groups.google.ca/group/comp.l...cc67e712fe1a00
http://groups.google.ca/group/comp.l...634766e280d1bd
http://groups.google.ca/group/comp.l...f13f7c80b13640

--
Programming is what happens while you're busy making other plans.
Apr 13 '07 #26
Walter Roberson wrote:
In article <46************ ***@spamcop.net >,
Kenneth Brody <ke******@spamc op.netwrote:
I seem to recall that someone posted several months back about a
"cryptograp hic filesystem", for which there was no way to test a
file's existence.

Michael Wojcik initiated that subthread, discussing
'steganographic "deniable"' (SD) filesystems.

http://groups.google.ca/group/comp.l...cc67e712fe1a00
http://groups.google.ca/group/comp.l...634766e280d1bd
http://groups.google.ca/group/comp.l...f13f7c80b13640
Thank you and Kenneth for the information. As I understand it from
these messages, on such a filesystem, reading foo.txt would always
succeed, regardless of whether it had ever been written to, and
writing to it would destroy any information stored in a file using any
other filename. Doesn't that mean a file's existence can reliably be
determined? It simply always exists.

Apr 13 '07 #27

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
16846
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
19117
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
14994
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
9589
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
10049
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9998
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8876
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...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3967
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3567
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.