C (programming language)
C program to read data from file using fgets() function
Introduction
The fgets()
function in C is a versatile tool for reading data from text files. It offers a safer and more controlled approach compared to other file reading functions like gets()
. In this guide, we’ll explore how to use fgets()
to effectively read data from files in C programs.
Key Concepts
- fgets() Syntax: C
char *fgets(char *str, int size, FILE *stream);
str
: The character array where the read string will be stored.size
: The maximum number of characters to read, including the null terminator.stream
: The file pointer pointing to the open file.
- Return Value:
- Returns a pointer to the
str
if successful. - Returns
NULL
if an error occurs or the end of the file is reached.
- Returns a pointer to the
Steps to Read Data from a File
- Include Necessary Header: C
#include <stdio.h>
- Open the File: C
FILE *fp = fopen("filename.txt", "r");
- Replace “filename.txt” with the actual file name.
- “r” mode opens the file for reading.
- Check for File Opening Errors: C
if (fp == NULL) { printf("Error opening file!\n"); return 1; // Indicate error }
- Read Data Line by Line using fgets(): C
char buffer[100]; // Adjust buffer size as needed while (fgets(buffer, sizeof(buffer), fp) != NULL) { // Process the read line (e.g., print it) printf("%s", buffer); }
- Close the File: C
fclose(fp);
Example Code
C
#include <stdio.h>
int main() {
FILE *fp = fopen("myfile.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
char line[50];
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);
return 0;
}
Key Points to Remember
fgets()
preserves the newline character (\n
) if present in the file.- It stops reading at
size - 1
characters or when it encounters a newline, whichever comes first. - Always check the return value of
fgets()
to handle errors or the end of the file. - Choose an appropriate buffer size to accommodate the expected line lengths.
- Close the file using
fclose()
when finished to release resources.
Additional Notes
- Consider using
ferror()
to check for errors during file operations. - Use
feof()
to determine if the end of the file has been reached. - For more complex file handling tasks, explore other file I/O functions in C.