c - Code doesn't work, getting error: segmentation fault(core dumped) -


can explain why snippet of code doesn't work? intended duplicate file, when compile segmentation fault(core dumped), appreciate critics. sorry if there typos.

#include <stdio.h> #include <stdlib.h>  #define bufsize 256 #define maxlen 30  void copy(file *source,file *dest);      int main(void) {        file *fs, *fa;                              // fs source file, fa copy         char file_src[maxlen];                      // name of source file        char file_app[maxlen];                      // name of copy file         puts("file copy program\n\n");        puts("enter name of source file:");        gets(file_src);                             // file name        if(fs=fopen(file_src,"r")==null)           // error checking        {              fprintf(stderr,"cant open %s.\n",file_src);              exit(exit_failure);        }        if(setvbuf(fs,null,_iofbf,bufsize)!=0)   //  set buffer fs         {              fprintf(stderr,"cant create input buffer.\n");              exit(exit_failure);        }        puts("now enter copy name file:");        gets(file_app);                             // file name         if(fa=fopen(file_app,"w")==null)            // error checking        {              fprintf(stderr,"cant open %s.\n",file_app);              exit(exit_failure);        }        if(setvbuf(fa,null,_iofbf,bufsize)!=0)      // set buffer fa        {              fprintf(stderr,"cant create output buffer.\n");              exit(exit_failure);        }        copy(fs,fa);                              // copy file fs fa         if(ferror(fs)!=0)        {              fprintf(stderr,"error in reading file\n");              exit(exit_failure);        }        if(ferror(fa)!=0)        {              fprintf(stderr,"error in writing file\n");              exit(exit_failure);        }        puts("done");        return 0; }  void copy(file *source,file *dest) {        size_t bytes=0;         static char temp[bufsize];         while(bytes=fread(temp,sizeof(char),bufsize,source) > 0)                fwrite(temp,sizeof(char),bytes,dest); } 

this:

if(fs=fopen(file_src,"r")==null) 

is wrong. ending assigning fs null, when open succeeds, not checked , causes fault when null used in later calls.

it must be

if((fs = fopen(file_src, "r")) == null) 

due how operator priority works in c.

by way, generic copying program should open files in binary mode.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -