Linux系统编程之获取文件大小的lseek和stat两种实现方法

今天写代码时用到sendfile函数,需要获取文件大小的功能。下面就用lseek和stat函数的两种方法来实现获取文件大小的功能吧。

#include <sys/types.h>
#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int stat(const char *pathname, struct stat *statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);

一、lseek函数实现

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void)
{
	int fd;
	long result;

	if((fd = open("netdev.c", O_RDONLY)) < 0)
	{
		perror("Open Error");
		exit(1);
	}

	if((result = (long)lseek(fd, 0, SEEK_END)) < 0)
	{
		perror("Lseek Error");
		exit(1);
	}

	printf("File size:\t%ld\n", result);

	return 0;
}

二、stat函数实现

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(void)
{
	int ret;
	long result;
	struct stat st;

	if((ret = stat("netdev.c", &st)) < 0)
	{
		perror("Stat Error");
		exit(1);
	}

	result = (long)st.st_size;
	printf("File size:\t%ld\n", result);

	return 0;
}

三、运行效果

[ycxie@fedora Workspace]$ ./lseek_demo
File size:	191
[ycxie@fedora Workspace]$ ./stat_demo
File size:	191
[ycxie@fedora Workspace]$ ls -l netdev.c
-rw-rw-r--. 1 ycxie ycxie 191 Apr 30 13:18 netdev.c

Leave a Reply

Your email address will not be published. Required fields are marked *