Question

Reading and Writing Complete Files in C: The first part of the lab is to write...

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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The above problem can be solved in the following steps-

STEP 1- First we will code the read_file() method. In this function, we will first read a file using file pointer.

We will use read permission to open the file. Then traverse the entire file to compute the length of the file.

Then using dynamic memory allocation, create an array of characters of size=length of file.

Use rewind() function to get to the beginning of file. And again start traversing the file and store each character of file in character array declared above.

Finally, print the contents of character array.

STEP 2- Here we will code the write_file() method. We will use file pointer to open a file with write permission.

Then declare a character array. And ask the user to enter a sentence.

Then using fputs() method, put this sentence in the file opened. And finally close the file pointer.

Check the file if the sentence was written properly.

STEP 3- In the main method, we will call the read_file() and write_file() methods.

C CODE-

#include <stdio.h>
#include <stdlib.h>
//fuction to read file
void read_file(){
   //create a FILE pointer
   FILE *fptr;
   //character variable
   char ch;
   //to store the length of file
int lengthFile = 0;
//open a file, here file name is scores.txt and open it with read permission
fptr = fopen( "read.txt" , "r" );
  
//check if fptr is NULL, means there was error in opening file
   if(fptr == NULL){
       printf("Error opening file");
       //exit the code
       exit(0);
   }
  
//run a loop till the file ptr eaches EOF
    while(1) {
        //store the character
   ch = fgetc(fptr);
   //if we've reached End of File, break the loop
   if( ch == EOF ) {
      break ;
       }
       //increment the length of file
       lengthFile++;
   }
   //char array declared using dynamic allocation
char *s = (char *)malloc(lengthFile * sizeof(char));
//rewind the file ptr to point to beginning of file
rewind(fptr);
printf("\n");
//counter for string
int i = 0;
//again run a loop to traverse the file
while(1) {
        //store the character
        ch = fgetc(fptr);
        //check if we've reached End of file
   if( ch == EOF ) {
   break ;
   }
   //store the character to string
   s[i] = ch;
   i++; //increment counter
}
//display the file string
for(int k=0;k<lengthFile;k++){
    printf("%c",s[k]);
}
//close the file pointer
fclose(fptr);
}
//function to write to a file
void write_file(){
   //file pointer
   FILE *fptr;
   //character variable
   char ch;
   //open a file with write permission
   fptr = fopen("write.txt","w");
   //declare a character array
   char str[10000];
   //check if fptr is NULL, means there was error in opening file
   if(fptr == NULL){
       printf("Error opening file");
       //exit the code
       exit(0);
   }
   //prompt user to enter a sentence
   printf("\n\nEnter sentence to be written : ");
  
   fgets(str, sizeof(str), stdin);   //store the user input
  
   //put the string onto the file
   fputs(str, fptr);
   //close the file
   fclose(fptr);
}
//main method that calls the read_file and write_file method
int main()
{
read_file();
write_file();
return 0;
}

Image of C CODE-

OUTPUT-

read.txt

output on console-

write.txt

If this answer helps, please give an up vote and feel free to comment for any query.

Add a comment
Know the answer?
Add Answer to:
Reading and Writing Complete Files in C: The first part of the lab is to write...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a C Program that uses file handling operations of C language to copy the contents...

    Write a C Program that uses file handling operations of C language to copy the contents of a file called “original.dat” to another file called “copy2.dat”. Here, you will read and write from/to the files line by line with the help of fgets() and fputs() functions. Sample file “original.dat” has been provided. Please note that the new file “copy2.dat” should have exactly same contents as in “original.dat”. #include <stdio.h> int main() { FILE *fptr1, *fptr2; if((fptr1=fopen("original.dat","r"))==NULL) printf("\n Error opening File");...

  • How do I complete this problem? * CENGAGE MINDIAP > Terminal Opening Files and Performing FileInput...

    How do I complete this problem? * CENGAGE MINDIAP > Terminal Opening Files and Performing FileInput in C++ 0 Opening Files and Performing File Input Flowers.cpp flowers.dat 1 // Flowers.cpp - This program reads names of flowers and whether they are grown in shade or sun from an input 2 // file and prints the information to the user's screen. 3.// Tnput: flowers.dat. 4 // Output: Names of flowers and the words sun or shade. Summary In this lab, you...

  • Task 1: Reading files Part A - Read a word Implement a function word from.file(file) that...

    Task 1: Reading files Part A - Read a word Implement a function word from.file(file) that takes a file as input and returns the first word in the file. Hint: the string methods split and strip will be useful. Example: calling word from file('files/task1A.txt') returns 'Once'. Part B - Read a table Implement a function nested int.list from file(file) that takes a file containing lines of integers that are separated by commas as input and returns the file contents formatted...

  • 16.43 Lab 13C: Palindromes with Files and Functions Overview This is a demonstration of reading and...

    16.43 Lab 13C: Palindromes with Files and Functions Overview This is a demonstration of reading and writing files, along with using user-defined functions. Objectives Be able to read from an input file, perform string manipulation on each line of the file within a function, and write to an output file. Provided input file: A single input file named myinput.txt is provided that contains a few lines of text. bob sees over the moon never odd or even statistics dr awkward...

  • In Python Please! 16.42 Lab 13B: Palindromes with Files Overview This is a demonstration of reading...

    In Python Please! 16.42 Lab 13B: Palindromes with Files Overview This is a demonstration of reading and writing files. Objectives Be able to read from an input file, perform string manipulation on each line of the file, and write to an output file. Provided input file: A single input file named myinput.txt is provided that contains a few lines of text. bob sees over the moon never odd or even statistics dr awkward Provided output file: A single output file...

  • Writing Unix Utilities in C (not C++ or C#) my-cat The program my-cat is a simple...

    Writing Unix Utilities in C (not C++ or C#) my-cat The program my-cat is a simple program. Generally, it reads a file as specified by the user and prints its contents. A typical usage is as follows, in which the user wants to see the contents of my-cat.c, and thus types: prompt> ./my-cat my-cat.c #include <stdio.h> ... As shown, my-cat reads the file my-cat.c and prints out its contents. The "./" before the my-cat above is a UNIX thing; it...

  • You will be reading in 3 files in the program. One will contain a list of...

    You will be reading in 3 files in the program. One will contain a list of 1000 words in unsorted order. The second file will contain 1000 words in sorted order. The final file will contain 20 words to be searched for. The main program has been written for you. You will be implementing three functions: bool readWords(string array[], int size, string fileName); int linearSearch(string wordToFind, const string words[], int size); int binarySearch(string wordToFind, const string words[], int size); The...

  • need this in c programming and you can edit the code below. also give me screenshot...

    need this in c programming and you can edit the code below. also give me screenshot of the output #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define LINE_SIZE 1024 void my_error(char *s) { fprintf(stderr, "Error: %s\n", s); perror("errno"); exit(-1); } // This funciton prints lines (in a file) that contain string s. // assume all lines has at most (LINE_SIZE - 2) ASCII characters. // // Functions that may be called in this function: // fopen(), fclose(), fgets(), fputs(),...

  • A. File I/O using C library functions File I/O in C is achieved using a file...

    A. File I/O using C library functions File I/O in C is achieved using a file pointer to access or modify files. Processing files in C is a four-step process: o Declare a file pointer. o Open the desired file using the pointer. o Read from or write to the file and finally, o Close the file. FILE is a structure defined in <stdio.h>. Files can be opened using the fopen() function. This function takes two arguments, the filename and...

  • In Unix/Linux, input and output are treated as files and referenced by the operating system using file descriptors. When you open a shell session, for example, three file descriptors are in use: 0 st...

    In Unix/Linux, input and output are treated as files and referenced by the operating system using file descriptors. When you open a shell session, for example, three file descriptors are in use: 0 standard input (stdin) 1 standard output (stdout) 2 standard error (stderr) By default, the command interpreter (shell) reads keyboard input from file descriptor 0 (stdin) and writes output to file descriptor 1 (stdout), which appears on the screen. As you explored in Lab 2, input/output can be...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT