linux下c语言 读取文件

      linux读取文件要用到stdio.h文件,在/usr/include下包含大部分的C头文件,sys/types.h也位于其中,/usr/src/linu-版本号 存放有你的内核源代码。

在linux下读文件也是fopen("文件名","方式"),方式有r,w等,下面为一段读文件的代码(cat 7_3.c)

1 #include <sys/types.h>
2 #include <stdio.h>
3
4  int main(void)
5 {
6 float value,total[10];
7 int count,label;
8 FILE *fp;
9
10 for (count=0;count<10;count++)
11 total[count]=0;
12
13 if (!(fp=fopen("test.dat","r")))
14 {
15 printf("Error in open file!\n");
16 exit(1);
17 }
18
19 while (fscanf(fp,"%d %f",&label,&value))
20 {
21 total[label]+=value;
22 if (feof(fp))
23 {
24 break;
25 }
26 }
27
28 for (count=0;count<10;count++)
29 {
30 printf("%d: %f\n",count,total[count]);
31 }
32 return 0;
33 }

编译

$ gcc -Wall -o 7_3 7_3.c

test.dat文件为

$ cat test.dat

结果为:

原文地址:https://www.cnblogs.com/djcsch2001/p/2048140.html