简体   繁体   中英

C read data from one file and store calculations in another file

I'm a beginner to C language. Here I want to read data from file *fileptrIn and do some calculations, and store the answers in *fileptrOut. But I get a infinite loop with the first element in the file *fileptrIn. It prints only the first element in the file *fileptrIn repeatedly in the terminal. As I don't get any compilation errors, I'm unable to detect the error. Any suggestions to edit my code?

#include<stdio.h>

int main(void)
{
int value;
int total = 0;
int count = 0;

FILE *fileptrIn;

fileptrIn = fopen("input.txt", "r");

if(fileptrIn == NULL)
{
    printf("\nError opening for reading.\n");

    return -1;
}

printf("\nThe data:\n");

fscanf(fileptrIn, "%d", &value);

while(!feof(fileptrIn))
{
    printf("%d", value);

    total += value;

    ++count;
}

fclose(fileptrIn);

return 0;
}
while(!feof(fileptrIn))
{
    printf("%d", value);

    total += value;

    ++count;
}

You are not reading anything inside loop so the file pointer dont advance to reach EOF

In addition to the other answer, and continuing from my comment, you need to validate all input. You can accomplish this while removing the while (!feof(file)) problem as follows:

while (fscanf (fileptrIn, "%d", &value) == 1) {
    printf ("%d", value);
    total += value;
    ++count;
}

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