I'm supposed to read a file in C with a structure that looks like this
A:
1
2
3
4
B:
1 1
2 2
3 3
4 4
C:
1 1 1
2 2 2
3 3 3
4 4 4
The file is always separated into three parts and each part starts with an identifier (A:, B:,..). Identifier is followed by unspecified number of rows containing data. But in each part the format of the data is different. Also it's not just integers but that's not important in this question.
I don't have a problem reading the file. My question is what would be an optimal way to read such a file? It can contain thousands of rows or even more parts than just three. The result should be for example string arrays each containing rows from a different part of the file.
I didn't post any code because I don't need/want you to post any code either. Idea is good enough for me.
char **lines;), allocate some initial number of pointers, assign them to lines. Then read each line with (e.g.fgets()), trim the newline, allocate based onlength+1, assign the new memory tolines[next]and copy from your buffer filled byfgets()tolines[next]. You keep count of the number of pointers and whenused == available, yourealloc (lines, ...doubling the number of pointers and keep going. See this answerstdinis just a file-stream, so open a file and replacestdinwith your file stream pointer.strcspn()andstrspn()to the same end) Or you can usestrtok()to separate on the delimiters (orstrsep()if you must preserve empty-fields).