954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read integers from a file

Can some one help me to :

How to Read integers stored in a text file in the following format :

26 52 23 41 19 61 54 4 19 95 84 25 55 22
(integers delimted by a space.)

to be used for sorting later.

Have tried following code:

#include
#include

void main()
{
FILE *fp;
int *x,i=0;
int a,b;

fp=fopen("file1.txt","r");
if (fp==NULL)
{
printf("File Cannot be opened.\n");
}
fseek(fp,0L,2);
a=ftell(fp);
rewind(fp);
fseek(fp,+1,0);
b=ftell(fp);
while (b

mrb260478
Newbie Poster
5 posts since Aug 2004
Reputation Points: 10
Solved Threads: 0
 

Rule 1) A pointer isn't an array. Just because you say int *x doesn't mean you can immediately use x as if it were an array. You need to allocate memory to it first.

Rule 2) main returns int.

Rule 3) Don't try to use the file positioning functions until you actually know what you're doing. Just read from the file and everything will work.

It's really as simple as this:

#include <stdio.h>

int main ( void )
{
  FILE *in;
  int list[50];
  int i;

  in = fopen ( "file1.txt", "r" );

  if ( in != NULL ) {
    for ( i = 0; i < 50; i++ ) {
      if ( fscanf ( in, "%d", list[i] ) != 1 )
        break;
    }

    for ( j = 0; j < i; j++ )
      printf ( "%d - %d\n", j, list[j] );

    fclose ( in );
  }

  return 0;
}

If you want the list to grow indefinitely to meet the contents of the file, you have no choice but to allocate and resize the memory for a pointer manually (assuming you really are using C even though you posted in the C++ forum).

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You