Pig
Pig

Reputation: 2122

How to check if fwrite() works in C?

I am trying to read 256 bytes of whatever data in my input file and construct the information of them into a struct, then write that struct into my output file. Since I can't simply open and read the output file, I wonder what I should do to make sure I have sucessfully written the struct to my output file?

Upvotes: 0

Views: 1177

Answers (5)

James McPherson
James McPherson

Reputation: 2576

You've got several basic issues. Firstly, you need to verify that the data you have read in is valid. Secondly, having constructed your data structure in memory you need to write it out to a different file. Thirdly, you want to guarantee that this has been written out correctly - but you don't say what you are allowed to in order to verify the output file's correctness.

Reading the data in is easy - fread() is your friend here. I would read it all into a (void *) of the appropriate size.

What I've done in similar data in / data out use-cases in the past is to include a simple (depending on the application) checksum as the first element in your output data structure. Use bcopy() or memcpy() to transfer your read-in data to your output structure, then calculate the checksum on the data and update the checksum field.

Finally, you fwrite() all that data to the output file, and check the return value - the number of objects written out. If there is an error (number written is less than desired), you need to check errno and handle the error case. In my copy of the manual (Solaris 11.x), the error codes possible for fwrite(3c) are those for fputc(3c).

Finally finally, you can determine whether sufficient bytes have been written to the output file by comparing the statbut from a stat() call immediately after opening the output file, and one immediately your fwrite() + fclose() has returned.

Upvotes: 0

lillibolero
lillibolero

Reputation: 1

Check the return code as chux suggested. Open the input and output files in a hex editor and compare the first 256 bytes. Emacs has one that works well enough.

Upvotes: -1

jia103
jia103

Reputation: 1134

If you opened the file for reading and writing, you should also be able to fseek to the beginning (offset 0) and re-read the file from there. That's assuming you're ok with opening the file for reading and writing together.

Upvotes: -1

Mustafa Chelik
Mustafa Chelik

Reputation: 2184

You can read again the file and cast it to your struct and check it's values.

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60017

Check the return value from fwrite- i.e. read manual page http://www.cplusplus.com/reference/cstdio/fwrite/

Upvotes: 3

Related Questions