<分区>
我想使用stat
函数。但我不知道如何用变量来做。我从其他进程获取 DIRECTORY 和子目录的值。
if( stat( DIRECTORY/sub-dir, &st ) == 0 )
{--}
我收到如下错误消息 "error: invalid operands to binary/"
<分区>
我想使用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/