简体   繁体   中英

How to read numbers from file and save the mean of them into the same file?

I have a txt file with two columns:

1 2
3 4
5 6
7 8

I would like to read those numbers, calculate the mean and save the result into the third column in the same file. I opened my file for update "r+" but it seem not to work. Reading is fine but when I add the third column something wrong is happening with the file ... It seems that its being rewritten, theres no original content in it when I call my fun - after the first loop instruction. Any ideas?

#include <stdio.h>
#include <stdlib.h>

void fun(const char *filename)
{
    double num1 = 0, num2 = 0, num3 = 0;
    FILE *f;
    if((f = fopen(filename, "r+")) == NULL)
    {
        exit(-1);
    }

    while(fscanf(f, "%lf %lf", &num1, &num2) != EOF)
    {
        //printf("num1 = %.2f, num2 = %.2f\n", num1, num2);
        num3 = num1 + num2;
        fprintf(f, "%lf %lf %lf\n", num1, num2, num3/2.0);
    }

    fclose(f);
}

int main(int argc, char **argv)
{
    fun("numbers.txt");

    return 0;
}

When my program ends execution, I would like to have in my txt file 3 columns:

1 2 1.5
3 4 3.5
5 6 5.5
7 8 7.5

Tried also this but my program just hangs out:

#include <stdio.h>
#include <stdlib.h>

void fun(const char *filename)
{
    double num1 = 0, num2 = 0, num3 = 0;\

    FILE *f;
    if((f = fopen(filename, "r+")) == NULL)
    {
        exit(-1);
    }

    int write_at = 0, read_at = 0;

    while(fscanf(f, "%lf %lf", &num1, &num2) != EOF)
    {
        read_at = ftell(f);
        fseek(f, write_at, SEEK_SET);
        num3 = num1 + num2;
        fprintf(f, "%lf %lf %lf\n", num1, num2, num3/2.0);
        write_at = ftell(f);
        fseek(f, read_at, SEEK_SET);
    }

    fclose(f);
}

int main(int argc, char **argv)
{
    fun("numbers.txt");
    return 0;
 }

Open a temporary file and save the results there. Upon successful completion of reading the entire "numbers.txt" and writing the temp file, delete the original and rename the temp.

With file processing, this has the nice advantage that if the process fails in some fashion (IO error, data format error, etc.) the original is still intact. Fairly common with editors.

Another approach is to store the "new" file in memory and write it out at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM