c - 如何在 C 中使用 fscanf() 仅读取文本文件的某些部分
问题描述
我必须从具有以下格式的文本文件中读取文件名:
#start Section-1
file1 file2 file3
file4
#end Section-1
#start Section-2
some random text
#end Section-2
有什么方法可以使用 fscanf() 函数来读取文件名并忽略其他所有内容?
解决方案
假设您只关心 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,则需要更改。此示例代码也不包括任何错误检查或处理。
推荐阅读
- javascript - 使用 innerHTML 将 javascript 对象输出到 HTML 代码中
- python - DBSCAN 算法
- spring-boot - 在 spring-boot 应用程序中使用 Micrometer 和 OpenFeign
- azure - Azure 诊断设置(预览版)
- svelte - 如何使用 SCSS 在 svelte 中拥有多个 css 包
- python - AWS 实例(Jupyter 笔记本)停止响应
- mysql - 移动值并在传输后删除它们
- javascript - 如何将多个钩子状态渲染到我的 JSX 中?
- azure - 无法获得将 SPFX webpart 与 Azure Devops 连接的同意
- firebase - URL 重写会使 Firebase 云功能响应来自我的自定义域吗?