Rolex Pearlmaster Replica
  Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
This article is part of in the series
Published: Friday 1st March 2024

How To Use The C Library Function Fprintf()

C's fprintf() function shares similarities to the printf() function, in that they are both used to output text. 

The key difference between them is that fprintf() shares formatted output to a file stream rather than on the stdout console.

In this brief guide, we will help you understand what fprintf() is and how to use it.

What is the fprintf() Function?

Programmers sometimes find the need to write data into files rather than the terminal, and this is where the fprintf() function comes in. 

In C, the function is known as the format print function. You can find the function's definition in the stdio.h header file. 

The interesting thing about this function is that it can send a formatted output string to a stream. It counts the number of characters successfully written to the file and returns the count. If the function fails, it returns an EOF.

Syntax of the fprintf() Function 

Declaring the fprint() function in a C program is quite straightforward. You can use the syntax:

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

 

In C, when using the fprintf function, you provide a stream, which is a pointer to a file object where you want to write data and a format containing the text you want to write to the stream. 

If the operation is successful, fprintf() returns an integer indicating the number of characters written to the file.

Parameters Supported by fprintf()

The fprintf() function can accept two arguments: stream and format.

The stream argument is the pointer to a FILE object. It helps identify the sequence of file objects where data should be written. 

The C string represents the text from the file indicated by the stream pointer. 

You can include format tags, which will be substituted with the values provided in the subsequent arguments.

The blueprint of a format tag is as follows:

% [flags][width][.precision][length]specifier.

 

Let's understand the components of this tag one after another, beginning with the flags.

Flags

Flags Description
(space) If no sign is specified, a blank space comes before the value.
- The text is aligned to the left.
+ A plus (+) or minus (-) sign is added before the result.
0 Pads the number with zeroes rather than spaces.
# It is used with o, x, or X specifiers when all values except zero are preceded by 0, 0x, or 0X.

 

Width

Width Description
(number) This indicates the minimum number of characters to be written into the file. If the printed value is smaller than this number, spaces fill the gap between the two numbers.
* This denotes that the width isn't specified in the format string but is provided as an integer argument after the argument that needs formatting.

 

Precision

.precision Description
.number It sets the minimum number of digits needed for the printed number in the file for integer specifiers like i, d, u, o, x, or X. If the number is smaller than the specified minimum, leading zeros (0) are added. If the number exceeds the specified minimum, it won't be truncated. All characters are printed by default until a null character is found unless a specific value is provided.
.* It indicates that the precision isn't specified within the format string itself; instead, it's provided separately as an integer argument to the function.

 

Specifiers

Specifier Meaning
c C character
d or i Signed decimal integer
e (mantissa) Used for scientific notation using e character
E (mantissa) Used for scientific notation using the E character
f Decimal floating-point number
g shorter of %f or %e
G shorter of %f or %E
o signed octal
p Pointer address
s String of characters
u Unsigned decimal integer
x unsigned hexadecimal number
X unsigned hexadecimal number

 

Length

Length Description
l It's understood as either a long or an unsigned long integer for characters or character strings (c and s) and integer specifiers (d, i, o, u, x, and X).
h This argument for length can be understood as either an unsigned short integer or a short integer. It's only applicable to integer specifiers.
L This argument is seen as a long double and is only relevant for floating-point specifiers such as g, f, R, and e.

 

Depending on the format string passed to the fprintf() function, it may expect some additional arguments. Additionally, these extra arguments expect a value for every "%" tag present in the format string.

The Return Value of the fprintf() Function

This function returns an integer value representing the number of characters printed into a file.

If the function encounters some issue when writing to the file stream, it stops and returns a negative value. 

Example of fprintf() Function

Before you use the fprintf() function in C, you must open the text file in write mode in a specific position. Of course, you will need to use a file pointer. 

Next, you must write the string into the file by passing the pointer and the string to the fprintf() function. Here's an example:

#include <stdio.h>

int main() {

  char input[100];

  FILE *filePointer;

  int numberOfInputs, i;

  filePointer = fopen("output.txt", "w");

  if (filePointer == NULL) {

    printf("Error: Unable to open file!");

    return 0;

  }

  printf("Enter number of inputs to write to the file: ");

  scanf("%d", &numberOfInputs);

  for (i = 1; i <= numberOfInputs; i++) {

    printf("Enter input %d: ", i);

    scanf("%s", input);

    fprintf(filePointer, "Input %d: %s\n", i, input);

  }

  fclose(filePointer);

  return 0;

}

 

This program prompts the user for a certain number of inputs, writes those inputs to a file along with their indices, and then closes the file.

Let's assume a user gives this program the following inputs:

Enter number of inputs to write to the file: 3

Enter input 1: Apple

Enter input 2: Banana

Enter input 3: Orange

 

After the user enters these inputs, the program writes them into a file named "output.txt" in the following format:

Input 1: Apple

Input 2: Banana

Input 3: Orange

 

Another Example of fprintf() Function

The program below prompts the user for student information and then writes it to a file named "student_info.txt" before closing the file.

#include <stdio.h>

int main() {

  // Initializing file pointer.

  FILE *file_pointer;

  file_pointer = fopen("student_info.txt", "w");

  // If file_pointer is a null pointer, the file opening failed.

  if (file_pointer == NULL) {

    printf("Failed to open file!");

    return 0;

  }

  int roll_number;

  char name[50];

  float gpa;

  // Input student info from the user.

  printf("Enter student's name: ");

  scanf("%s", name);

  printf("Enter student's roll number: ");

  scanf("%d", &roll_number);

  printf("Enter student's GPA: ");

  scanf("%f", &gpa);

  // Writing data into the file.

  fprintf(file_pointer, "Name: %s\n", name);

  fprintf(file_pointer, "Roll Number: %d\n", roll_number);

  fprintf(file_pointer, "GPA: %.2f\n", gpa);

  // Close opened file.

  fclose(file_pointer);

  return 0;

}

 

Let's assume that the user gives the program these inputs:

Enter student's name: John Doe

Enter student's roll number: 12345

Enter student's GPA: 3.75

 

After the user enters this information, the program creates a file named "student_info.txt" and writes the following content into it:

Name: John Doe

Roll Number: 12345

GPA: 3.75

 

If the file creation or writing fails, the program will output "Failed to open file!" instead of creating the file and writing the information.

Latest Articles


Tags

  • Data structures
  • algorithm
  • Print Node
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • Pygame
  • NumPy Pad()
  • Unlock
  • Bypass
  • pytorch
  • zipp
  • steam
  • multiprocessing
  • type hinting
  • global
  • argh
  • c vs python
  • Python
  • stacks
  • Sort
  • algorithms
  • install python
  • Scopes
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • % Operator
  • Python YAML
  • Crack
  • Reddit
  • lightning
  • zip files
  • python reduce
  • library
  • dynamic
  • local
  • command line
  • define function
  • Pickle
  • enqueue
  • ascending
  • remove a node
  • Django
  • function scope
  • Tuple in Python
  • pandas groupby
  • pyenv
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • Hack
  • sdk
  • python automation
  • main
  • reduce
  • typing
  • ord
  • print
  • network
  • matplotlib inline
  • Pickling
  • datastructure
  • bubble sort
  • find a node
  • Flask
  • calling function
  • tuple
  • GroupBy method
  • Pythonbrew
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Keygen
  • cloud
  • pyautogui
  • python main
  • reduce function
  • type hints
  • python ord
  • format
  • python socket
  • jupyter
  • Unpickling
  • array
  • sorting
  • reversal
  • Python salaries
  • list sort
  • Pip
  • .groupby()
  • pyenv global
  • NumPy arrays
  • Modulo
  • OpenCV
  • Torrent
  • data
  • int function
  • file conversion
  • calculus
  • python typing
  • encryption
  • strings
  • big o calculator
  • gamin
  • HTML
  • list
  • insertion sort
  • in place reversal
  • learn python
  • String
  • python packages
  • FastAPI
  • argparse
  • zeros() function
  • AWS Lambda
  • Scikit Learn
  • Free
  • classes
  • turtle
  • convert file
  • abs()
  • python do while
  • set operations
  • data visualization
  • efficient coding
  • data analysis
  • HTML Parser
  • circular queue
  • effiiciency
  • Learning
  • windows
  • reverse
  • Python IDE
  • python maps
  • dataframes
  • Num Py Zeros
  • Python Lists
  • Fprintf
  • Version
  • immutable
  • python turtle
  • pandoc
  • semantic kernel
  • do while
  • set
  • tabulate
  • optimize code
  • object oriented
  • HTML Extraction
  • head
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • Pytest
  • pandas.reset_index
  • NumPy
  • Infinite Numbers in Python
  • Python Readlines()
  • Trial
  • youtube
  • interactive
  • deep
  • kernel
  • while loop
  • union
  • tutorials
  • audio
  • github
  • Parsing
  • tail
  • merge sort
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • unittest
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • Studio
  • excel
  • sgd
  • deeplearning
  • pandas
  • class python
  • intersection
  • logic
  • pydub
  • git
  • Scrapping
  • priority queue
  • quick sort
  • web development
  • uninstall python
  • python string
  • code interface
  • PyUnit
  • round numbers
  • train_test_split()
  • Flask module
  • Software
  • FL
  • llm
  • data science
  • testing
  • pathlib
  • oop
  • gui
  • visualization
  • audio edit
  • requests
  • stack
  • min heap
  • Linked List
  • machine learning
  • scripts
  • compare string
  • time delay
  • PythonZip
  • pandas dataframes
  • arange() method
  • SQLAlchemy
  • Activator
  • Music
  • AI
  • ML
  • import
  • file
  • jinja
  • pysimplegui
  • notebook
  • decouple
  • queue
  • heapify
  • Singly Linked List
  • intro
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Download
  • No
  • nlp
  • machiine learning
  • dask
  • file management
  • jinja2
  • ui
  • tdqm
  • configuration
  • deque
  • heap
  • Data Structure
  • howto
  • dict
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • KMS
  • Office
  • modules
  • web scraping
  • scalable
  • pipx
  • templates
  • python not
  • pytesseract
  • env
  • push
  • search
  • Node
  • python tutorial
  • dictionary
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • linspace
  • numbers_list
  • Tool
  • Key
  • automation
  • website data
  • autoscale
  • packages
  • snusbase
  • boolean
  • ocr
  • pyside6
  • pop
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Assertions
  • Matplotlib Plotting
  • any() Function
  • Activation
  • Patch
  • threading
  • scrapy
  • game analysis
  • dependencies
  • security
  • not operation
  • pdf
  • build gui
  • dequeue
  • linear search
  • Add Node
  • Python tools
  • function
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • matplotlib
  • Recursion Limit
  • License
  • Pirated
  • square root
  • website extract python
  • steamspy
  • processing
  • cybersecurity
  • variable
  • image processing
  • incrementing
  • Python is a beautiful language.