473,890 Members | 1,397 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

File exist

Hi all
Can anyone tell me how can I check that a file exist or no.I mean when
you use this commands
FILE *fp;
if(!fp)
//Could not open the file
doen't show why it can not open it,may be the file doesn't exist.Now
tell me what should I do!
Thanks

Apr 16 '06
52 7561
Mr John FO Evans <mi***@orpheusm ail.co.uk> wrote:
After reading all the comments on this thread I am astounded that the 'C'
standard does not require that fopen returns a meaningful error when it
fails.
fopen() is required to return a null pointer when it fails. This means
"the file could not be opened". To require more information (e.g., in
errno) would be tricky. For example, how do you describe what level of
"meaningful " you demand without making assumptions about how the
underlying IO system works - assumptions that _will_ be inaccurate
sooner or later?
Surly this is an ommision - or perhaps it is a acceptance that
computer systems suppliers do not like standards and hence do not provide
meaningful error returns from their lower level routines?


It is at least an acknowledgement of the fact that _if_ you run across
such a crummy OS, you can't blame the implementation for not having more
information to give the user in the first place.

Richard
Apr 19 '06 #31
Mr John FO Evans <mi***@orpheusm ail.co.uk> writes:
After reading all the comments on this thread I am astounded that the 'C'
standard does not require that fopen returns a meaningful error when it
fails. Surly this is an ommision - or perhaps it is a acceptance that
computer systems suppliers do not like standards and hence do not provide
meaningful error returns from their lower level routines?


Not at all. The C standard merely doesn't require *all*
implementations to report why fopen() failed. This allows C to be
implemented on a wide variety of systems, some of which may not always
provide meaningful information about errors.

The only errno values required by the C standard are EDOM, EILSEQ, and
ERANGE. (The corresponding error messages on one system are "Argument
out of domain", "Illegal byte sequence", and "Result too large",
respectively.)

But implementations are free to set errno on a failed fopen(), and to
provide more error codes than the minimal set required by the standard
-- and in fact most implementations do so.

Something like this:

errno = 0;
if ((f = fopen(filename, "r")) == NULL) {
perror(filename );
}

is very likely to give a meaningful error message on most systems --
and in fact is guaranteed to do so on many systems. If your
implementation doesn't give you a meaningful error message, you can
still complain to your vendor; you just can't argue that the
implementation doesn't conform to the C sftandard.

Having said that, I will acknowledge one weakness. There's no way for
a program to tell whether the implementation sets errno to a
meaningful value. You can generally tell by reading the
implementation' s documentation, but that's not very helpful if you're
trying to write portable code.

If fopen() fails and errno is non-zero, it's possible that it was set
by some function called by fopen() for reasons having nothing to do
with fopen's failure. For example, fopen() might call malloc(),
malloc() could fail and set errno, then fopen() could fall back to
some alternative mechanism that doesn't use dynamically-allocated
memory, and then fail because the file doesn't exist. (That
particular scenario isn't very plausible, but something along those
lines could happen.)

It might have been more convenient if each library function defined in
the standard were required on failure to either (a) set errno to a
meaningful value, or (b) reset it to the value it had before the call.
If that were the case, then this:

errno = 0;
if ((f = fopen(filename, "r")) == NULL) {
if (errno == 0) {
fprintf(stderr, "fopen failed for %s\n", filename);
}
else {
perror(filename );
}
}

could always be depended on to produce a meaningful error message.

--
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.
Apr 19 '06 #32
Mr John FO Evans wrote:
After reading all the comments on this thread I am astounded that the 'C'
standard does not require that fopen returns a meaningful error when it
fails. Surly this is an ommision


I don't think so and I partially disagree with some answer in this
thread. Strictly speaking, a failure reported by fopen in "r+" mode
means that the file cannot be read nor write which is the same as "does
not exist" from the point of view of C, whatever the reason is. If you
want a more subtle diagnostic which matches better the user's
expectation, then you have to rely on the filesystem API (e.g. stat).
One cannot state that stat() is not standard on one hand and expect an
information about something that C ignores (e.g. access rights) on the
other hand.

my .02 euro.

a+, ld.
Apr 19 '06 #33
Laurent Deniau wrote:
Mr John FO Evans wrote:
After reading all the comments on this thread I am astounded that the
'C' standard does not require that fopen returns a meaningful error
when it
fails. Surly this is an ommision
I don't think so and I partially disagree with some answer in this
thread. Strictly speaking, a failure reported by fopen in "r+" mode
means that the file cannot be read nor write which is the same as "does
not exist" from the point of view of C, whatever the reason is.


I disagree, does not exist and cannot be opened are very different concepts.
If you
want a more subtle diagnostic which matches better the user's
expectation, then you have to rely on the filesystem API (e.g. stat).
One cannot state that stat() is not standard on one hand and expect an
information about something that C ignores (e.g. access rights) on the
other hand.


Yes you can, it just means that you have to go to something outside the
C standard to achieve it, be that the Posix standard or some other
extension.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Apr 19 '06 #34
Keith Thompson wrote:

Kenneth Brody <ke******@spamc op.net> writes:
Keith Thompson wrote:
[...]
Usually the best approach is to try to open the file, and handle the
error if the attempt fails. Providing information about *why* it
failed can be useful, but it isn't absolutely necessary, and it can't
be done portably.


Isn't this portable?

... proper #include's, etc. implied ...

errno=0;
f = fopen(filename, mode);
if ( f == NULL )
{
if ( errno != 0 )
perror(filename );
else
fprintf(stderr, "fopen() of %s failed.\n",file name);
exit(EXIT_FAILU RE);
}


No, since the standard doesn't say that fopen() sets errno on failure.
perror() could print something silly like "foo.txt: No error", or
"foo.txt: File exists".


Hence the "errno=0" prior to fopen(), and the check for "errno != 0"
prior to calling perror().

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

Kenneth Brody wrote:
Keith Thompson wrote:
[...]
Usually the best approach is to try to open the file, and handle the
error if the attempt fails. Providing information about *why* it
failed can be useful, but it isn't absolutely necessary, and it can't
be done portably.


Isn't this portable?

... proper #include's, etc. implied ...

errno=0;
f = fopen(filename, mode);
if ( f == NULL )
{
if ( errno != 0 )
perror(filename );
else
fprintf(stderr, "fopen() of %s failed.\n",file name);
exit(EXIT_FAILU RE);
}


It's portable, but it might always print out "fopen() of %s failed.\n"
and never give a reason on some implementations .


Which I suppose qualifies for "can't be done portably" in terms of
actually getting the reason. However, the above is portable, and
will give the reason on those platforms that tell you why. On
platforms that don't tell you why, there's not much that you can
do, is there? (Even non-portably. Unless the "real" error number
is stored somewhere, but not placed in errno, sort of like the
Windows GetLastError() call. Of course, all the Windows C compilers
that I've seen set errno for you.)

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

In article <ku************ @news.flash-gordon.me.uk>, Flash Gordon <sp**@flash-gordon.me.uk> writes:

I disagree, does not exist and cannot be opened are very different concepts.


Always? I've seen filesystems where they're indistinguishab le, such
as steganographic "deniable" filesystems where the proper key is
required to determine both the existence and contents of a particular
"file". Without that key, it's impossible to prove the existence or
nonexistence of the file.

Since it's completely possible to use such a filesystem under C's I/O
model (the "filename" passed to fopen becomes the key to the file),
there are potentially implementations for which there is no difference
between "does not exist" and "cannot be opened".

--
Michael Wojcik mi************@ microfocus.com

As always, great patience and a clean work area are required for fulfillment
of this diversion, and it should not be attempted if either are compromised.
-- Chris Ware
Apr 19 '06 #37
Michael Wojcik wrote:
In article <ku************ @news.flash-gordon.me.uk>, Flash Gordon <sp**@flash-gordon.me.uk> writes:
I disagree, does not exist and cannot be opened are very different concepts.
Always? I've seen filesystems where they're indistinguishab le, such
as steganographic "deniable" filesystems where the proper key is
required to determine both the existence and contents of a particular
"file". Without that key, it's impossible to prove the existence or
nonexistence of the file.


My opinion is that your inability to see something does not change its
existence. So I would say that running under such a system just makes it
impossible to use non-standard means to determine if a file exists, that
does not translate in to the file not existing if you can't open it (or
tell it exists) because you don't have the key.
Since it's completely possible to use such a filesystem under C's I/O
model (the "filename" passed to fopen becomes the key to the file),
there are potentially implementations for which there is no difference
between "does not exist" and "cannot be opened".


With a system where it is guaranteed that no looking or permissions will
prevent you from opening a file then if you can't open a file it doesn't
exist. However, that *still* does not make the two concepts different,
it just makes detecting whether a file exists easy on *that* implementation.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc

Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
Apr 19 '06 #38
Kenneth Brody <ke******@spamc op.net> writes:
Keith Thompson wrote:
Kenneth Brody <ke******@spamc op.net> writes:
> Keith Thompson wrote:
> [...]
>> Usually the best approach is to try to open the file, and handle the
>> error if the attempt fails. Providing information about *why* it
>> failed can be useful, but it isn't absolutely necessary, and it can't
>> be done portably.
>
> Isn't this portable?
>
> ... proper #include's, etc. implied ...
>
> errno=0;
> f = fopen(filename, mode);
> if ( f == NULL )
> {
> if ( errno != 0 )
> perror(filename );
> else
> fprintf(stderr, "fopen() of %s failed.\n",file name);
> exit(EXIT_FAILU RE);
> }


No, since the standard doesn't say that fopen() sets errno on failure.
perror() could print something silly like "foo.txt: No error", or
"foo.txt: File exists".


Hence the "errno=0" prior to fopen(), and the check for "errno != 0"
prior to calling perror().


No, it's still not 100% portable (i.e., it's not guaranteed by the
standard). A failing fopen() could legally set errno to a non-zero
value that has nothing to do with the reason the fopen() call failed.
I presented a (rather implausible) example elsewhere in this thread.

I suspect that most real implementations set errno to something
meaningful, but it's not required.

--
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.
Apr 19 '06 #39
Keith Thompson wrote:

Kenneth Brody <ke******@spamc op.net> writes:
Keith Thompson wrote: [...] Hence the "errno=0" prior to fopen(), and the check for "errno != 0"
prior to calling perror().
No, it's still not 100% portable (i.e., it's not guaranteed by the
standard). A failing fopen() could legally set errno to a non-zero
value that has nothing to do with the reason the fopen() call failed.
I presented a (rather implausible) example elsewhere in this thread.


I know that the standard doesn't guarantee that fopen() will set errno
on failure. But does it really allow it to change errno to a non-zero
value that's not the actual error? Is this a "legal" implementation
within fopen()?

...
if ( it_failed )
{
errno = rand();
return(NULL);
}
...

Okay, so someone will probably point out that it's not allowed to call
rand() for some reason. :-)

So how about:

if ( it_failed )
{
errno = (int)time(NULL) ;
return(NULL);
}
I suspect that most real implementations set errno to something
meaningful, but it's not required.


Well, does "99.99% portable" qualify? :-)

I wonder if someone wants to implement a C environment where it does
all of the "legal, but probably not taken into account" behaviors?
Things like setting errno to something other than the "real" value,
or randomly zeroing memory on "a[i] = i++".

No, this is not me volunteering to do so. :-)

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

Apr 20 '06 #40

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

Similar topics

10
17222
by: lamar_air | last post by:
I have a python script and i want to delete a file on my computer c:\....\...\.. .txt what's the script to do this? I know how to write to files but i also need to know how to delete a file.
2
14419
by: Chris Fink | last post by:
I am using the System.IO.File class to determine if a file exists on a network share. The File.Exists method keeps returning false, even though the file does exist. The MSDN documentation states, "If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path."
4
4092
by: Mike | last post by:
Hi, I am looking for function in .Net library that let me know if exist any file if I specified template. Eg: I specify "*.txt" and if any file (1.txt, 2.txt, .. ) exists then I can get True or at least file name . And if does not exist Fasle or empty string. Of course I can use VB6 function Dir, but maybe .Net contains
1
2595
by: Tim Failes | last post by:
This seems a trival question, but I cannot get it to work properly... Essentially my question is, how can I create a text file, and guarantee it is given the current date/time as the Creation Time? My code is creating a file correctly, but the CreationTime is (sometimes) set to the CreationTime of an old file that has previously been removed. The line of code creating the file is _LogFileWriter = newFile.CreateText()
3
2147
by: tshad | last post by:
I have a function that downloads a file to the users computer and it works fine. The problem is that I then want the program to rename the file (file.move) to the same name plus todays date. The problem is that when you run the program it gets to the: Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name)
26
4976
by: Army1987 | last post by:
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; int main(int argc, char *argv) { FILE *in, *out;
7
19151
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!
3
2060
by: brook | last post by:
hey all - i´m new to php and having trouble writing a simple code which should create a file. here is the most simplified version: <?php $content = "my content"; $path = "test.txt"; if(!chmod($path, 0744)) { echo "error, $path"; exit; } else {
65
5126
by: Hongyu | last post by:
Dear all: I am trying to write to a file with full directory name and file name specified (./outdir/mytestout.txt where . is the current directory) in C programming language and under Unix, but got errors of Failed to open file ./outdir/mytestout.txt. Below is the code: #include <stdio.h>
0
9980
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
11236
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
10836
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
10926
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
9643
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
8018
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
5856
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...
2
4278
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3287
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.