0

I have to read in a file such as

apple
grape
banana

And store it into a string, but fgets only reads up to the newline and stops, so its only reading in apple.

How do I get around this? Or how can I store the three words all as separate strings?

char* readFile(const char *fileName)
{
    FILE *inFile;
    inFile=fopen(fileName, "r");

    char **stringInFile;
    stringInFile = malloc(sizeof(char*)*50);
    char *data = fgets(stringInFile,50,inFile);
    printf("%s", data);

    fclose(inFile);

    return data;
}

This is all in C btw.

Carson
  • 1,147
  • 5
  • 19
  • 41

2 Answers2

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

char** readFile(const char *fileName);

int main(int argc, char **argv){
    char **data = readFile(argv[1]);
    int i;
    for(i=0; data[i] ; ++i){
        puts(data[i]);
        free(data[i]);
    }
    free(data);
    return 0;
}

char** readFile(const char *fileName){
    FILE *inFile;
    inFile=fopen(fileName, "r");

    char **stringInFile;
    stringInFile = calloc(50, sizeof(char*));
    char line[256];
    int i = 0;
    while(fgets(line, sizeof(line), inFile)){
        char *p = strchr(line, '\n');
        if(p)
            *p = 0;
        if(i < 50 - 1)
            stringInFile[i++] = strdup(line);
    }

    fclose(inFile);

    return stringInFile;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

fgets() is only reading one Line by each call, and sets the file courser to the next line. If you want to read the fully file, you have to iterate it. To check if you are at the end, you can check for the EOF flag with feof(). Resulting in, for me working:

char* readFile(const char *fileName)
{
FILE *inFile;
inFile=fopen(fileName, "r");

char **stringInFile;
stringInFile = malloc(sizeof(char*)*50);
while(!feof(inFile))
{
  printf("%s", fgets(stringInFile,50,inFile));
}

fclose(inFile);

return stringInFile;
}

And, you don't need the variable data - fgets() first parameter is a character Array, where is it automatical stored(for example Apple in your programm).

darksider
  • 64
  • 4
  • It's important to note that `feof(fileptr)` will only be true if you actually attempted to read beyond the end of the file. `fgets` will happily return the last line, including the newline at the end of the file, but `feof` will be false. Then you'll attempt another `fgets`, which will return `NULL` because there is no more data to read, and the result is `printf("%s", NULL);`, which may crash your program in a segfault or print some string depending on your C library. [More info can be found here](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) –  Mar 28 '15 at 23:06