#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; 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); } There is an issue with this code when I run gdb. fd1 and fd2 dont give same values. I set break at
while((n1=read(fd1, buffer, 512) > 0)) to get the values of fd1 and fd2 and then "n" and thentry it again. the values are different. Can you point the mistake and tell me how to fix it
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int fd1, fd2;
char buffer[100];
long int n1;
if((fd1 = open(argv[1], O_RDONLY)) == -1)
{
printf("problem to open file for reading ");
exit(1);
}
if((fd2 = open(argv[2], O_CREAT|O_WRONLY|O_TRUNC,0700)) == -1)
{
printf("problem to open file for writing ");
exit(2);
}
while((n1=read(fd1, buffer, 512)) > 0) //read n1 bytes each time until EOF
if(write(fd2, buffer, n1) != n1) // if the bytes read and written has mismatch
{
printf("writing problem ");
exit(3);
}
if(n1 == -1) // if unable to read bytes
{
printf("Reading problem ");
exit(4);
}
close(fd2);
exit(0);
}
It can be solved using the above code
Get Answers For Free
Most questions answered within 1 hours.