简体   繁体   中英

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.

You could just read it into a string in one go rather than by-line, eg

  • 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 (ie 1, length ) into the buffer
  • put a nul in your buffer at the end of the fread (ie use the return value of fread not the length)
  • fclose

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM