Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program to be written in C, NOT C++: Write a program to offer a list of several

ID: 3850255 • Letter: P

Question

Program to be written in C, NOT C++:

Write a program to offer a list of several functions. When your program is started, show a menu of three functions as follows:

1. Hello World!

2. List files

3. Exit

Please select:

After the user makes his choice by typing the index of the function, your program should read the user input into a 1024-byte buffer, and then execute the corresponding function.

1. If the user input is 1, create a new process with fork()and print out Hello World! in the child process. The parent process should wait for its child process to complete. Then reprint the menu and ask the user for choice.

2. If the user input is 2, create a new process with fork() and run “ls” in the child process to list all the files in the current directory. The parent process should wait for its child process to complete. Then reprint the menu and ask the user for choice.

3. If the user input is 3, the program terminates.

4. If the user input is not 1, 2, or 3, print out an error message, reprint the menu and ask the user for choice.

Here is a sample execution on a Linux machine:

1. Hello World!

2. List files

3. Exit

Please select: 1

Hello World!

1. Hello World!

2. List files

3. Exit

Please select: 2

file1 file2 file3

1. Hello World!

2. List files

3. Exit

Please select: 4

Invalid choice!

1. Hello World!

2. List files

3. Exit

Please select: 3

Hints:
1. You can use the function fgets() to read user input into a buffer.
2. How to use execlp() to list all the files in the current directory.

Explanation / Answer

The code is given below :

#include <iostream> // Needed to perform IO operations
using namespace std;

int main() { // Program entry point
cout << "hello, world" << endl; // Say Hello
return 0; // Terminate main()
}   

output :

1. Hello World!
2. List files
3. Exit
Please select: 1
Hello World!