944,026 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 8294
  • C++ RSS
Nov 5th, 2007
0

Read integers from a file

Expand Post »
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 <stdio.h>
#include <conio.h>

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<a)
{
fscanf(fp," %d ",x[i]);
printf ("%2d - %d\n",i,x[i]);
++i;
b=ftell(fp);
//printf("ftell = %d y = %d\n",b,a);
}
fclose(fp);


}

Output (which is wrong, which is obvious):

0 - 1735
1 - 11552
2 - 12576
3 - 13111
4 - 2613
5 - 12576
6 - 11552
7 - 12576
8 - 13617
9 - 12853
10 - 8202
11 - 8242
12 - 8237
13 - 12849

Please help.

Manish
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
mrb260478 is offline Offline
5 posts
since Aug 2004
Nov 5th, 2007
0

Re: Read integers from a file

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:
  1. #include <stdio.h>
  2.  
  3. int main ( void )
  4. {
  5. FILE *in;
  6. int list[50];
  7. int i;
  8.  
  9. in = fopen ( "file1.txt", "r" );
  10.  
  11. if ( in != NULL ) {
  12. for ( i = 0; i < 50; i++ ) {
  13. if ( fscanf ( in, "%d", list[i] ) != 1 )
  14. break;
  15. }
  16.  
  17. for ( j = 0; j < i; j++ )
  18. printf ( "%d - %d\n", j, list[j] );
  19.  
  20. fclose ( in );
  21. }
  22.  
  23. return 0;
  24. }
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).
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Operating Systems
Next Thread in C++ Forum Timeline: Need help reading a file





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC