如何读取文件和跳过x行

时间:2018-05-10 04:54:31

标签: c file-handling

我的代码只打印前x行。如果你能给我一些关于我缺少的东西的话,我真的很感激,

#include <stdio.h>
int main ( void )
{
    static const char filename[] = "testfile.txt";

    int lineNumbers[] = {1,2};
    size_t numElements = sizeof(lineNumbers)/sizeof(lineNumbers[0]);
    size_t currentIndex = 0;

    FILE *file = fopen ( filename, "r" );
    int i =0;
    if ( file != NULL )
    {
        char line [ 328 ]; /* or other suitable maximum line size */
        while ( fgets ( line, sizeof line, file ) != NULL )
        { /* read a line */
            i++;
            if (i  == lineNumbers[currentIndex])
            {
                fputs( line, stdout ); /* write the line */
                if (++currentIndex == numElements)
                {
                    break;
                }
            }
        }
    fclose ( file );
}

1 个答案:

答案 0 :(得分:1)

使用额外的fgets跳过您不想要的行 给定x = 2,y = 3和输入文件:

1 read me
2 read me
3 dont read me
4 dont read me
5 dont read me
6 read me 
7 read me
8 dont read me
9 dont read me
10 dont read me
11 read me 
12 read me

以下计划:

#include <stdio.h>
int main ( void )
{
    static const char filename[] = "testfile.txt";

    int x = 2;
    int y = 3;
    size_t currentIndex = 0;

    FILE *file = fopen(filename, "r");
    char line [ 328 ]; /* or other suitable maximum line size */

    // until the end of file
    int linenumber = 0;
    while(!feof(file)) {
        // read x lines
        for(int i = x; i; --i) {
            if (fgets(line, sizeof(line), file) == NULL) break;
            ++linenumber;
            // and print them
            printf("READ %d line containing: %s", linenumber, line);
        }
        // skip y lines
        for(int i = y; i; --i) { 
            // by reading a line...
            if (fgets(line, sizeof(line), file) == NULL) break;
            ++linenumber;
            // and discarding output
        }
    }
    fclose(file);
}

产生以下输出:

READ 1 line containing:     1 read me
READ 2 line containing:     2 read me
READ 6 line containing:     6 read me 
READ 7 line containing:     7 read me
READ 11 line containing:     11 read me 
READ 12 line containing:     12 read me