在C上正确使用Stat

nec*_*net 16 c posix file

为什么这样做:

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

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

printf("%d",size);
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

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

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

printf("%d",size);
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppe 28

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

buf = malloc(sizeof(struct stat));
Run Code Online (Sandbox Code Playgroud)

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

free(buf);
Run Code Online (Sandbox Code Playgroud)

  • (但是不要忘记之后"免费").) (15认同)

Muh*_*ser 10

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

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

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

printf("%d",size);
Run Code Online (Sandbox Code Playgroud)

上面的代码只声明了一个指针,但实际上没有分配内存空间.

你应该修改代码看起来像这样:

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);
Run Code Online (Sandbox Code Playgroud)

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