Archived

This topic is now archived and is closed to further replies.

MadProgrammer

how to check to see if a file exists?

Recommended Posts

how do i see if a file exists without creating it? this is the code i thought up: ifstream in; in.open(filename); if(in.fail()) { in.close(); return false; } in.close(); return true; basically, thats what i thought up... heres the wierd thing: it works perfectly in Borland C++ 5.02, but in Visual Studio .NET, it doesnt work... It creates a blank file, and then returns true.... pissing me off... any ideas?? M@ the MadProgrammer

Share this post


Link to post
Share on other sites
ifstream();

ifstream( const char* szName, int nMode = ios::in, int nProt = filebuf::openprot );
ifstream( filedesc fd );
ifstream( filedesc fd, char* pch, int nLength );

Parameters

szName

The name of the file to be opened during construction.

nMode

An integer that contains mode bits defined as ios enumerators that can be combined with the bitwise OR ( | ) operator. The nMode parameter must have one of the following values:

ios::in The file is opened for input (default).


ios::nocreate If the file does not already exist, the function fails.


ios::binary Opens the file in binary mode (the default is text mode).
Note that the ios::nocreate flag is necessary if you intend to test for the file’s existence (the usual case).

-----------8<-----------[snip]

As you can see ios::nocreate is not set default.

so use :
in.open(filename, ios::in|ios::nocreate);





What does God want?
Does God want goodness or the choice of goodness?
Is a man who chooses the bad perhaps in some way better than a man who has the good imposed upon him?


[edited by - Zorak on December 26, 2002 10:46:22 PM]

Share this post


Link to post
Share on other sites
Zorak - that''s using the old iostream library. With standard iostreams, the ios::nocreate isn''t required - input streams never create a file - and there is no constructor using a file descriptor (except as an extension).


#include <fstream> // never <fstream.h>

inline bool FileExists( const std::string& filename )
{
return std::ifstream( filename.c_str() ).is_open();
}



[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

Share this post


Link to post
Share on other sites
thanks, zorak, thats what i had to do...

M@ the MadProgrammer

oh, and God wants the choice of goodness, therefore he gives us the option of goodness vs badness, hence all the bad stuff in this world...

[edited by - MadProgrammer on December 27, 2002 1:18:01 PM]

Share this post


Link to post
Share on other sites