Solving Confusion with fgets & 2D Arrays

  • Thread starter Thread starter VirObitus
  • Start date Start date
  • Tags Tags
    Confused
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 2K views
VirObitus
Messages
19
Reaction score
0
Im attempting to read a .txt file, and store each line as a separate instance of an array. The code I've written causes each instance of the responses array to become the last line in the .txt file. Do I need to make a 2D array to get what I want? If so, how would I go about doing that?

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

void main(void)
{
  FILE* spResponses;
  char* saythis[30];
  char* responses[30];
  int i = 0;
  
    if ((spResponses = fopen("c:\\responses2.txt", "r")) == NULL)                           //open file
    {
       printf("Error opening input file!\n");
    }
    else
    {

            while(fgets(saythis, sizeof (saythis), spResponses) != NULL)
            {
         
                responses[i] = saythis;
                i++;
                
            }
            fclose(spResponses);
        
    }
    
  printf("%s\n\n", responses[0]);
  printf("%s\n\n", responses[1]);
  printf("%s\n\n", responses[2]);
  printf("%s\n\n", responses[3]);
  printf("%s\n\n", responses[4]);
          
  system("PAUSE");	
  return 0;
}
 
Physics news on Phys.org
Your program looks OK except for just a few points:
1. If the lines of the files do not exceed 30 characters, the line
char* saythis[30];
should be changed to
char saythis[30];
to get a buffer array of 30 characters including the '\0' terminator.
The line as is assigns memory for 30 pointers to arrays, but no memory for the strings themselves.
2. The line
responses = saythis;
could be changed for
responses =strdup(saythis);
The modified version will assign memory to make a copy of each string.
Otherwise all members of responses will contain the pointer to the array saythis, meaning that they all have values of the last line.
3. Note that fgets retrieves the new-line character (at the end of the line). If this is not what you want, you may want to remove it.
 
thanks a ton, that was exactly what i needed!