C - String Output Functions

In C, you can use several standard library functions to output strings to the console or other output streams. These functions help you display text and formatted strings to the user. Here are some commonly used string output functions in C:

1. printf:

printf is a versatile output function used for formatted output in C. You can use the %s format specifier to display strings.

char greeting[] = "Hello, World!";
printf("Message: %s\n", greeting);

2. puts:

puts is used to display a string followed by a newline character ('\n') to the console. It automatically adds a newline character at the end of the string.

char message[] = "This is a message.";
puts(message);

3. fputs:

fputs is similar to puts, but it allows you to specify the output stream. You can use fputs to write a string to a file or a different output stream.

char data[] = "Data to write to a file.";
FILE *file = fopen("output.txt", "w");
fputs(data, file);
fclose(file);

4. putc and fputc:

putc and fputc are used to output individual characters to the console or a file. You can use them to output each character of a string individually.

char word[] = "Hello";
for (int i = 0; word[i] != '\0'; i++) {
putc(word[i], stdout);
}

5. fwrite:

fwrite is used to write data, including strings, to a file. It allows you to specify the number of elements, size of each element, and the output stream.

char buffer[] = "Data to write to a binary file.";
FILE *binaryFile = fopen("data.bin", "wb");
fwrite(buffer, sizeof(char), strlen(buffer), binaryFile);
fclose(binaryFile);

6. fprintf:

fprintf allows you to format and print strings to a specified output stream, including the console or a file.

int num = 42;
FILE *output = fopen("output.txt", "w");
fprintf(output, "The answer is %d.\n", num);
fclose(output);

These functions are useful for displaying and writing strings in C programs. Choose the appropriate function based on your specific requirements, whether you need formatted output, automatic newline handling, or writing to files.