File handling in c

1.2k views Asked by At

I made a simple program to read the no of values and then, those values from file and storing them in an array and print the values of array.

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

void main(){
    int i=0,j=0,n,no[n];
    FILE *fp=fopen("input.txt","r");
    if(fp==NULL)
        printf("File input error\n");
    else{
        fscanf(fp,"%d",&n);
        *no=(int *)malloc(n*sizeof(int));
        while(i<n){
            fscanf(fp,"%d",&no[i]);
            printf("%d\t",no[i]);
            i++;
        }
    }
}

My input file was as follows

10 37 21 55 52 68 97 02 00 103 84

and the output I got is

37 21 55 52 68 97 2 0

Why do I see this output?

2

There are 2 answers

0
Tlacenka On

In your code, you are trying to read n elements without checking for EOF. You should add a condition comparing fscanf with number of scanned elements (in this case 1) and therefore avoid reaching EOF unknowingly.

5
R Sahu On

The line

    *no=(int *)malloc(n*sizeof(int));

is not right. I am surprised your compiler didn't warn you.

*no is of type int. You are assigning a pointer to an int.

Using gcc, I get the following warning.

soc.c: In function ‘main’:
soc.c:11:12: warning: assignment makes integer from pointer without a cast
         *no=(int *)malloc(n*sizeof(int));

Also, the line

int i=0,j=0,n,no[n];

is not correct. n is not initialized before being used to define no.

Here's an updated version of your program that should work.

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

void main(){
   int i=0,j=0,n;
   int* no;
   FILE *fp=fopen("input.txt","r");
   if(fp==NULL)
      printf("File input error\n");
   else{
      if ( fscanf(fp,"%d",&n) == 1 )
      {
         no = malloc(n*sizeof(int));
         while(i<n){
            if ( fscanf(fp,"%d", &no[i]) == 1 )
            {
               printf("%d\t",no[i]);
            }
            else
            {
               // Unable to read the number.
               // Get out of the loop.
               break;
            }
            i++;
         }
      }
      else
      {
         // Unable to read n.
         // Print some message to indicate the error
      }
   }
}