Saturday, 3 December 2016

Reading lines out of a file and putting them into a string array


Question;
What I would like to do is be able to read a line out of a file and stick it into an array of strings. This is what I have so far but it does not seem to work.
...
char line [128];
char file [10][128];

plist = fopen("plist1.txt", "r");

while(fgets(line, sizeof line, plist) != NULL){
   file[i][0]= line;
   i++;
}

I tried doing file[i][0] = *line; and I was able to print out the first character of each line. Is this the best way to do what I am trying to do?
Also, the number of lines in a text file will vary so I would like to have my array be of variable length instead of 10.
EDIT: I have tried two solution listed below. Both give me a segmentation fault dealing with either strcpy or the fgets.
1.  while (fgets(file[i], sizeof(file[i]), plist))
       i++;

2.  while (fgets(line, sizeof(line), plist)){
       strcpy(file[i], line);
       i++;
    }

1st Answer; Try this:
while (fgets(file[i], sizeof(file[i]), plist))
    i++;
Alternatively

while (fgets(line, sizeof(line), plist))
    strcpy(file[i], line);
-----------------------------------------------------------------------------


------------------------------------------------------------------------------------------------------------------------------


2nd Answer;


Here is a fully working solution, assuming plist1.txt contains a line of text per line. fgets() will by default also include a newline at the end, that you need to get rid of. It is also a good idea to use symbolic constants so that you can change them easily later on if you so want.

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

#define BUF 128 /* can change the buffer size as well */
#define TOT 10 /* change to accomodate other sizes, change ONCE here */

int main(void) {
    char line[TOT][BUF];
    FILE *plist = NULL; 
    int i = 0;
    int total = 0;

    plist = fopen("plist1.txt", "r");
    while(fgets(line[i], BUF, plist)) {
        /* get rid of ending \n from fgets */
        line[i][strlen(line[i]) - 1] = '\0';
        i++;
    }

    total = i;

    for(i = 0; i < total; ++i)
        printf("%s\n", line[i]);

    return 0;
}





No comments:

Post a Comment