为什么这样做:

char *fd = "myfile.txt";
struct stat buf;

stat(fd, &buf);
int size = buf.st_size;

printf("%d",size);

但这不起作用:
char *fd = "myfile.txt";
struct stat *buf;

stat(fd, buf);
int size = buf->st_size;

printf("%d",size);

最佳答案

它不起作用的原因是第一个示例中的buf是在堆栈上分配的。
在第二个示例中,您只有一个指向struct stat的指针,它指向任何地方(可能指向地址0x0,即空指针),您需要为它分配内存,如下所示:

buf = malloc(sizeof(struct stat));

那么这两个例子都应该有效。使用malloc()时,请务必在使用完free()后使用struct stat
free(buf);

关于c - 正确使用Stat on C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3138600/

10-11 03:47
查看更多