c - 统计函数调用

标签 c stat

<分区>

我想使用stat 函数。但我不知道如何用变量来做。我从其他进程获取 DIRECTORY 和子目录的值。

if( stat( DIRECTORY/sub-dir, &st ) == 0 )
{--}

我收到如下错误消息 "error: invalid operands to binary/"

最佳答案

您需要创建一个字符串并将其传递给 stat()。假设 VLA 支持(C99 或 C11,相关选项可用),则:

char path[strlen(DIRECTORY) + strlen(subdir) + sizeof("/")];
snprintf(path, sizeof(path), "%s/%s", DIRECTORY, subdir);
struct stat st;
if (stat(path, &st) != 0)
    ...oops!...
else
    ...process data...

如果您没有 VLA 支持,您可以使用固定大小的数组或 malloc()free()

或者:

char path[PATH_MAX];  // Beware: not always defined; _POSIX_PATH_MAX?

或者:

size_t pathlen = strlen(DIRECTORY) + strlen(subdir) + sizeof("/");
char *path = malloc(pathlen);
if (path != 0)
{
    snprintf(path, pathlen, "%s/%s", DIRECTORY, subdir);
    struct stat st;
    if (stat(path, &st) != 0)
        ...oops!...
    else
        ...process data...
    free(path);
}

关于c - 统计函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19663042/

相关文章:

c - 如何仅计算路径中的目录数

c - stat() 不适用于 .so 文件

c - C中链表插入函数问题

c - 访问dll中的全局变量

c - 如何使用 stat() 检查命令行参数是否是目录?

c - 强制创建的文件或文件夹具有特定的统计结构

c - 可变长度数组上 sizeof 的行为(仅限 C)

c - 使用 setsockopt;当套接字从另一端关闭时,read 返回 0 而不是 -1

c - 链接堆栈未链接?

python - 如何使用 os.listdir 在 Python3 中获取文件信息?