c - open() using O_APPEND does not update EOF -
i writing copy of dup() function (i studying book linux api).
i have file named temp.txt contains 1 line following string: hello, world.
here code:
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> //naive implementation int dup_t(int old) { if(old == -1) { errno = ebadf; return -1; } int flags; flags = fcntl(old, f_getfl); if(flags == - 1) { errno = ebadf; return -1; } int new; if((new = fcntl(old, f_dupfd)) == - 1) { errno = ebadf; return - 1; } return new; } int main(int argc, char *argv[]) { if(argc == 1) { printf("error, no arguments given\n"); exit(-1); } int fd, cpfd; if((fd = open(&argv[1][0], o_rdwr | o_append)) == -1) { printf("error opening file\n"); exit(-1); } cpfd = dup_t(fd); if(cpfd == -1) { printf("error dup_t()\n"); exit(-1); } if(close(fd) == -1) { printf("error closing fd\n"); exit(-1); } if(write(cpfd, "kostas", 6) == - 1) { printf("error writting\n"); exit(-1); } if(close(fd) == -1) { printf("error closing fd\n"); exit(-1); } if(write(cpfd, "kostas", 6) == - 1) { printf("error writting\n"); exit(-1); } if(close(cpfd) == -1) { printf("error closing cpfd\n"); exit(-1); } } so, running ./prog temp.txt successfully, file temp.txt must contain following string. hello, worldkostas
by running command cat temp.txt output hello, world, but, if open file on text editor nano hello, world (followed new line contains) kostas.
why cat command produce incorrect output? why there new line added @ end of string hello, world ?
i not looking workaround, interested in finding out reason of error/problem.
the file has been updated to:
hello, world[eol] kostas[no end-of-line here]catoutput file content exactly, wont output final eol, terminal show aftercat:bash> cat xxx hello, world kostasbash>
note: bash> prompt, prompt may contains carrier return, put cursor @ beginning of line, consider situation
before output prompt:
bash> cat xxx hello, world kostas ^cursor here after carrier return:
bash> cat xxx hello, world kostas ^cursor here finally output prompt:
bash> cat xxx hello, world bash> ^cursor here so, prompt may overwrite last line of output of cat if no eol @ end of file.
btw:
- when using
vimopening file, [noeol] shown @ bottom left indicate file without eol @ end of file - when using
zsh,%shown if last command doesn't output eol @ end, , zsh output eol.
Comments
Post a Comment