0

I am a bit confused about how to modify my code to return a buffer that stores multiple lines of a file as a string and not just the first line.

char * readFile ( char * filename){
    char text[500];
    char * input=NULL;
    FILE *fptr;
    fptr=fopen(filename,"r");
    if (fptr == NULL) {
        return NULL;
    }
    fgets(text, 500, fptr);

    fclose(fptr);
    input=malloc(sizeof(char)*(strlen(text)+1));
    if (input == NULL) {
        return NULL;
    }
    strcpy(input,text);

    return input;
}
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • Your code returns a `char *`, not a `FILE *`. You'd return a file pointer by `return fptr;`. You should close `fptr` before you return unless you return the file pointer, but then you can't also return the string. If you want to read more than one line, how many lines do you want to read, and how do you tell the function that's how many to read (hint: function arguments). Or do you want to return the whole file content? – Jonathan Leffler Feb 21 '21 at 20:45
  • You should check that `fgets()` was successful. – Jonathan Leffler Feb 21 '21 at 20:46
  • I need the function to open and reads the contents of the file and return the contents as a string (char *). the length varied depending on the input –  Feb 21 '21 at 20:47
  • One way would be to put fgets in a loop and realloc input each time through the loop. But checking the length of the file and allocating that much space with one malloc would be better yet. – Jerry Jeremiah Feb 21 '21 at 20:50
  • 1
    So you want to slurp the whole contents of the file into memory. OK; it can be done — in fact, I'd lay odds there are multiple questions that ask for exactly that already. It's probably easier to answer than to find a duplicate, though. The combination of `fseek()` and `ftell()` can tell you how big the file is (at the moment — if the file is in use, it might grow or shrink after you find out how big it is); you can use the size to allocate the space, and then `fread()` to read the data into memory. And you can add a null byte at the end to ensure you've got a string rather than a byte array. – Jonathan Leffler Feb 21 '21 at 20:50
  • to loop and realloc would be best that similar to what we have actually done before. I have never looped fgets before how would that look –  Feb 21 '21 at 20:57
  • How do you think it might look, @IgorM? Most likely, you'd read line segments into a fixed-size buffer, and then copy them into an appropriately sized result buffer. But that's not as efficient or effective as one allocation. However, if the input is coming from a terminal or a pipe (or some other device types, including sockets), then you can't tell a priori how much data will be available — so incremental allocation becomes necessary. – Jonathan Leffler Feb 22 '21 at 05:44

0 Answers0