首页 > 解决方案 > 如何在 C 中使用 fscanf() 仅读取文本文件的某些部分

问题描述

我必须从具有以下格式的文本文件中读取文件名:

#start Section-1

    file1 file2 file3
file4

#end Section-1

#start Section-2

    some random text

#end Section-2

有什么方法可以使用 fscanf() 函数来读取文件名并忽略其他所有内容?

标签: c

解决方案


假设您只关心 Section-1 和 #end 之后的文件名,您可以跳到 section-1 ,然后在关闭文件之前阅读到 #end ...

示例代码

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

int main(void) {
    FILE * fp;
    fp = fopen("example.txt", "r");
    char temp[20];
    //skip to Section-1
    do{
        fscanf(fp, "%s", temp);
    }while(strcmp (temp, "Section-1"));
    //print out all filenames
    for(;;){
        fscanf(fp, "%s", temp);
        if(strcmp(temp, "#end") == 0) break;
        //do whatever you want with the filenames instead of print them
        printf("%s ", temp); //prints file1 file2 file3 file4
    }
    //close file
    fclose(fp);
  return 0;
}

这是根据您的问题做出很多假设,例如您不关心名为“section-1”的点之后的内容

它也只是一个示例,如果您的实际名称不是第 1 节,则必须稍微更改它。如果文件名大于 20,则需要更改。此示例代码也不包括任何错误检查或处理。


推荐阅读