insert text inside a line
-
21-09-2019 - |
Question
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.
Solution
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:
size_t n = strlen(newbuff);
if (n >= 2)
strcpy(o_rec_buf + n - 1, "E\n");
/* memcpy(o_rec_buf+n-1, "E\n", 3); works too */
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, when feof()
returns 'true', no line will be read by fgets
, and buff
will be NULL
, but newbuff
will be unchanged. In other words, newbuff
will contain data from the last fgets
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
and newbuff
not of type char *
?
OTHER TIPS
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'.