Here:
printf("File copy was successful, with %d byte copied\n", fdDestination );
fdDestination
is a file descriptor, it's not the number of bytes written. 0
, 1
and 2
are your three standard streams, 3
will be your input file which is opened first, so 4
will be your output file, that's why it's always outputting 4
.
You want to save the return value from write()
, and use the value of that instead (after checking that return value for errors, of course, which you should be doing for read()
as well).
EDIT: Slightly modifying your code:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#define My_Full_Name "AAA!"
int main(void) {
size_t buffersize = (size_t) (4 * 5.75);
char buffer[buffersize];
char source_file[200];
char destination_file[200];
ssize_t bytes_read, bytes_written;
int fdSource, fdDestination;
mode_t mode = S_IRUSR | S_IWUSR;
printf("Welcome to File Copy by %s\n", My_Full_Name);
printf("Enter the name of the source file: ");
scanf("%s", source_file);
printf("Enter the name of the destination file: ");
scanf("%s", destination_file);
fdSource = open(source_file, O_RDONLY);
if (fdSource < 0) {
perror("Open failed!!");
return 1;
} else {
bytes_read = read(fdSource, buffer, sizeof(buffer));
fdDestination = open(destination_file, O_CREAT | O_WRONLY | mode);
if (fdDestination < 0) {
perror("Oups!! cannot create file again!!");
return 1;
} else {
bytes_written = write(fdDestination, buffer, sizeof(buffer));
printf("current content of buffer: %s\n", buffer);
printf("current value of buffer size = %zd \n", buffersize);
printf("File copy was successful, with %d byte copied\n",
bytes_written);
}
}
return 0;
}
gives me this:
paul@local:~/src/c/fpc$ cat infile
12345678901234567890123
paul@local:~/src/c/fpc$ ./fpc
Welcome to File Copy by AAA!
Enter the name of the source file: infile
Enter the name of the destination file: outfile
current content of buffer: 12345678901234567890123
current value of buffer size = 23
File copy was successful, with 23 byte copied
paul@local:~/src/c/fpc$ cat outfile; echo ""
12345678901234567890123
paul@local:~/src/c/fpc$