c - 在 C 中读取文件的一部分
问题描述
我有一个包含几个不同部分的文件。所有部分都有一个开始部分和结束部分线来区分部分。
如何从第 2 节中读取行?
>start Section-1
Some words are here.
>end Section-1
>start Section-2
Other words are also here.
>end Section-2
使用我当前的代码,所有文件都被打印(除了单词分隔部分之外的所有部分)。我知道问题是在我fgets
读取文件直到#end Section-2 之前,我可能需要另一个while循环来读取特定开始部分的行。但我不确定如何更改代码,以便它只会在第 2 节内输出单词。
预期输出:
Other
words
are
also
here.
我现在得到的:
Some
words
are
here.
Other
words
are
also
here.
我的代码:
#define MAXSTR 1000
#define END ">end Section-2\n"
#define ENDWORD ">end"
#define STRWORD ">start"
#define SECTION "Section-2"
int main () {
FILE *file;
char lines[MAXSTR];
char delim[2] = " ";
char *words;
if ((file = fopen("sample.txt", "r")) == NULL) {
printf("File empty.\n");
return 0;
}
while (strcmp(fgets(lines, MAXSTR, file), END) != 0) {
words = strtok(lines, delim);
while (words != NULL && strcmp(words, STRWORD) != 0
&& strcmp(words, SECTION) != 0
&& strcmp(words, ENDWORD) != 0) {
printf("%s\n", words);
words = strtok(NULL, delim);
}
}
fclose(fileUrl);
return 0;
}
解决方案
你的想法是正确的。关键是当你找到第一个"Section-X"
读取的时候设置一个标志,然后在设置该标志时,标记每一行直到"Section-X"
找到关闭,此时你退出你的读取循环。
"Section-X"
您可以使用整行或仅使用"Section-X"
标识符(我在下面选择)来检查您喜欢的任何内容。要定位"Section-X"
文本,只需使用strrchr()
查找每行中的最后一个空格,然后从下一个字符到您的部分的行尾进行比较,例如
#include <stdio.h>
#include <string.h>
#define MAXC 1024
int main (int argc, char **argv) {
if (argc < 2) { /* validate 1 arg givent for filename */
fprintf (stderr, "usage: %s file [\"Section-X\" (default: 2)]\n", argv[0]);
return 1;
}
const char *section = argc > 2 ? argv[2] : "Section-2", /* set section */
*delim = " ";
char line[MAXC];
int found = 0; /* found flag, 0-false, 1-true */
FILE *fp = fopen (argv[1], "r"); /* open file */
if (!fp) { /* validate file open for reading */
perror ("fopen-fp");
return 1;
}
while (fgets (line, MAXC, fp)) { /* read each line */
line[strcspn (line, "\n")] = 0; /* trim \n from end */
char *p = strrchr(line, ' '); /* pointer to last space */
if (p && strcmp (p + 1, section) == 0) { /* compare "Section-X" */
if (found++) /* check/set found flag */
break; /* break loop if 2nd "Section-X" */
continue;
}
if (found) { /* if found set, tokenize each line */
for (p = strtok (line, delim); p; p = strtok (NULL, delim))
puts (p);
}
}
}
示例使用/输出
将您的输入存储在文件中dat/sections.txt
并读取默认值"Section-2"
:
$ ./bin/read_sections dat/sections.txt
Other
words
are
also
here.
阅读"Section-1"
:
$ ./bin/read_sections dat/sections.txt "Section-1"
Some
words
are
here.
看看事情,如果你有问题,请告诉我。
推荐阅读
- javascript - 构造“const increment = ()();”是什么?用 JavaScript 做什么?
- swift - 通过按下它来更改空数组中uiimageview的颜色
- r - 比较两列并在R中提取不匹配时如何描述
- math - 为什么我们乘以 2 PI 来创建一个圆
- java - 为什么 java 对象比较在 '==' 和 .equals() 方法上都失败了?
- javascript - 浏览器和nodejs上有没有可以将base64字符串转换为utf8字符串的API?
- kubernetes - 如何在 helmchart 中设置自定义发布名称
- php - Facebook登录并通过命令行获取帖子
- java - 如果在并发操作中不存在,则 JPA 插入实体
- node.js - MariaDB 连接到 ExpressJS 访问被拒绝,没有密码错误