Search code examples
carraysstdinfgetsfeof

How do I read the contents of a file in C and store it into an array using fgets()?


So I need to create a word search program that will read a data file containing letters and then the words that need to be found at the end for example:

f a q e g g e e e f


o e q e r t e w j o


t e e w q e r t y u


government


free

and the list of letters and words are longer but anyway I need to save the letters into an array and i'm having a difficult time because it never stores the correct data. here's what I have so far

#include <stdio.h>

int main()
{
int value;
char letters[500];

while(!feof(stdin))
{
   value = fgets(stdin);

   for(int i =0; i < value; i++)
   {
      scanf("%1s", &letters[i]);
   }

   for(int i=0; i<1; i++)
   {
      printf("%1c", letters[i]);
   }
}
}

I also don't know how I am gonna store the words into a separate array after I get the chars into an array.


Solution

  • You said you want to read from a data file. If so, you should open the file.

    FILE *fin=fopen("filename.txt", "r");
    if(fin==NULL)
    {
        perror("filename.txt not opened.");
    }
    

    In your input file, the first few lines have single alphabets each separated by a space.

    If you want to store each of these letters into the letters character array, you could load each line with the following loop.

    char c;
    int i=0;
    while(fscanf(fin, "%c", &c)==1 && c!='\n')
    {
        if(c!=' ')
        {
            letters[i++]=c;
        }
    }
    

    This will only store the letters and is not a string as there is no \0 character.

    Reading the words which are at the bottom may be done with fgets().

    Your usage of the fgets() function is wrong.

    Its prototype is

    char *fgets(char *str, int n, FILE *stream);
    

    See here.

    Note that fgets() will store the trailing newline(\n) into string as well. You might want to remove it like

    str[strlen(str)-1]='\0';
    

    Use fgets() to read the words at the bottom into a character array and replace the \n with a \0.

    and do

    fgets(letters, sizeof(letters, fin);
    

    You use stdin instead of the fin here when you want to accept input from the keyboard and store into letters.

    Note that fgets() will store the trailing newline(\n) into letters as well. You might want to remove it like

    letters[strlen(letters)-1]='\0';
    


    Just saying, letters[i] will be a character and not a string.

    scanf("%1s", &letters[i]);
    

    should be

    scanf("%c", &letters[i]);