簡體   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