c - 从c中的文件中读取文本并忽略“一些评论”
问题描述
我目前正在制作一个程序来读取这个文本文件(从意大利语翻译)并将一行存储在一个单链表中。但我不得不忽略评论。注释以“#”开头。在我的列表节点中,我必须有成分、符号和数量,没有注释。
Input file:
#ingredients for donut
milk l 0.25
flour g 300
oil l 0.05 # a spoon
eggs u 2
butter g 50
yogurt g 50 # white yogurt
# enjoy your meal
struct nodo {
char ingredient[15];
char simbol[2];
float quantity;
struct nodo * next;
};
我尝试了一些代码,现在我被困在这个(读取功能):
struct nodo * read (struct nodo * top) {
FILE *fp;
fp = fopen("ingredients.txt", "r");
char comment[30];
char comm;
while(!feof(fp)) {
fscanf(fp, "%c", &comm);
if(comm == '#') {
fgets(comment, 30, fp);
}
struct nodo * new = CreaNodo();
fscanf(fp, "%s%s%f", new->ingredient, new->simbol, &new->quantity);
if(!top) top = new;
else {
new->next = top;
top = new;
}
}
fclose(fp);
return top;
}
解决方案
第二个 fscanf 没有非注释行的第一个字符(它在 comm 变量中丢失)。
fgets()'ing 每一行,然后在该行中搜索'#',如果没有找到,则 sscanf()'ing 行更容易(我的观点)并且可能更有 I/O 效率。
推荐阅读
- javascript - Javascript/MaxMSP - javascript 新手,创建循环
- ambari - 从源代码在 CentOS 7 上构建 Ambari 2.7.5,两周前工作,现在失败
- bash - 测试序列化 JSON-B 输出时出现“404 Not Found”错误
- android - 不同类型 Qualcomm DSP 的术语
- hadoop - 水槽正在向我要推送的 hdfs 文件添加一个随机数(test.csv > test.csv.1591560702234)
- c++ - 使用 Wt c++ 时找不到 Postgres 标头
- python - 使用变量类设置 div 内文本的颜色
- python - 试图在 BASEMAP (Python) 上绘制数据点
- javascript - HighCharts:为样条数据集设置 id?
- javascript - 从包含的 JavaScript 中选择父 div