获取文件大小fseek、stat、fstat

#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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值