tags:

views:

303

answers:

5
#include<stdio.h>


void main()
{
FILE  *fp,*fp1;
char c;
fp=fopen("test.txt","r");
fp1=fopen("test1.txt","w");
c=getc(fp);
while(c!=EOF)
{
 if (c=="")
 {
  c=getc(fp);
  continue;
 }
 else 
  fprintf(fp1,"%s",c);
 c=getc(fp);
}
fclose(fp);
fclose(fp1);

}
+9  A: 

Because character is not a string.

Try fputc.

BTW: The c should be int, otherwise you won't be able to detect EOF. EOF > 255.

EFraim
Nitpick: EOF is usually (but doesn't have to be) less than 0.
Michael Burr
+5  A: 

c=="" also won't work like you think it does.

Blindy
+3  A: 

Your problem is the fprintf("%s") of the variable c. c is not a string, it's a single character. Replace that line with

fprintf(fp1,"%c",c);

And it will work. There are better ways to actually copy the contents of one file to another.

Nelson
better ways like?
mekasperasky
Well the best way would be "cp". But I gather this is an exercise or you're trying to do something more interesting, like filter the contents while copying.The biggest problem with the approach above is reading a character at a time is very slow. At a minimum you want to read and write the files a chunk at a time via read()/write() or fread()/fwrite() or the like with a block size of about 16k.
Nelson
yeah i am stripping all the white spaces .. developing a lexer. so as of now its not working with that method
mekasperasky
+6  A: 

There are a number of things wrong with the code that might cause problems.

fp and fp1 should be checked against NULL after being assigned the result of fopen to check for file open failures.

The type of c should be int so that you can properly distinguish EOF from a valid character read correctly.

c == "" attempts to compare character value with the address of a literal zero-length string.

fprintf(fp1,"%s",c) interprets that character value c as the address of a constant string and attempts to follow this address to print a string. This is the most likely error to cause a segmentation fault.


Less important style issues.

The return value of main should be an int. It's portably correct even if many implementations do allow void main(void).

As the body of your if clause matches what would happen if the loop ran to the end and is followed by a continue, it would be probably be clearer to remove this clause and apply an if statement with the opposite of what you think c=="" should become, to what is currently the else statement.

Charles Bailey
A: 

The code gives segmentation fault due to illegal memory access, fprintf looks for null character to terminate and in this process accesses invalid memory location.
Also file pointers must be checked for null and code should exit gracefully if any of them is null otherwise it will also cause a segfault.

Neeraj