c - copying content of one file to other using system calls -


here trying copy content of 1 file other(unix) using open read , write system calls reason code running infnite time... , not getting error if me out!!

#include<unistd.h> #include<stdio.h> #include<sys/types.h> #include<fcntl.h> #include<stdlib.h> #include<string.h> int main(int args,char *ar[]) { char *source=ar[1]; char *dest="def.txt"; char *buf=(char *)malloc(sizeof(char)*120); int fd1,fd2; fd1=open(source,o_creat,0744); fd2=open(dest,o_creat,0744); while(read(fd1,buf,120)!=-1) { printf("%s",buf); //printf("processing\n"); write(fd2,buf,120); } printf("process done"); close(fd1); close(fd2); } 

thanx in advance...

there quite few issues in code.

  • the first , obvious is, never check errors (malloc, open, close). in case wondering: yes, need check close.
  • then open calls not correct, because not specify file access mode. quoting man 2 open: the argument flags must include 1 of following access modes: o_rdonly, o_wronly, or o_rdwr. invoking undefined behavior here.
  • also handling of return value of read wrong. check errors, if no error happens, program loop indefinitely. note end-of-file not considered error. instead read returns number of bytes read (which don't check). upon end-of-file return value 0.
  • your main function not return value. try running gcc or clang -wall -wextra see issues these.
  • casting return value of malloc considered harmful way.

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

c++ - End of file on pipe magic during open -