#include <stdio.h>
#include <stdlib.h>
#define RIG 5
#define COL 11
int main()
{
FILE *fp;
fp=fopen("swamp.txt","r");
if((fp=fopen("swamp.txt","r"))==NULL)
{
puts("ERROR!");
return -1;
}
char *swamp[RIG][COL];
while(fscanf(fp,"%s",swamp)!=EOF)
{
printf("%s\n",swamp);
}
fclose(fp);
return 0;
}
I'm working with files and I'm getting 2 warnings for the fscanf
inside the while
. Can somebody explain to me why?
Let's assume
swamp.txt
contains:and that you want to read these lines into the array
swamp
in your program. Then you might revise your code along these lines. Notice that this avoids opening the file twice, amongst other cleanup operations.The output is:
Note that the code protects against overflow from a long file by counting words as they're read. You already checked
fopen()
— that was good. I improved the error message, though. In my opinion, you should never callfopen()
with a literal string for the file name because when you report an error on opening the file, you need the file name in the error message, so you'd have to repeat yourself. I fixed the type of the array so it is a 2D array ofchar
and not a 2D array of (uninitialized)char
pointers. I arranged to pass each row of the array tofscanf()
in turn. I limited the length of the input for each word to prevent overflows there, too.For
test.txt
as below:you can obtain data with this code (it can process words up to 8 characters in 4 rows and 3 columns):