繁体   English   中英

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

[英]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*/
}

我希望上面的程序将整个文件读入C语言的String中。我希望filePtr是该字符串,并且example.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,它会在字符串中显示吗?

谢谢。

您可以将其一次性读入字符串中,而不用逐行阅读,例如

  • 打开文件
  • 阅读长度;
    • 寻找到最后; 使用ftell获取长度,然后fseek返回起点
    • 或fstat文件以获取长度
  • m为长度+1分配一个新的缓冲区
  • 将整个文件(即1, length )读入缓冲区
  • 在fread的末尾在缓冲区中放置一个nul(即,使用fread的返回值而不是长度)
  • FCLOSE

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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