Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to extract data from a data file "test.dat" which contains some text as well. The file is as follows:

nx=200, ny=200
cow
1	2
5	6
4	9
2	0
3	8
goat
1	2
3	2
2	4



I have written the code as follows:


C
int A[10][10];
char buff[100];

FILE *in;
in=fopen("test.dat","r");

int i,j;

fgets(buff,100,in);
 fgets(buff,100,in);   

 for(i=1;i<=5;i++)
    {for(j=1;j<=2;j++)
        {fscanf(in,"%d",&A[i][j]);}}
        
      fgets(buff,100,in);   
      puts(buff);
    
for(i=6;i<=8;i++)
    {for(j=1;j<=2;j++)
        {
		  fscanf(in,"%d",&A[i][j]);
		}
	}	   
        fclose(in);

	
	
for (i=1;i<=8;i++)
    {
    for(j=1;j<=2;j++)
       {
           printf("%d\t",A[i][j]);
       }
           printf("\n");
    }


I get the following output:
1	2	
5	6	
4	9	
2	0	
3	8	
0	268501009	
0	2	
0	4200638	



The first five lines are ok, but the last 3 lines are junk. Please suggest what needs to be done.
Posted
Updated 29-Jul-15 3:05am
v2

1 solution

I would have written instead (warning, no error-checking performed):
C
 #include <stdio.h>
 #include <stdlib.h>

 #define BUFSIZE 100
 #define SIZE 10

int main()
{
  char buf[BUFSIZE];
  int a[SIZE][2];

  FILE * fp = fopen("test.dat", "r");

  int count = 0;
  while (fgets(buf, BUFSIZE, fp))
  {
    if (sscanf(buf, "%d %d", &a[count][0], &a[count][1]) == 2)
      count++;
  }

  int n;
  for (n=0; n<count; ++n)
  {
    printf("%d %d\n", a[n][0], a[n][1]);
  }

  fclose(fp);

  return 0;

}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900