C Tutorial

C Tutorial C Language Environment Setup Execution flow of C program C printf and Scanf C Data type C Token Variable in C Operators in C Comments in C Escape Sequence in C C – Storage Classes C Decision control statement Loop Statement in C Break, continue and goto statement in C Type Casting in C Function in C Recursion in C String in C C Array Pointer in C Dynamic memory allocation C –Structure Nested Structure in C Union in C File Handling in C C pre-processor Static Function In C Sizeof In C Selection Sort In C Scope Of Variables In C Runtime Vs Compile Time In C Random Access Lseek In C Queue Implementation In C Pseudo Code In C Prototype In C Pointer To Pointer In C Pointer Arithmetic In C Passing Array To Function In C Null Character In C Merge Sort In C Macros In C Library Functions In C Memory Leak In C Int In C Goto And Labels In C Fibonacci Series In C Fflush In C Derived Data Types In C Data Types In C Const Vs Volatile In C Character Set In C Character Class Tests In C Calloc In C C Pointers Arrays In C Include In C Clrscr In C C Vs Java String Literals In C Types Of Pointers In C Variables In C Volatile In C Why C Is A Middle Level Language Infix To Postfix Program In C Ceil function in C LCM of two numbers in C Quick sort in C Static in C function pointer as argument in C Top Array Keywords in C Add two numbers using the function in C Armstrong program in C using function Array, Declaring Arrays and Array Initialization Limitations of Inline Function in C Merge and Merge sort with example in C Do-While Loop in C For Loop in C While-Loop in C Difference between while and do-while loop in C Array Of Structures in C Data Structures And Algorithms in C Types Of Structures In C How to Avoid Structure Padding in C Use of Structure in C Do WHILE LOOP in C Programming Examples For Loop in C Programming Examples Entry Control Loop in C Exit control loop in C Infinite loop in C Nested loop in C pow() function in C String Handling functions in C Prime Number code in C Factorial Program in C using For Loop Factorial Program in C Using While Loop Fibonacci Series in C Using For Loop Fibonacci series in C using while loop Prime Number Program in C using for Loop While Loop in C programming examples Built-in functions in C Assert() Function C vs Java Strings Call Back Function in Embedded C Else If Ladder fgets() function Ftell() Function getc() function getch() function gets() function Heap Sort Nested if-else statement Pi() Function Positioning of file Write() function abs() function in C Attributes in C C program to find factorial of a number using Recursion Ferror() in c fopen() function in C Fibonacci series program in C using Recursion Formatted Input and output function in C Snake Game in C User Defined Functions in C Beep() function in C Cbrt() function in C Hook() function in C Isalnum() function in C C Program to find the Roots of a Quadratic Equation C Switch Statements Difference between rand() and srand() function in C Difference between while and for loop in C Doubly Linked list in C Example of Iteration in C How to use atoi() function in C How to use floor() function in C How to use sine() function in C How to use Typedef Struct in C Integer Promotions in C C Program Swap Numbers in cyclic order Using Call by Reference C Program to Find Largest Number Using Dynamic Memory Allocation C Program to Find the Largest Number using Ternary Operator C/C++ Program to Find the Size of int, float, double and char Find the Largest Three Distinct Elements in an Array using C/C++ Loop Questions in C Modulus on Negative Numbers in C Multiplication table program in C using For loop Nested Loops in C Programming Examples C Program for Mean and Median of an Unsorted Array Results of Comparison Operations in C and C++ Reverse a Stack using Recursion in C Simple hash() function in C strcat() Function in C Sum of N numbers in C using For loop Use of free() function in C Write a program that produces different results in C and C++ C Function Argument and Return Values Keywords in C Bank management system in C Calendar application in C Floor() Function in C Free() Function in C How to delete a file in C How to move a text in C Remove an element from an array in C Unformatted input() and output() function in C What are linker and loader in C SJF Scheduling Program in C Socket Programming in C Structure in C Tower of Hanoi in C Union Program in C Variable Declaration in C What is Linked List in C While Loop Syntax in C fork() in C GCD program in C Branching Statements in C Comma Operator in C Control statement in C Double Specifier in C How to create a binary file in C Long int in C Palindrome Number in C Pure Virtual Function in C Run Time Polymorphism in C Types of Array in C Types of Function in C What is a buffer in C What is required in each C Program Associativity of Operators in C Bit Stuffing Program in C Actual and Formal Parameters Addition of two Numbers in C Advantages of function in C Arithmetic Progression Program in C Binomial Coefficient Program in C Difference between Array and List in C Diffie-Hellman Algorithm in C How to convert a number to words in C How to convert a string to hexadecimal in C Difference between If and Switch Statement in C C and C++ Binary Files C program that does not Suspend when Ctrl+Z is Pressed Different ways to Declare the Variable as Constant in C Range of Int in C C Program to find the size of a File FIFO Example in the C Language For loop in C Programming GCD program of two numbers in C GPA Calculator in C How to Calculate Time Complexity in C How to include graphics.h in C How to measure time taken by a function in C How to return a Pointer from a Function in C What is the main in C Addition of Matrix in C Booleans in C C Program for Extended Euclidean algorithms C Program of Fencing the Ground Ceil and Floor in C Compound Interest Program in C Displaying Array in C Distance Vector Routing Protocol Program in c Dos.h Header File in C Language DSA Program in C Explain the two-way selection in C Fee Management System in C File Operations in C Malloc function in C Multiplication Table in C Simple Programs in C Language tolower() Function in C Type Conversion in the C Why does sizeof(x++) not Increment x in C Advantages of Dynamic Memory Allocation in C Armstrong Number in C Assignment Operator Program in C Banker’s Algorithm in C Binary Search in C with Best and Worst Time Complexity Caesar Cipher Program in C Call by Value and Call by Reference in C Conditional Operator in C CRC Program in C Deadlock Detection Program in C Decimal to Binary in C Difference between If Else and Nested If Else in C Difference between Pre-increment and Post-increment in C Difference between Scope and Lifetime in C Evaluation of Arithmetic Expression in C Explain the Increment and Decrement Operators in C Fseek Function in C Functions in C How to Find Square Free Numbers in C Length of an Array Function in C OpenGL in C Projects on C language in 2023 Purpose of a Function Prototype in C Stdio.h in C Two-Dimensional array in C What is String Comparison in C C Compilers for Windows Functions and Recursion in C How to Declare Boolean in C How to Declare Character in C How to Round up a number in C How to use strlen() in C Pointer Declaration in C Algorithm for String Palindrome in C C Program to find ASCII value of a character Constant Pointer in C How to find string length in C using strlen() function Implicit and Explicit in C Indirect Recursion in C Input and Output functions in C isupper() in C Jump Statement in C Lifetime of a Variable in C Linker Error in C Language Numeric Constant in C Size of Pointer in C Square Root in C Language Static and Dynamic Memory allocation String Declaration in C Strong Number in C Symmetric Matrix in C Types of C Tokens What is a Size of Pointer in C What is Increment and Decrement Operator in C 1 2 3 4 Series Program in C Advantages and Disadvantages of C Language C Program for Polynomial Addition C Program to Count the Number of Vowels in a String C Programming Errors and Solutions Compilation Errors in C Complex C Programs Difference between Argument and Parameter in C Difference between char s[] and char *s in C Evaluation of Postfix Expression Using Stack in C Find Leftmost and Rightmost Set Bit of a Number fprintf and fscanf in C Introduction to Dynamic Array in C Print Address in C Realloc function in C Ternary Operators in C Types of Tokens in C with Examples Difference between Static and Dynamic Memory Allocation in C Addition Program in C Array Definition in C Array of Pointers in C Arrow Operator in C Average of Two Numbers in C Binary to Decimal in C Binary to Octal in C BREAK STATEMENT in C C Programming Operators Questions C Programs Asked in Interview Calculator Program in C C Program to Read and Print an Employee's Detail Using Structure Bubble Sort Algorithm in C C Program to Find Area and Perimeter of Circle C Program to Check Whether a Given Number is Even or Odd C in Roman Numerals C Program to Make a Simple Calculator Using Switch Case Insertion Sort Program in C How to take input in string in C GCC Conflicting Types in C Function Definition in C Format Specifier for Hexadecimal in C Flowchart in C Float in C Fizzbuzz Implementation in C Conditional Statement in C Conio.h functions list in C Constants in C Dynamic Array in C Decision Making Statements in C Continue Statement in C Creation of Thread in C DFS Algorithm in C Difference between parameter and arguments in C Dijkstra's Algorithm in C Leap Year Program in C Jump Statements in C Modulus Operator in C Memory Allocation in C Simple Interest Program in C Reverse Array in C Recursive Function in C Queue in C Printing Pascal’s Triangle in C Preprocessor Directives in C Perror() in C Perfect Number in C Programming Language Parameter Passing Techniques in C Pascal Triangle in C Patterm Program in C Affine cipher in C Dereferencing pointer in C Internal static variable vs External static variables in C Difference between exit(0) and exit(1) in C Booth's Algorithm in C Condition Control Statements in C Double Specifier in C Dynamic variables in C How to print alphabets in C How to print char array in c Order of Evaluation in C Order of Operations in C Semantic Error in C Size of String Variable in C SJF PREEMPTIVE SCHEDULING PROGRAM C: Tree in C Arithmetic Progression Program in C Array, Declaring Arrays, and Array Initialization ARRAYS IN C Assert() Function in c Atoi in C Bar3d() function in C Graphics Beep function in c Bigint (BIG INTEGERS) in C with Example Builtin functions of GCC compiler Fibonacci series in C Priority Queue in C 2D ARRAY IN C 7 Best IDEs for C/C++ Developers in 2022 Addition of Two Numbers in C Advantages and Disadvantages of C Language Advantages of Function in C Algorithm for String Palindrome in C What is fgets in C language 2d Shearing Program in C Recursion Questions In C Static Identifier in C Inserting elements in an array using C Language complex.h Header File in C fsetpos()(set file position) in C Comparator function of qsort() in C Print Hex in C strnset() function in C %d in C Butterfly Star pattern in C C form format in Excel Scan Line Polygon Filling in C 8 Queens Problem in C Back Trace in C BSS (Block Started by Symbol) Data Segment in C language Class C in Networking Strings in C Programming What is Circular linked list? What is Loop in C BITWISE OPERATOR IN C LANGUAGE BOMB DIFFUSION PROGRAM IN C LANGUAGE

fprintf and fscanf in C

Introduction

C programming is a popular and widely used programming language known for its flexibility, portability, and powerful features. It provides various functions and libraries that can perform different programming tasks, including input/output (I/O) operations. Two of the most important functions in C for performing I/O operations are fprintf() and fscanf().

The fprintf() function writes formatted data to a file or stream. It is similar to the printf() function in that it allows the user to format data in a specific way, but instead of writing to the console, it corresponds to a file or stream. This function is useful for creating files, generating reports, or logging data. The syntax for the fprintf() is similar to the printf() function, but instead of writing to the console, it corresponds to a file or stream. The fprintf() function is a powerful tool that can be used for various tasks in C programming.

The fscanf function, on the other hand, reads formatted data from a file or stream. It extracts data from a file or stream and stores it in variables in a specific format. This function is used when the data in the file is within a particular form, and the programmer wants to extract and use that data in the program. The fscanf() function reads input data from a file and stores it in variables according to the format specified. This function is commonly used for reading configuration files, log files, or data files.

Understanding the usage of fprintf() and fscanf() is essential for C programmers who need to perform I/O operations on files. These functions are important in writing and reading data from files and streams, an important aspect of many programs. The usage of these functions can vary depending on the application, and it is important to understand their syntax, formatting options, and common errors to avoid mistakes and make the code more efficient.

In C programming, the formatting options for fprintf() and fscanf() are essential in formatting the data to be written or read from files or streams. Formatting options are used to control the appearance of the data and ensure that the data is in a specific format for easy reading and processing. The formatting options include conversion specifiers, flags, field width, and precision. Understanding these options is essential in writing efficient code that can perform I/O operations with ease.

In this article, we will explore the usage of fprintf() and fscanf() in C programming, the different formatting options used in these functions, and common errors that occur when using these functions. We will also discuss the difference between fprintf() and fscanf() and their usage in C programming. We will provide examples of how these functions are used in different applications and discuss best practices for using these functions in programming.

fprintf()

Syntax:

int fprintf(FILE *stream, const char *format, ...);
  • The first argument, stream, is a pointer to a FILE structure representing the file or output stream to which the formatted data will be written. This argument can be a file pointer returned by fopen or a pointer to stdout or stderr, defined in the stdio.h library.
  • The second argument, format, is a string that contains the format codes that define how the output should be formatted.
  • The remaining arguments are the values to be formatted and output according to the format string.

The format string is made up of normal characters and formatting codes. Normal characters are the output directly to the stream, while formatting codes are replaced with the corresponding formatted value.

Formatting codes begin with a percent sign (%) and are followed by a code that indicates the type of value to be formatted. The most common formatting codes are:

  1. %d: This format specifier prints or reads integer values in decimals. For example, printf("%d", x) will print the value of x as a decimal integer.
  2. %f: This format specifier prints or reads floating-point values in decimals. For example, printf("%f", x) will print the value of x as a floating-point number.
  3. %c: This format specifier prints or reads character values. For example, printf("%c", x) will print the value of x as a character.
  4. %s: This format specifier prints or reads strings. For example, printf("%s", str) will print the str value as a string.
  5. %x: This format specifier prints or reads integer values in hexadecimal format. For example, printf("%x", x) will print the value of x as a hexadecimal integer.
  6. %o: This format specifier prints or reads integer values in octal format. For example, printf("%o", x) will print the value of x as an octal integer.
  7. %p: This format specifier prints or reads pointer values. For example, printf("%p", ptr) will print the value of ptr as a pointer.
  8. %e or %E: These format specifiers print or read floating-point values in scientific notation. For example, printf("%e", x) will print the value of x as a floating-point number in scientific notation.
  9. %u: This format specifier prints or reads unsigned integer values in decimals. For example, printf("%u", x) will print the value of x as an unsigned decimal integer.
  10. %g or %G: These format specifiers are used to print or read floating-point values in either decimal or scientific notation, whichever is shorter. For example, printf("%g", x) will print the value of x as a floating-point number in either decimal or scientific notation, whichever is shorter.

Example:

For example, the following code snippet uses fprintf to write a formatted string to a file:

#include <stdio.h>


int main() {
    FILE *fp;  // Declare file pointer
    char name[20] = "John";  // Declare string variable
    int age = 27;  // Declare integer variable
    
    fp = fopen("example.txt", "w");  // Open file for writing
    if (fp == NULL) {  // Check if file could not be opened
        printf("Error: Could not open file\n");
        return 1;  // Return with error code
    }
    


 fprintf(fp, "Hello Everyone:\n");  // Write formatted string to file
    fprintf(fp, "My name is %s\n", name);
   fprintf(fp, "I am %d years old\n", age);
    
    fclose(fp);  // Close file
    
    return 0;  // Return success code
}

In this example, we first include the stdio.h header file, which provides the fprintf function. We then declare a file pointer fp, a variable string name, and an integer age.

Next, we open a file called "example.txt" for writing using the fopen function. The second argument to fopen specifies the mode to open the file; "w" indicates that we want to open the file for writing (and create a new file if it does not exist). If fopen returns NULL, we display a message and exit, regardless of the error code.

We then use fprintf to write two lines of formatted text to the file. The first line includes the name variable, which we insert into the string using the %s format specifier. The second line consists of the age variable, which we insert using the %d format specifier. Both lines end with a newline character (\n) to ensure that each line is written on a separate line in the file.

Finally, we close the file using the fclose function to ensure that all data is written to the file and to release any resources used by the file.

Output:

When we run this program, it will create a file called "example.txt" in the same directory as the program. The file will contain the following text:

Hello Everyone:
My name is John
I am 27 years old

Formatting Options in fprint()

fprintf also supports several formatting options that control the output's width, precision, and alignment. Some of the most common options include:

  • Width specifier: Specifies the minimum width of the output, which can be useful for aligning columns of data. For example, %5d would output an integer with a minimum width of 5 characters.
  • Precision specifier: Specifies the number of decimal places to be used when formatting floating point numbers. For example, %.2f would output a floating-point number with 2 decimal places.
  • Left or right alignment: Specifies whether the output should be left-aligned (%-10s) or right-aligned (%10s).

Example

For example, the following code snippet demonstrates some of these formatting options:

#include <stdio.h>


int main() {
    FILE *fp;  // Declare file pointer
    char name[20] = "John";  // Declare string variable
    int age = 27;  // Declare integer variable
    double height = 1.75;  // Declare double variable
    
    fp = fopen("example.txt", "w");  // Open file for writing
    if (fp == NULL) {  // Check if file could not be opened
        printf("Error: Could not open file\n");
        return 1;  // Return with error code
    }
    
    // Write formatted string to file
    fprintf(fp, "Name: %s\n", name);
    fprintf(fp, "Age: %d\n", age);
    fprintf(fp, "Height: %.2f meters\n", height);
    fprintf(fp, "Name: %-10s Age: %3d Height: %5.2f\n", name, age, height);
    
    fclose(fp);  // Close file
    
    return 0;  // Return success code
}

In this example, we first declare a file pointer fp, a variable string name, an integer age, and a double variable height.

We then open a file called "example.txt" for writing using the fopen function, checking for errors as before.

We use fprintf to write four lines of formatted text to the file. The first two lines are straightforward, using the %s and %d format specifiers to insert the name and age variables, respectively. The third line demonstrates how to format a double value using the %f format specifier, which prints the value with six decimal places by default. We use the .2 precision specifier to limit the number of decimal places to two and add the "meters" suffix to clarify that the value represents height.

The fourth line demonstrates some additional formatting options. We use the - flag to left-justify the name string within a 10-character width. We use the 0 flags to pad the age value with zeros instead of spaces. We use the 3-precision specifier to limit the age field to three characters and the 5.2 precision specifier to limit the height field to five characters with two decimal places. The result is a neatly formatted table of values.

Finally, we close the file using fclose.

Output:

When we run this program, it will create a file called "example.txt" in the same directory as the program. The file will contain the following text:


Name: John
Age: 27
Height: 1.75 meters
Name: John       Age: 027 Height:  1.75

How to use fprintf to write formatted data to stdout

fprintf can also be used to write data to stdout, the standard output stream typically displayed on the console. To write to stdout, you can pass the stdout pointer as the first argument to fprintf.

Here's an example program that demonstrates how to use fprintf to write formatted data to stdout:

#include <stdio.h>


int main() {
    char name[20] = "Alice"; // Declare a string variable
    int age = 25; // Declare an integer variable
    double height = 1.62; // Declare a double variable


    // Use fprintf to write formatted data to stdout
    fprintf(stdout, "Name: %s\n", name);
    fprintf(stdout, "Age: %d\n", age);
    fprintf(stdout, "Height: %.2f meters\n", height);
    fprintf(stdout, "Name: %-10s Age: %3d Height: %5.2f\n", name, age, height);


    return 0; // Return success code
}

In this program, we declare a name string variable, an age integer variable, and a double height variable.

Then, we use fprintf to write formatted data to stdout. The first argument to fprintf is stdout, which represents the standard output stream. The second argument is a format string specifying how the data should be formatted. We use format specifiers such as %s (for strings), %d (for integers), and %f (for doubles) to specify the type of data being written. We also use precision specifiers such as .2 to control the number of decimal places displayed for the height variable.

The last line demonstrates some additional formatting options. We use the - flag to left-justify the name string within a 10-character width. We use the 0 flags to pad the age value with zeros instead of spaces. We use the 3 precision specifier to limit the age field to three characters and the 5.2 precision specifier to limit the height field to five characters with two decimal places.

When we run this program, it will produce the following output on the console:

Name: Alice
Age: 25
Height: 1.62 meters
Name: Alice      Age: 025 Height:  1.62

As you can see, fprintf allows us to format easily and output data to the console using various formatting options. It can be very useful when creating programs that produce text-based output or require formatted data to be displayed to the user.

Like most functions in C, fprintf returns a value that indicates whether the function was executed successfully or encountered an error. The function would return the number of characters written to the stream or a negative value if an error occurred.

For example, if the file specified by stream could not be opened for writing, fprintf would indicate an error by returning a negative value.

One important consideration when using fprintf is that it can be vulnerable to buffer overflow attacks if not used correctly. In a buffer overflow, data is written beyond the end of a buffer, which can cause memory corruption and potentially allow an attacker to execute arbitrary code.

To prevent buffer overflow attacks when using fprintf, it's important to use the appropriate format codes and to ensure that the buffer size properly bounds the output data.

In summary, fprintf is a powerful function in the C programming language that allows formatted data to be written to a file or stdout. It can be used to write strings, numbers, and other data types and supports various formatting options to control the output format. However, using fprintf correctly is important to avoid buffer overflow attacks and other errors.

fscanf()

The fscanf function in C reads data from a file, just like the scanf function is used to read data from the standard input (keyboard). The main difference between scanf and fscanf is that scanf reads from the standard input, whereas fscanf reads from a file. fscanf has a similar syntax to scanf, but takes an additional argument - a file pointer that specifies the file to read from.

The syntax of the fscanf() function is as follows :

int fprintf(FILE *stream, const char *format , ...);
  • Here, the stream is a pointer to the file to read from,
  • the format is a string specifying the data format to be read,
  • the ellipsis (...) indicates that additional arguments may correspond to the values to be read.

The format string for fscanf is similar to that for scanf, with a few differences. The format string can contain whitespace characters (spaces, tabs, and newlines) that are ignored when reading data. The format string can also contain conversion specifiers that specify the type of data to be read and how to format it. Some common conversion specifiers are:

Format SpecifierDescription
%dInteger
%iInteger
%oOctal integer
%xHexadecimal integer
%uUnsigned integer
%fFloating-point number
%eScientific notation (floating-point number)
%gShortest representation of %e or %f
%cCharacter
%sString
%pPointer
%nNumber of characters read so far
%[]Scanset

Note: Scansets are used in the format string of the fscanf() function to specify a set of characters to be read as input. The scans are determined utilizing the %[ ] format specifier. For example, the format string "%[a-zA-Z]" specifies a scanset that reads any number of alphabetic characters (upper or lower case).

The fscanf function returns the number of successfully read and assigned items. If the function encounters an error while reading, it returns a value less than the number of items requested. A file that reaches the end before all items have been read, fscanf, returns a value less than the number of items ordered.

For example, the following fscanf statement reads an integer value from a file:


int num;
fscanf(fp, "%d", &num);

Here, fp is a pointer to a file, and %d is the conversion specifier that specifies that an integer value should be read from the file. The &num argument addresses the integer variable num, where the value will be stored.

fscanf returns the number of items successfully read from the input stream. If this value is less than the number of variables in the argument list, it means that there was an error reading the input data.

In addition to conversion specifiers, the format string can also contain whitespace characters (such as spaces and tabs) that are used to skip over unwanted input data.

Example:

The following example shows how to use fscanf to read formatted data from a file:

Suppose we have a file named "example.txt" that contains the following data:

John 25
Mary 30
Bob 40

The following program demonstrates how to read this data from the file using the fscanf() function:

#include <stdio.h>


int main()
{
    FILE *fp;
    char name[20];
    int age;


    fp = fopen("example.txt", "r");
    
    while (fscanf(fp, "%s %d", name, &age) != EOF)
    {
       printf("\n Hello Everyone \n");
        printf("My name is %s and I am  %d years old \n", name, age);
    }


    fclose(fp);


    return 0;
}

In this program, we first declare a pointer to a FILE object named "fp". We also declare two variables: "name", which is an array of characters used to store the name read from the file, and "age", which is an integer used to store the age read from the file.

Next, we use the fopen() function to open the file "example.txt" for reading. The second argument to fopen() is "r", which specifies that we want to open the file in read mode.

We then use a while loop to repeatedly call fscanf() until the end of the file is reached. In each iteration of the loop, fscanf() reads the next line of data from the file, using the format string "%s %d" to specify that it should read a string followed by an integer. The values read are stored in the "name" and "age" variables.

Finally, we use printf() to display the data we read from the file and close the file using the fclose() function.

Output:

When we run this program, we get the following output:


Hello Everyone
My name is John and I am 25 years old


Hello Everyone
My name is Mary and I am 30 years old


Hello Everyone
My name is Bob and I am  40 years old

As we can see, the program successfully reads the data from the file and displays it on the console.

In addition to these options, the format string can include whitespace characters, such as spaces, tabs, and newlines, which are ignored when reading input.

fscanf can read data from stdin, the standard input stream. It is often useful when building command-line programs that need to accept user input from the console.

Here's an example of how to use fscanf to read two integers from the console:


#include <stdio.h>


int main() {
    char name[50];
    int age;


    printf("Please enter your name and age: ");
    fscanf(stdin, "%s %d", name, &age);


    printf("Your name is %s and your age is %d\n", name, age);


    return 0;
}

In this example, we first declare a character array name of size 50 and an integer variable age to store the input data. We then use printf to display a prompt asking the user to enter their name and age. The %s format specifier is used to read a string of characters, and the %d format specifier is used to read an integer value.

When fscanf is called, it waits for the user to enter their input in the console. Once the user enters their information and presses, enter, fscanf reads the input and stores the values in the variable's name and age, respectively.

Finally, we use printf to display the input values to the user.

Output:

The output of the program will be something like this:

Please enter your name and age: John 30

Please enter your name and age: John 30
Your name is John and your age is 30

In this example, we assume that the user enters their name and age separated by a space. If the user enters their name with a space, fscanf will only read the first part of the name and leave the rest in the input stream. To read a full name with spaces, we can use the %[^\n] format specifier, which reads a string of characters until a newline character is encountered. Here's an example:

#include <stdio.h>


int main() {
    char name[50];
    int age;


    printf("Please enter your name and age: ");
    fscanf(stdin, "%[^\n] %d", name, &age);


    printf("Your name is %s and your age is %d\n", name, age);


    return 0;
}

In this example, the %[^\n] format specifier reads a string of characters until a newline character is encountered, which marks the end of the input line. The name variable is now able to store a full name with spaces.

When running the program and entering a name with spaces, the output will be something like this:

Please enter your name and age: John Smith 30
Your name is John Smith and your age is 30

The fscanf() function is a powerful tool for reading input data from a file in C. It allows you to specify the input data format using format specifiers, and it can read mixed data types from a file. By understanding how to use the fscanf() function and its format specifiers, you can easily read input data from a file and use it in your C program. However, it is important to handle errors that may occur while reading input data using the function and to ensure that your program behaves correctly in these situations.

Difference between fscanf and fprintf in C

fscanf() and fprintf() are two important file input/output functions in C programming that allow reading data from and writing data to files, respectively. There are some similarities between them, but there are also significant differences. A few key differences can be seen between fscanf and fprintf:

Featurefscanf()fprintf()
PurposeRead data from a fileWrite data to a file
Function Signatureint fscanf(FILE *file_pointer, const char *format, ...);int fprintf(FILE *file_pointer, const char *format, ...);
ArgumentsTakes three arguments: file pointer, format string, and a list of variables to store the read data.Takes three arguments: file pointer, format string, and a list of variables to write data to the file.
Return ValueReturns the number of items that are successfully read.Returns the number of characters written.
Format StringSpecifies the format of the data to be read from the file.Specifies the format of the data to be written to the file.
File Pointer PositionThe position indicator is updated automatically after each read operation.The position indicator is updated automatically after each write operation.
Data TypesCan read data of different types like int, float, char, string, etc.Can write data of different types like int, float, char, string, etc.
Error HandlingReturns -1 if there is an error while reading data from the file.Returns a negative value if there is an error while writing data to the file.
Buffer OverflowMay lead to buffer overflow attacks if input data is not validated properly.Not prone to buffer overflow attacks.
Format String VulnerabilityNot prone to format string vulnerabilities.May lead to format string vulnerabilities if the format string is not validated properly.
Text and Binary ModesSupports reading data from both text and binary files.Supports writing data to both text and binary files.
Use CasesUsed for reading input data from files.Used for writing output data to files.
Multiple Data ReadingCan read multiple data from a file at a time.Cannot write multiple data to a file at a time.
Printing to ConsoleCannot print data to the console using fscanf().Can print data to the console using fprintf().

Understanding the differences between fscanf() and fprintf() is important for properly utilizing file input/output operations in C programming.

Best Practices for using fscanf and fprintf:

fscanf and fprintf are widely used in various fields such as data processing, scientific computing, and system programming. Here are some real-world examples of how these functions are used in actual programs:

  1. Validate Input Data: It is important to validate input data when using fscanf() to avoid buffer overflow attacks. Always ensure that the data read from the file is of the expected format and size. If the input data is not validated properly, it can cause the program to crash or even lead to security vulnerabilities.
  2. Validate Format String: When using fprintf(), it is important to validate the format string to avoid format string vulnerabilities. A format string vulnerability occurs when an attacker can manipulate the format string used in a function to perform malicious actions. To prevent this, only use trusted format strings or validate user input before using it in the format string.
  3. Error Handling: Always check the return values of the fscanf() and fprintf() functions to ensure that the operations are successful. If an error occurs, handle it gracefully and take appropriate action. For example, if fscanf() returns -1, it indicates an error in reading data from the file. Handle this error by closing the file and displaying an error message.
  4. Use Appropriate Data Types: Use appropriate data types for reading and writing data. For example, use the %d format specifier for integer values, %f for float values, and %s for strings. The correct data type ensures the data is read or written correctly and avoids unexpected behavior.
  5. Use Text Mode for Text Files: Text mode when reading or writing data to text files. Text mode translates line endings between different operating systems automatically. On the other hand, binary mode reads and writes data in binary format, which can lead to incorrect line endings.
  6. Use Binary Mode for Binary Files: Use binary mode when reading or writing data to binary files. Binary mode reads and writes data in binary format, which is useful for non-text files like images, audio, and video.
  7. Close Files Properly: Always close files after reading or writing data. It ensures that the file is released and available for other processes. Leaving files open can lead to resource leaks, which can cause the program to crash or behave unexpectedly.
  8. Use Appropriate Memory Allocation: When reading data using fscanf(), properly allocate the data storage variables. Allocate enough memory to store the data being read to avoid buffer overflows.
  9. Use Constants for File Names: Instead of hardcoding, use constants to store file names. It makes it easier to change file names in the future and avoids errors caused by mistyping file names.
  10. Use Descriptive Variable Names: Use descriptive variable names for variables used in file input/output operations. It makes the code easier to read and understand, especially with large programs.

By following these best practices, developers can avoid common errors and ensure secure, efficient, and error-free implementation of file input/output operations using fscanf() and fprintf() in C programming.

Real-world Examples of using fscanf and fprintf in C:

fscanf and fprintf are widely used in various fields, such as data processing, scientific computing, and system programming. Here are some real-world examples of how these functions are used in actual programs:

  1. Data processing: fscanf and fprintf are commonly used in data processing applications, such as text file parsers and database management systems. For example, a program that reads data from a CSV file and converts it into a database table can use fscanf to read the input data and fprintf to write the output data to a database file. The program can efficiently process large amounts of data and store it in an easily queried and analyzed format using these functions.
  2. Scientific computing: fscanf and fprintf are also widely used in scientific applications such as numerical simulations and data analysis tools. For example, a program that reads data from a text file containing experimental results can use fscanf to read the input data and fprintf to write the output data to a graph or chart. Using these functions, the program can visualize and analyze the data meaningfully, helping scientists and researchers understand complex phenomena and make important discoveries.
  3. System programming: fscanf and fprintf are also used in system programming applications, such as device drivers and operating system utilities. For example, a program that reads data from a serial port and writes it to a log file can use fscanf to read the input data and fprintf to write the output data to the log file. The program can monitor and analyze system events and troubleshoot issues in real-time using these functions.
  4. File management: fscanf and fprintf are also used in file management applications, such as file converters and backup tools. For example, a program that reads data from a proprietary file format and converts it to a standard form can use fscanf to read the input data and fprintf to write the output data to a new file. The program can convert and transfer files between different systems and applications using these functions, helping users access and use their data more effectively.

In summary, fscanf and fprintf are versatile functions in various applications, ranging from data processing and scientific computing to system programming and file management. By leveraging the power of these functions, programmers can efficiently read and write data to files and other sources and build robust and reliable applications that can handle various data inputs and outputs.

Error Handling in fprintf and scanf in C :

Error handling is an important aspect of programming in C, especially when working with file I/O functions such as fprintf and fscanf. These functions are used to read from and write to files, respectively, and errors can occur during these operations, leading to unexpected behavior, program crashes, or data corruption. In this answer, we will discuss error handling in fprintf and fscanf in detail, covering common error scenarios and how to handle them.

Error handling in fprintf :

fprintf is a function that writes formatted output to a file. It takes a format string and a list of variables containing the output values and writes the formatted output to the specified file. The return value of fprintf is the number of characters written or a negative value if an error occurs.

Common error scenarios in fprintf include:

a) File not found: If the file specified in the fopen function cannot be found, fprintf will return a negative value. It can occur if the file name is misspelled or the file does not exist. To handle this error, you should check the return value of fopen and handle the error appropriately. For example:

FILE *fp = fopen("myfile.txt", "w");
if (fp == NULL) {
   printf("Error: File not found.");
   exit(1);
}

In this example, the fopen function opens the file myfile.txt for writing. The program will print an error message and exit if the file cannot be found.

b) Output conversion error: If the output values cannot be converted to the format specified in the format string, fprintf will return a negative value. It can occur if the output values are not of the expected type or if the output values cannot be represented in the specified format. To handle this error, you should check the return value of fprintf and handle the error appropriately. For example:

int x = 100;
int result = fprintf(fp, "%s", x);
if (result < 0) {
   printf("Error: Output conversion error.");
   exit(1);
}

The fprintf function writes the integer value 100 to the file as a string in this example. The program will print an error message and exit if the value cannot be represented as a string.

c) Disk full: If the disk is full, fprintf will return a negative value. It can occur if the file system is full or the disk is physically damaged. To handle this error, you should check the return value of fprintf and handle the error appropriately. For example:

int x = 100;
int result = fprintf(fp, "%d", x);
if (result < 0) {
   printf("Error: Disk full.");
   exit(1);
}

The fprintf function writes the integer value 100 to the file in this example. If the disk is full, the program will print an error message and exit.

d) File permissions: If the file permissions do not allow writing, fprintf will return a negative value. It can occur if the file is read-only or the user cannot write. To handle this error, you should check the return value of fopen and handle the error appropriately. For example:

FILE *fp = fopen("myfile.txt", "w");
if (fp == NULL) {
   printf("Error: File permissions error.");
   exit(1);
}

In this example, the fopen function opens the file myfile.txt for writing. The program will print an error message and exit if the user cannot write to the file.

Error handling in fscanf :

fscanf is a function that reads formatted input from a file. It takes a format string and a list of variables to store the input values and reads the formatted information from the specified file. In fscanf, the return value is the number of input values successfully read or a negative value if an error occurs.

Common error scenarios in fscanf include:

a) File not found: If the file specified in the fopen function cannot be found, then fscanf will return a NULL value. It can occur if the file name is misspelled or the file does not exist. To handle this error, you should check the return value of fopen and handle the error appropriately. For example:

FILE *fp = fopen("myfile.txt", "r");
if (fp == NULL) {
    printf("Error: File not found.");
    exit(1);
}

In this example, the fopen function opens the file myfile.txt for reading. The program will print an error message and exit if the file cannot be found.

b) End of file: If fscanf encounters the end of the file before all input values have been read, it will return a value less than the number of input values specified. It can occur if the file contains more input values or if the input values must be correctly formatted. To handle this error, you should check the return value of fscanf and handle the error appropriately. For example:

int x, y, z;
int result = fscanf(fp, "%d %d %d", &x, &y, &z);
if (result < 3) {
    printf("Error: End of file or incorrect format.");
    exit(1);
}

The fscanf function reads three integer values from the file in this example. If the end of the file is encountered before all three values are read, or if the values are not correctly formatted, the program will print an error message and exit.

c) Input conversion error: If the input values in the file do not match the format string provided to fscanf, the function will return a value less than the number of input values specified, and the input variables will be left unchanged. It can occur if the input values are not of the expected type or if the input values are not in the desired format. To handle this error, you should check the return value of fscanf and handle the error appropriately. For example:

int x;
int result = fscanf(fp, "%d", &x);
if (result < 1) {
    printf("Error: Input conversion error.");
    exit(1);
}

The fscanf function reads an integer value from the file in this example. The program will print an error message and exit if the input value is not an integer.

In summary, error handling is an essential aspect of programming in C. When using the fprintf and fscanf functions to write to and read from files, you should always check the return values and handle errors appropriately. Doing so ensures your program behaves correctly and does not crash or produce unexpected results.

Conclusion :

In conclusion, fscanf and fprintf are important functions in the C programming language used to read input from files and write output to files, respectively. Both functions are essential for performing file I/O operations in C programs and are widely used in various fields such as data processing, scientific computing, and system programming.

Fscanf is used to read input from files or standard input streams (stdin) and supports various format specifiers for reading information of different data types, such as integers, floating-point numbers, and strings. It is important to handle errors that may occur during the execution of fscanf, such as format errors, input/output errors, and end-of-file errors. Proper error handling ensures the program behaves correctly and does not crash or produce incorrect results.

Similarly, fprintf is used to write output to files or standard output streams (stdout) and supports various format specifiers for writing output of different data types, such as integers, floating-point numbers, and strings. Like fscanf, it is important to handle errors that may occur during the execution of fprintf, such as output errors, disk full errors, and other system errors.

While fscanf and fprintf are similar in their usage, there are some differences between the two functions regarding functionality and usage. For example, fscanf is used to read input from files, while fprintf is used to write output to files. Additionally, these functions should be used carefully and with proper precautions, as they can potentially cause data corruption or security issues if not used properly.

To use fscanf and fprintf effectively, it is important to follow best practices for file I/O operations. It includes using appropriate error-handling techniques, ensuring that input/output data is valid and sanitized, and optimizing the code for efficiency and speed.

In conclusion, mastering file I/O operations in C, including fscanf and fprintf, is essential for building robust and reliable programs that handle various data inputs and outputs. By following best practices and using these functions carefully, programmers can harness the power of file I/O operations to build powerful and efficient applications in C.