Question

In: Computer Science

C program! Create a list of 5 things-to-do when you are bored (in the text file...

C program!

Create a list of 5 things-to-do when you are bored (in the text file things.txt, one line each), where each thing is described as a string of characters of length in between 10 and 50.

Design a C program to read these things in (from stdin or by input redirection) and store them in the least memory possible (i.e., only the last byte in the storage for each string can be the null character).

After reading things in, your C program continues to accept input from the user, it ignores whatever the user enters but the return key, and for each return key it randomly chooses one out of the 5 things to print to the stdout.

Your C program iterates the process for ever until the user enters an EOF (which means by input redirection your program terminates at the end of file).

By randomly choosing a thing, it means you should try to make the probability distribution as evenly as possible to any one of the 5 things-to-do.

Any help is appreciated!!

Thank you!!

Solutions

Expert Solution

The C program to handle a file with 5 lines and randomly print one line from the file till user enter EOF is:

#include<stdio.h>
//Including stdlib to use exit() function
#include<stdlib.h>
//Including time.h library to seed srand() function
#include<time.h>

//random() function returns a random number in specified range
int random(){
    //srand() sets seed for rand() function to generate random function
    srand(time(NULL));
    //rand()%max generates a random number in range (0,max)
    int number= rand()%5;
    return number;
}

//Program execution starts here
int main(){
    /*For communication between file and program we need to
    create a pointer of type FILE */
    FILE *fptr;
    //Declaring a string array of size 5 with each string size 50
    char text_lines[5][50];

    /*fopen("textfile","r") is a function to open a textfile.
    Second argument denotes mode. "r" is used for reading*/
    //If file is empty then error message is printed
    if((fptr=fopen("C:\\hobbies.txt","r"))==NULL){
        printf("Error reading file");
        exit(1);
    }
    int i=0;
    /*fgets() function gets a line from the opened text file
    and stores the line in first argument*/
    //Storing each new line in already declared char array text_lines
    while(fgets(text_lines[i],sizeof text_lines[i],fptr)!=NULL){
        fscanf(fptr,"%[^\n]",text_lines[i]);
        i++;
    }
    //We are done with the file. So closing file opening fclose()
    fclose(fptr);
    char lines[25];
    int rand_num;
    printf("Entering infinite loop. Press EOF(-1) to exit.\n");
    /*Entering a infinte loop to repeatedly take a input from user
    and randomly print a line from the textfile*/
    //The loop exits when user enter EOF
    //Remember value of EOF in c is -1.
    //So when user enter -1 this loop terminates
    while(i!=-1)
    {
        printf("Enter ctrl+z to exit, else enter input: ");
        scanf("%s",&lines);
        if (atoi(lines)==EOF)
        {
            break;
        }
        
        /*Calling random() funciton to randomly get a index
        to access text_lines[] array which contain the read file*/
        rand_num = random();
        printf("%s\n",text_lines[rand_num]);
    }
    printf("\nGood bye!!!");
    return 0;
}

To access a file in a program we first need to create a pointer of FILE to allow communication between the file and program. To read a file from a directory we need to use fopen() function and mention the file directory in the fopen() function. This opens the file in program.

Now to read a line from the file I used fgets() function reads a line from the opened file. Remember that gets() function is similar to scanf() function but unlike scanf() function gets() function reads a entire line. Similarly fgets() reads only one line from a file. '

I have stored each line in a String array to randomly print a line when user enter a input and enter a return key. Then I randomly printed a line of the file stored in string array by randomly generating a index value.

I have tested the code and validated output.The code is working good. I am sharing the test file I created and the output of the program.

Remember the file directory and the file name I mentioned in fopen() function is the file in my computer. You should create a text file in your computer and paste the file directory and file name in the fopen() function in code for executing the code.

**If you don't change the directory in fopen() function to your file directory the code will throw error.

Hope this answer helps you.

Thank you :)


Related Solutions

C or C++ program Create a list of 5 things-to-do when you are bored (in the...
C or C++ program Create a list of 5 things-to-do when you are bored (in the text file things.txt, one line each), where each thing is described as a string of characters of length in between 10 and 50. Design a C program to read these things in (from stdin or by input redirection) and store them in the least memory possible (i.e., only the last byte in the storage for each string can be the null character). After reading...
Write a C++ program to create a text file. Your file should contain the following text:...
Write a C++ program to create a text file. Your file should contain the following text: Batch files are text files created by programmer. The file is written in notepad. Creating a text file and writing to it by using fstream: to write to a file, you need to open thew file as write mode. To do so, include a header filr to your program. Create an object of type fsrteam. Open the file as write mode. Reading from a...
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. In paragraph 1 Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. In pragraph 2 Replace "We" with v"i" This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would...
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. Replace "sh" with ph This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would not do that Paragraph 2 We...
WRITE A C++ PROGRAM TO IMPLEMENT THE CONCEPT OF INDEX (Create index in text file)
WRITE A C++ PROGRAM TO IMPLEMENT THE CONCEPT OF INDEX (Create index in text file)
Create a c++ program that: Create an input file using notepad ( .txt ). When testing...
Create a c++ program that: Create an input file using notepad ( .txt ). When testing your program using different input files, you must change the filename inside your program otherwise there will be syntax errors. There are a finite number of lines to be read from the data file. But we can’t assume to know how many before the program executes; so, the standard tactic is to keep reading until you find the “End of File” marker. Input date...
Write a C program that Reads a text file(any file)  and writes it to a binary file....
Write a C program that Reads a text file(any file)  and writes it to a binary file. Reads the binary file and converts it to a text file.
Add an item to a Text File / C++ the program will prompt for a filename...
Add an item to a Text File / C++ the program will prompt for a filename AND then prompt for a text file item. text file items always contain an unknown amount of spaces, (see getline). Allow the user to put both the filename and the extensions, like groceries.txt or retirementToDo.clist Don't add any directory information to the filenames, use them as typed. If the file does exist, the item will be APPENDED to the end of the file. If...
Using C++, write a code that this program always stores text file output into a text...
Using C++, write a code that this program always stores text file output into a text file named "clean.txt". -The program should read one character at a time from "someNumbers.txt", and do the following. -If it is a letter, print that letter to the screen, AND also store it in the text file. All letters should be converted to lowercase beforehand. -If it is a number, print that number to screen, but do NOT store it in the text file....
Python File program 5: Word Frequencies (Concordance)    20 pts 1. Use a text editor to create...
Python File program 5: Word Frequencies (Concordance)    20 pts 1. Use a text editor to create a text file (ex: myPaper.txt) It should contain at least 2 paragraphs with around 200 or more words. 2. Write a Python program (HW19.py) that asks the user to provide the name of the text file. Be SURE to check that it exists! Do NOT hard-code the name of the file! Use the entry provided by the user! read from the text file NOTE:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT