将文件中的数据求和并写入文件末尾c语言
时间: 2024-03-10 16:46:35 浏览: 107
可以按照以下步骤实现将文件中的数据求和并写入文件末尾:
1. 打开文件并读取数据,将数据累加求和。
```c
FILE *fp;
float sum = 0;
float num;
fp = fopen("filename.txt", "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
while (fscanf(fp, "%f", &num) == 1) {
sum += num;
}
```
2. 关闭文件,并重新打开文件以追加数据。
```c
fclose(fp);
fp = fopen("filename.txt", "a");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
```
3. 将求和结果写入文件末尾。
```c
fprintf(fp, "Sum: %.2f\n", sum);
fclose(fp);
```
完整代码如下:
```c
#include <stdio.h>
int main() {
FILE *fp;
float sum = 0;
float num;
fp = fopen("filename.txt", "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
while (fscanf(fp, "%f", &num) == 1) {
sum += num;
}
fclose(fp);
fp = fopen("filename.txt", "a");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
fprintf(fp, "Sum: %.2f\n", sum);
fclose(fp);
return 0;
}
```
阅读全文