如何在c中操作输入文件中的数据?

时间:2018-03-25 18:41:00

标签: c io

我目前正在研究一些代码,这些代码旨在从输入文件中获取一些数据,找到平均值,然后将输出打印到单独的输出中。我不是在寻找一个完整的答案,只是一个提示。我知道我必须以某种方式存储数据以便操纵它,但我正在将数据作为字符串读取。 这是输入:

  

3 11 12 05 1 8.7

     

3 11 11 56 143 8.6

     

3 11 13 01 163 8.9

     

3 10 18 05 1 7.3

     

3 10 19 01 1 7.3

     

2 28 01 02 2 -1.0

     

2 28 09 07 2 -0.5

     

6 10 17 00 111 18.7

我们试图根据右边的倒数第二个数字找到右边最后一个数字的平均值。 这是我到目前为止所做的:

#include <stdio.h>
#include <ctype.h>

int main() {

    FILE* input_file = fopen("input_data.txt", "r");
        if (input_file == NULL){
            printf("something went wrong");
            return 1;
        }
    FILE* output_file = fopen("station_averages_summary.txt", "w");
        if (output_file == NULL){
            printf("something went wrong");
            return 1;
        }
    int month, day, hour, minute, station;
    float temp;
    char data[500];
    while((fgets(data, 500, input_file))!= NULL) {
        fscanf(input_file, "%d %d %d %d %d %f", &month, &day, &hour, &minute, &station, &temp);
        fprintf(output_file, "%d, %d, %d, %d, %d, %.2f\n", month, day, hour, minute, station, temp);

            }


    fclose(input_file);
    fclose(output_file);
    return 0;
}

这一切确实是将输入打印到输出文件中。

2 个答案:

答案 0 :(得分:0)

Can you elaborate a little more clear your question ? The calculation you want to do isn't clear for me.

But for what I understood, you already have the values read from the file, so just add the calculation after the fscanf line and before the fprintf. If you need all the values from the file, you have to read all the file and store the values read in an array, iterate through it, calculate what you need and then store in the output file.

答案 1 :(得分:0)

You can declare a struct to represent a line of the file:

struct entry {
    int month, day, hour, minute, station;
    float temp;
};

Then, you can declare an array of those structs. You will have to estimate the number of lines in the file.

struct entry input[500]

When you read the file, you can fill out the array:

size_t counter = 0;
while(fgets(data, 500, input_file != NULL)) {
    struct entry* current = input + counter;
    fscanf(input_file, "%d %d %d %d %d %f", &(current->month), &(current->day), &(current->hour), &(current->minute), &(current->station), &(current->temp));
    ++current;
}
int size = current;

Then, you can iterate over the array and calculate the average.