C语言文件求和追加到末尾
需求描述:从文件中读取数据,求和之后添加到文件的末尾
#include<stdio.h>
//任务:从文件中读取数据,求和之后添加到文件的末尾
void SumFromFile(char *filename){
FILE *fp;
if((fp = fopen(filename,"a+")) == NULL){
printf("fail to open");
exit(0);
}
//以追加和读取的形式进行操作
float num1,sum = 0.0;
char tmp;
while(!feof(fp)){
char num[20];
//数字数组用来储存数字
int index = 0;
//当文件非空
tmp = fgetc(fp);
while(isdigit(tmp) || tmp == '.'){
//printf("111");
//当tmp为数字或者小数点
num[index++] = tmp;
//printf("%111c",tmp);
tmp = fgetc(fp);
}
num[index] = '\0';
//储存结果
num1 = atof(num);
printf("num:%4f\n",num1);
sum+=num1;
}
printf("sum:%4f",sum);
printf("\n写入到文件末尾\n");
fseek(fp,-0L,SEEK_END);
fputchar(' ');
char result[20];
sprintf(result,"%4f",sum);
fputs(result,fp);
fclose(fp);
}
int main()
{
SumFromFile("data.txt");
return 0;
}