需要在 C 中使用 rewind() 处理文件的帮助

问题描述 投票:0回答:1

这是我的代码:

#include <stdio.h>

void correctNumbers(FILE* input, FILE* output) {
    int year, month, day;
    int amount;

    while (fscanf(input, "%d-%d-%d,%d", &year, &month, &day, &amount) == 4) {

        if (amount < 0) {
            amount = 0;
        }

        fprintf(output, "%d-%d-%d,%d\n", year, month, day, amount);
    }
}

double averageValue(FILE* output){
    double sum = 0; 
    double total = 0;
    int year, month, day, amount;
    
    /*fclose(output);
    output = fopen("corrected.txt", "r");*/
 
    while(fscanf(output, "%d-%d-%d,%d", &year, &month, &day, &amount) == 4){
        total++;
        sum += amount;
    }
    printf("Average value: %.2lf\n", sum/total);
    return sum/total;
}

void maxVisit(FILE* output) {
    int year, month, day, amount;
    int maxDay;  
    int maxVisitors = -1; 
    
    /*fclose(output);
    output = fopen("korrigiert.txt", "r");*/

    while (fscanf(output, "%d-%d-%d,%d", &year, &month, &day, &amount) == 4) {
        if (amount >= maxVisitors) {
           
            maxDay = day;
            maxVisitors = amount;
        }
    }
    printf("Day with the highest amount of visitors: %d\n", maxDay);
}


int main(int argc, char* argv[]){
    FILE* input;
    FILE* output;

    if(argc < 2){
        printf("Pls include a filename\n");
        return 0;
    }else{
        input = fopen(argv[1], "r");
        output = fopen("corrected.txt", "w");
        if(input == NULL || output == NULL){
            printf("File doesnt exist or failed to open\n");
            return 0;
        }
    }

    correctNumbers(input, output);
    rewind(output);
    averageValue(output);
    rewind(output);
    maxVisit(output);

    fclose(input);
    fclose(output);

    return 0;
}

每个功能应该做什么:

correctNumbers = corrects the negative numbers in a given file to 0 and write them in a new file called "corrected.txt" 
averageValue = calculates the averageValue of the visitors (the last number in the given file on each date) in corrected.txt.
maxVisit = calculates the day that had the highest amounts of visitors in corrected.txt.
main = give the main function a file that needs to be corrected. Do correction, averagevalue, maxvisitor. Close the files.

所有功能都在做它们应该做的事情。

给定的文件如下所示:(最后一个数字是访问者数量)

2021-10-05,-3
2021-10-06,-2
2022-02-02,7
2022-02-03,10
2022-02-04,9

更正后的文件将如下所示:

2021-10-5,0
2021-10-6,0
2022-2-2,7
2022-2-3,10
2022-2-4,9

如果程序运行,它将输出:

Average value: 4.50
Day with the highest amount of visitors: 3

现在的代码方式我明白了:

Average value: -nan
Day with the highest amount of visitors: 0

我在行之间放置了一些 printf 命令,发现如果我像这样使用 rewind() ,那么 while 循环不起作用。

但是对于一个任务,我必须在主函数中使用 rewind() 。谁能帮我做对吗?

现在我的问题是我发送这个程序的方式不起作用,因为我对 rewind() 的使用在某种程度上是错误的,这是我的猜测,但我不明白为什么。因为如果我启用放入函数 AverageValue 和 maxVisitor 中的注释并禁用 rewind() 行,则程序可以完美运行

c function file rewind
1个回答
0
投票

@Weather Vane 哦哇,用

w+
打开文件解决了问题!我需要对
w+ and r+
进行研究,看看到底有什么不同。非常感谢你

© www.soinside.com 2019 - 2024. All rights reserved.