1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
int **array = NULL;
int nb_of_line = 0;
int nb_of_column = 0;
int column_nb = 0;
int line_nb=0;
//First pass of the file to calculate the number of line
while (!feof(fp))
{
int i = 0;
int j = 0;
int local_nb_of_column = 0;
end_of_line_found = 0;
while(end_of_line == 0)
{
//read a line or the 255 first characters
fgets(255,buff, fp);
//check if the line is something we want to keep
if(buff[0] == '*' || (buf[0] > '9' && buf[0] < '0'))
{
//discard line, comments line, or invalid number
continue;
}
//parse the row or the first 255 characters of it.
while(buff[i] != 0)
{
if(buf[i] == '\n')
{
end_of_line_found = 1;
break;
}
if(buff[i] >'9' && buff[i] < '0')
{
local_nb_of_column++;
}
i++;
}
}
nb_of_line ++;
if(local_nb_of_column > column_nb)
{
column_nb = local_nb_of_column;
}
}
//come back at the beginning of the file.
fseek(fp, 0, SEEK_SET);
//allocation of the array:
array = char(**)malloc(sizeof(char *) * nb_of_line);
for(i = 0; i < nb_of_line; i++)
{
array[i] = char(*)malloc(sizeof(char *) * nb_of_column);
}
//Second pass of the file to fill the array
while (!feof(fp))
{
int i = 0;
int j = 0;
end_of_line_found = 0;
char buff[255];
char current_buff[10];
while(end_of_line == 0)
{
//read a line or the 255 first characters
fgets(255,buff, fp);
//check if the line is something we want to keep
if(buff[0] == '*' || (buf[0] > '9' && buf[0] < '0'))
{
//discard line, comments line, or invalid number
continue;
}
//parse the row or the first 255 characters of it.
while(buff[i] != 0)
{
if(buf[i] == '\n')
{
end_of_line_found = 1;
break;
}
if(buff[i] >'9' && buff[i] < '0')
{
//In case the next char is not a number, we consider it as a separator
current_buff[j++] = 0;
//convert the string in integer
array[line_nb][column_nb++] = atoi(current_buff);
j = 0;
}
else
{
current_buffer[j++] = buff[i];
}
i++;
}
}
line_nb ++;
column_nb = 0;
}
nb_total=i; |
Partager