在行内插入文本
我有一个文件指针,我将其与 fgets() 一起使用,以给我一个完整的行以及缓冲区中的新行。 我想替换 1 个字符并在新行之前添加另一个字符。这可能吗? 例如:
buffer is "12345;\n"
output buffer is "12345xy\n"
这是代码:
buff = fgets((char *)newbuff, IO_BufferSize , IO_handle[i_inx]->fp);
nptr = IO_handle[i_inx]->fp;
if(feof(nptr))
{
memcpy((char *)o_rec_buf+(strlen((char *)newbuff)-1),"E",1);
}
else
{
memcpy((char *)o_rec_buf+(strlen((char *)newbuff)-1),"R",1);
}
如您所见,我正在替换此处的新行(示例行如上所示)。 我想插入文本并保留新行,而不是我上面所做的事情。
I have a file pointer which I am using with fgets() to give me a complete line along with the new line in the buffer.
I want to replace 1 char and add another character before the new line. Is that possible?
For example:
buffer is "12345;\n"
output buffer is "12345xy\n"
This is the code:
buff = fgets((char *)newbuff, IO_BufferSize , IO_handle[i_inx]->fp);
nptr = IO_handle[i_inx]->fp;
if(feof(nptr))
{
memcpy((char *)o_rec_buf+(strlen((char *)newbuff)-1),"E",1);
}
else
{
memcpy((char *)o_rec_buf+(strlen((char *)newbuff)-1),"R",1);
}
As you can see I am replacing the new line here (example line is shown above).
I want to insert the text and retain the new line instead of what I am doing above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法按照自己想要的方式插入一个字符。如果您确定
o_rec_buf
有足够的空间,并且该行始终以";\n"
结尾,那么您可以执行以下操作:请注意,使用
feof()
像你这样做的方式大多数时候都是错误的。feof()
告诉您在文件命中后是否遇到文件结束条件。如果您在循环中运行上述代码,当feof()
返回 'true' 时,fgets
不会读取任何行,并且buff
> 将为NULL
,但newbuff
将保持不变。换句话说,newbuff
将包含上次fgets
调用的数据。您将处理最后一行两次。请参阅 CLC 常见问题解答 12.2 了解更多信息和解决方案。最后,为什么全是演员?
o_rec_buf
和newbuff
不是char *
类型吗?You can't insert one character the way you want to. If you are sure the
o_rec_buf
has enough space, and that the line will always end in";\n"
, then you can do something like:Note that using
feof()
like the way you do is an error most of the times.feof()
tells you if you hit end-of-file condition on a file after you hit it. If you are running the above code in a loop, whenfeof()
returns 'true', no line will be read byfgets
, andbuff
will beNULL
, butnewbuff
will be unchanged. In other words,newbuff
will contain data from the lastfgets
call. You will process the last line twice. See CLC FAQ 12.2 for more, and a solution.Finally, why all the casts? Are
o_rec_buf
andnewbuff
not of typechar *
?如果缓冲区有足够的空间,您需要使用 memmove 将预告片进一步移动 1 个字符并更新您需要的字符。
确保不要忘记 memmove 结尾的 '\0'。
If the buffer has enough space, you'll need to move the trailer 1 character further, using memmove and update the char you need.
Make sure you do not forget to memmove the trailing '\0'.