473,542 Members | 2,081 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Checkup: better way to test for file existence?

Hello,

I see other references in this newsgroup saying that the only standard
C++ way to test for file existence is some variant of my code below;
can someone please confirm...or offer alternatives?

Additionally, might there be cross-platform alternatives, say in a
library like Boost, or something else?

-Matt

#include <fstream>

/*
[class FileHandle contains 'fstream file' and previously-initialed
'string filename'.]
*/

bool
FileHandle::exi sts()
{
bool retval = false;

// TODO/XXX: Is there a better way to
// test the existence of a file
// without opening it?

file.open(filen ame.c_str(), ios::in | ios::binary);

if (!file.fail()) retval = true;

file.close();

return retval;
}

--
Remove the "downwithspamme rs-" text to email me.
Jul 23 '05 #1
14 7681

"Matt" <ma**@downwiths pammers-mengland.net> wrote in message
news:18******** *************** *********@4ax.c om...
Hello,

I see other references in this newsgroup saying that the only standard
C++ way to test for file existence is some variant of my code below;
can someone please confirm...or offer alternatives?
You must have misread them, or read some that were not
correct. There is no way in standard C++ to detect
conclusively the nonexistence of a file. (If an
open succeeds when using a mode other than once which
will create a nonexistent file, then of course that
does indicate that the file previously existed). But
if an open fails, that does not necessarily mean it
doesn't exist. All you can determine is if an attempt
to open a file succeeded or failed. An attempt to open
could fail for a variety of reasons depending upon the
environment, including but not limited to: insufficient
OS permissions, device where file resides is offline, does
not exist, etc. Many implementations do provide extensions
for obtaining more detailed information about i/o, but
they're not standard.

Additionally, might there be cross-platform alternatives, say in a
library like Boost, or something else?
There probably are some which address at least a small
number of environments. Try google.


-Matt

#include <fstream>

/*
[class FileHandle contains 'fstream file' and previously-initialed
'string filename'.]
*/

bool
FileHandle::exi sts()
{
bool retval = false;

// TODO/XXX: Is there a better way to
// test the existence of a file
// without opening it?
Depends upon what 'better' means. There is no way
at all using standard C++. AFAIK platform-specific
solutions are provided by most implementations .

file.open(filen ame.c_str(), ios::in | ios::binary);

if (!file.fail()) retval = true;

file.close();

return retval;
}


If this function returns 'false', all that means
is that the file could not be opened (for an unknown
reason). Nothing more, nothing less.

-Mike
Jul 23 '05 #2
You can test this with an old school C function:

#include "unistd.h."
#include <iostream>
#include <string>
int main(int argc, char **argv)
{
int ret(0);
std::string fname("C:\\AUTO EXEC.BAT");
ret = access(fname.c_ str(), F_OK);
if (ret == -1)
std::cout << "Access on file " << fname << " is denied" <<
std::endl;

system("Pause") ;
return EXIT_SUCCESS;
}

more specific tests this if you can get access to the file.

Jul 23 '05 #3
Matt wrote:
bool
FileHandle::exi sts()
{
bool retval = false;

// TODO/XXX: Is there a better way to
// test the existence of a file
// without opening it?


Why would you want to test for the existence of a file if you don't want to
open it?
If you just want to make sure it's there so you can open it later, that's
not a good idea since something could change in between (file
removed/created/renamed, permissions changed, device unmounted, whatever).

Jul 23 '05 #4

wi******@hotmai l.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
You can test this with an old school C function:
'access()' is not a C (or C++) function, it's an extension
provided by some implementations . Also your use of it below
does not indicate a guarantee of a file's existence or nonexistence,
only whether it is accessible. An fstream object can already provide
this information.

#include "unistd.h."
#include <iostream>
#include <string>
int main(int argc, char **argv)
{
int ret(0);
std::string fname("C:\\AUTO EXEC.BAT");
ret = access(fname.c_ str(), F_OK);
if (ret == -1)
std::cout << "Access on file " << fname << " is denied" <<
std::endl;

system("Pause") ;
return EXIT_SUCCESS;
}

more specific tests this if you can get access to the file.


Here the topic is ISO standard C++. Your 'solution' is specific
to a UNIX implementation, so is not applicable to other platforms,
and is not topical here.

-Mike
Jul 23 '05 #5
On Mon, 14 Feb 2005 20:35:07 +0100, Rolf Magnus <ra******@t-online.de>
wrote:
Why would you want to test for the existence of a file if you don't want to
open it?
I'm using (in an application I'm building to simulate a
more-complicated, future design) the existence or non-existence of
files as a means of inter-process communication.

(eg, while one process is processing a certain event, it writes a
zero-sized-file, then deletes said file when the event completes. A
separate process polls the existence of said file to see if the event
is continuing. I doubt I can give you many more details beyond that
without explaining more in depth my application and prototype.)
If you just want to make sure it's there so you can open it later, that's
not a good idea since something could change in between (file
removed/created/renamed, permissions changed, device unmounted, whatever).


Yes, obviously. However, that's not what I'm trying to do. See
above.

-Matt
--
Remove the "downwithspamme rs-" text to email me.
Jul 23 '05 #6
On Mon, 14 Feb 2005 19:13:35 GMT, "Mike Wahler"
<mk******@mkwah ler.net> wrote:

"Matt" <ma**@downwiths pammers-mengland.net> wrote in message
news:18******* *************** **********@4ax. com...
Hello,

I see other references in this newsgroup saying that the only standard
C++ way to test for file existence is some variant of my code below;
can someone please confirm...or offer alternatives?


You must have misread them, or read some that were not
correct. There is no way in standard C++ to detect
conclusively the nonexistence of a file.


Fair enough. I'll rephrase my question:

What might you recommend as the best possible method/algorithm to
detect the non-existence of a file (even though it may not catch all
cases as noted below) in lieu of having a definitive means to do so
accurately.

As I read from the info below, there is no conclusive way to do this.
Hence there is no real answer to the problem.

What I'm looking for are alternative answers that get me "as close as
possible."
Additionally, might there be cross-platform alternatives, say in a
library like Boost, or something else?


There probably are some which address at least a small
number of environments. Try google.


Thanks for the google tip. I have been looking, even prior to this
post. My search was not initially productive, hence my post here.

-Matt

--
Remove the "downwithspamme rs-" text to email me.
Jul 23 '05 #7

"Matt" <ma**@downwiths pammers-mengland.net> wrote in message
news:c9******** *************** *********@4ax.c om...
On Mon, 14 Feb 2005 19:13:35 GMT, "Mike Wahler"
<mk******@mkwah ler.net> wrote:

"Matt" <ma**@downwiths pammers-mengland.net> wrote in message
news:18******* *************** **********@4ax. com...
Hello,

I see other references in this newsgroup saying that the only standard
C++ way to test for file existence is some variant of my code below;
can someone please confirm...or offer alternatives?


You must have misread them, or read some that were not
correct. There is no way in standard C++ to detect
conclusively the nonexistence of a file.


Fair enough. I'll rephrase my question:

What might you recommend as the best possible method/algorithm to
detect the non-existence of a file (even though it may not catch all
cases as noted below) in lieu of having a definitive means to do so
accurately.

As I read from the info below, there is no conclusive way to do this.
Hence there is no real answer to the problem.

What I'm looking for are alternative answers that get me "as close as
possible."


If you open the file as "input only, don't create" then
barring the circumstances I cited, a return of 'true'
from 'istream::fail( )' would probably mean 'not found'.

std::ifstream input("filename ");
if(!input)
std::cerr << "open failed, file probably does not exist\n";

-Mike
Jul 23 '05 #8
On Mon, 14 Feb 2005 11:58:04 -0600, Matt
<ma**@downwiths pammers-mengland.net> wrote:
Additionally , might there be cross-platform alternatives, say in a
library like Boost, or something else?


I had a peak at Boost, there appears to be a file "exists()" method in
its filesystem library:

http://www.boost.org/libs/filesystem/doc/

I may check this out and use it, not sure yet.

-Matt
--
Remove the "downwithspamme rs-" text to email me.
Jul 23 '05 #9
You could try something like this:

bool FileExists( std::string strFile )
{
bool bSuccess = true;
struct _stat stFile;

if( _stat( strFile.c_str() , &stFile ) == -1 )
bSuccess = false;

return bSuccess;
}

For linux, replace _stat with stat...

Jul 23 '05 #10

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

Similar topics

5
3366
by: Thierry S. | last post by:
Hello. I would to test the existence of a variable before to use it (like isset($myVar) in PHP). I try using "if myVar: ", but there is the error meesage (naturally): "NameError: name 'myVar' is not defined" Please, could you tell me what for function exist to test the variable with Python?
2
5340
by: David | last post by:
I'm using following code for checking a file existence. I's working fine for given folder. Is there a way to check a file exitance in subfolders? Thanks in advance, David Option Compare Database Public Function adhFileExists(strName As String) As Boolean On Error Resume Next
12
1794
by: DC Gringo | last post by:
How do I test for existence of a file in the file system: If FileExists(myVariable & ".pdf") = True pnlMyPanel.Visible = True End If -- _____ DC G
4
5850
by: Gabe Moothart | last post by:
Hello, In one of my asp.net applications I test the existence of a file, like so: File.Exists(Server.MapPath("/path/file.jpg"))); This was failing, even though the path returned by Server.MapPath was clearly present. After some debugging, I discovered that the the asp.net account didn't have permission to execute File.Exists. Apparently...
0
7330
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...
0
7571
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. ...
0
5867
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...
1
5246
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...
0
3380
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...
0
3376
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1798
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
1
943
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
620
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...

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.