Hi,
I wrote this simple file copy program to copy contents from input to output file. The program kind of rins into an infinite loop at read/write stage. Can anyone please point out where I am going wrong.
Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
/* size of chunk to be transfered */
#define CHUNK_SIZE 512
int main(int argc, char *argv[]){
int infile_fd, outfile_fd; /* input and output file descriptors */
int error_read = 0; /* variables to record error status */
long *ptr;
/* check for right cmd line arguments */
if(argc != 3){
fprintf(stdout,"Usage : %s <input_file> <output_file>\n", argv[0]);
exit(1);
}
/* Open input file for reading */
if((infile_fd = open(argv[1], O_RDONLY)) == -1){
fprintf(stdout, "Cannot open file for reading\n");
exit(1);
}
/* open output file for writing */
if((outfile_fd = open(argv[2], O_WRONLY | O_CREAT)) == -1){
fprintf(stdout, "Cannot open file for writing\n");
exit(1);
}
/* Alllocate CHUNK SIZE of array from heap */
ptr = (void *)malloc(CHUNK_SIZE);
/* read returns 0 when end of file is reached */
while((error_read = read(infile_fd, ptr, CHUNK_SIZE)) != 0){
write(outfile_fd, ptr, CHUNK_SIZE);
}
close(infile_fd);
close(outfile_fd);
free(ptr);
return 0;
}
Thanks,
Livin