#include <stdio.h>
int main() {
char *line = NULL;
size_t len = 0;
ssize_t read;
printf("Enter a line of text: ");
read = getline(&line, &len, stdin);
if (read != -1) {
printf("You entered: %s", line);
} else {
printf("Error reading input");
}
free(line);
return 0;
}
- Include the necessary header file for standard input/output operations.
- Define the
main
function. - Declare a pointer
line
to a character and initialize it to NULL
. Declare a variable len
of type size_t
to store the length of the line. - Declare a variable
read
of type ssize_t
to store the number of characters read by getline
. - Prompt the user to enter a line of text using
printf
. - Call the
getline
function, passing the address of the line
pointer, the address of the len
variable, and stdin
as arguments. Assign the return value to the read
variable. - Check if the value of
read
is not equal to -1, indicating successful input. - If input was successful, print the entered line using
printf
. - If there was an error reading input (if
read
is -1), print an error message. - Free the memory allocated for the line using the
free
function. - Return 0 to indicate successful program execution.