Question

Write a C program to print the contents of a text file line-by-line but backwards so...

Write a C program to print the contents of a text file line-by-line but backwards so that the last line is printed first. The filename should be specified as a command-line argument.

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

For this problem, we need to have knowledge of command line arguments and file handling. Following is the brief overview of the code which is meant for the same.

  • First, the file name passed as cmd arguments should be checked whether it is correct or not.
  • Then as file reading is done from top to down, but we want it in the reverse order so we can just call the function recursively and print the line by line data in reverse order.
  • For the recursive function, the base case would occur when we are unable to read anything i.e. at the end of the file.
  • Otherwise, we need to call this function recursively and then print the current line read.

Following is the code for the same.

#include<stdio.h>
#include<stdlib.h>
void printInReverse(FILE *fp){
   // defining the variables for using the getline function.
   int len = 0;
    int read = 0;
   char *line = NULL;
   // using the getline function for finding reading line by line
   read = getline(&line, &len, fp);
   // if it is the last line then return
   if(read == -1){
      return;
   }else{
      // calling recursively for next lines
      // and then print the line
      printInReverse(fp);
      printf("%s
", line);
   }
}
int main(int argc,char* argv[])
{
   // storing the file_name in this variable
   char *file_name;
    int counter;
    if(argc==1)
       // if no file name is given
        printf("
No File Name passed");
    if(argc==2)
    {
        // if it is given
        file_name = argv[1];
      // file pointer
      FILE *fp;
      // opening the file
      fp = fopen(file_name, "r");
      // checking if the file is not opened properly
      if(fp == NULL){
         printf("File Not Present or wrong file given");
      }
      // calling the function for printing the lines in reverse order
      printInReverse(fp);
      // last print statement
      printf("Done Reading ! ! !");
      // closing the file
      fclose(fp);
    }else{
       printf("Command line arguments should not be other than file name");
   }
    return 0;
} 

The file which is taken as the input is as follows:

This is the first line
This is the second line
This is the third line
This is the forth line
.
.
.
This is the second last line
This is the last line

The snippet of the sample Output:

If you have any problem regarding the understanding of the solution, do let me know in the comment section.

Don't forget to like the solution, it really means a lot!

Thanks!

Add a comment
Know the answer?
Add Answer to:
Write a C program to print the contents of a text file line-by-line but backwards so...
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
  • In C Programming Language, write a simple program to read one text file and print to...

    In C Programming Language, write a simple program to read one text file and print to screen all its text. Make use of the stderr and exit program statements should there not be only one text file identified on the command line. If successful then before fclose of the text file, use the fputs program statement to write a line "72 degrees Sunny light wind. Nice!\n". print the return code of fputs (should be zero). close and exit. Test program...

  • Write a C program to run on ocelot to read a text file and print it...

    Write a C program to run on ocelot to read a text file and print it to the display. It should optionally find the count of the number of words in the file, and/or find the number of occurrences of a substring, and/or take all the words in the string and sort them lexicographically (ASCII order). You must use getopt to parse the command line. There is no user input while this program is running. Usage: mywords [-cs] [-f substring]...

  • //Done in C please! //Any help appreciated! Write two programs to write and read from file...

    //Done in C please! //Any help appreciated! Write two programs to write and read from file the age and first and last names of people. The programs should work as follows: 1. The first program reads strings containing first and last names and saves them in a text file (this should be done with the fprintf function). The program should take the name of the file as a command line argument. The loop ends when the user enters 0, the...

  • Write a C program called last10 that prints the last ten lines of a text file....

    Write a C program called last10 that prints the last ten lines of a text file. The program can be used from the command line with: last10 filename or last10 If there is no filename, last10 processes standard input.

  • Write a complete C program that inputs a paragraph of text and prints out each unique...

    Write a complete C program that inputs a paragraph of text and prints out each unique letter found in the text along with the number of times it occurred. A sample run of the program is given below. You should input your text from a data file specified on the command line. Your output should be formatted and presented exactly like the sample run (i.e. alphabetized with the exact spacings and output labels). The name of your data file along...

  • (Python 3) Write a program that reads the contents of a text file. The program should...

    (Python 3) Write a program that reads the contents of a text file. The program should then create a dictionary in which the keys are individual words found in the file and the values are the number of times each word appears and a list that contains the line numbers in the file where the word (the key) is found. Then the program will create another text file. The file should contain an alphabetical listing of the words that are...

  • in c++ please. Write a program that reads the contents of a text file. The program...

    in c++ please. Write a program that reads the contents of a text file. The program should create a map in which the keys are the individual words found in the file and the values are the number of times each word appears. For example, if the word "the" appears 128 times, the map would contain an element with "the" as the key and 128 as the value. The program should either display the frequency of each word or create...

  • Write a program to read a text file, place each line it reads into an array....

    Write a program to read a text file, place each line it reads into an array. Then print the array’s contents one line at a time. Then add to the end of the text file “Success”. Use error exception handling and if the text file does not exist print "Error file not found." Always print "It worked." as part of the try clause. Upload a zip folder file of the .py and text file. roses are roses are red, violets...

  • Write a C program which will display the contents of a file in base-16 (hexadecimal) and...

    Write a C program which will display the contents of a file in base-16 (hexadecimal) and in ASCII. Complete the following tasks: Obtain the name of the input file from the command line. If the command-line is “./hexdump xxx.bin” then argv[1] will contain “xxx.bin”. Open the file for binary input Print the entire file, 16-bytes per line. Each line should begin with an 8-digit hexadecimal offset into the file. This is the count of the bytes that you have already...

  • C++ (1) Write a program to prompt the user for an input and output file name....

    C++ (1) Write a program to prompt the user for an input and output file name. The program should check for errors in opening the files, and print the name of any file which has an error, and exit if an error occurs. For example, (user input shown in caps in first line, and in second case, trying to write to a folder which you may not have write authority in) Enter input filename: DOESNOTEXIST.T Error opening input file: DOESNOTEXIST.T...

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