首页 > 解决方案 > C- 查找我打开的文本文件的当前行

问题描述

我需要一个解决方案来在文本文件中找到当前使用的行。我打开它:

FILE *fp;
fp=fopen(“data.txt”, “ r+“);

标签: cfiledata-manipulation

解决方案


要跟踪包含您当前正在处理的文本行的文件中的哪一行,您可以使用计数变量。这是一个简单的例子

while (fgets(buffer, BUFLEN, fp) != NULL)
{
    printf("Line %d: %s", line, buffer);
    if (buffer[strlen(buffer)-1] != '\n') 
    // fgets didnt read an entire line, so increment the file pointer to
    // the start of the next line. also, output the newline since it wasn't
    // part of buffer above
    {
        int ch;
        do
        {
            ch = fgetc(fp);
        }
        while (ch != '\n' && ch != EOF);
        putchar('\n');
    }
    line++;
}

推荐阅读