c - 如何使用 sscanf 提取子字符串?
问题描述
我有一个文件,其中行具有类似的格式,如下所示:
id: 1 address: tcp://localhost:8101
id: 2 address: tcp://128.134.59.1:8102
现在,对于每一行,我想提取从 tcp 开始的所有内容,直到行尾。我尝试一一读取文件并为此使用 sscanf ,但似乎我的模式匹配是错误的,因为它从不匹配。匹配从 tcp 开始一直到行尾的子字符串的正确方法是什么?
char **id = malloc(sizeof(char *) * (nodes + 1));
for (size_t i = 0; i < nodes; i++) {
char *inter_id = calloc(25, sizeof(char));
if ((read = getline(&line, &len, fp)) != -1) {
if (1 != sscanf(line, "%(tcp:*)", inter_id)) {
fprintf(stderr, "Error: could not parse the address.\n");
exit(1);
}
}
id[i] = inter_id;
}
id[nodes] = NULL;
解决方案
id
这对我有用,假设每行的, number 和之间的空格数address...
是相同的。
int main() {
FILE* file = fopen("file.txt", "r");
char buffer[100];
for (int i = 0; i < 2; i++) {
int id;
// The reading is below. %d refers to the number that will be stored in
// the variable id. %s refers to the char sequence that will be stored in
// the memory pointed by buffer.
fscanf(file, "id: %d address: %s\n", &id, buffer);
printf("%s\n", buffer);
}
fclose(file);
}
file.txt
包含两行:
id: 1 address: tcp://localhost:8101
id: 2 address: tcp://128.134.59.1:8102
程序输出:
tcp://localhost:8101
tcp://128.134.59.1:8102
推荐阅读
- xaml - Xamarin:按钮被框架覆盖
- ruby-on-rails - 在调用关系的类方法中返回原始关系
- lazarus - 防止使用`TSelectDirectoryDialog`时需要手动滚动到“预选”文件夹
- php - 计算拆分中的输入值 - PHP
- c# - 电池耗尽时,紧凑型框架应用程序将被删除
- sql-server - 实体框架核心 - 错误:不支持关键字:“服务器”
- reactjs - 如何使用 create-react-kotlin-app 运行 Kotlin + React + Redux?
- apache-spark - Spark count dataframe 来估计输出分区,然后在没有缓存的情况下高效地写入?
- reactjs - Typescript 如何扩展原生 HTML 元素?
- docker - docker-compose 错误:需要卷而不是字符串