Functions read()
and write()
and their cousins are used for binary files. Reading a text file would be better using fgets()
and analysing the contents of each line, then outputting that line with the extra fields you calculate. Bear in mind that fgets()
retains any newline
, which has to be removed before appending text to that line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LLEN 100
int main(void)
{
FILE *inf, *outf;
int val1, val2, val3, sum;
char buff[LLEN];
if((inf = fopen("input.txt", "rt")) == NULL) {
perror("Can't open file input.txt");
exit(1);
}
if((outf = fopen("output.txt", "wt")) == NULL) {
perror("Can\t open file output.txt");
exit(1);
}
if(fgets(buff, LLEN, inf) == NULL) { // read the header
perror("Cannot read header line");
exit(1);
}
buff [ strcspn(buff, "\r\n") ] = '\0'; // truncate any newline
fprintf(outf, "%s sum average\n", buff); // write expanded header line
while(fgets(buff, LLEN, inf) != NULL) { // read each line
buff [ strcspn(buff, "\r\n") ] = '\0'; // truncate any newline
if(sscanf(buff, "%*s%d%d%d", &val1, &val2, &val3) != 3) { // ignore ID
perror("Cannot convert fields");
exit(1);
}
sum = val1 + val2 + val3;
fprintf(outf, "%s%9d%7d \n", buff, sum, sum/3);
}
if (fclose(outf))
perror("Unable to close output file");
fclose(inf);
return 0;
}
Output file:
ID UNIX C Language Network sum average
20150001 98 95 97 290 96
20150002 84 88 90 262 87
Incidentally your average was incorrect on the last line!
4
solved low level file input output calculate “sum” and “average” [closed]