假如这个文件是在“/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转换为摄氏度了