Linux下C语言实现获取指定目录下某个文件里面的数据

假如这个文件是在“/home/lls/APUE/ch2/tem/"这个目录下,以”28“开头命名的。
内容是
在这里插入图片描述
假如我们要获取2190这个数据。

下面就是代码

/*代码IO3.C的优化*/                                                                
  2 
  3 #include <stdio.h>
  4 #include <stdlib.h>
  5 #include <string.h>     
  6 #include <assert.h>
  7 #include <sys/types.h>
  8 #include <dirent.h>
  9 #include <string.h>
 10 #include <unistd.h>
 11 #include <fcntl.h>
 12 
 13 static char buff[512];
 14 static char distination_file[128];
 15 float gettemp(char *dirpath)
 16 {       
 17         int fd,data_size;
 18         //打开指定打目录dirpath
 19         DIR * dir = opendir(dirpath);
 20         struct dirent *direntp;
 21         assert(dir != NULL);
 22 
 23         //列出dir里面所以的文件夹和文件 
 24         while((direntp = readdir(dir)) !=NULL)
 25         {
 26                 //拿文件名的前俩位和28比较,如果有一个文件的名字前俩个字符是28,则返0             
 27                 if(strncmp(direntp->d_name,"28",2) == 0)
 28                 {
 29                         printf("find file:%s\n",direntp->d_name);
 30                         
 31                         //将dirpath和ent->d_name写入到fw_file这个字符数组中
 32                         sprintf(distination_file,"%s%s%s",dirpath,direntp->d_name,"    /w1_slave");
 33                         printf("要读取打目标文件是:%s\n",distination_file);
 34 
 35                         fd = open(distination_file, O_RDWR);
 36                         
 37                         //使文件偏移量移到文件尾,得到文件内容大小
 38                          data_size = lseek(fd, 0, SEEK_END);
 39 
 40                         //然后又使文件偏移量移到文件头,这样才能读文件的内容
 41                         lseek(fd, 0, SEEK_SET);
 42 
 43                         if(data_size=0)
 44                                 printf("这是个控文件\n");
 45                         read(fd,buff,sizeof(buff));
 46                         printf("读到的数据为:%s\n",buff);
 47                         
 48                         //strstr函数返回字符“t=”buff字符串中首次出现的地址
 49                         char *C = strstr(buff,"t=");
 50                         
 51 
 52                         //数据类型转换
 53                         float tem = atof((C+2))/100;
 54                         return (tem);
 55                 }
 56         }
 57         closedir(dir);
 58 }
 59 
 60 int main()      
 61 {
 62 
 63         char dirpath[200] ="/home/lls/APUE/ch2/tem/";
 64         float Tem = gettemp(dirpath);
 65 
 66         printf("Tem = %2.2f摄氏度\n",Tem);
 67         return 0;
 68 
 69 
 70 }                               

运行结果截图,这里我把2190转换为摄氏度了
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值