0

can anybody show me

wat's wrong with my code .

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
  FILE *fp1,*fp2;
  char ch,ch1;
  fp1=fopen("ma.dat","r");
  fp2=fopen("na.dat","w");
   while(!feof(fp1))
    {
      ch=fgetc(fp1);
      fprintf(fp2,"%c ",ch);
    }    
    fclose(fp1);
    fclose(fp2);

}

i 'm trying to read from a file and writing to another file. some problem exist .

thank's in advance

user1
  • 1
  • 2

1 Answers1

1

Change your while loop -

while(1) // or TRUE or for(;;)
{
  ch=fgetc(fp1);
  // or if (fp1 == -1)
  if (feof(fp1)) { // you're printing eof to fp2... not a good idea.
    break;
  }
  fprintf(fp2, "%c", ch); // or fputc(ch, fp2); your string format included a space!
}

or the shorter (and idiomatic) -

while ((ch = fgetc(fp1)) != EOF) 
  fputc(ch. fp2);

Or your could use the linux specific,

fseek(fp1, 0L, SEEK_END);
long sz = ftell(fp1);
fseek(fp, 0L, SEEK_SET);
sendfile(fp2, fp1, 0, sz);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249