2014-02-25 48 views
0

readtofile.c如何將文本文件的行讀入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是該字符串,如果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

'char buffIter [100];''和'fgets(bufferIter,200,filePtr)'是絕對不好的(第二個參數fgets是'尺寸'又名將被讀取的字符數) – fvu

+0

facepalm *,改變它。 –

回答

4

您可以一次性讀取到字符串中,而不是逐行讀取,例如,

  • 的fopen文件
  • 閱讀長度;或者
    • fseek到最後;使用FTELL得到長度然後FSEEK回到開始
    • 或FSTAT該文件以得到長度
  • 的malloc爲長度的新緩衝液+ 1
  • FREAD整個文件(即1, length)插入緩衝
  • 把NUL在緩衝區的FREAD結束(即使用FREAD不是長度的返回值)
  • FCLOSE

這將使你的原始文件數據,並不會處理轉義等

相關問題