您的位置:首页 > 运维架构 > Linux

linux下c语言 读取文件

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

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

#include <sys/types.h>
#include <stdio.h>

int main(void)
{
float value,total[10];
int count,label;
FILE *fp;

for (count=0;count<10;count++)
total[count]=0;

if (!(fp=fopen("test.dat","r")))
{
printf("Error in open file!\n");
exit(1);
}

while (fscanf(fp,"%d %f",&label,&value))
{
total[label]+=value;
if (feof(fp))
{
break;
}
}

for (count=0;count<10;count++)
{
printf("%d: %f\n",count,total[count]);
}
return 0;
}


编译

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

test.dat文件为

$ cat test.dat



结果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: