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.
You can’t insert one character the way you want to. If you are sure the
o_rec_bufhas 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, andbuffwill beNULL, butnewbuffwill be unchanged. In other words,newbuffwill contain data from the lastfgetscall. 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_bufandnewbuffnot of typechar *?