I think I'm semi-close to a solution, but it's just not happening for me. I'm having trouble populating my dynamically allocated multidimensional array with data from a text file. Here's what I have:
#include <stdio.h>
#include <stdlib.h>
#define MAXLINELEN 18
FILE *getOpen();
int main()
{
FILE *inFile; // Declares inFile pointer as a FILE type.
char **matrix;
int nrows; // number of rows.
int ncols; // number of columns.
int i;
int row;
int col;
char singleLine[MAXLINELEN];
// Open the text file containing the matrix.
inFile = getOpen();
// Read in each line of the matrix from the .txt file to obtain the
// number of rows and columns so memory can be allocated for
// the matrix.
nrows = 0;
ncols = 0;
while (fgets(singleLine, MAXLINELEN - 1, inFile) != NULL)
{
nrows++;
ncols++;
printf("#%d: %s\n", nrows, singleLine);
}
matrix = malloc(nrows * sizeof(char *));
if(matrix == NULL)
{
printf("Out of memory.\n");
exit(1);
}
for(i = 0; i < nrows; i++)
{
matrix[i] = malloc(ncols * sizeof(char *));
if(matrix[i] == NULL)
{
printf("Out of memory.\n");
exit(1);
}
}
printf("Memory allocated successfully!\n");
// THE PROBLEM IS IN THESE NEXT STATEMENTS!!!!!
for (row = 0; row < nrows; row++)
{
for (col = 0; col < ncols; col++)
{
while (fscanf(inFile, "%s %s\n", matrix) != EOF);
// HOW DO I FILL THE MATRIX WITH THE DATA???!!!!!
printf("%s %s\n", matrix);
}
}
system("pause");
return 0;
}
/* =============================================
getOpen
=============================================
This function opens the file for reading, and
returns the file name back to the program for
use.
*/
FILE *getOpen()
{
FILE *fname;
char name[21];
printf("\nEnter a file name: ");
gets(name);
fname = fopen(name, "r");
if (fname == NULL)
{
printf("Failed to open the file %s.\n", name);
exit(1);
}
printf("File was successfully opened!\n");
return(fname);
}
I have tried scanf, fscanf, fgets, and fgetc. NOTHING IS WORKING!!!
PLEASE HELP!!!!!!!!!!!!!
Thanks!