使用C语言fstat函数获取文件的大小
在进行文件读写操作时,有时候需要知道文件的大小,以便更好地进行数据处理。而C语言提供了fstat函数来获取文件的大小信息,使得文件操作更加便捷。
fstat函数的原型如下:
int fstat(int fildes, struct stat *buf);
其中,第一个参数fildes是已打开文件的文件描述符,第二个参数buf是指向一个stat结构体的指针,用于存储获取到的文件信息。
代码示例:
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;
struct stat sb;
fd = open("example.txt", O_RDONLY);
if (fstat(fd, &sb) == -1) {
perror("fstat");
return 1;
}
printf("File size: %lld bytes\n", (long long) sb.st_size);
return 0;
}
在上面的示例中,通过open函数打开example.txt文件并传入O_RDONLY模式,获取到