954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

filecopy

hi everyone,
the below program is yielding error "segmentation fault",when it is run under unix. This is a file copy program using command line arguements.
Without using command line arguement,i mean,taking filenames directly in the program runs successfully. Can anyone tell me what
"segmentation fault" means in unix?
-------------------

#include<stdio.h>
int main(int argc,char *argv[])
{
   FILE *fp,*ft;
   char ch;
   
   if(argc!=3)
   {
       printf("error");
       exit();
   }
   fp=fopen("argv[1]","rb");
   ft=fopen("argv[2]","wb");
  
   while(!feof(fp))
   {
         ch=fgetc(fp);
         fputc(ch,ft);
   }
   fclose(fp);
   fclose(ft);
 return 0;
}
santoshmath
Newbie Poster
7 posts since Aug 2007
Reputation Points: 10
Solved Threads: 0
 

Since you read neither
http://www.daniweb.com/forums/thread78060.html
nor
http://www.daniweb.com/forums/announcement118-3.html

I'll be brief and mention only one of the bugs in your code.
Remove "argv[1]" quotes.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

The next bug is at line 15 -- feof() doesn't work the way you think. Instead, you should code it like this (which will only work with text files. binary files are coded differently because the EOF character could be a valid character in the file.):

while( (ch=fgetc(fp)) != EOF)
{
   fputc(ch,ft);
}

Another bug: failing to check that the two files were successfully opened. If the source file in argv[1] doesn't exist then no point attempting go open the output file and copy. And if the output file can not be created pointerft will be NULL and the copy loop will fail causing segment violation.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

thank you very much. I successfully ran that program in all compilers-unix,tc,vc++.The real bug was-i took double quote "" to argv[1] and argv[2].Although there was no compiler error,but
both files didn't open successfully

santoshmath
Newbie Poster
7 posts since Aug 2007
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You