读取行直到c编程中的特定行

Reading lines until specific line in c programming

我想打印行直到指定行。文本文件的内容写入缓冲区数组,如下例所示。如何从第一行打印到第五行或第六行?

代码:

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

int main(int argc, const char * argv[]) {

    char *buffer;
    int c;
    FILE *input;
    int i = 0;
    size_t buffer_size;

    input = fopen( "input.txt", "r");
    if ( input == NULL ) {
        perror("Error");
    }

    buffer_size = BUFSIZ;
    if ((buffer = malloc(buffer_size)) == NULL) {
        fprintf(stderr, "Error allocating memory (before reading file).\n");
        fclose(input);
    }


    while ((c = fgetc(input)) != EOF) {
        buffer[i++] = c;
    }

    //puts(buffer);


    fclose(input);  
    free(buffer);
    return 0;
}

文本文件的内容:

1 test
2 test
3 test test
4 test
5 test test
6 test
7 test

像这样fgets()很容易做到

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

int main(void)
 {
    char   buffer[BUFSIZ];
    FILE  *input;
    size_t lineCount;
    size_t maxLine;

    input = fopen("input.txt", "r");
    if (input == NULL)
     {
        perror("Error");
        return -1;
     }

    maxLine   = 5;
    lineCount = 0;
    while ((lineCount < maxLine) && (fgets(buffer, sizeof(buffer), input) != NULL))
     {
        puts(buffer);
        lineCount += 1;
     }

    return 0;
 }

阅读 link 中的手册,了解其工作原理。

使用getline()函数。此外,您还可以检查出现的回车 return \r 以确定新行。跟踪计数,您将能够打印到您想要的行。

#include <stdio.h>

int main(void) {
    FILE *input;
    int c, line, numOfLine = 0;

    printf("input line number : ");
    scanf("%d", &line);

    input = fopen("data.txt", "r");//Error handling is omitted

    while ((c = fgetc(input)) != EOF) {
        putchar(c);
        if(c == '\n' && ++numOfLine == line)
            break;
    }

    fclose(input);  
    return 0;
}