在文本文件中搜索字符串并解析该行(Linux、C)
这是“如何解析配置文件”的问题。 基本上我有一个包含所有类型设置的文本文件(/etc/myconfig)。我需要读取该文件并搜索该字符串:
wants_return=yes
一旦找到该字符串,我需要解析它并仅返回等号之后的内容。 我尝试过使用 fgets 和 strtok 的组合,但我在这里感到困惑。 无论如何,有人知道可以执行此操作的函数吗?
代码受到赞赏。
谢谢
This is "how to parse a config file" question.
Basically i have a text file (/etc/myconfig) that has all kind of settings. I need to read that file and search for the string:
wants_return=yes
once I locate that string I need to parse it and return only whatever it is after the equal sign.
I've tried using a combinations of fgets and strtok but I'm getting confused here.
in any case anyone knows a function that can perform this?
Code is appreciated.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这有效:(注意:我不确定 fgets 是否应该在返回的字符串中包含换行符;如果不是,您可以删除对它的检查)
This works: (note: I'm unsure if fgets is supposed to include the newline character in the returned string; if it isn't, you can drop the check for it)
下面是一个使用 strtok 的简单示例:
请注意,您需要对其进行一些额外的错误检查,但这可以解析我扔给它的文件。
Here's a quick example using
strtok
:Note, you'll need to put some additional error checking around it, but this works to parse the files I threw at it.
从您的评论来看,您似乎已经使用 fgets 从文本文件中获取了适当的行并将其加载到字符缓冲区中。您可以使用 strtok 解析该行中的标记。
如果您使用字符串 buffer 作为第一个参数运行它,它将返回该字符串中的第一个标记。如果您在第一个参数设置为 NULL 的情况下运行相同的命令,它将从同一原始字符串返回后续标记。
如何检索多个令牌的简单示例:
对于第二个 strtok 调用,您可以将
"="
替换为""
以返回所有内容到字符串的末尾,而不是在下一个等号处断开。From your comment, it looks like you're already getting the appropriate line from the text file using fgets and loading it into a character buffer. You can use strtok to parse the tokens from the line.
If you run it with the string buffer as the first argument, it will return the first token from that string. If you run the same command with the first argument set to NULL it will return subsequent tokens from the same original string.
A quick example of how to retrieve multiple tokens:
For the second strtok call, you can replace the
"="
with""
to return everything to the end of the string, instead of breaking off at the next equal sign.对于 POSIX shell,我会使用类似以下内容:
当然,如果您正在寻找使用 C STDIO 库的答案,那么您确实需要查看 STDIO 文档。
With a POSIX shell, I'd use something like:
Of course, if you're looking for an answer that uses the C STDIO library, then you really need to review the STDIO documentation.