How to Use fputs in C: Syntax, Example, and Tips
In C,
fputs writes a string to a file stream without adding a newline. You use it by passing the string and the file pointer, like fputs("text", filePointer);.Syntax
The fputs function writes a null-terminated string to the specified file stream. It does not add a newline character automatically.
const char *str: The string to write.FILE *stream: The file pointer where the string will be written.
The function returns a non-negative value on success, or EOF on error.
c
int fputs(const char *str, FILE *stream);
Example
This example opens a file named output.txt for writing, writes a string using fputs, and then closes the file.
c
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { perror("Failed to open file"); return 1; } const char *text = "Hello, fputs!"; if (fputs(text, file) == EOF) { perror("Failed to write to file"); fclose(file); return 1; } fclose(file); return 0; }
Common Pitfalls
Common mistakes when using fputs include:
- Not checking if the file was opened successfully before writing.
- Assuming
fputsadds a newline automatically (it does not). - Not checking the return value of
fputsfor errors. - Writing to a file opened in the wrong mode (e.g., reading mode).
c
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "r"); // Wrong mode for writing if (file == NULL) { perror("Failed to open file"); return 1; } // This will fail because file is opened in read mode if (fputs("Hello", file) == EOF) { perror("Write failed"); } fclose(file); return 0; }
Output
Write failed: Bad file descriptor
Quick Reference
Remember these tips when using fputs:
- Always open the file in write or append mode before writing.
fputswrites exactly the string you give it, no newline added.- Check the return value to catch errors.
- Close the file after writing to save changes.
Key Takeaways
Use
fputs to write strings to files without adding newlines.Always open the file in write or append mode before using
fputs.Check the return value of
fputs to detect write errors.Remember to close the file after writing to ensure data is saved.
fputs does not add a newline; add one manually if needed.