Search code examples
cfilefopenfgets

writing and reading from file


I've written the following snippet to write n random numbers to a file. After writing, I read from the file and store the numbers in an array. The problem I'm facing is that when I read from the file I get extra numbers.

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

int main(void)
{
    int limit,i=0;
    int numbers[100];
    char line[100];
    printf("Enter the number of random number to be generated(max 1000)");
    scanf("%d",&limit);
    FILE *fpi;
    fpi=fopen("input.txt","w");
    for(i=0;i<limit;i++)
    {
        fprintf(fpi,"%d\n",rand());
    }
    fclose(fpi);
    FILE *file;
    file = fopen("input.txt", "r");
    while(fgets(line, sizeof line, file)!=NULL)
    {
        numbers[i]=atoi(line);
        i++;
    }
    printf("%d\n\n",i);
    int totalNums = i;
    for (i=0 ; i<totalNums ; i++)
    {
        printf("%d\n",numbers[i]);
    }
    fclose(file);
    return 0;
}

If I give limit=3 and I write 3 numbers to the file, eg.47,18836,431. When I read from the file and print it I get 6 values out of which the first 3 are junk and the next 3 are the ones that were written.

If I comment out the writing part and just try to read from the file I get the correct output of only 3 numbers. So I think that there is some problem in my code that writes to the file part. Can someone help me out with it.


Solution

  • Reset i to 0 before reading from file. e.g.

    //your code before
    i=0; //reset i
    while(fgets(line, sizeof line, file)!=NULL) 
    {      
        numbers[i]=atoi(line); 
        i++;
    }
    //your code after