且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从带有文本的文件中读取数据

更新时间:2023-02-19 21:22:46

我会写的(警告,没有执行错误检查):

  #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 ;

}


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:


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.

I would have written instead (warning, no error-checking performed):
 #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;

}