I am writing a copy of the dup()
function (I am studying a book for the Linux api).
I have a file named temp.txt
which contains one line with the following string: Hello, World
.
Here is the 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 the 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, by running ./prog temp.txt
successfully, the file temp.txt
must contain the following string. Hello, WorldKostas
By running the command cat temp.txt
the output I get is Hello, World
, but, if I open the file on a text editor like nano
I get Hello, World
(followed by a new line which contains) kostas
.
Why does the cat
command produce an incorrect output?
Why is there a new line added at the end of the string Hello, World
?
I am not looking for a workaround, I am interested in finding out the reason of the error/problem.