importing and exporting .txt FILE file in C

0

The algorithm should read from 1,000 to 15,000 real numbers, add all and perform a media, I did several import processes, and export the final result, but none copied.

#include <stdio.h>
int main(void)
{
int count,count_auxiliar;
float media;
float entrada[10]; 

/*
    FAZER IMPORTACAO NESTE MOMENTO
*/
//para coontador de 0 ate nenhuma entrada, contador recebe +1
for(count=0; count!=EOF; count++)
{
    // le entrada de arquivo
    scanf("%f",&entrada[count]);
    //contador auxiliar tem como funcao usar mesmo valor de contador mas sem alterar nada apenas para auxiliar no calculo da media
    count_auxiliar=count;

    // realiza media de arquivo de entrada
    media=entrada[count]+media;
    count_auxiliar--;
    media=media / count_auxiliar;
}

/*
    FAZER EXPORTACAO DE RESULTADO FINAL "MEDIA"
*/

return 0;
}

I will leave the code and comment where I need help, in case I import a TXT file, with N values read all and calculate a media, and give final result in another TXT file.

    
asked by anonymous 17.04.2017 / 17:35

1 answer

0

First, you are reading the numbers of the default entry ( stdin ), not a .txt file. Is that what you want to do?

Second, what you're doing with count is very weird. Why do you start at zero, increments each number, and waits for the number to be EOF (= -1)? To test if a stream is over, you use feof(FILE *) , in this case feof(stdin) .

Also passing &entrada[count] to scanf() causes it to write in parts in the array until it reads the 11th number when it writes out of array and scuttle your stack.

It is best to redo the whole program, with a function that receives the file open, reads all the numbers, and returns the average of them. For this, just a double to serve as an accumulator and a int to count the number of numbers read.

Then:

double
calcular_media(FILE * input) {
    double accum = 0.0, tmp = 0.0;
    int count = 0;

    while (!feof(input)) {
        if (fscanf(input, "%lf ", &tmp) < 1)
            exit(-1); // Se houve erro de leitura, quebre
        accum += tmp;
        count ++;
    }

    return accum / count;
}

The part of opening the input file, calling calcular_media() and writing the output file you can do, right?

    
17.04.2017 / 19:56