C fprintf() and fscanf()

fprintf() and fscanf() are functions in the C programming language that are used for input and output operations with files.

fprintf() is used to write formatted data to a file. Its syntax is as follows:

int fprintf(FILE *stream, const char *format, ...);

Here, stream is a pointer to a FILE object that represents the file you want to write to. format is a string that specifies the format of the data to be written, similar to the format strings used in printf(). The ... indicates that you can pass additional arguments based on the format specifier in the format string.

Here’s an example that demonstrates the usage of fprintf():

#include <stdio.h>

int main() {
   FILE *file = fopen("output.txt", "w");
   if (file != NULL) {
      int num = 42;
      fprintf(file, "The number is %d\n", num);
      fclose(file);
   } else {
      printf("Error opening the file\n");
   }
   
   return 0;
}

In this example, the fprintf() function is used to write the string "The number is 42\n" to the file “output.txt”. The file is opened in write mode ("w"), and if the file opening is successful, the file is closed using fclose().

fscanf() is used to read formatted data from a file. Its syntax is as follows:

int fscanf(FILE *stream, const char *format, ...);

Similar to fprintf(), stream is a pointer to a FILE object representing the file you want to read from. format is a string that specifies the format of the expected input, and ... indicates that you can pass additional arguments to store the read data.

Here’s an example that demonstrates the usage of fscanf():

#include <stdio.h>

int main() {
   FILE *file = fopen("input.txt", "r");
   if (file != NULL) {
      int num;
      fscanf(file, "%d", &num);
      printf("The number read from the file is %d\n", num);
      fclose(file);
   } else {
      printf("Error opening the file\n");
   }
   
   return 0;
}

In this example, the fscanf() function is used to read an integer from the file “input.txt” using the %d format specifier. The value is then stored in the num variable, which is later printed to the console.

It’s important to check the return values of both fprintf() and fscanf() to handle any potential errors that may occur during file I/O operations.

Writing File : fprintf() function

The fprintf() function in C is used to write formatted data to a file. It works similar to the printf() function, but instead of printing to the console, it writes the output to a file.

The syntax of fprintf() is as follows:

int fprintf(FILE *stream, const char *format, ...);

The stream parameter is a pointer to a FILE object that represents the file you want to write to. It can be a pointer to a file opened using fopen(), such as stdout for standard output or a file pointer returned by fopen().

The format parameter is a string that specifies the format of the data to be written. It can contain format specifiers like %d for integers, %f for floating-point numbers, %s for strings, etc. These format specifiers are replaced by the corresponding values passed as additional arguments.

Here’s an example that demonstrates the usage of fprintf():

#include <stdio.h>

int main() {
   FILE *file = fopen("output.txt", "w");
   if (file != NULL) {
      int num = 42;
      float pi = 3.14159;
      char str[] = "Hello, World!";
      
      fprintf(file, "Integer: %d\n", num);
      fprintf(file, "Float: %.2f\n", pi);
      fprintf(file, "String: %s\n", str);
      
      fclose(file);
   } else {
      printf("Error opening the file\n");
   }
   
   return 0;
}

In this example, a file named “output.txt” is opened in write mode ("w"). Then, fprintf() is used to write formatted data to the file. Three lines are written, each containing different data types. The %d specifier is used to print an integer, %f with %.2f is used to print a float with two decimal places, and %s is used to print a string. Finally, the file is closed using fclose().

After running this program, the “output.txt” file will be created (or overwritten if it already exists) and will contain the following content:

Integer: 42
Float: 3.14
String: Hello, World!

Remember to handle any potential errors that may occur during file operations by checking the return value of fopen() and fprintf().

Reading File : fscanf() function

The fscanf() function in C is used to read formatted data from a file. It allows you to extract values from a file based on specified format specifiers, similar to how scanf() reads input from the console.

The syntax of fscanf() is as follows:

int fscanf(FILE *stream, const char *format, ...);

The stream parameter is a pointer to a FILE object that represents the file you want to read from. It can be a pointer to a file opened using fopen(), such as stdin for standard input or a file pointer returned by fopen().

The format parameter is a string that specifies the format of the expected input in the file. It contains format specifiers like %d for integers, %f for floating-point numbers, %s for strings, etc. These format specifiers specify the type of data you want to read and where to store it.

Here’s an example that demonstrates the usage of fscanf():

#include <stdio.h>

int main() {
   FILE *file = fopen("input.txt", "r");
   if (file != NULL) {
      int num;
      float pi;
      char str[100];
      
      fscanf(file, "%d", &num);
      fscanf(file, "%f", &pi);
      fscanf(file, "%s", str);
      
      printf("Integer: %d\n", num);
      printf("Float: %.2f\n", pi);
      printf("String: %s\n", str);
      
      fclose(file);
   } else {
      printf("Error opening the file\n");
   }
   
   return 0;
}

In this example, a file named “input.txt” is opened in read mode ("r"). Then, fscanf() is used to read data from the file. Three fscanf() calls are made, each corresponding to a line in the file. The format specifiers %d, %f, and %s are used to read an integer, a float, and a string, respectively. The values are stored in the corresponding variables num, pi, and str. After reading the values, they are printed using printf().

Assuming the “input.txt” file contains the following content:

42
3.14159
Hello, World!

The output of the program will be:

Integer: 42
Float: 3.14
String: Hello,

Note that the string output is truncated because %s stops reading at the first whitespace character encountered. To read a full line including spaces, you can use the %[^\n] format specifier instead, like %[^\n]s.

Remember to handle any potential errors that may occur during file operations by checking the return value of fopen() and fscanf().

C File Example: Storing employee information

Certainly! Here’s an example of storing employee information using files in C:

#include <stdio.h>

struct Employee {
    int id;
    char name[50];
    float salary;
};

int main() {
    int numEmployees;
    printf("Enter the number of employees: ");
    scanf("%d", &numEmployees);

    struct Employee employees[numEmployees];

    // Getting employee details
    for (int i = 0; i < numEmployees; i++) {
        printf("\nEnter details for Employee %d:\n", i + 1);
        printf("ID: ");
        scanf("%d", &employees[i].id);
        printf("Name: ");
        scanf("%s", employees[i].name);
        printf("Salary: ");
        scanf("%f", &employees[i].salary);
    }

    // Storing employee details in a file
    FILE *file = fopen("employees.txt", "w");
    if (file != NULL) {
        for (int i = 0; i < numEmployees; i++) {
            fprintf(file, "%d,%s,%.2f\n", employees[i].id, employees[i].name, employees[i].salary);
        }
        fclose(file);
        printf("\nEmployee information stored successfully.\n");
    } else {
        printf("Error opening the file.\n");
    }

    return 0;
}

In this example, we use a structure Employee to represent employee information. The structure has three members: id (integer), name (character array), and salary (float).

The program prompts the user to enter the number of employees and then dynamically allocates an array of Employee structures based on the given count.

It then loops over each employee, prompts for their details (ID, name, and salary), and stores the information in the corresponding array element.

Finally, the program opens a file named “employees.txt” in write mode, writes the employee details in a comma-separated format (id,name,salary), and closes the file.

Please note that this example assumes that the user enters valid input and does not perform extensive error checking. It’s important to add appropriate error handling and input validation in real-world scenarios to ensure the correctness and robustness of the program.