Fawaz
Fawaz

Reputation: 1

Copy text file content into a 2D Array in C

I want to copy the content of a file that has a 10 by 10 array of characters to a 2D array. I verified but the compiler gives me an empty screen. The file is opening since the program dosen't print: "error in opening file", i would appreciate it if you help me. This is my code:

#include<stdio.h>
#include<string.h>

int main()
{
   char puzzle[10][10], line[10];
   int i,j, rows=0;
   FILE *fp;
   fp=fopen("arr.txt", "r");
   if (fp== NULL) { 
      printf("Error in opening file\n");
      return 1;
   }

   while(!EOF)
   {
      if(fgets(line, 10, fp) != NULL){
         for(i=0; i<(strlen(line)-1); i++)
            puzzle[rows][i] = line[i];
      }
      rows++;   
   }
   for(i=0; i<10; i++)
      for(j=0; j<10; j++)
         printf("%c", puzzle[i][j]);
}

Thank you

Upvotes: 0

Views: 1730

Answers (2)

R Sahu
R Sahu

Reputation: 206567

You are using the wrong size for the arrays.

When a line has 10 characters, you need to have

// 10 characters, the newline and the terminating null character.
char line[12];
char puzzle[10][12];

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

You reading-loop condition will always be false, so you never read anything. This will led to undefined behavior when you print out the uninitialized puzzle matrix.

The macro EOF is defined as -1, and in C anything non-zero is true, and since you negate this "true" value through the ! operator your condition will be false.

The usual newbie way to do it is using

while (!feof(fp)) { ... }

but that's the wrong solution (in most cases).

Instead do

while (fgets(line, sizeof line, fp) != NULL) { ... }

By the way, you might still have undefined behavior if the line you read is less than 9 characters, as not all of the puzzle matrix will be initialized. You might want to initialize it first, which can be done when you define it:

char puzzle[10][10] = { 0 };

Also note that if the lines you read are exactly 9 characters or longer, then the fgets call will not include the newline in the string.

Upvotes: 1

Related Questions