【问题标题】:How do I know if a file exists in C?我如何知道文件是否存在于 C 中?
【发布时间】:2015-03-27 22:42:20
【问题描述】:

我如何知道某个文件是否存在于 C 语言的当前目录中?我正在提示用户,我正在尝试查看他们输入的文件是否已经存在。这是我得到的:

int a=0;
char ing[100];
FILE * inp;


while (a=0);
{
    printf("Input file name: ");
    scanf("%s", ing);
    inp=fopen(ing , "r");
        if (inp==NULL)
            a=0;
        else
            a=1;
}

每当我输入一个不存在的文件时,我就会发现 cmd 没有响应。每当我输入一些存在的东西时,它都能正常工作,这很好。我只是不知道如果 NULL 不起作用,我到底需要输入什么。

【问题讨论】:

标签: c file input


【解决方案1】:

替换:

while (a=0)

与:

while (a==0)

检查使用这个:

if( access( ing, F_OK ) != -1 ) {
    // exists
} else {
    // not exist
}

【讨论】:

    【解决方案2】:

    使用 c 中的 access() 函数,我们可以知道文件的存在和分配给我们的权限。文件。

      if(access(filename,Checking option)==0)
                 printf("success\n");
       else
         printf("...\n");
    

    检查选项:

         R_OK - Check for the read operation
         W_OK - check for the write operation
         X_OK - check for the execute operation
         F_OK - check for the existence of the file
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多