C/C++の中で、どのようにファイルやディレクトリが存在するかを判断しますか?


1.C++は簡単な方法です。

#include <iostream>
#include <fstream>
using namespace std;
#define FILENAME "stat.dat"
int main()
{
     fstream _file;
     _file.open(FILENAME,ios::in);
     if(!_file)
     {
         cout<<FILENAME<<" ";
      }
      else
      {
          cout<<FILENAME<<" ";
      }
      return 0;
}
.c言語のライブラリを利用する方法:関数名:access功  エネルギー:ファイルのアクセス権限を確定するためのものです。  法:int access(const char*filename、int amode);以前はこの関数を使ったことがありませんでしたが、今日はデバッグでこの関数を発見しました。とても使いやすいと思います。特にファイルやフォルダが存在するかどうかを判断する時は、ファイルの場合は読み書きの権限を検出できます。フォルダの場合は、存在するかどうかを判断するしかありません。以下はMSDN:int_から摘出します。access(const char*path、int mode);Return ValueEach of these functions returns 0 if the file has the given mode.The function returns C 1 if the named file does not exist or is not accessible in the given mode;in this case,errno is set as follows:EACCESAccess denied:file's permission setting does allow specifed access.ENOENT Filename or path not found.PaameterspathFictoryaccess function determines whether the specified file exists and can be accessed as specified by the value of mode.When used with directores,uaccess determines only whether the specified directory exists;in Windows NT、all directores have read and write access.mode Value            Checks File For 00                              Existence only 02                              Write permission 04                              Read permission 06                              Read and write permission Example

/* ACCESS.C: This example uses _access to check the
 * file named "ACCESS.C" to see if it exists and if
 * writing is allowed.
 */
#include  <io.h>
#include  <stdio.h>
#include  <stdlib.h>
void main( void )
{
   /* Check for existence */
   if( (_access( "ACCESS.C", 0 )) != -1 )
   {
      printf( "File ACCESS.C exists " );
      /* Check for write permission */
      if( (_access( "ACCESS.C", 2 )) != -1 )
         printf( "File ACCESS.C has write permission " );
   }
}
Output File ACCESS.C.exists File ACCESS.has write permission 3.windowsプラットフォームの下でAPI関数FindFirstFile(...):(1)ファイルが存在するかどうかを確認する:

#define _WIN32_WINNT 0x0400
#include "windows.h"
int
main(int argc, char *argv[])
{
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind;
  printf ("Target file is %s. ", argv[1]);
  hFind = FindFirstFile(argv[1], &FindFileData);
  if (hFind == INVALID_HANDLE_VALUE) {
    printf ("Invalid File Handle. Get Last Error reports %d ", GetLastError ());
  } else {
    printf ("The first file found is %s ", FindFileData.cFileName);
    FindClose(hFind);
  }
  return (0);
}
(2)カタログが存在するかを確認する。