【问题标题】:How do I read the lines of a text file into a large string in C?如何将文本文件的行读入 C 中的大字符串?
【发布时间】:2014-02-25 16:56:38
【问题描述】:

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 中的字符串。 我希望 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? @ $ % \\ \\\ \\\\ \ \ 
"\\" "\\\" "\"

如何分隔新行?就像来自 "...and mouse. Escape chars..." 如果我​​按原样使用 fgets,它会在字符串中显示为这样吗?

谢谢。

【问题讨论】:

  • char buffIter[100];fgets(bufferIter, 200, filePtr) 绝对不好(fgets 的第二个参数是 size 也就是将被读取的字符数)
  • facepalm*,改了。

标签: c string fgets


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多