Chinaunix首页 | 论坛 | 博客
  • 博客访问: 50112
  • 博文数量: 31
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 23
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-01 11:00
文章分类
文章存档

2014年(24)

2013年(7)

我的朋友

分类: LINUX

2014-09-09 10:21:42

原文地址:用lseek计算文件长度 作者:kangear

lseek计算文件长度

作者:kangear

源代码:


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<sys/types.h>
  4. #include<sys/stat.h>
  5. #include<fcntl.h>
  6. #include<unistd.h>

  7. int main(int argc,char *argv[])
  8. {
  9.     int fd,length;
  10.     if(argc<2)
  11.     {
  12.        puts("Please input the open file pathname!\n");
  13.       exit(1);
  14.     }
  15.     
  16.     if((fd=open(argv[1],O_RDONLY))<0)
  17.     {
  18.      perror("Open file failure!");
  19.      exit(1);
  20.     }

  21.     if((length = lseek(fd,0,SEEK_END))<0)
  22.     {
  23.        perror("lseek file failure!");
  24.     }
  25.         
  26.     printf("The file's length is %d\n",length);
  27.     close(fd);
  28.     exit(0);
  29. }

 lseek源程序.rar   
 

说明:

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;我也理解了,做的时候却不一样,很是郁闷……

 

(下一步要解决 perrorfprintf的区别)

阅读(555) | 评论(0) | 转发(0) |
0

上一篇:gcc基础

下一篇:没有了

给主人留下些什么吧!~~