#include <stdio.h>
#include <sys/stat.h> //stat头文件
#include <fcntl.h> //open头文件
#include <unistd.h> //close头文件
/*************************************************************************
struct stat {
dev_t st_dev; //文件的设备编号
ino_t st_ino; //节点
mode_t st_mode; //文件的类型和存取的权限
nlink_t st_nlink; //连到该文件的硬连接数目,刚建立的文件值为1
uid_t st_uid; //用户ID
gid_t st_gid; //组ID
dev_t st_rdev; //(设备类型)若此文件为设备文件,则为其设备编号
off_t st_size; //文件字节数(文件大小)
unsigned long st_blksize; //块大小(文件系统的I/O 缓冲区大小)
unsigned long st_blocks; //块数
time_t st_atime; //最后一次访问时间
time_t st_mtime; //最后一次修改时间
time_t st_ctime; //最后一次改变时间(指属性)
};
*************************************************************************/
//dd if=/dev/zero of=test_50Byte.bin count=1 bs=50
void test_fstat(void)
{
int fd = 0;
struct stat fstatbuf = {0};
fd = open("test_50Byte.bin", O_RDWR);
if (fstat(fd, &fstatbuf) < 0) {
perror("fstat input file");
}
printf("[fstat]test_50Byte.bin file size = [%ld] Byte\n\n", fstatbuf.st_size);
close(fd);
}
int main() {
int rval = 0;
struct stat statbuf = {0};
if (stat("test_50Byte.bin", &statbuf) < 0) {
perror("stat input file");
rval = -1;
return rval;
}
printf("[stat]test_50Byte.bin file size = [%ld] Byte\n\n", statbuf.st_size);
/*************************************************************************/
test_fstat();
/*************************************************************************/
FILE *in = NULL;
int file_size = 0;
do {
in = fopen("test_50Byte.bin", "rb");
if (in == NULL) {
perror("test_50Byte.bin");
rval = -1;
break;
}
if (fseek(in, 0, SEEK_END) < 0) {
perror("fseek input file");
rval = -1;
break;
}
file_size = ftell(in);
printf("[fseek]test_50Byte.bin file size = [%d] Byte\n\n", file_size);
if (fseek(in, 0, SEEK_SET) < 0) {
perror("fseek input file");
rval = -1;
break;
}
} while (0);
if (in) {
fclose(in);
in = NULL;
}
return rval;
}
打印
[stat]test_50Byte.bin file size = [50] Byte
[fstat]test_50Byte.bin file size = [50] Byte
[fseek]test_50Byte.bin file size = [50] Byte