低级文件输入输出计算"总和"和"平均"

时间:2015-12-09 17:09:59

标签: c

这是我的代码

#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>

#define BUFFERSIZE 512
int main()
{
        int infd;
        int bytes;
        int i;
        int outfd;
        char buffer[BUFFERSIZE];

        if((infd = open("input.txt", O_RDONLY)) <0)
        {
                perror("Can't open file d11-9.in");
        }
        if((outfd = open("output.txt", O_CREAT|O_WRONLY, S_IWRITE))<0)
        {
                printf("Can\t open file output.txt");
        }

        while((bytes = read (infd, buffer, BUFFERSIZE))>0)
        {
                for(i=0;i<bytes; ++i)
                {
                        putchar(buffer[i]);
                }
                write(outfd, buffer, bytes);
        }
        close(infd); 
        close(outfd);
        return 0;
}      

这是input.txt

ID              UNIX    C Language      Network
20150001        98      95              97
20150002        84      88              90

这是output.txt

ID              UNIX    C Language      Networ  sum     average
20150001        98      95              97      290     96
20150002        84      88              90      262     84

我想编写读取input.txt并计算总和和平均值!! 像output.txt一样制作

我不知道如何编码 请帮我一把!!

1 个答案:

答案 0 :(得分:1)

函数read()write()及其表兄弟用于二进制文件。使用fgets()并分析每一行的内容,然后使用您计算的额外字段输出该行,读取文本文件会更好。请注意fgets()保留任何newline,必须在将文字附加到该行之前将其删除。

#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;
}

输出文件:

ID              UNIX    C Language      Network sum     average
20150001        98      95              97      290     96 
20150002        84      88              90      262     87 

顺便说一句,你的平均值在最后一行是不正确的!