linux 使用lseek函数来获取文件大小
来源:互联网 发布:mac无法存储屏幕快照 编辑:程序博客网 时间:2024/06/05 14:33
一、获取文件大小
/*测得文件大小*/ int filelen;int fd;
int filelen= lseek(fd,0L,SEEK_END); lseek(fd,0L,SEEK_SET); printf("file size is %d\n",filelen);
二、lseek使用说明
表头文件
#include<sys/types.h>
#include<unistd.h>
定义函数
off_t lseek(int filde,off_t offset ,int whence);
EEK_SET 将读写位置指向文件头后再增加offset个位移量。
SEEK_CUR 以目前的读写位置往后增加offset个位移量。
SEEK_END 将读写位置指向文件尾后再增加offset个位移量。
当whence 值为SEEK_CUR 或SEEK_END时,参数offet允许负值的出现。
下列是较特别的使用方式:
1) 欲将读写位置移到文件开头时:
lseek(int fildes,0,SEEK_SET);
2) 欲将读写位置移到文件尾时:
lseek(int fildes,0,SEEK_END);
3) 想要取得目前文件位置时:
lseek(int fildes,0,SEEK_CUR);
返回值
当调用成功时则返回目前的读写位置,也就是距离文件开头多少个字节。若有错误则返回-1,errno 会存放错误代码。
可能设置erron的错误代码:
EBADF: fildes不是一个打开的文件描述符。
ESPIPE:文件描述符被分配到一个管道、套接字或FIFO。
EINVAL:whence取值不当。
代码列子:
#define BUFFER_SIZE 1024int main(int argc,char **argv) { int readfd, writefd; long filelen=0; int ret=1; char buffer[BUFFER_SIZE]; char *ptr; /*打开源文件*/ if((readfd=open("test.txt", O_RDONLY|O_CREAT)) == -1) { printf("Open Error\n"); exit(1); } /*创建目的文件*/ if((writefd=open("dest.txt", O_WRONLY|O_CREAT)) == -1) { printf("Open Error\n"); exit(1); } /*测得文件大小*/ filelen= lseek(readfd,0L,SEEK_END); lseek(readfd,0L,SEEK_SET); printf("read file size is %d\n",filelen); /*进行文件拷贝*/ while(ret) { ret= read(readfd, buffer, BUFFER_SIZE); if(ret==-1) { printf("read Error\n"); exit(1); } write(writefd, buffer, ret); filelen-=ret; bzero(buffer,BUFFER_SIZE); } close(readfd); close(writefd); exit(0); }
阅读全文
0 0
- linux 使用lseek函数来获取文件大小
- Linux 通过lseek()来实现文件大小的设置
- Linux 通过lseek()来实现文件大小的设置
- Linux 通过lseek()来实现文件大小的设置
- Linux 通过lseek()来实现文件大小的设置
- linux lseek函数使用感受
- Linux 获取文件大小--C函数
- Linux 获取文件大小--C函数
- linux获取文件大小的函数
- Linux 获取文件大小--C函数
- Linux ---lseek() 函数
- linux文件函数-lseek
- Linux ---lseek() 函数
- Linux ---lseek() 函数
- Linux---lseek函数
- Linux下获取文件大小,检索目录函数
- Linux下获取文件大小,检索目录函数
- 【Linux】使用read、write、lseek函数实现文件读写操作
- JAVA使用ScriptEngine 解析脚本
- 安卓开发——为动态添加的EditText加载xml文档属性
- c++ 段错误 (core dumped )原因分析
- [入门]android概述
- 关于warning C4995的屏蔽问题
- linux 使用lseek函数来获取文件大小
- 动态创建dw的时候运行失败及列名选择
- java 两个字符串连接程序
- spring DI四种依赖注入方式
- Object类的理解
- 理解RAID
- DBCP2使用jtds中出现AbstratMethodError的问题
- <s:checkbox id="doSele" name="tags" value="true" 的 fieldValue= 取值问题
- Self powers Problem 48