Search code examples
cstringfgets

How do I read the lines of a text file into a large string in C?


readtofile.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char **argv) {
      /*For File input, I'm copying the lines of the file into a 
       * large string with fgets*/
        FILE *filePtr;

        char buffIter[200];//How much fgets iterates by???
        char *pToken;      //Should hold the large string.

        filePtr = fopen(argv[2],"r");// the filename is passed as the second argument

        while(fgets(bufferIter, 200, filePtr){ ...?

                  filePtr = something?


      /*For File input*/
}

I want the above program to read an entire file into a String in C. I want the filePtr to be that string and if the example.txt looks like:

This is a test file.
Here are some strings like cat, dog and mouse.
Escape chars too \n \a \" \b \t.
Specials cases? @ $ % \\ \\\ \\\\ \ \ 
"\\" "\\\" "\"

How would the new lines be separated? Like from "...and mouse. Escape chars..." Would it show up like this in the string if I use fgets as I am?

Thanks.


Solution

  • You could just read it into a string in one go rather than by-line, e.g.

    • fopen the file
    • read the length; either
      • fseek to the end; use ftell to get the length then fseek back to the start
      • or fstat the file to get the length
    • malloc a new buffer for length + 1
    • fread the whole file (i.e. 1, length) into the buffer
    • put a nul in your buffer at the end of the fread (i.e. use the return value of fread not the length)
    • fclose

    This would give you the raw file data and wouldn't process escapes, etc.