I was thinking of reading some data from a file and perform calculation on it. The job has been broken down as follow:
1. welcome message and ask for input filename
2. read header from file that tells the size of the upcoming 2d array in the input file
3. dynamically allocate a 2d array
4.1 reading the remainder of the file in a do loop, line by line
4.2 parse the line, break down the value and insert into each element of the array defined earlier
5. ask for further parameters
7. result output
the file will look something like this, where the first line states the size of the array the program need to deal with.
1.0, 2.0, 3.0
4.0, 5.0, 6.0
7.0, 8.0, 9.0
while I have no problem with 1, 2, 5, 6 and 7, 3 to 4 seems to pose some trouble for me, especially 4.
I been successful in dynamically allocating 1d array using runtime input, so thats fine. I have read that 2d array is just a nested allocation, so I guess that will also be fine (will just have to try it).
The thing I really stumble on is the parsing of the file. Parsing that I have came across usually involves fgets() and strtok(), embarassingly I seem not to be able to understand the long code others have written. However I am wondering as why there wasn't a more "high level" way.
Surely as the designer of the program, I have already predefined the input format, easiest thing to do will be fscanf("%format%", fp). because I have defined the input format (all float numbers), if I am able to produce a format string base on the input at the start of the file ("%d, %d, %d" in the example case), I will never have to go through the trouble of working through defining a parse function. Trouble is if this is just php or fortran I will write a do loop to create a format string, however when it comes to C, as I know it doesn't support string, I don't know how shall I perform this.