我仅有的代码仅打印前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 );
}

最佳答案

使用多余的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

关于c - 如何读取文件并跳过x行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50265724/

10-09 05:34
查看更多