C fputs
Created By: chatGPT
fputs is a standard C library function used to write a string to a file. Unlike
fprintf
, it writes a string directly without any format specifiers. This function is useful in scenarios where you simply want to output a string to a file or another output stream. Here’s a brief overview of how to use fputs
:// Include the necessary header
#include <stdio.h>
int main() {
FILE *file;
// Open a file in write mode
file = fopen("example.txt", "w");
if (file == NULL) {
perror("Unable to open file!");
return 1;
}
// String to write
const char *str = "Hello, World! This is written using fputs!";
// Write string to file
fputs(str, file);
// Close the file
fclose(file);
return 0;
}
In this example, the str string is written to a file named example.txt using the fputs function. It opens the file in write mode using
fopen
, checks if the file was opened successfully, and then proceeds to write the string. Finally, it closes the file using fclose
to ensure all resources are released properly.// The following code snippet demonstrates how to read back the written content
#include <stdio.h>
int main() {
FILE *file;
char buffer[255];
// Open the file in read mode
file = fopen("example.txt", "r");
if (file == NULL) {
perror("Unable to open file!");
return 1;
}
// Read content from file
fgets(buffer, sizeof(buffer), file);
// Print content to console
printf("Read from file: %s\n", buffer);
// Close the file
fclose(file);
return 0;
}