Table of contents
1.
Introduction
2.
What is fprintf() in C?
3.
Syntax of fprintf() in C
4.
Parameters of fprintf() in C
5.
Return Value of fprintf() in C
6.
Example
7.
Frequently Asked Questions
7.1.
Can fprintf() be used to append data to an existing file?
7.2.
What happens if the file cannot be opened or written to?
7.3.
Is it necessary to close the file after using fprintf()?
8.
Conclusion
Last Updated: Nov 25, 2024

fprintf() in C

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

fprintf() is a function in the C language that is used to write formatted outputs for files. It allows you to print text, numbers, and other data types to a file with specified formatting. With fprintf(), you can create and write to files, which makes it a useful tool for storing data, generating reports, or logging information. This function is almost similar to printf(), but instead of displaying data on the console, it writes it to a file you specified. 

fprintf() in C

In this article, we will discuss the syntax, parameters, return value, and examples of using fprintf() in C.

What is fprintf() in C?

fprintf() is a standard library function in C that is used to write formatted output to a file. It is similar to the printf() function, which prints formatted output to the console. However, instead of printing to the console, fprintf() writes the output to a specified file.

The fprintf() function takes a file pointer as its first argument, which indicates the file where the output will be written. The file pointer is obtained by opening a file using the fopen() function. The subsequent arguments to fprintf() specify the format string and the values to be printed, just like in printf().

Syntax of fprintf() in C

The syntax of the fprintf() function in C is:

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

 

In this syntax: 

  • FILE *stream: This is the file pointer that specifies the file where the output will be written. It is obtained by opening a file using the fopen() function.
     
  • const char *format: This is the format string that specifies how the output should be formatted. It can contain plain text, conversion specifiers (e.g., %d for integers, %f for floating-point numbers), & other formatting options.
     
  •  ...: This represents optional arguments that correspond to the conversion specifiers in the format string. These arguments provide the actual values to be printed.
     

The fprintf() function returns the total number of characters written to the file. If an error occurs, it returns a negative value.

Parameters of fprintf() in C

The fprintf() function takes the following parameters:

1. FILE *stream:

  • This parameter is a pointer to the FILE object that represents the file where the output will be written.
     
  • It is obtained by opening a file using the fopen() function.
     
  • The file must be opened in write mode ("w") or append mode ("a") to allow writing.
     

2. const char *format:

  • This parameter is a string that specifies the format of the output.
     
  • It can contain plain text, conversion specifiers, & other formatting options.
     
  • Conversion specifiers start with the '%' character & are followed by a character that specifies the type of value to be printed (e.g., %d for integers, %f for floating-point numbers, %s for strings).
     
  • Additional formatting options can be included between the '%' & the conversion specifier (e.g., width, precision, flags).
     

3. ...:

  • This parameter represents optional arguments that correspond to the conversion specifiers in the format string.
     
  • The number & type of arguments must match the conversion specifiers used in the format string.
     
  • For example, if the format string contains "%d %f", there should be two arguments: an integer & a floating-point number.
     

Note: The fprintf() function reads the format string, processes the conversion specifiers, and applies formatting options to generate the formatted output. It then writes the output to the specified file.

Return Value of fprintf() in C

The fprintf() function returns an integer value that indicates the status of the write operation. Let’s see what the return value represents:

Positive Value:

  • If fprintf() successfully writes the formatted output to the file, it returns the total number of characters written.
     
  • This includes all the characters specified in the format string & the values of the arguments.
     
  • The return value does not include the null terminator ('\0') that is automatically appended to the end of the output.

Negative Value:

  • If an error occurs during the write operation, fprintf() returns a negative value.
     
  • The specific value returned depends on the type of error encountered.
     
  • Common errors include:

    - Invalid file pointer (e.g., trying to write to a file that is not open)

- Disk full or unable to write to the file

- Invalid format specifiers or arguments


It is important to check the return value of fprintf() to ensure that the write operation was successful. If an error occurs, you can handle it appropriately in your program.

Let’s look at an example of checking the return value of fprintf():

FILE *file = fopen("output.txt", "w");
if (file == NULL) {
    printf("Error opening file.\n");
    return 1;
}
int result = fprintf(file, "Hello, %s!\n", "world");
if (result < 0) {
    printf("Error writing to file.\n");
    fclose(file);
    return 1;
}

fclose(file);


In this example, we first check if the file was successfully opened. If not, we print an error message and return. After writing to the file using fprintf(), we check the return value. If it is negative, indicating an error, we print an error message, close the file, and return. If the write operation was successful, we simply close the file.

Example

Let’s take an example that shows the use of fprintf() in C:

#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    char name[] = "Ravi";
    int age = 25;
    float score = 91.5;
    int result = fprintf(file, "Name: %s\nAge: %d\nScore: %.2f\n", name, age, score);
    if (result < 0) {
        printf("Error writing to file.\n");
        fclose(file);
        return 1;
    }

    printf("Data written to file successfully.\n");
    fclose(file);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


In this example: 

1. We include the `stdio.h` header file to use the fprintf() function & other file I/O functions.
 

2. In the `main()` function, we open a file named "output.txt" in write mode using `fopen()`. We store the file pointer in the `file` variable.
 

3. We check if the file was opened successfully by comparing `file` with `NULL`. If it is `NULL`, we print an error message & return.
 

4. We declare and initialize variables `name` (a string), `age` (an integer), and `score` (a floating-point number) to store the data we want to write to the file.
 

5. We use fprintf() to write the formatted data to the file. The format string specifies the structure of the output, and the variables `name`, `age`, and `score` are provided as arguments to be printed.
 

6. We store the return value of fprintf() in the `result` variable & check if it is negative, indicating an error. If an error occurred, we print an error message, close the file, & return.
 

7. If the write operation was successful, we print a success message.
 

8. Finally, we close the file using `fclose()` to release the file resources & ensure that all the data is written to the file.
 

After running this program, a file named "output.txt" will be created (if it doesn't exist) or overwritten (if it already exists). The file will contain the following content:

Name: Ravi
Age: 25
Score: 91.50


This example shows how fprintf() can be used to write formatted data to a file in C.

Frequently Asked Questions

Can fprintf() be used to append data to an existing file?

Yes, by opening the file in append mode ("a"), fprintf() will append data to the end of the file.

What happens if the file cannot be opened or written to?

If the file cannot be opened or written to, fprintf() will return a negative value indicating an error.

Is it necessary to close the file after using fprintf()?

Yes, it is important to close the file using fclose() to ensure that all data is written & to release file resources.

Conclusion

In this article, we discussed the fprintf() function in C, which allows us to write formatted output to a file. We learned about its syntax, parameters, and return value and saw an example of how to use it effectively. With the help of fprintf(), we can create and manipulate files programmatically, which enables us to store data, generate reports, and perform various file I/O operations in C programs.

You can also check out our other blogs on Code360.

Live masterclass