views:

140

answers:

1

Hey there, How do I go about copying text inside a text file into a multidimensional character array?

supposing the text file( text_file.txt) contained

this is the first line

this is the second line

this is the third line

#include <stdio.h>
int main(void){
 FILE *f;
 f=fopen("text_file.txt","r");
 if (f==NULL){
  printf("invalid!");
  return 1;
  }
 else {
  printf("successful");
  }

 char copied_text[80][80];

 while (!feof(f)){
  int i=0,j=0;
  fgets(copied_text[i][j],"%s",f);
  i++;
  }

 return 0;
}

-thank you.

+1  A: 

I think your code almost work.
Just move the declaration of int i out of the loop.
Change the first parameter of fgets to copied_text[i] because it needs a pointer here.
Change the second parameter of fgets to 80 because it should be a int indicates the acceptable string length.

#include <stdio.h>
int main(void){
    FILE *f;
    f=fopen("text_file.txt","r");
    if (f==NULL){
        printf("invalid!\n");
        return 1;
    }
    else {
        printf("successful\n");
    }

    char copied_text[80][80];

    int i=0;
    while (!feof(f)){
        fgets(copied_text[i],80,f);
        ++i;
    }

    for(int i = 0; i <3; ++i)
        printf("%s\n", copied_text[i]);
    return 0;
}
Raymond
`while (!feof(...))` is almost always wrong, and this case is no exception. You should change that to `while (fgets(...) != NULL)`.
caf
There should also be a check that no more than 80 lines are entered.
Jonathan Leffler
you guys are right. there are still a lot to improve in the sample code from engineering point of view. I just tried to modify the original code to express the basic idea.
Raymond