C Programming: Understanding and Using the fscanf() Function 🎯

beginner
21 min

C Programming: Understanding and Using the fscanf() Function 🎯

Welcome to our comprehensive guide on the fscanf() function in C programming! In this lesson, we'll explore this powerful tool, learn its usage, and dive into some practical examples.

What is fscanf()? 📝

fscanf() is a function in C that reads formatted data from a stream (such as a file) into variables. It's similar to printf(), but instead of printing data, it scans data.

Why Use fscanf()? 💡

Using fscanf() helps you read data from files in a structured manner. It allows you to read specific types of data (such as integers, strings, and floats) and store them in variables, making your code more efficient and easier to manage.

Syntax and Parameters 📝

c
int fscanf(FILE *fp, const char *format, ...);
  • fp: The file pointer for the file from which you want to read data.
  • format: A format string that specifies the type and order of the data you want to read.
  • ...: Variable arguments that correspond to the variables you want to store the scanned data.

Basic Example 💡

Let's consider a simple example:

c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); int num1, num2; char str[100]; fscanf(file, "%d%s%d", &num1, str, &num2); printf("Number 1: %d\n", num1); printf("String: %s\n", str); printf("Number 2: %d\n", num2); fclose(file); return 0; }

In this example, we're reading data from a file named example.txt. The file should contain three space-separated values: an integer, a string, and another integer. The fscanf() function reads these values and stores them in the corresponding variables.

Advanced Example 💡

In this advanced example, we'll read a CSV file and store the data in a 2D array.

c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { FILE *file = fopen("data.csv", "r"); int rows, cols; int **data = NULL; // Get the number of rows and columns fscanf(file, "%d,%d", &rows, &cols); // Allocate memory for the 2D array data = (int **)malloc(rows * sizeof(int *)); for (int i = 0; i < rows; i++) { data[i] = (int *)malloc(cols * sizeof(int)); } // Read and store the data for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { fscanf(file, "%d", &data[i][j]); } } // Process the data // ... // Free the memory for (int i = 0; i < rows; i++) { free(data[i]); } free(data); fclose(file); return 0; }

In this example, we're reading a CSV file that contains multiple rows and columns of integers. We first read the number of rows and columns from the file, then allocate memory for a 2D array to store the data. After reading and storing the data, we can process it as needed.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `fscanf()` function in C programming?

Happy coding! 🎉