I'm trying to read numbers from a file. The file has the following format:
2 4 5 7
3 2 4 7
I tried to do that using fscanf
to collect all the numbers up to the newline and store the number in an array and the same with the second line. But proceed directly from the second line does not start again and store this in another array. Is it possible to do this using fscanf
?
int main(void)
{
FILE* fp;
int *vec = malloc(sizeof(int)*6);
int *vec_2 = malloc(sizeof(int)*6);
int row, i;
fp = fopen("vector.txt","r");
for(i = 0; i < row; i++) //I don't know how to read until newline
fscanf(fp, "%d", &vec[k]); //here store the first row in the array
for(i = 0; i < row; i++)
fscanf(fp, "%d", &vec_2[i]); //start reading here from the second row
free(vec);
free(vec_2);
return 0;
}
row has to be initialized to 6 and possibly col too, you may use the following using two-dimensional array.
Anytime data is stored in lines, best to consider
fgets()
.This solution adapts to N rows and user selectable column width