正确使用Stat on C [英] Correct use of Stat on C

查看:108
本文介绍了正确使用Stat on C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样做:

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

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

printf("%d",size);


但这不起作用:


But this does not work:

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

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

printf("%d",size);

推荐答案

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

The reason for it not working is that buf in the first example is allocated on the stack. In the Second example you only have a pointer to a struct stat, pointing to anywhere (probably pointing to address 0x0, i.e. a NULL pointer), you need to allocate memory for it like this:

buf = malloc(sizeof(struct stat));

然后这两个示例都应该起作用.使用malloc()时,请务必记住在使用完struct stat之后使用free():

Then both examples should work. When using malloc(), always remember to use free() after you are finished with using the struct stat:

free(buf);

这篇关于正确使用Stat on C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆