fputs() is a standard library function in C programming used for writing a string to a file.
It writes the null-terminated string pointed to str and identifies the specified output file stream.
File Output: `fputs()` enables writing entire strings to files and output text data.
Error Handling: The return value of `fputs()` can be used to check for errors during the write operation.
int fputs(const char *str, FILE *stream);
"str": Pointer to the null-terminated string to be written.
"stream": Pointer to a "FILE" object that identifies the output stream.
The "fputs()" function returns a non-negative value on success, or "EOF" (defined in "stdio.h") on failure.
#include <stdio.h> int main() { FILE *file; char str[] = "Hello, world!\n"; // Open the file in write mode file = fopen("output.txt", "w"); // Check if file opened successfully if (file == NULL) { perror("Error opening file"); return 1; } // Write the string to the file if (fputs(str, file) == EOF) { perror("Error writing to file"); fclose(file); return 1; } // Close the file fclose(file); printf("String written to file successfully.\n"); return 0; }
#include <stdio.h> int main() { FILE *file; char str[] = "This line will be appended.\n"; // Open the file in append mode file = fopen("output.txt", "a"); // Check if file opened successfully if (file == NULL) { perror("Error opening file"); return 1; } // Write the string to the file if (fputs(str, file) == EOF) { perror("Error writing to file"); fclose(file); return 1; } // Close the file fclose(file); printf("String appended to file successfully.\n"); return 0; }
#include <stdio.h> int main() { FILE *file; char str1[] = "First line\n"; char str2[] = "Second line\n"; char str3[] = "Third line\n"; // Open the file in write mode file = fopen("output.txt", "w"); // Check if file opened successfully if (file == NULL) { perror("Error opening file"); return 1; } // Write the strings to the file fputs(str1, file); fputs(str2, file); fputs(str3, file); // Close the file fclose(file); printf("Strings written to file successfully.\n"); return 0; }