Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to check if file exists ?

Status
Not open for further replies.

OOP

Programmer
Feb 5, 2001
94
SG
Hello, i'm using ifstream to open a file in a directory. The problem is that the program will create the file if it does not exists (using <open> function). I would like the program to display an error msg if it could'nt find the file.
What function should i use? Thanks in advance for all suggestions.
 
What version of the librarys are you using? The following code leaves my c:\ untouched

Code:
#include <iostream>
#include <fstream>


void main()
{
	std::fstream in;
	in.open(&quot;c:\\dontcreateme.txt&quot;);
	



}


if you are using the versions found in the .h files you can
1:not (preferred solution)
2:use std::ios::nocreate as one of your flags.

WR
 
You can use the FindFirstFile function. Here is a MSDN example, you can use this code to see if a file exists or not:

#define _WIN32_WINNT 0x0400

#include <windows.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;

printf (&quot;Target file is %s.\n&quot;, argv[1]);
hFind = FindFirstFile(argv[1], &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf (&quot;Invalid File Handle. GetLastError reports %d\n&quot;, GetLastError ());
return (0);
}
else
{
printf (&quot;The first file found is %s\n&quot;, FindFileData.cFileName);
FindClose(hFind);
return (1);
}
}
 
If you were using Qt(commercial or non-commercial editions), you would simply do :

Code:
#include <qfile.h>
...
if (!QFile::exists (&quot;path/myfile.txt&quot;))
  //print error
...

Unfortunately we're in Visual C++ forum, but the Qt framework is easily usable with Visual C++ 6 and .NET versions.

--
Globos
 
use
if(GetFileAttributes(&quot;path\file&quot;) == INVALID_FILE_ATTRIBUTES){file does not exist}

Ion Filipski
1c.bmp
 
if your programming in C. use access()

int access(const char *path, int mode);

with mode, use F_OK to determine file existance.

so

n = access(&quot;./filename&quot;, F_OK);

and check for return value of n.
 
Thanks for all of your respones, i'll try the codes. [2thumbsup]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top