在C上正确使用Stat
为什么这样做:
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,即一个NULL指针),你需要为它分配内存,如下所示:
buf = malloc(sizeof(struct stat));
然后两个例子都应该有效。 使用malloc()
,在使用struct stat
后总是记得使用free()
:
free(buf);
这只是一个简单的内存分配问题。
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);
这将分配内存,并在使用后释放。
在第二个中,您使用指向您的指针 – 不知道在哪里。 stat
将偶然能够正确地填充指向区域中的值(您的程序可能在这里突然终止)。 然后,由于您不知道这些数据的位置,您可以使用它buf->st_size
但也许有人使用了您不拥有的内存区域。
创建结构或指向结构的指针是一个很大的区别。 第一个代码创建结构,第二个代码创建指针,指向不存在的结构。 使用malloc或calloc,您可以分配内存,您的结构将被初始化。 在此之后,您可以执行任何操作,并且当您不再需要此结构时,必须使用free()函数释放分配的空间。
你没有为你的指针花花公子分配任何内存。
你应该为buf分配内存。
buf = malloc(sizeof(struct stat));
现在它会起作用。
这应该可以解决您的问题和另一个:文件大小可以是32位或64位int。 此示例假定使用64位计算机。
#include #include 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. }