如何在c中的变量中仅存储文件的结束位

我的守则如下:

#include  int main(int argc, char *argv[]){ char line1[128]; char line2[128]; char line3[128]; char rem_text[128]; FILE *f; f = fopen((argv[1]), "r"); if (!f) { printf("error"); } else { fscanf(f, "%127[^\n]\n%127[^\n]\n%127[^\n]\n%127[^\n] ", line1, line2,line3, rem_text); printf("1:%s\n", line1); printf("2:%s\n", line2); printf("3:%s\n", line3); printf("4:%s\n", rem_text); fclose(f); } return 0; } 

除了一个细节,该计划几乎按预期运作。 它应该做的是,取一个文件的前三行并将它们存储在单个变量中。 (有效)但我想将文件的整个剩余位存储到自己的变量中。 我怎么做?

例如,如果我的test.txt文件包含

 Kapitel 1 chapter_21.txt chapter_42.txt 'Would you tell me, please, which way I ought to go from here?' 'That depends a good deal on where you want to get to,' said the Cat. 'I don't much care where -' said Alice. 'Then it doesn't matter which way you go,' said the Cat. '- so long as I get SOMEWHERE,' Alice added as an explanation. 'Oh, you're sure to do that,' said the Cat, 'if you only walk long enough.' 

我想将Kapitel 1存储为Title

chapter_21.txt作为chapter_a

chapter_42.txt作为chapter_b

 'Would you tell me, please, which way I ought to go from here?' 'That depends a good deal on where you want to get to,' said the Cat. 'I don't much care where -' said Alice. 'Then it doesn't matter which way you go,' said the Cat. '- so long as I get SOMEWHERE,' Alice added as an explanation. 'Oh, you're sure to do that,' said the Cat, 'if you only walk long enough.' 

作为rem_text

主要是因为我最近没有写C,并且提供一些例子,最重要的是(虽然这不是真正的正确的论坛),以寻求可能遵循的极端批评,以加强我现在变得迟钝的编码技能,我建议:

 #include  #include  #include  FILE *Fopen(const char *path, const char *mode) { FILE *rv = fopen(path, mode); if(rv == NULL) { perror(path); exit(EXIT_FAILURE); } return rv; } int main(int argc, char *argv[]){ char buf[4096]; char *line[4] = {0}; FILE *f; f = argc > 1 ? Fopen(argv[1], "r") : stdin; if(fread(buf, sizeof *buf, sizeof buf, f) == sizeof buf) { fprintf(stderr, "This file is too big. Need to implement dynamic sizing\n"); exit(EXIT_FAILURE); } line[0] = buf; for(int i=1; line[i-1] && i < sizeof line / sizeof *line; i++) { line[i] = strchr(line[i-1], '\n'); if(line[i]) { *line[i] = '\0'; line[i] += 1; } } for(int i=0; i < sizeof line / sizeof *line; i++) { printf("line[%d] = %s\n", i, line[i]); } return 0; } 

请注意,动态调整数组大小是一件好事,知道该怎么做。 留给读者练习。