Write a C program that prompts the user to enter a line of text on the keyboard then echoes the entire line. The program should continue echoing each line until the user responds to the prompt by not entering any text and hitting the return key. Your program should have two functions, writeStr and readLn, in addition to the main function. The text string itself should be stored in a char array in main. Both functions should operate on NUL-terminated text strings.
writeStr takes one argument, a pointer to the string to be displayed, and it returns the number of characters actually displayed. It uses the write system call function to write characters to the screen.
readLn takes two arguments, one that points to the char array where the characters are to be stored and one that specifies the maximum number of characters to store in the char array. Additional keystrokes entered by the user should be read from the OS input buffer and discarded. readLn should return the number of characters actually stored in the char array. It should not store the newline character ‘\n’. It uses the read system call function to read characters from the keyboard.
Explanation:
Code:
#include <unistd.h>
#include <string.h>
int writeStr(char* buffer)
{
buffer[strlen(buffer) + 1] = '\0';
return write(1 ,buffer , strlen(buffer));
}
int readLn(char* buffer,int maxSize)
{
int bytes = read(0, buffer, maxSize);
if(buffer[0] == '\n')
return 0;
return bytes;
}
int main(void) {
char* buffer;
const int maxSize = 45;
while(readLn(buffer,maxSize))
{
int bytesWritten = writeStr(buffer);
}
return 0;
}
OUTPUT:
hello
hello
good morning
good morning
Get Answers For Free
Most questions answered within 1 hours.