$29
Lab 5
This lab is for the class to understand possible operations on files.
Your task is to write a program that generates a text file called answer.txt.
This is to be done using the fopen() and fclose() functions with appropriate flags and permissions.
In all the operations below, notice how the file operations affect the “cursor” (seek) position in the file.
Note that you can retrieve seek position using ftell().
1. After opening the file, use fwrite() to write the following string to the file:
Hello world, this is my attempt to write to a file using the freade() operation.
Note: when working with on-stack declared char[] variables, sizeof(myString) returns the
number of characters in the string that also includes ‘\0’, so you need to use sizeof(myString)-1. For
malloc’d strings you cannot use sizeof(myString).
2. Notice you made a typo and need to correct it.
a. First, seek to the beginning of the file using the fseek() operation
i. Fseek has multiple pre-defined values that can be used as the third parameter:
SEEK_SET, SEEK_END, SEEK_CUR, read about those in the manual
b. Seek to the beginning of the file
c. Now seek to the position 62 of the file
d. Use ftell() to print the current position of the cursor – should be 62
e. Verify you are about to modify the letter r by using fgetc()
f. Use ftell() to print the current position of the cursor
g. Seek back 1 byte : fseek accepts negative values as a second parameter
h. Use fwrite() to replace “read” with “writ” in the text file
3. Seek to the end of the file
4. Seek 2 positions past the end of the file
5. Try writing “hi” using the fwrite
6. Close the file using fclose()
7. Notice that gedit (the default text editor), as well as the default vscode txt editor complains if
you try to open the file, as the file contains “holes” – i.e. zero bytes
8. Use hexdump -C to observe the proper contents of the file. Looking at the values of the
hexdump, explain what the difference between the three dots is before “hi” at the end of the
file.
Please submit your C file.