Understanding of fputs() fgets() in C Language
Hello, fellow C programmers! In this blog post, I’m going to explain two very useful functions for working with files in
ef="https://en.wikipedia.org/wiki/C_(programming_language)#">C: fputs() and fgets(). These functions allow you to write and read strings from a file, respectively. Let’s see how they work and why they are so handy!What is a fputs() fgets() in C Language?
In the C programming language, fputs()
and fgets()
are library functions used for reading and writing text to and from files, respectively. They are typically used when working with text files in C.
fputs()
:
fputs()
stands for “file puts” and is used to write a string to a specified file stream.- Its syntax is:
int fputs(const char *str, FILE *stream);
str
is the string you want to write to the file.stream
is a pointer to the file stream where you want to write the string.- It returns a non-negative value if successful and
EOF
(end-of-file) if there’s an error.
Example:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w");
if (file != NULL) {
fputs("Hello, fputs!", file);
fclose(file);
} else {
printf("Failed to open the file.\n");
}
return 0;
}
fgets()
:
fgets()
stands for “file gets” and is used to read a line of text from a specified file stream.- Its syntax is:
char *fgets(char *str, int n, FILE *stream);
str
is a character array where the read line will be stored.n
is the maximum number of characters to read (typically the size of the character array).stream
is a pointer to the file stream from which you want to read.- It returns
str
if successful andNULL
on failure or when the end of the file is reached.
Example:
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
file = fopen("example.txt", "r");
if (file != NULL) {
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Read: %s", buffer);
}
fclose(file);
} else {
printf("Failed to open the file.\n");
}
return 0;
}
Examples of fputs() fgets() in C Language?
Here are examples of using fputs()
and fgets()
in C to write and read text from a file:
- Using
fputs()
to Write to a File:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w"); // Open the file in write mode
if (file != NULL) {
char text[] = "This is a sample text.\nHello, fputs!";
if (fputs(text, file) != EOF) {
printf("Text successfully written to the file.\n");
} else {
printf("Error writing to the file.\n");
}
fclose(file);
} else {
printf("Failed to open the file.\n");
}
return 0;
}
- Using
fgets()
to Read from a File:
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
file = fopen("example.txt", "r"); // Open the file in read mode
if (file != NULL) {
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Read: %s", buffer);
}
fclose(file);
} else {
printf("Failed to open the file.\n");
}
return 0;
}
Advantages of fputs() fgets() in C Language
The fputs()
and fgets()
functions in the C programming language offer several advantages for working with text files:
- Simplicity: Both functions are relatively simple to use, making them accessible for beginners and experienced programmers alike. They provide a straightforward way to read from and write to text files.
- Portability:
fputs()
andfgets()
are part of the C standard library, which means they are available on virtually all C compilers and platforms. This makes your code portable across different systems without modification. - Buffered I/O: These functions provide buffered I/O, which means they read or write data in chunks rather than one character at a time. This can significantly improve the performance of your file I/O operations, especially when dealing with large files.
- Line-Oriented:
fgets()
is particularly useful for reading lines of text from a file. It automatically stops reading when it encounters a newline character ('\n'
), allowing you to process files line by line. - Error Handling: Both functions provide error handling through their return values. They return
NULL
orEOF
in case of an error, making it easy to check for and handle errors in your file operations. - Text Mode Handling:
fgets()
andfputs()
are designed for text files. They automatically handle newline characters correctly, translating them between the platform-specific newline representations (e.g.,\n
on Unix-like systems and\r\n
on Windows). - Memory Management:
fgets()
reads data into a character array you provide, allowing you to control memory allocation. This can help prevent buffer overflows and memory-related issues. - Compatibility with Standard I/O Functions: These functions work seamlessly with other standard I/O functions like
fprintf()
,fscanf()
,printf()
, andscanf()
, allowing you to build complex file processing pipelines using the C standard library. - Human-Readable Code: The use of
fputs()
andfgets()
makes your code more human-readable because it clearly indicates the intention of reading from or writing to a file.
Disadvantages of fputs() fgets() in C Language
While fputs()
and fgets()
in C have their advantages, they also come with some limitations and potential disadvantages, especially when compared to other file I/O methods:
- Text-Only Handling:
fputs()
andfgets()
are designed for text file handling. If you need to work with binary files or perform low-level file operations, they may not be suitable. - Line Length Limitation:
fgets()
reads data line by line, and it’s limited by the size of the character array you provide as a buffer. If you have long lines or lines longer than your buffer size, you’ll need to handle line continuation and merging manually. - Inefficient for Large Files: For very large files, reading or writing line by line with
fgets()
andfputs()
can be inefficient, as it involves many system calls. More efficient methods like memory-mapped files or reading/writing in larger chunks may be preferable. - Buffer Management: You need to manage the buffer size yourself when using
fgets()
. If the buffer is too small to hold a complete line, you risk truncating the data. On the other hand, if the buffer is too large, it may be wasteful in terms of memory usage. - Platform-Specific Newline Handling: While
fgets()
andfputs()
handle newline characters in text files, the exact handling depends on the platform. This can lead to compatibility issues if you need to process files across different systems with different newline conventions (e.g.,\n
on Unix-like systems and\r\n
on Windows). - Limited Error Handling: While these functions return
NULL
orEOF
on error, the error information is limited. You might not get detailed information about the cause of the error, making it challenging to diagnose and handle issues. - Not Ideal for Complex Parsing: If you need to perform complex parsing of structured data within a file (e.g., parsing CSV or XML files),
fgets()
may not be the most suitable choice. Specialized parsing libraries or regular expressions might be more appropriate. - No Random Access:
fgets()
andfputs()
are sequential file access functions, meaning you can’t easily jump to a specific position in the file or overwrite specific parts of the file without additional logic. - Performance Overhead: The use of
fgets()
andfputs()
introduces some performance overhead due to the buffering mechanism, which may not be significant for most applications but could matter in certain high-performance scenarios.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.