This program is supposed to copy from a source file to a destination file. The files are to be given as command line parameters, source file being the first parameter and the destination file being the second one. My problem is that the contents of source are not entirely copied to the destination. I'll proceed by showing the parts of my program. In the comments I'll give a concrete example of what happens. So my source is a text file containing
Code:
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int fd, fd2, res, size;
char* buffer2;
struct stat buf;
Here I open the source:
Code:
fd = open(argv[1], O_RDONLY);
if(fd == -1) { //File doesn't exist
perror("open: ");
exit(EXIT_FAILURE); //Ends the calling process
}
Here I call stat to get the source's info and I also allocate the source's size to buffer2:
Code:
//the struct buf now contains this file's info(i-node?)
if(stat(argv[1], &buf)<0) {
perror("stat");
exit(EXIT_FAILURE); //error
}
size = buf.st_size;
buffer2 = malloc(sizeof(char)*(size));
Then I read source's contents into buffer2(**Please read the comments**):
Code:
while ((res = read(fd, buffer2, 100)) != 0) {
if (res == -1) {
perror("read: ");
exit(EXIT_FAILURE);
}
//res reaches 19
printf("%s", buffer2); //prints "Oh hi Im that guy"
}
Here I create the destination file:
Code:
if((fd2 = open(argv[2], O_RDWR | O_CREAT | O_TRUNC))==-1) {
perror("open ");
exit(EXIT_FAILURE);
}
Giving it same permissions as source:
Code:
//make destination file's permissions the same as those of the source
if(fchmod(fd2, buf.st_mode) == -1) {
perror("fchmod");
exit(EXIT_FAILURE);
}
Copying contents contents of buffer2 into destination(This is where I think something goes wrong):
Code:
//copying text
if (write(fd2, buffer2, sizeof(buffer2)) != sizeof(buffer2)) {
perror ("write: ");
exit(EXIT_FAILURE);
}
Reading back from destination(**Please read the comments**):
Code:
/* file pointer to file beginning */
if (lseek(fd2, 0, SEEK_SET) == -1) {
perror ("seek: ");
exit(EXIT_FAILURE);
}
// Read-in file in 100 byte blocks
while ((res = read(fd2, buffer2, 100)) != 0) {
if (res == -1) {
perror("read: ");
exit(EXIT_FAILURE);
}
buffer2[res] = '\0'; //res only reaches 8
printf("%s\n", buffer2); // prints "Oh hi Im"
}
Closing the files:
Code:
if (close(fd2) == -1) {
perror("close: ");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
perror("close: ");
exit(EXIT_FAILURE);
}
I've attached the whole .c file for you guys to take a look.