有比简单地打开文件更好的方法吗?

int exists(const char *fname)
{
    FILE *file;
    if ((file = fopen(fname, "r")))
    {
        fclose(file);
        return 1;
    }
    return 0;
}

当前回答

像这样使用stat:

#include <sys/stat.h>   // stat
#include <stdbool.h>    // bool type

bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

像这样叫它:

#include <stdio.h>      // printf

int main(int ac, char **av) {
    if (ac != 2)
        return 1;

    if (file_exists(av[1]))
        printf("%s exists\n", av[1]);
    else
        printf("%s does not exist\n", av[1]);

    return 0;
}

其他回答

您可以使用realpath()函数。

resolved_file = realpath(file_path, NULL);
if (!resolved_keyfile) {
   /*File dosn't exists*/
   perror(keyfile);
   return -1;
}

通常,当您想要检查一个文件是否存在时,这是因为如果它不存在,您想要创建该文件。如果您不想创建该文件,Graeme Perrow的答案很好,但如果您想创建该文件,那么它很容易受到竞态条件的影响:在您检查它是否存在和您实际打开它并写入它之间,另一个进程可能会创建该文件。(别笑…如果创建的文件是一个符号链接,这可能会有不好的安全隐患!)

如果你想检查文件是否存在,并在它不存在时自动创建文件,这样就没有竞态条件,然后使用这个:

#include <fcntl.h>
#include <errno.h>

fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
  /* failure */
  if (errno == EEXIST) {
    /* the file already existed */
    ...
  }
} else {
  /* now you can use the file */
}

是的。使用stat()。请参阅forstat(2)的手册页。

如果文件不存在,Stat()将失败,否则很可能成功。如果它确实存在,但是您对它所在的目录没有读访问权,那么它也会失败,但在这种情况下,任何方法都将失败(您如何根据访问权限检查可能看不到的目录的内容?很简单,你不能)。

哦,正如其他人提到的,您还可以使用access()。然而,我更喜欢stat(),因为如果文件存在,它会立即为我提供许多有用的信息(它最后一次更新是什么时候,它有多大,拥有文件的所有者和/或组,访问权限,等等)。

FILE *file;
    if((file = fopen("sample.txt","r"))!=NULL)
        {
            // file exists
            fclose(file);
        }
    else
        {
            //File not found, no memory leak since 'file' == NULL
            //fclose(file) would cause an error
        }

从Visual c++的帮助来看,我倾向于使用

/* 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\n" );
      /* Check for write permission */
      if( (_access( "ACCESS.C", 2 )) != -1 )
         printf( "File ACCESS.C has write permission\n" );
   }
}

同样值得注意的是_access的模式值(const char *path,int模式):

00:只存在 02:写权限 04:读权限 06:读写权限

因为在文件存在但无法按要求打开的情况下,fopen可能会失败。

编辑:看看Mecki的帖子就知道了。Stat()看起来确实是一种更整洁的方式。何鸿燊的嗡嗡声。