Reading integer input from a text file in C

Feroz Ahmad bio photo By Feroz Ahmad Comment
I'm writing this post so that it comes handy whenever I will need this in future. Many times you need to read from a text file in order to take numeric inputs for problems. I have used the function fscanf().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <stdlib.h>
int main()
{
	FILE *textfile=fopen("IntegerArray.txt","r");
	int arr[100050],i,lim,num;
	if (textfile == NULL)
    {
        printf("Error Reading File\n");
        exit (0);
    }
    i=0;
	while(fscanf(textfile, "%d", &num) >0 )
	{
		arr[i++]=num;
	}
    lim=i;
    printf("\n Lim : %d \n",lim);
    for (i = 0; i < lim; i++)
    {
           printf("%d : %d\n",i, arr[i]);
    }
    fclose(textfile);
    return 0;
}
comments powered by Disqus