The C language reads data into an array line by line from an txt file

  • 2020-05-10 18:33:57
  • OfStack

First, you need to know how the data is stored.


65 2
722 542
691 514
644 506
588 524
565 558
608 580
648 586
696 572
482 564

Line 1 represents the number of Numbers and dimensions, so read in the information first:


<span style="white-space:pre">	</span>FILE *fp = fopen("2D_Jesscia_keypos.txt", "r");
	if ( !fp ) 
	{
		fprintf( stderr, "! Error: faild to open keypos file \n" );
		return -1;
	}
	fscanf(fp, "%d %d%c", &in.numberofpoints, &dim, &ne);

In this way, the number information is obtained, which is convenient to dynamically allocate memory, and then the data can be read in line by line:


<span style="white-space:pre">	</span>in.pointlist = (REAL *) malloc( in.numberofpoints * 2 * sizeof(REAL) );
	char buf[1024];
	char pt1, pt2;
	for (i = 0; i < in.numberofpoints; i++)
	{
		if (!feof(fp))
		{
			if (fgets(buf, 1024, fp) == NULL)
				break;
			sscanf(buf, "%s %s\n", &pt1, &pt2);
			in.pointlist[2 * i] = atoi(&pt1);
			in.pointlist[2 * i + 1] = atoi(&pt2);		
		}
	}

Note that you are now reading each line into buf, which is of string type, and then using sscanf to read the contents to pt1 and pt2, and using the atoi function to get the value of the data type.


Related articles: