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!

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

but the problem is, this way it goes in an infinite loop. What I want is to write from one file to another..
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.