linux下c语言 读取文件

    转自: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

结果为:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值