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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function to check if “C:\\myFile.txt” exists

Status
Not open for further replies.

d00ape

Programmer
Apr 2, 2003
171
SE
I know there is a small function that checks if a file exists but I can’t find it.
 
Non-standard library function _access() from io.h header:
Code:
#include <io.h>
...
if (_access(filepath,0) != 0) 
{
// No such file
}
A portable way to check file existence:
Code:
#include <cstdio>
bool isExist(const char* filepath)
{
  FILE* f = 0;
  if (filepath && (f=fopen(filepath,"r")) != 0)
    fclose(f);
  return f != 0;
}
 
Code:
bool FileIO::CheckFileExists ( CString path )
{
  WIN32_FIND_DATA data;
  HANDLE hFile = FindFirstFile( path, &data );

  if ( hFile == INVALID_HANDLE_VALUE ) // directory doesn't exist
    return (FALSE);
  else 
  {
    // is it folder or file?
    FindClose(hFile);
    if ( data.dwFileAttributes ) return ( true );
  }
  return ( false );
}
 
Note: Beeing able to see the file doesn't necessarily mean you have the rights to access it.

If you mean to check if it exists but also access it in some manner, use CreateFile with the OPEN_EXISTING flag set.

See

Windows API and thus not as portable as ArkM's suggestion. But, hey, who cares ;-)

/Per

&quot;It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top