Call system UNIX - File copy in C -
i try create copy of source file target file empty.
the algorithm is: read stdin , write source file, read on file , write text in target file.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #define buffsize 8192 int main(){ int fdsource, fdtarget; int n, nr; char buff[buffsize]; fdsource = open("source.txt", o_rdwr | o_creat, s_irusr | s_iwusr); // create , open source file in read/write if (fdsource < 0){ printf("source file open error!\n"); exit(1); } fdtarget = open("target.txt", o_wronly | o_creat, s_irusr | s_iwusr); // create , open source file in write if (fdtarget < 0){ printf("target file open error!\n"); exit(1); } printf("\ninsert text:\n"); while ((n = read(stdin_fileno, buff, buffsize)) > 0){ // read stdin , write source file if ((write(fdsource, buff, n)) != n){ printf("source file write error!\n"); exit(1); } } while ((read(fdsource, buff, n)) > 0){ // read source file , write target file if ((write(fdtarget, buff, n)) != n){ printf("source file open error!\n"); exit(1); } } close(fdsource); close(fdtarget); exit(0); return 0; }
the problem code "you have opened both file in initial stage". solve problem open source file in write mode , write data, close , reopen source file in read mode, open target file in write mode. modified code given below , not tested
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #define buffsize 8192 int main(){ int fdsource, fdtarget; int n; char buff[buffsize]; fdsource = open("source.txt", o_rdwr | o_creat, s_irusr | s_iwusr); // create , open source file in read/write if (fdsource < 0){ printf("source file open error!\n"); exit(1); } printf("\ninsert text:\n"); while ((n = read(stdin_fileno, buff, buffsize)) > 0){ // read stdin , write source file if ((write(fdsource, buff, n)) != n){ printf("source file write error!\n"); exit(1); } } close(fdsource); fdsource = open("source.txt", o_rdwr | o_creat, s_irusr | s_iwusr); // create , open source file in read/write if (fdsource < 0){ printf("source file open error!\n"); exit(1); } fdtarget = open("target.txt", o_wronly | o_creat, s_irusr | s_iwusr); // create , open source file in write if (fdtarget < 0){ printf("target file open error!\n"); exit(1); } while ((read(fdsource, buff, n)) > 0){ // read source file , write target file if ((write(fdtarget, buff, n)) != n){ printf("source file open error!\n"); exit(1); } } close(fdsource); close(fdtarget); exit(0); return 0; }
if wrong anywhere use logic mentioned above.
Comments
Post a Comment