Originally Posted by
paddyMatches
I don't mean to come across ungrateful but that reads as a re-write of my general syntax and not addressing my problem.
Yes, it is intended as an example of what I might write based on what you attempted, not a fix of your problems per se. The idea is for you to read the code and my comments, and from there understand what you should have done.
If you really want to address your problem directly rather than try to understand my example so as to learn from it, let's put your function into a test program:
Code:
#include <stdio.h>
#define ROW 10
#define COLUMN 4
void readFile(char fName)
{
FILE *fNamePtr;
int i, j;
char wordArray[ROW][COLUMN];
fNamePtr = &fName;
if ((fNamePtr = fopen("myfile.dat", "r")) == NULL)
{
printf("File could not be opened.");
}
else
{
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COLUMN; j++)
{
fscanf(fNamePtr, "%s", wordArray[i][j]);
}
}
}
}
int main(void)
{
readFile('x');
return 0;
}
Now we compile your code with gcc 5.4.0:
Code:
test.c: In function ‘readFile’:
test.c:12:14: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
fNamePtr = &fName;
^
test.c:24:34: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
fscanf(fNamePtr, "%s", wordArray[i][j]);
We see two warnings. The first warning tells you that you made a nonsensical assignment:
fName is a char, so &fName is a pointer to char. A pointer to char has nothing to do with a pointer to FILE, yet you're trying to assign &fName to fNamePtr despite fNamePtr being a pointer to FILE. In fact, you can safely delete this line, especially since you immediately assign to fNamePtr after this.
Next, and more importantly, the second warning tells you that you made an incorrect use of fscanf. You want to read into wordArray[i][j], and used the %s format specifier. %s is used to read strings, but wordArray[i][j] is a char. Therefore, you have a mismatch in type.
Actually, you don't want to read into wordArray[i][j], and if you did, you would use %c with &wordArray[i][j]. Rather, you want to read into wordArray[i], so you should have written:
Code:
fscanf(fNamePtr, "%s", wordArray[i]);
Furthermore, as I mentioned twice already, you don't need the nested loops.
Therefore, we can see that your problem is that you did not compile at a sufficiently high warning level and then did not heed the warnings. You went on to find that your program did not work, but of course since you did not heed a warning that actually mattered.