import and export file . txt FILE in C

Asked

Viewed 137 times

0

The algorithm should read from 1000 to 15000 ( 1 thousand to 15 thousand) real numbers, sum all and carry out a average, I made several import processes, and final result export, 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 import a TXT file, with N values read all and calculate a media, and give end result in another TXT file.

1 answer

0

First, you are reading the default input numbers (stdin), not from a.txt file. That’s exactly what you want to do?

Second, what are you doing with count is very weird. Why you start at zero, increment each number, and wait for the number to be EOF(= -1)? To test whether a stream finished, you use feof(FILE *), in this case feof(stdin).

Also pass &entrada[count] to the scanf() causes him to write in parts in array until he reads the 11th number, when he writes off the array and sacks his pile.

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

So:

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 to open the input file, call calcular_media() and write the output file you can do, right?

  • In fact I do not know much programming, so what can help me I appreciate, if possible send your Whatsapp there that is easier! then I’ll explain everything in detail!

  • @Agenaro: I don’t mind sending my Whatsapp, but the ideal was that we could resolve as many of your doubts here on website so that this can help others who later find this question and have the same doubts as you...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.