Reading Data from Files
Reading data from files is a fundamental part of file handling in C. The two primary functions used for this purpose are fscanf and fread. The fscanf function is designed for reading formatted text data from a file, much like how scanf reads input from the standard input. You use fscanf when you want to extract values such as strings, integers, or floating-point numbers from a text file, following a specific format. On the other hand, the fread function is used for reading raw binary data from a file. With fread, you can read a specified number of bytes into a buffer, making it suitable for handling data that is not in a human-readable text format, such as images or serialized structures.
main.c
input.txt
123456789101112131415161718192021#include <stdio.h> int main() { FILE *file = fopen("input.txt", "r"); if (file == NULL) { printf("Unable to open file.\n"); return 1; } char name[50]; // Read a string from the file if (fscanf(file, "%49s", name) == 1) { printf("Read from file: %s\n", name); } else { printf("Failed to read data from file.\n"); } fclose(file); return 0; }
Always check for the end-of-file condition or errors when reading data from a file. Functions like fscanf and fread return values that indicate how much data was successfully read, which helps you detect issues such as reaching the end of the file or encountering read errors.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 12.5
Reading Data from Files
Swipe to show menu
Reading data from files is a fundamental part of file handling in C. The two primary functions used for this purpose are fscanf and fread. The fscanf function is designed for reading formatted text data from a file, much like how scanf reads input from the standard input. You use fscanf when you want to extract values such as strings, integers, or floating-point numbers from a text file, following a specific format. On the other hand, the fread function is used for reading raw binary data from a file. With fread, you can read a specified number of bytes into a buffer, making it suitable for handling data that is not in a human-readable text format, such as images or serialized structures.
main.c
input.txt
123456789101112131415161718192021#include <stdio.h> int main() { FILE *file = fopen("input.txt", "r"); if (file == NULL) { printf("Unable to open file.\n"); return 1; } char name[50]; // Read a string from the file if (fscanf(file, "%49s", name) == 1) { printf("Read from file: %s\n", name); } else { printf("Failed to read data from file.\n"); } fclose(file); return 0; }
Always check for the end-of-file condition or errors when reading data from a file. Functions like fscanf and fread return values that indicate how much data was successfully read, which helps you detect issues such as reaching the end of the file or encountering read errors.
Thanks for your feedback!