• C

Reading strings from a file into an array

The program I have written is to read an unknown number of strings (names) out of a file (no more than 20), sort them is ascending order, print them, then continuously prompt the user for a name to search.  The program works great when the string array is initialized directly within the program.  When I ask for the strings to be read from a file the program does not work.  can anyone help me figure out how to correctly code this so the strings can be read from the file?

If it helps the program compiles, it just won't run.  Upon running the program a memory fault error is given.

Here is the program:

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

#define NUMWORDS 20
#define LENWORDS 25

void displayName (void);
void selection (char words [][]);
void printWords (char words [][]);
void getInput (char words [][]);
int search (int start, int end, char words [][], const char s[]);

//Main controls the

int main (int argc, char *argv[])
   FILE *infptr;
   char words [NUMWORDS][LENWORDS];
   if (argc <= 1)
     printf("\nNot enough command line arguments.\n");
   infptr = fopen (argv [1], "r");
   if ((infptr)==NULL)
      printf("\nERROR: Unable to open data for reading.\n\n");
   if ((argc>=2) && ((infptr)!=NULL))
      int i;
      for (i=0; i < NUMWORDS; i++)
         if (fscanf(infptr, "%s", words[i]) != EOF)strcpy(words[i],"");
      displayName ();
      selection (words);
      printWords (words);
      getInput (words);
   //Format and finish.
   printf ("\n");
   return 0;

//The name of the programmer is displayed.
void displayName (void)
   printf("\nName: Chandra Parr\n\n");

void selection (char words [][LENWORDS])
   int i,j,k;
   int currMin=0;
   char temp[NUMWORDS];

   for (j=0; j < 19; j++)
      for (k=j+1; k < 20; k++)
         if (strcmp(words[currMin], words[k])>0)
         strcpy(temp, words[currMin]);
         strcpy(words[currMin], words [j]);

void printWords (char words [][LENWORDS])
   int i;

   for (i=0; i < NUMWORDS; i++)
      printf ("\n%d: %s", i, words[i]);
   printf ("\n\n");

void getInput (char words [][LENWORDS])
   int result;
   int scanResult;
   char searchWord [LENWORDS];

         printf("Please enter a word to search (or quit to stop): ");
         scanResult = scanf ("%s", searchWord);
         if (scanResult == 1)
            result = search (0, NUMWORDS - 1, words, searchWord);
            printf("The word \"%s\"", searchWord);
            if (result == -1)
               printf (" was not found.\n");
               printf (" was found at position %d.\n", result);
//         while (scanResult == 1);
         while (scanResult == 1 && strcmp (searchWord, "quit") != 0);

int search (int start, int end, char words [][LENWORDS], const char s[])
   int middle, cmpRes;
   if (start > end)
      return (-1);
   else if (start == end)
      if (strcmp(words[start], s) == 0)
         return start;
         return (-1);
      middle = (start + end) / 2;
      cmpRes = strcmp(words[middle],s);
      if (cmpRes == 0)
         return middle;
      else if (cmpRes > 0)
         return search(start, middle - 1, words, s);
         return search (middle + 1, end, words, s);
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

There are several things wrong with your input-strings-from-file code:

1) You are using fscanf(...,"%s",...) to read the string.  fscanf() reads the string upto the first whitespace.
The file contains names, presumably of the form "firstName lastName", fscanf() will stop reading when
it hits the space between firstName and lastName.

2) fscanf() does not perform input buffer overflow checking.  If the string you read from the file
exceeds 25 characters, you will overflow the destination buffer, corrupting memory.

3) Your EOF test is backward.  After successfully reading a value, you then immediately overwrite
it with the empty string.

Consider using fgets() rather than fscanf() to avoid these problems.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.