You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言stat检测~/下目录?解决重复创建目录报错问题

问题:stat无法检测~/目录下已存在的文件夹,导致重复创建报错

我希望在~/testdir目录不存在时创建它。测试前已手动创建了该目录,但stat函数无法检测到它,导致程序再次尝试创建目录,最终报错mkdir: cannot create directory ‘/home/pi/testdir’: File exists,且该问题仅出现在~/目录下。

相关代码

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

void main()
{
   system("mkdir ~/testdir");
   struct stat st = {0};
   if (stat("~/testdir", &st) == -1)
   {
       system("mkdir ~/testdir");
   }
}

执行结果

mkdir: cannot create directory ‘/home/pi/testdir’: File exists

问题原因与解决方法

  • 核心原因:stat是系统调用,不会解析Shell中的~(家目录缩写),只有Shell环境会处理这个符号。所以stat("~/testdir", &st)实际是在查找当前目录下名为~的文件夹里的testdir,而非用户的家目录,自然找不到已存在的/home/pi/testdir,进而进入分支执行重复创建命令。另外原代码开头就调用了一次system("mkdir ~/testdir"),这本身就会触发首次创建尝试,即使后续判断正确也会先报错。
  • 解决办法:
    1. 用环境变量拼接通用路径:通过getenv("HOME")获取当前用户的家目录,拼接成完整路径后再调用stat和mkdir,示例代码:
      #include <stdio.h>
      #include <stdlib.h>
      #include <sys/stat.h>
      #include <string.h>
      
      int main() {
          char *home_dir = getenv("HOME");
          if (home_dir == NULL) {
              perror("Failed to get home directory");
              return 1;
          }
      
          char dir_path[256];
          snprintf(dir_path, sizeof(dir_path), "%s/testdir", home_dir);
      
          struct stat st = {0};
          if (stat(dir_path, &st) == -1) {
              if (mkdir(dir_path, 0755) == -1) {
                  perror("mkdir failed");
                  return 1;
              }
          }
          return 0;
      }
      
    2. 直接使用绝对路径(不推荐):把~/testdir替换成固定的家目录路径(如/home/pi/testdir),但换用户运行时会失效。
    3. 移除多余的创建命令:原代码开头的system("mkdir ~/testdir")完全多余,必须删除,否则无论后续判断是否正确都会先执行一次创建操作。

内容的提问来源于stack exchange,提问作者Eddy Sorngard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:53:24