【问题标题】:Check if a file exist检查文件是否存在
【发布时间】:2021-12-25 20:32:00
【问题描述】:

如何在不使用完整路径的情况下检查 APPDATA 中是否存在文件?

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

int main(void)
{
    if (access("%APPDATA%\\changzhi_leidianmac.data", F_OK) != -1)
    {
        printf("File Found......");
    }
    else
    {
        printf("File not found !!!!");
    }

    return 0;
}

【问题讨论】:

    标签: c file


    【解决方案1】:

    您可以使用getenv

    #include <stdlib.h>
    
    int main(void)
    {
        char *appdata = getenv("APPDATA");
        ...
        ...
    }
    

    之后使用snprintf

    【讨论】:

      【解决方案2】:
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      
      #include <unistd.h>
      
      
      int main(void)
      {
          //  Define the trailing portion of the file path.
          static const char FileName[] = "\\changzhi_leidianmac.data";
      
          //  Get the value of environment variable APPDATA or fail if it is not set.
          const char *APPDATA = getenv("APPDATA");
          if (!APPDATA)
          {
              fputs("Error, the environment variable APPDATA is not defined.\n",
                  stderr);
              exit(EXIT_FAILURE);
          }
          printf("APPDATA is %s.\n", APPDATA);
      
          //  Figure the space needed.  (Note that FileName includes a null terminator.)
          size_t Size = strlen(APPDATA) + sizeof FileName;
      
          //  Get space for the full path.
          char *Path = malloc(Size);
          if (!Path)
          {
              fprintf(stderr,
                  "Error, unable to allocate %zu bytes of memory for file path.\n",
                  Size);
              exit(EXIT_FAILURE);
          }
      
          //  Copy APPDATA to the space for the path, then append FileName.
          strcpy(Path, APPDATA);
          strcat(Path, FileName);
          printf("Full file path is %s.\n", Path);
      
          //  Test whether the file exists and report.
          if (0 == access(Path, F_OK))
              puts("The file exists.");
          else
          {
              puts("The file does not exist.");
              perror("access");
          }
      }
      

      【讨论】:

        【解决方案3】:

        C 没有任何访问环境变量的规定。您需要使用库或系统命令来获取数据。

        【讨论】:

        • 等等...getenv(3)呢?
        • getenv 在 C 2018 7.22.4.6 中指定。
        • C 没有任何用于访问环境变量的规定。 从根本上说,这表明完全缺乏思考。如果程序无法访问环境变量,为什么它们还会存在?
        • getenv一个库函数,甚至是一个标准库。我从来没有说过它做不到。不过,我希望提出问题的人能找到一个好的答案。
        • @thripper:标准 C 库是 C 的一部分,getenv 是 C 用于访问环境变量的规定。
        猜你喜欢
        • 1970-01-01
        • 2021-07-22
        • 2013-07-17
        • 2012-12-23
        • 2016-09-04
        相关资源
        最近更新 更多