在C上正确使用Stat

时间:2010-06-29 07:15:05

标签: c file posix

为什么这样做:

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);

6 个答案:

答案 0 :(得分:25)

它不起作用的原因是第一个例子中的buf被分配在堆栈上。 在第二个例子中,你只有一个指向struct stat的指针,指向任何地方(可能指向地址0x0,即一个NULL指针),你需要像这样为它分配内存:

buf = malloc(sizeof(struct stat));

然后两个例子都应该有效。使用malloc()时,请务必在使用free()完成后使用struct stat

free(buf);

答案 1 :(得分:10)

这只是一个简单的内存分配问题。

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;

buf = malloc(sizeof(struct stat));

stat(fd, buf);
int size = buf->st_size;
printf("%d",size);

free(buf);

这将分配内存,并在使用后自由。

答案 2 :(得分:2)

在第二个中,你使用指向你的指针 - 不知道在哪里。 stat偶然能够正确地填充指向区域中的值(您的程序可能在这里突然终止)。然后,由于您不知道这些数据的位置,您可以使用它buf->st_size,但也许有人使用了您不拥有的内存区域。

答案 3 :(得分:1)

创建结构或指向结构的指针之间存在很大差异。第一个代码创建结构,第二个代码创建指针,指向不存在的结构。使用malloc或calloc可以分配内存,并初始化您的结构。在此之后,您可以执行任何操作,并且当您不再需要此结构时,必须使用free()函数释放分配的空间。

答案 4 :(得分:1)

您没有为指针dude分配任何内存。

你应该为buf分配内存。

buf = malloc(sizeof(struct stat));

现在它会起作用。

答案 5 :(得分:0)

这应解决您的问题和另一个:文件大小可以是32位或64位int。此示例假定使用64位计算机。

#include <stat.h>
#include <errno.h>

char *file = "myfile.txt";
long long size; //st_size can be a 64-bit int.
struct stat *buf = malloc(sizeof(struct stat)); //allocates memory for stat structure.
errno = 0; //always set errno to zero first.

if(stat(file, buf) == 0)
{
    size = buf->st_size;
    printf("Size of \"%s\" is %lld bytes.\n", file, size);
}
else
{
    perror(file);    //if stat fails, print a diagnostic.
}