相当于缓冲区上的 fgets?
我最初是使用 fgets() 逐行解析文件。
现在我改变了一些东西,以便我已经将整个文件放在缓冲区中。我仍然喜欢逐行读取该缓冲区以进行解析。是否有为此设计的东西,或者我是否需要创建一个循环来检查 0x0A
char
此时?
I was originally parsing a file line by line using fgets()
.
Now I changed things so that I already have my entire file in a buffer. I still like to read that buffer line by line for parsing purposes. Is there something designed for this, or do I need to make a loop that inspects for 0x0A
char
s at this point?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
memchr
(带有一点您自己的包装器代码,以memcpy
结尾)是完全等价的 - 就像fgets
它需要最大长度将处理(应该是剩余输入缓冲区大小和输出缓冲区大小的最小值)并扫描,直到遇到所需的字符(将是'\n'
)或用完输入/输出空间。但请注意,对于内存缓冲区中已有的数据,您可能希望跳过复制到单独的输出缓冲区的步骤,除非您需要在不修改输入的情况下以空值终止输出。许多初学者 C 程序员经常犯这样的错误:认为他们需要空终止,而实际上只需改进一些接口以采用(指针,长度)对就足够了,允许您传递/处理子字符串而不复制它们。例如,您可以使用以下方法将它们传递给
printf
:printf("%.*s", (int)length, start);
memchr
(with a little bit of your own wrapper code, ending withmemcpy
) is the exact equivalent - likefgets
it takes a maximum length it will process (should be the min of the remaining input buffer size and the size of your output buffer) and scans until it hits the desired character (which will be'\n'
) or runs out of input/output space.Note that for data already in a buffer in memory, though, you might want to skip the step of copying to a separate output buffer, unless you need to null-terminate the output without modifying the input. Many beginner C programmers often make the mistake of thinking they need null termination, when it would really suffice to just improve some of your interfaces to take a (pointer, length) pair, allowing you to pass/process substrings without copying them. For instance you can pass them to
printf
using:printf("%.*s", (int)length, start);
您可以使用 sscanf 函数来实现此目的。如果您确实需要一整行,类似这样的东西应该可以解决问题:(
这将读取最多 50 个字符长的行。一如既往,请小心长度和
0
终止符。并检查返回值的sscanf
以防出现问题。)您可以使用指针算术来移动缓冲区(只需添加“返回”行长度 + 1)。
You could use the
sscanf
function for this. If you actually need a whole line, something like this should do the trick:(This will read lines at most 50 chars long. As always, careful with the length and
0
terminators. And check the return value ofsscanf
in case something went wrong.)You can use pointer arithmetics to move your buffer along (just add "returned" line length + 1).
sscanf 可能适合你,也可能不适合你。
There is sscanf which may or may not work for you.
如果您正在寻找 C 函数,
strtok()
和strsep()
都会根据指定字符分割字符串。If you're looking for C functions,
strtok()
andstrsep()
will both split a string on a specified character.对于 C 语言,我认为这应该有效:
For C, this should work, I think: