?
Solved

Reading strings from a file into an array

Posted on 2004-11-16
1
Medium Priority
?
209 Views
Last Modified: 2012-05-05
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

//Prototypes
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++)
   {
      currMin=j;
      for (k=j+1; k < 20; k++)
         if (strcmp(words[currMin], words[k])>0)
            currMin=k;
         strcpy(temp, words[currMin]);
         strcpy(words[currMin], words [j]);
         strcpy(words[j],temp);
   }
}

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];

      do
      {
         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");
            else
               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;
      else
         return (-1);
   else
   {
      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);
      else
         return search (middle + 1, end, words, s);
   }
}
0
Comment
Question by:csunnypl2
1 Comment
 
LVL 23

Accepted Solution

by:
brettmjohnson earned 750 total points
ID: 12598343
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.

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
Suggested Courses

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question