如何将文本文件的行读入C中的大字符串?

时间:2014-02-25 16:56:39

标签: c string fgets

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*/
}

我希望上面的程序将整个文件读入C中的String。 我希望filePtr是该字符串,如果exam​​ple.txt看起来像:

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

新线如何分开?就像“......和鼠标。逃脱字符......”如果我像我一样使用fgets,它会在字符串中显示出来吗?

感谢。

1 个答案:

答案 0 :(得分:4)

您可以一次性将其读入字符串而不是按行,例如

  • fopen the file
  • 读长度;或
    • fseek到最后;使用ftell获取长度,然后回到起点
    • 或fstat文件以获取长度
  • malloc一个长度为+ 1的新缓冲区
  • 将整个文件(即1, length)放入缓冲区
  • 在fread结尾处放入你的缓冲区(即使用fread的返回值而不是长度)
  • FCLOSE

这将为您提供原始文件数据,并且不会处理转义等。