I need to read a file and store at each time step each line (int) in a array of integers and then work in this array.
The input looks like this:
0 16 12
1 10 17
2 14 8
3 12 17 16
9 14 16 19 13 5
19 16 6 17 11 15 9 4 12 18 8
Then using something like this I can read and print each lines but I can not save each line in an array per time.
char matrix[500][500], space;
int numbers[500], i = 0, j;
int elementsA[10000];
FILE *fp = fopen("mygraph", "r");
int blabla[1000000];
int a;
while(!feof(fp))
{
fscanf(fp, "%d", &numbers[i]); // getting the number at the beggining
fscanf(fp, "%c", &space); // getting the empty space after the number
fgets(matrix[i++], 500, fp); //getting the string after a number
a ++;
}
for(j = 0; j < i; j++)
printf("%d %s %d\n", numbers[j], matrix[j]);
return(0);
}
Thanks everybody for helping me.
One possible approach uses these steps:
1) get a file pointer: FILE *fp = fopen("c:\\dir1\\file.txt", "r");
2) use fgets()
in two ways:
first to count number of lines in file, and get longest line (hint: count spaces for number of ints)
(with this information, you can create and allocate memory for a 2D int
array)
second restart from beginning to read one line at a time.
3) use strtok()
(or strtok_r()
) to parse each line into integers and place into your array
4) free all memory and exit.
Here is a way to get the information to allocate your arrays:
Give the input (each line must contain a \n, as this one does):
0 16 12
1 10 17
2 14 8
3 12 17 16
9 14 16 19 13 5
19 16 6 17 11 15 9 4 12 18 8
The following code will provide number of lines and highest number of ints/line in file,
Then create your array:
int GetParamsOfFile(char *path, int *numInts) ;
int main(void)
{
int lines;
int mostInts;
int **array=0;
lines = GetParamsOfFile("place your path here", &mostInts);
// rows columns (will correlate with rows and column of your file)
array = Create2D(array, lines, mostInts);//creates array with correct number of rows and columms;
//Here is where you would re-read your file, this time, populating your new array.
//I will leave this part to you...
free2DInt(array, mostInts);
return 0;
}
int GetParamsOfFile(char *path, int *numInts)
{
FILE *fp = fopen(path, "r");
int spaces=0, lines=0, sK=0;
char *line; //choose big here
char *buf;
line = malloc(1000);
line = fgets(line, 1000, fp);
while(line)
{
lines++;
spaces = 0;
buf = strtok(line, " ");
while(buf)
{
spaces++;
buf = strtok(NULL, " ");
}
(spaces > sK)?(sK = spaces):(sK==sK);
line = fgets(line, 1000, fp);
}
*numInts = sK;
fclose(fp);
free(line);
return lines;
}
int ** Create2D(int **arr, int rows, int cols)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<rows;y++)
{
arr[y] = calloc(cols, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int rows)
{
int i;
for(i=0;i<rows; i++)
if(arr[i]) free(arr[i]);
free(arr);
}