用lseek计算文件长度
作者:kangear
源代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include<sys/types.h>
- #include<sys/stat.h>
- #include<fcntl.h>
- #include<unistd.h>
- int main(int argc,char *argv[])
- {
- int fd,length;
- if(argc<2)
- {
- puts("Please input the open file pathname!\n");
- exit(1);
- }
-
- if((fd=open(argv[1],O_RDONLY))<0)
- {
- perror("Open file failure!");
- exit(1);
- }
- if((length = lseek(fd,0,SEEK_END))<0)
- {
- perror("lseek file failure!");
- }
-
- printf("The file's length is %d\n",length);
- close(fd);
- exit(0);
- }
说明:
fd所指文件: s1
s1内容为 : 1234567890
源代码 : lseek.c
编译好 : lseek
截图
运行成功时:
不输入s1时:(pathname)
删除s1之后运行:
不知道如何让lseek失败,所以没有进行lseek失败测试:
(空)
程序的第23行为功能实现函数。
附上lseek用法:
#include
off_t lseek (int filedes, off_t offset, int whence);
返回值:若成功则放回新的文件偏移量,若出错则返回-1
疑惑的是:计算结果比实际多一位,这个问题和好解决的但是就是把offse变为1,但是老师讲的是0;我也理解了,做的时候却不一样,很是郁闷……
(下一步要解决 perror与fprintf的区别)