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

时间:2017-12-01 15:16:13

标签: c

我的代码如下:

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.'

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

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

Kapitel 1

我想将Title存储为chapter_21.txt

chapter_achapter_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

$(document).ready(function() { if(window.location.hash) { $('html, body').animate({ scrollTop: $(window.location.hash).offset().top - 20 }, 500); } });

1 个答案:

答案 0 :(得分:0)

主要是因为我现在不能写C,并提供一些例子,最重要的是(虽然这不是一个非常正确的论坛),以征求可能会遵循的极端批评。磨砺我现在变得迟钝的编码技巧,我建议:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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;
}

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