簡體   English   中英

如何在 C 中使用 fscanf() 僅讀取文本文件的某些部分

[英]How to read only certain parts of text file using fscanf() in C

我必須從具有以下格式的文本文件中讀取文件名:

#start Section-1

    file1 file2 file3
file4

#end Section-1

#start Section-2

    some random text

#end Section-2

有什么方法可以使用 fscanf() function 來讀取文件名並忽略其他所有內容?

假設您只關心 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,則需要更改。 此示例代碼也不包括任何錯誤檢查或處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM