Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Confused about fgets

  1. Dec 24, 2008 #1
    Im attempting to read a .txt file, and store each line as a seperate 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 (Text):
     #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");

                while(fgets(saythis, sizeof (saythis), spResponses) != NULL)
                    responses[i] = saythis;
      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]);
      return 0;
  2. jcsd
  3. Dec 24, 2008 #2
    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.
  4. Dec 24, 2008 #3
    thanks a ton, that was exactly what i needed!
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook