1

A part of this C code is bugging me, and I can't see what I am doing wrong. I am not trying to get someone to write the complete code, since this is my homework assignment, but I would really like to know what am I doing wrong here. So this is a part of main:

FILE *fp,*fd;
fp=fopen("test1.txt","r");
if (fp==NULL)
    return -1;
fd=fopen("test2.txt","w");
if (fd==NULL)
    return -2;
while (fp != EOF){
    fread(fd,1,10,fp);
}
//read_copy(fp,fd);
fclose(fp);
fclose(fd);
return 0;

And I can't seem to figure out why it doesn't work. With while written like this, it goes into an infinite loop. If I try to put a fscanf() in while, it gives me seg fault. So what am I doing wrong? Thx!

unwind
  • 391,730
  • 64
  • 469
  • 606
Nebbs
  • 139
  • 1
  • 9

3 Answers3

1

The fread() function only accepts one argument of type FILE *.

You're essentially overwriting the C library's internal file representation with data from the file.

See any basic reference for the proper prototype for fread(). You need a buffer, something like:

char buffer[1024];

fread(buffer, 1, sizeof buffer, fp);

Also, you must of course check the return value of fread(). Further, I would suggest using better names than fd and fp, they're pretty opaque.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • but the problem is, this way it goes in an infinite loop. What I want is to write from one file to another.. – Nebbs Feb 06 '13 at 11:04
1

This should help: In C, how should I read a text file and print all strings

When using

 fwrite(buf, 1, nread, stdout);

The stdout is the output stream. You can use a file stream ( FILE * ) instead of stdout.

Community
  • 1
  • 1
Yves Lange
  • 3,914
  • 3
  • 21
  • 33
0

You need to read the data into a buffer and write it out. Something like:

FILE *in, *out;
char buffer[SZ]; /* Define some size */
int nrd;

/* Do the whole dance opening files, etc */

while((nrd = fread(buffer, 1, SZ,  in)) > 0)
    fwrite(buffer, 1, nrd, out);

/* If nrd == 0 --> Reached EOF
   If nrd <  0 --> Some kind of error */

The condition in the while tries to read up to SZ bytes and checks what came of it, the fwrite writes out what was read. Check the manual pages.

vonbrand
  • 11,412
  • 8
  • 32
  • 52