I am trying to append some text to an already opened file. I'd like to append the pid number at the end of my file. For example: Lorem ipsum dolor sit amet orci aliquam. 14872
. My code works fine except I am failing at making my program print the space between the last character of the file and the first digit of the pid. I've tried to use lseek()
by adding 1
as offset from the end of the file and, as I previously said, failed miseably. I don't understand what's wrong, because apparently I am getting all expected results:
Buffer size: 5.
Buffer content: 14872.
Current position: 41.
and then this output:
Lorem ipsum dolor sit amet orci aliquam.14872
which makes no sense to me. So here it is my code:
void writeintheend(const int fd, const int pid, const int base)
{
char *buffer;
int buffer_size = getcharsfromint(pid, base);
printf("Buffer size: %d.\n", buffer_size);
buffer = (char *) malloc (sizeof(char) * buffer_size);
sprintf(buffer, "%d", pid);
printf("Buffer content: %s.\n", buffer);
//It should add a space and then write the pid
lseek(fd, 1, SEEK_END);
printf("Current position: %d.\n", lseek(fd, 0, SEEK_CUR));
write(fd, buffer, buffer_size);
free(buffer);
}