在文件解析中使用 fgets()
我有一个包含多行的文件。
我正在对文件进行标记,如果标记包含 .word
,我想将该行的其余部分存储在 c 字符串中。
所以如果: 数组:.word 0:10
我想将 0:10 存储在 c 字符串中。
我正在执行以下操作:
if (strstr(token, ".word")) {
char data_line[MAX_LINE_LENGTH + 1];
int word_ret = fgets(data_line, MAX_LINE_LENGTH, fptr);
printf(".word is %s\n", data_line);
}
问题是 fgets()
抓取下一行。我如何获取当前行的剩余部分?这可能吗?
谢谢你,
I have a file which contains several lines.
I am tokenizing the file, and if the token contains contains .word
, I would like to store the rest of the line in c-string.
So if:array: .word 0:10
I would like to store 0:10 in a c-string.
I am doing the following:
if (strstr(token, ".word")) {
char data_line[MAX_LINE_LENGTH + 1];
int word_ret = fgets(data_line, MAX_LINE_LENGTH, fptr);
printf(".word is %s\n", data_line);
}
The problem with this is that fgets()
grabs the next line. How would I grab the remainder of the current line? Is that possible?
Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
strstr() 返回一个指向“:word”第一个字符所在位置的指针。
这意味着如果你加上“:word”的长度(5个字符),你将得到一个指向“:word”后面的字符的指针,这就是你想要的字符串。
strstr() returns a pointer to where the first character of ":word" is found.
This means that if you add the length of ":word" (5 characters) to that, you will get a pointer to the characters after ":word", which is the string you want.
首先,很明显,您只需要对解析的每一行使用一次 fgets,然后使用存储该行的缓冲区。
接下来有一整行,你有几种选择:如果字符串格式是固定的(比如“.word”),那么你可以使用“strstr”函数的结果来定位“.word”的开头,前进6个字符(包括space) 并从找到的位置打印所需的单词。
另一种选择更复杂,但实际上更好一点。它正在使用“strtok”功能。
First of all it is obvious that you need to use fgets only once for every line you parse and then work with a buffer where the line is stored.
Next having a whole line you have several choices: if the string format is fixed (something like " .word") then you may use the result of "strstr" function to locate the start of ".word", advance 6 characters (including space) from it and print the required word from the found position.
Another option is more complex but in fact is a liitle bit better. It is using "strtok" function.
您需要已经将输入读入缓冲区,我假设它是令牌,然后从那里您只需从 strstr 的返回值 + “.word”的长度复制到末尾缓冲区。这就是我要做的:
您可以将 5 或 6 添加到指针位置(取决于“.word”后面是否有空格)以获取该行的其余部分。
另请注意,strncpy 和 fgets 中的大小参数包含终止 NUL 字符的空间。
You need to have already read the input into a buffer, which I'm assuming is token, and from there you just copy from the return value of strstr + the length of ".word" to the end of the buffer. This is what I'd do:
You could add 5 or 6 to the pointer location (depending on whether or not there's going to be a space after ".word") to get the rest of the line.
Also note that the size parameter in strncpy and fgets includes space for the terminating NUL character.