In: Computer Science
int main(int argc, char *argv[]){ int fd1, fd2; char buffer[100]; long int n1; if(((fd1 = open(argv[1], O_RDONLY)) == -1) || ((fd2 = open(argv[2], O_CREAT|O_WRONLY|O_TRUNC,0700)) == -1)){ perror("file problem "); exit(1); } while((n1=read(fd1, buffer, 512) > 0)) if(write(fd2, buffer, n1) != n1){ perror("writing problem "); exit(3); } // Case of an error exit from the loop if(n1 == -1){ perror("Reading problem "); exit(2); } close(fd2); exit(0); }
Could anyone fix the two issues in the while loop, so the ouput can be "writing problem : Bad file descriptor"
We need to just read byte by byte from the file i.e. instead of 512 bytes we need to read 1 byte at a time. I just changed the line
while((n1=read(fd1, buffer, 512) > 0))
to
while((n1=read(fd1, buffer, 1) > 0))
now my contents in 1st file are getiing copied and written to 2nd
file.
I'm attaching my code below:
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]){
int fd1, fd2;
char buffer[100]; long int n1;
fd1= open(argv[1], O_RDONLY);
fd2 = open(argv[2],O_CREAT|O_WRONLY|O_TRUNC,0700);
if(fd1==-1 || fd2 == -1){
perror("file problem ");
exit(1);
}
//char buffer[20];
size_t nbytes;
ssize_t bytes_read;
while((n1=read(fd1, buffer, 1) > 0))
if(write(fd2, buffer, n1) != n1){
perror("writing problem "); exit(3);
}
// Case of an error exit from the loop
if(n1 == -1){
perror("Reading problem ");
exit(2);
}
close(fd2);
exit(0);
}