Lesson 50: File I/O Part 4: String I/O (fputs, fgets)
These functions handle reading and writing entire lines or strings to files.
Writing a String: fputs()
Writes a null-terminated string to the specified file stream. Important: fputs does not automatically write a newline character (\n). You must add it manually.
Syntax: int fputs(const char *str, FILE *stream);
c FILE *fp = fopen("log.txt", "a"); // Append mode
if (fp != NULL) { fputs("This is line one.", fp); fputs("\n", fp); // Manual newline fputs("This is line two.\n", fp); fclose(fp); }
Reading a String (Line): fgets()
Reads a string (up to a specified length) from the stream until a newline character is encountered, end-of-file, or the maximum size is reached. It includes the newline character if found.
Syntax: char *fgets(char *str, int n, FILE *stream);
str: Buffer to store the read string.n: Maximum number of characters to read (size of the buffer).stream: The file stream.
c char buffer[100]; FILE *fp = fopen("log.txt", "r");
if (fp != NULL) { // Reads up to 99 chars + \0 while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("Read: %s", buffer); } fclose(fp); }
Note: fgets is generally safer than fscanf for reading strings as it prevents buffer overflow by limiting the input size.