Question
Reading and Writing Complete Files in C: The first part of the lab is to write a program to read the complete contents of a
Reading and Writing Complete Files in C:
The first part of the lab is to write a program to read the complete contents of a file to a string. This code will be used in subsequent coding problems. You will need 3 functions: main(), read_file() and write_file(). The main function contains the driver code. The read_file() function reads the complete contents of a file to a string. The write_file() writes the complete contents of a string to a file. The read_file() will require:
Open the file for reading Calculating the size of a file Allocating memory to read the file to a string Rewinding the file to the beginning Reading the files contents to the allocated string Close the file
There are a few ways to calculate the length of a file. Beware that some of these methods actually get the last position of the input buffer, which may not be the file length for very large files. I suggest using getc(file_name) until EOF is read with a counter. getc() reads one char at a time from a data stream. EOF will be read at the end of the text file. The rewind(file_name) function returns the file pointer to the beginning of the file. You can use getc() or fgets() to read the file into the string. Writing the file will require:
Open the file for writing Write the string to file Close the file
You can use putc() or fputs().
The main function should free() allocated memory before returning. Test your program by reading and writing a few files. Make sure to give the written file different names than the read files so you can compare them.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started