|Iman Anwarzai 01d02d99dc done||1 year ago|
|.gitignore||2 years ago|
|LICENSE||2 years ago|
|README.md||2 years ago|
|play_with_binary.c||1 year ago|
The purpose of this exercise is to explore the difference between writing in binary with
fwrite and writing characters with
Write a program in file play_with_binary.c that declares an integer variable
i and uses
fprintf to print the value of
i followed by a newline to a file named outputFile. Set the value of
i to 12 before you print it out. From your favourite text editor open outputFile and look at its contents. Now, look at the file’s contents using the command:
od -A d -c outputFile.
How many bytes are in the file? You can see the total from the
od output or you can use
wc. Be sure that you understand each command.
Add to your program so that it also prints out the value of
i in binary using
fwrite. Again look at outputFile from your favourite editor and using
od -A d -c outputFile. What is the size of the file now? What happens when you change the value of
i to 133? What about 558580545? At what point does the character representation of an integer take more space than its binary representation? If you don’t understand what is going on here, ask a friend or your instructor.
Add to your program so that it creates and opens a file nameFile. Into this file, write your full name. Close the file. Check what you have written by looking at the file contents with an editor or from the command line with
In the same program, open nameFile again - this time for reading. Using
fread, read the first 4 bytes into an integer variable and print out the value of the variable. Add code to check the return value from the
fread call to make sure that you have successfully read 4 bytes. Add a loop that continues to read and print integers, until you have read all of nameFile.
HINT: Use the return value from fread in the loop condition expression. Finally, to discover the «secret» value of your name, add together all the integers. Add code to print to standard out, the secret value of your name.
Push play_with_binary.c and your file nameFile.