[英]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.