低级文件操作实例代码

01 #include <stdio.h>
02 #include <stdlib.h>
03 #include <fcntl.h>
04 #include <unistd.h>
05 #include <string.h>
06 #include <sys/types.h>
07   
08   
09 #define FILE_TXT "sf.txt"
10 #define FILE_BIN "sf.bin"
11   
12 typedef struct student
13 {
14  int id;
15  char name[16];
16  double score;
17 }student;
18   
19 int main(void)
20 {
21  int fd_txt, fd_bin;
22  int i, result, len;
23  long offset = 0;
24  student stu_txt[3], stu_bin[3];
25  char buf[64];
26     
27  //打开二进制文件进行读
28  fd_bin = open(FILE_BIN, O_RDONLY);
29  if(fd_bin<0)
30  {//文件打开失败
31   perror("open");
32   exit(-1);
33  }
34    
35  memset(stu_bin, 0, sizeof stu_bin); //清空数据
36  for(i=0; i<sizeof(stu_bin)/sizeof(stu_bin[0]); i++)
37  {
38   result = read(fd_bin, &stu_bin[i], sizeof(stu_bin[i]));
39   if(result != sizeof(stu_bin[i]))
40   {
41    printf("read error.");
42    break;
43   }
44  }
45  printf("binary file read result:\n");
46  for(i=0; i<sizeof(stu_bin)/sizeof(stu_bin[0]); i++)
47  {
48   printf("%d %s %f\n",
49    stu_bin[i].id,
50    stu_bin[i].name,
51    stu_bin[i].score);
52  }
53  close(fd_bin);
54    
55  //打开文本文件进行读
56  fd_txt = open(FILE_TXT, O_RDONLY);
57  if( fd_txt < 0)
58  {//文件打开失败
59   perror("open");
60   exit(-1);
61  }
62  memset(stu_txt, 0, sizeof(stu_txt));
63  offset = 0;
64  for(i=0; i<sizeof(stu_txt)/sizeof(stu_txt[0]); i++)
65  {
66   char * p;
67   memset(buf, 0, sizeof(buf));
68   result = pread(fd_txt, buf, sizeof(buf), offset);
69   if(result <= 0)
70    break;
71   sscanf(buf, "%d %s %lf",
72      &stu_txt[i].id,
73       stu_txt[i].name,
74      &stu_txt[i].score);
75     
76   p = strstr(buf, "\n");
77   if(p)
78    *p = 0;
79   offset += strlen(buf) + 1;
80  }
81  printf("text file read result:\n");
82  for(i=0; i<sizeof(stu_txt)/sizeof(stu_txt[0]); i++)
83  {
84   printf("%d %s %f\n",
85    stu_txt[i].id,
86    stu_txt[i].name,
87    stu_txt[i].score);
88  }
89  close(fd_txt);
90    
91  return 0;
92 }

posted @ 2011-09-19 09:20  auleaf  阅读(147)  评论(0编辑  收藏  举报