c - Can't use lseek to add a space at the end of a file -
i trying append text opened file. i'd append pid number @ end of file. example: lorem ipsum dolor sit amet orci aliquam. 14872
. code works fine except failing @ making program print space between last character of file , first digit of pid. i've tried use lseek()
adding 1
offset end of file and, said, failed miseably. don't understand what's wrong, because apparently getting expected results:
buffer size: 5. buffer content: 14872. current position: 41.
and output:
lorem ipsum dolor sit amet orci aliquam.14872
which makes no sense me. here 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 space , write pid lseek(fd, 1, seek_end); printf("current position: %d.\n", lseek(fd, 0, seek_cur)); write(fd, buffer, buffer_size); free(buffer); }
seeking off end of file doesn't pad spaces leaves null bytes until written gap. you'll need write leading ' '
pid buffer write end (without seek past end of file).
Comments
Post a Comment