It is obvious you need a bit of help. Here is an example that is only 1 way of many to do this. Note: instead of complicating the example reading a variable number of elements in B
, it is simply coded to read 4
elements as they exist in the data file. Also, fscanf
is used to read from the file since you have a variable number and differing data to read in each line. This simplifies the code compared to reading the file character by character since the type of information read is int
. Read through the example (comments inline) and let me know if you have questions:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv) {
int *A, *B, *C, m, n, p; /* note *C is unused */
char *file;
/* test for required filename */
if (argc < 2) {
fprintf (stderr, "\n Error: insufficient input. usage: %s filename\n\n", argv[0]);
return 1;
}
/* assign filename, open file, validate opening */
file = argv[1]; /* you don't need 'file', you can simply use argv[1] */
FILE *fp = fopen (file, "r");
if (!fp) {
fprintf (stderr, "\n Error: file open failed for file '%s'\n\n", argv[0]);
return 1;
}
/* read & output m, n, p */
fscanf (fp, "%d\n%d\n%d\n", &m, &n, &p);
printf ("\n m: %d\n n: %d\n p: %d\n\n", m, n, p);
/* allocate memory for A and set values to null */
A = calloc (m * 2, sizeof(int));
/* read A */
int i = 0;
for (i = 0; i < m; i++)
fscanf (fp, "%d %d\n", &A [i*2], &A[i*2 + 1]);
/* output A */
printf ("Array A\n");
for (i = 0; i < m; i++)
printf (" [ %d %d ]\n", A [i*2], A[i*2 + 1]);
/* allocate memory for B and set values null */
B = calloc (n * p, sizeof(int));
/* read B */
for (i = 0; i < n; i++)
fscanf (fp, "%d %d %d %d\n", &B [i*p], &B[i*p + 1], &B[i*p + 2], &B[i*p + 3]);
/* output B */
printf ("\nArray B\n");
for (i = 0; i < n; i++)
printf (" [ %2d %2d %2d %2d ]\n", B [i*p], B[i*p + 1], B[i*p + 2], B[i*p + 3]);
printf ("\n");
/* close FP & free allocated memory */
fclose (fp);
if (A) free (A);
if (B) free (B);
return 0;
}
output:
$ ./bin/rmf dat/array.dat
m: 3
n: 2
p: 4
Array A
[ 1 2 ]
[ 3 4 ]
[ 5 6 ]
Array B
[ 7 8 9 10 ]
[ 11 12 13 14 ]
m
,n
andp
? – SleuthEyeint **
parameters? What layout are you planning to use for the arrays? Are they going to be 2D arrays or 1D arrays that you index appropriately? (It matters because if they're to be 2D arrays, you needint ***
parameters, most probably.) – Jonathan Leffler