
Text Data File to 2D Array?
Quote:
>I am not sure how to pass text from a data file to a 2D array in C. Any help
>would be greatly appreciated. I have declared the array globally, and opened
>the data file. I have no clue what code is necessary for reading the text into
>the array.
You do not give any clue as to the layout of the data in the file but at
a guess it consists of lines of items each of which is to be placed in a
corresponding 'row' in the array.
Assume that the data items in the file are ints separated by a comma and
that all arrays etc. have been declared then:
1. open the file (check for a valid file pointer)
2. While you are not at the end of the file.
2.1. Read in a line from the file. (fgets)
2.2 Use sscanf on the line just read in to assign the data to
individual elements in the array at the current row.
2.3 Increment the index for the row.
3. Close the file.
Making the array global is not necessary for this problem.
Steps 1 & 3 are normal file operations. Step two may be coded within a
function along the lines of:
long getFileData(FILE *stream, int **array, int numCols, int numRows);
The internals are not complicated in themselves but error checking will
increase the size of the function.
Quote:
>Also, can the text be read in a character at a time, or does it have to be read
>in as a string?
>Any help would greatly be appreciated.
>Please e-mail me.
Post here, read here
Quote:
>Thank you!
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Bob Wightman
--