A large number of regular data for a. txt document, such as 100 rows and 8 columns of data, reads it into a two-dimensional array (matrix) and leaves it for subsequent data processing.
The program uses a macro-defined method to determine the number of rows and columns that will be read by the program, reading the data into a two-dimensional array data[100][8].
Also add a test function read (), the function is to obtain a TXT document a large number of data lines, the project is to be used.
The procedure is as follows:
#include <stdio.h>
#include <stdlib.h>
/*
In order to read a specific number of rows later, a macro-defined method is used to determine the number of rows
Read () reads the number of rows in the file and can use the return value to make a global variable when the number of unknown file rows
*/
#define N 115//Line
#define L 8//Column
const CHARfile_name[50] = "D:\\dat.txt";
void Read (FILE *fp)
{int row=0;
char mid;
while (!feof (FP))
{
MID=FGETC (FP); Read a word from TXT text assigned value to mid
if (mid== ' \ n ') If this character is a line break
row++; Record the number of TXT data rows
}
row++; Last line does not have a newline character
printf ("Number of rows is%d\n", row);
Rewind (FP); Back to file start location
}
int main (int argc, char *argv[])
{
FILE *FP;
Double Data[n][l] = {0.0}; Two-dimensional arrays
int Index[n] = {0};Two-dimensional array row subscript
Double temp;
int I, J;
int count = 0; Counter, which records the floating-point numbers that have been read out
if ((Fp=fopen (file_name, "rb") = = = NULL) {
printf ("Please confirm file (%s) exists!\n", file_name);
Exit (1);
}
Read (FP); Number of rows Read
while (1==FSCANF (FP, "%le", &temp))//lf,le all can be, but nothing else,%e not
{
data[(index[count%l]) ++][count%l] = temp;
count++;
}
Fclose (FP); Close handle
/****** Processing Data ****************/
for (i=0;i<n;i++)
{ printf ("line%d data: \ n", i+1);
for (j=0;j<l;j++)
{
printf ("%5.3le", Data[i][j]);//.16f can be displayed by scientific notation when LE
}
printf ("\ n");
}
return 0;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C language reads large amounts of data into an array of files