0

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;
}
  • You will want to look at [**Why is while ( !feof (file) ) always wrong?**](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – David C. Rankin May 30 '17 at 05:20

2 Answers2

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

Pras
  • 4,047
  • 10
  • 20
0

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;
}
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • Thx it also worked :) Apart from this, what changes can i do to write multiple records to my new file *fileptrOut? :( @david-c-rankin –  May 30 '17 at 08:53
  • You are reading `int` values from a file, so generally you will store the values you read in an array. (initialize `int n = 0; int arrray[500] = {0};` at the beginning of your code and then on each read of `value` it is `array[n++] = value;` Then you can write the array to your `fileptrOut`. You have to choose the format you wish to write (e.g. 1-value per-line, 10-values per-line, whatever...) Basically it is `for (int i = 0; i < n; i++) fprintf (fileptrOout, "%d\n", array[i]);` (or whatever format you want) You must make sure you don't store more than your array can hold `:)` – David C. Rankin May 30 '17 at 10:28