Cstdio in C++
In this article, we will discuss the cstdio header file in C++ with its functions and examples.
The "cstdio" header file in C++ is used to handle input and output operations. It includes declarations for functions that manage file input and output operations in addition to handling conventional input and output.
The Standard Library, which is a set of classes, methods, and templates made available by the C++ Standard Library for common programming tasks, includes the functions and types described in "cstdio". The functions and types declared in the "cstdio" header are compatible with those in the "stdio.h" header since it is derived from the "stdio.h" header used by the C++ programming language.
The "cstdio" library in C++ includes the following frequently used types and functions:
1.Functions for input and output:
There are several functions for input and output in C++. Some functions are as follows:
a) printf():
Data is formatted and printed using the printf() function to the console or standard output stream.
Syntax:
It has the following syntax:
printf("format_string", arg1, arg2, ...);
Example:
Let's take an example of printing an integer and a floating-point number using the printf() function in C++.
#include <cstdio>
int main()
{
int n = 75;
float pi = 3.14159;
printf("The value of number is %d and the value of pi is %.2f\n", n, pi);
return 0;
}
Output:
The value of the number is 75 and the value of pi is 3.14
Explanation:
In this example, there are two placeholders in the format string: %d for the integer n and %.2f for the floating-point pi. The floating-point number is to be printed with two decimal places, according to the .2 in %.2f specification. The appropriate placeholders will be filled in with the values of n and pi.
b) fscanf():
The fscanf() function is used to read formatted data from a specified input stream, such as a file.
Syntax:
It has the following syntax:
int fscanf(FILE* stream, const char* format, arg1, arg2, ...);
Example:
Let's take an example of reading an integer and a floating-point number from a file with the fscanf() function:
#include <cstdio>
int main()
{
FILE *file = fopen("input.txt", "r");
// Open the file in read mode
if (file == nullptr)
{
printf("Failed to open the file.\n");
return 1;
}
int num;
float pi;
// Read an integer and a floating-point number from the file
int numItemsRead = fscanf(file, "%d %f", &num, &pi);
if (numItemsRead == 2)
{
printf("Read data successfully:\n");
printf("Number: %d\n", num);
printf("Pi: %.2f\n", pi);
}
else
{
printf("Failed to read data from the file.\n");
}
fclose(file);
// Close the file
return 0;
}
Output:
Failed to open the file.
Explanation:
In this example, we use fopen() to open a file called "input.txt" in read mode. Next, we read two numbers from the file using fscanf: an integer and a floating-point number. After that, we save the values in the variables num and pi, respectively. Similar to printf(), the format string in fscanf() describes how the data in the file is formatted.
c) getchar():
The getchar() function is used to read one character from the standard input.
Syntax:
It has the following syntax:
int getchar();
Example:
Let's take an example to read characters from standard input using the getchar() function until the user pushes the Enter key:
#include <cstdio>
int main()
{
printf("Enter a line of text (press Enter to finish):\n");
int ch;
// We use int to handle EOF
// Read characters until Enter (newline) is pressed
while ((ch = getchar()) != '\n') {
// Do something with the character (print it, process it, etc.)
putchar(ch);
}
return 0;
}
Output:
Enter a line of text (press Enter to finish):
ram
ram
Explanation:
In this example, the program asks the user to submit a line of text. The while loop repeatedly invokes the getchar() function to read characters from the standard input. In this case, the loop only prints the character using putchar as long as it is not the newline character ('n'). Upon pressing Enter, the loop will come to an end.
d) putchar():
A single character is produced using the putchar() function.
Syntax:
It has the following syntax:
int putchar(int character);
Example:
Let's take an example of outputting characters to the console using the putchar() function:
#include <cstdio>
int main()
{
printf("Outputting characters using putchar:\n");
// Output some characters using putchar
putchar('H');
putchar('i');
putchar('\n');
// Output a newline character
return 0;
}
Output:
Outputting characters using putchar:
Hi
Explanation:
In this example, the program utilizes the putchar() function to output the letters 'H', and 'i' one at a time. After that, it prints the newline character "n", which starts the next line's output cursor.
e) scanf():
The scanf() function is used to read formatted data from the standard input stream (often the keyboard).
Syntax:
It has the following syntax:
int scanf(const char *format, arg1, arg2, ...);
Example:
Let's take an example to read an integer and a floating-point number from standard input using the scanf() function:
#include <cstdio>
int main()
{
int num;
float pi;
printf("Enter an integer and a floating-point number: ");
scanf("%d %f", &num, &pi);
printf("You entered: %d and %.2f\n", num, pi);
return 0;
}
OUTPUT:
Enter an integer and a floating-point number: 3
3.5
You entered: 3 and 3.50
Explanation:
In this example, the user must enter an integer and a floating-point number. The scanf() function reads these numbers from the standard input based on the "%d%f" format string. When reading an integer, the format specifier %d is used, and when reading a floating-point value, the format specifier %f is used. The memory addresses for those variables must first be obtained using the & operator for scanf to store the input values into the variables num and pi.
f) fprintf():
Data is formatted and printed using the fprintf() function to a given output stream, such as a file.
Syntax:
It has the following syntax:
int fprintf(FILE* stream, const char* format, ...);
Example:
Let's take an example to write data to a file using the fprintf() function:
#include <stdio.h>
int main()
{
// Open the file in write mode
FILE* file = fopen("example.txt", "w");
if (file != nullptr) {
const char* name = "John";
int age = 30;
double salary = 50000.50;
// Write data to the file using fprintf
fprintf(file, "Name: %s\n", name);
fprintf(file, "Age: %d\n", age);
fprintf(file, "Salary: %.2f\n", salary);
// Close the file
fclose(file);
printf("Data was written to the file successfully.\n");
}
else
{
printf("Failed to open the file.\n");
}
return 0;
}
Output:
Data was written to the file successfully.
Explanation:
In this example, write mode ("w") is selected when a file called "example.txt" is opened. After that, using the fprintf() function, we add a person's name, age, and salary to the file. The associated variables (name, age, and salary) are designated by the format specifiers %s, %d, and %.2f.
2.Functions that handle files:
There are various functions that handle files. Some functions are as follows:
a) fopen():
It allows access to a file for input/output.
Syntax:
It has the following syntax:
FILE* fopen(const char* filename, const char* mode);
Example:
Let's take an example to demonstrate how the access the files for input/output using the fopen() function:
#include <stdio.h>
int main()
{
// Open a file in write mode
FILE* file = fopen("example.txt", "w");
if (file != nullptr)
{
// Write some data to the file
const char* message = "Hello, World!";
fputs(message, file);
// Close the file
fclose(file);
printf("Data was written to the file successfully.\n");
}
else
{
printf("Failed to open the file.\n");
}
return 0;
}
Output:
Data was written to the file successfully.
Explanation:
In this example, write mode ("w") is selected when a file called "example.txt" is opened. After that, using the fputs() function, we write the string "Hello, World!" to the file. Next, we use the fclose() function to close the file after writing the data.
b) fclose():
The fclose() function is used to close an open file.
Syntax:
It has the following syntax:
int fclose(FILE* stream);
Example:
Let's take an example to demonstrate how to close a file using the fclose() function:
#include <stdio.h>
int main()
{
// Open the file in write mode
FILE* file = fopen("example.txt", "w");
if (file != nullptr) {
// Write some data to the file
const char* message = "Hello, World!";
fputs(message, file);
// Close the file
int result = fclose(file);
if (result == 0) {
printf("File closed successfully.\n");
}
else
{
printf("Failed to close the file.\n");
}
}
else
{
printf("Failed to open the file.\n");
}
return 0;
}
Output:
The file closed successfully.
Explanation:
In this example, write mode ("w") is selected when a file called "example.txt" is opened. Use the fputs() function to write some data to the file. After that, we use the fclose() function to close the file. The return result of the fclose() function is examined to determine if the file was successfully closed or not.
c) fread():
The function fread() reads a block of data from a file.
Syntax:
It has the following syntax:
size_tfread(void* ptr, size_t size, size_t count, FILE* stream);
Example:
#include <stdio.h>
struct Employee {
char name[50];
int age;
double salary;
};
int main()
{
// Open the file in binary read mode
FILE* file = fopen("employees.dat", "rb");
if (file != nullptr)
{
// Read an array of Employee structures from the file
Employee employees[3];
size_telements_read = fread(employees, sizeof(Employee), 3, file);
// Close the file
fclose(file);
if (elements_read == 3)
{
// Print the data of the first employee
printf("Name: %s\n", employees[0].name);
printf("Age: %d\n", employees[0].age);
printf("Salary: %.2f\n", employees[0].salary);
}
else
{
printf("Failed to read data from the file.\n");
}
}
else
{
printf("Failed to open the file.\n");
}
return 0;
}
Output:
Failed to open the file.
Explanation:
In this example, the name, age, and salary of an employee are defined along with a basic Employee structure. Next, we open "employees.dat" in binary read mode ("rb"). From the file, we used the fread() function to read an array of three Employee structures. The elements_read variable holds the number of items that were successfully read.
d) fwrite():
The fwrite() function is used to write a block of data to a file.
Syntax:
It has the following syntax:
size_tfwrite(const void* ptr, size_t size, size_t count, FILE* stream);
Example:
#include <stdio.h>
struct Employee {
char name[50];
int age;
double salary;
};
int main()
{
// Create an array of Employee structures
Employee employees[3] = {
{"John", 30, 50000.50},
{"Jane", 28, 45000.75},
{"Mike", 35, 60000.25}
};
// Open the file in binary write mode
FILE* file = fopen("employees.dat", "wb");
if (file != nullptr)
{
// Write the array of Employee structures to the file
size_telements_written = fwrite(employees, sizeof(Employee), 3, file);
// Close the file
fclose(file);
if (elements_written == 3)
{
printf("Data was written to the file successfully.\n");
}
else
{
printf("Failed to write data to the file.\n");
}
}
else
{
printf("Failed to open the file.\n");
}
return 0;
}
Output:
Data was written to the file successfully.
Explanation:
In this example, the name, age, and salary of an employee are defined along with a basic Employee structure. After creating an array of Employee structures, we add some information to it. After that, we use the fopen() function to open a file called "employees.dat" in binary write mode ("wb"). The Employee structures are written to the file in their entirety using the fwrite() function. The fwrite() function return value is examined to test whether the data was successfully written.
e) fseek():
The file position indicator within a file is set by the fseek() function.
Syntax:
It has the following syntax:
int fseek(FILE *stream, long int offset, int origin);
Example:
#include <cstdio>
#include <cstdlib>
int main()
{
FILE* file = fopen("example.txt", "r");
if (file == nullptr)
{
perror("Error opening the file");
return EXIT_FAILURE;
}
// Move the file position indicator to the 10th byte from the beginning of the file
if (fseek(file, 10, SEEK_SET) != 0)
{
perror("Error using fseek");
return EXIT_FAILURE;
}
// Now read and print the rest of the file from the new position
char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != nullptr)
{
printf("%s", buffer);
}
fclose(file);
return EXIT_SUCCESS;
}
Output:
Error opening the file: No such file or directory
Explanation:
In this example, the program opens the file "example.txt", and uses the fseek() function to relocate the file position indication to the first 10 bytes of the file, then reads and outputs the entire file's contents from that point onward.
f) ftell():
The ftell() function returns the file position indicator's current location.
Syntax:
It has the following syntax:
long int ftell(FILE *stream);
Example:
#include <cstdio>
#include <cstdlib>
int main()
{
FILE* file = fopen("example.txt", "r");
if (file == nullptr)
{
perror("Error opening the file");
return EXIT_FAILURE;
}
// Move the file position indicator to the 10th byte from the beginning of the file
if (fseek(file, 10, SEEK_SET) != 0)
{
perror("Error using fseek");
return EXIT_FAILURE;
}
// Get the current file position indicator's offset
long int position = ftell(file);
if (position != -1)
{
printf("Current file position: %ld bytes\n", position);
}
else
{
perror("Error using ftell");
return EXIT_FAILURE;
}
fclose(file);
return EXIT_SUCCESS;
}
Output:
Error opening the file: No such file or directory
Explanation:
In this example, the program opens a file called "example.txt", and uses the fseek() function to shift the file position indication to the 10th byte from the beginning of the file, and then uses the ftell() function to get the position. On the console, the current offset is printed.
3. I/O Character:
There are various I/O characters. Some characters are as follows:
a) fgetc():
A single character can be read from a file using the fgetc() function.
Syntax:
It has the following syntax:
int fgetc(FILE *stream);
Example:
#include <cstdio>
int main()
{
FILE *file = fopen("example.txt", "r");
if (file == nullptr)
{
perror("Error opening the file");
return 1;
}
int ch;
// Read characters until the end of the file is reached
while ((ch = fgetc(file)) != EOF)
{
// Do something with the character (e.g., process, print, etc.)
putchar(ch);
}
fclose(file);
return 0;
}
Output:
Error opening the file: No such file or directory
Explanation:
This example reads text from the file "example.txt" in a loop using the fgetc() function until the file's end (represented by the EOF constant) is reached. After that, the putchar() function is used to print the characters to the console.
b) fputc():
One character can be written to a file using the fputc() function.
Syntax:
It has the following syntax:
int fputc(int character, FILE* stream);
Example:
#include <cstdio>
int main()
{
FILE* file = fopen("example.txt", "w");
// Open the file in write mode "w"
if (file == nullptr)
{
printf("Failed to open the file.\n");
return 1;
}
char ch = 'A';
// Write 'A' to the file using fputc
if (fputc(ch, file) == EOF)
{
printf("Error writing to the file.\n");
return 1;
}
// Close the file
fclose(file);
printf("A character is written to the file successfully.\n");
return 0;
}
Output:
A character is written to the file successfully.
Explanation:
In this example, the file "example.txt" is opened in write mode using the fopen() function. After that, the file is closed using the fclose() function after we use the fputc() function to add the character "A" to it.
4. File placement:
There are various file placement functions in C++. Some functions are as follows:
a.fseek():
The file position indicator can be set to a specified location within a file using the fseek() function.
Syntax:
It has the following syntax:
int fseek(FILE* stream, long int offset, int origin);
Example:
#include <cstdio>
int main()
{
FILE* file = fopen("example.txt", "r"); // Open the file in read mode ("r")
if (file == nullptr)
{
printf("Failed to open the file.\n");
return 1;
}
// Move the file position indicator to the 5th byte from the beginning of the file
if (fseek(file, 4, SEEK_SET) != 0)
{
printf("Error while seeking the file position.\n");
return 1;
}
// Read a character from the new position
int ch = fgetc(file);
if (ch != EOF)
{
printf("Character at the new position: %c\n", static_cast<char>(ch));
}
else
{
printf("Error reading character from the file.\n");
}
// Close the file
fclose(file);
return 0;
}
Output:
Error reading character from the file.
Explanation:
Here, we use the fopen() function to open the file "example.txt" in read-only mode. After that, the file position indication is moved to the 5th byte from the file's start using fseek (SEEK_SET). After that, we use the fgetc() function to read a character from the new place and print it to the console.
b. rewind():
This function returns the file position indication to its initial location.
Syntax:
It has the following syntax:
void rewind(FILE *stream);
Example:
#include <cstdio>
int main()
{
FILE *file = fopen("example.txt", "r");
if (file == nullptr)
{
perror("Error opening the file");
return 1;
}
// Move the file pointer to a specific position (e.g., offset of 5)
fseek(file, 5, SEEK_SET);
// Get the current file position
long int position = ftell(file);
if (position != -1L)
{
printf("Current position in the file: %ld\n", position);
}
else
{
perror("Error getting the position");
fclose(file);
return 1;
}
// Reset the file position back to the beginning of the file
rewind(file);
// Get the new current file position (should be 0)
position = ftell(file);
if (position != -1L)
{
printf("New position in the file after rewind: %ld\n", position);
}
else
{
perror("Error getting the position after rewind");
}
fclose(file);
return 0;
}
Output:
Error opening the file: No such file or directory
Explanation:
In this example, we open a file called "example.txt" in read mode (abbreviated "r"). After that, the file pointer is moved to position 5 relative to the file's start using the fseek() function. Before executing the rewind command, we first call the ftell() function to determine the file pointer's current position. The file position is returned to its initial location after using the rewind() function. The new current position should be 0 (the beginning of the file), which we can obtain by using the ftell() function once more.
5.More utility types and functions:
There are various utility types and functions in C++. Some functions are as follows:
a.remove():
A file can be removed from the file system using the remove() function.
Syntax:
It has the following syntax:
int remove(const char *filename);
Example:
#include <cstdio>
#include <iostream>
int main()
{
const char* filename = "example.txt";
// Check if the file exists before attempting to delete it
if (std::FILE* file = std::fopen(filename, "r"))
{
std::fclose(file);
// Attempt to delete the file
if (std::remove(filename) == 0)
{
std::cout<< "File deleted successfully.\n";
}
else
{
std::perror("Error deleting the file");
}
}
else
{
std::perror("Error opening the file");
}
Output:
Error opening the file: No such file or directory
Explanation:
In this example, we name the file we want to remove as "example.txt". We try to open the file in read mode ("r") to see if it already exists before attempting to delete it. If the file is already there, we immediately shut it before deleting it with the remove() function.
The function returns 0, and a success message is printed if the file deletion is successful. When a deletion error occurs, the function returns a non-zero value, and we use perror to print an error message.
Use of the remove function must be done with caution because there is no built-in means to undo the permanent deletion of the file from the file system. Always exercise caution when deleting files, and make sure you are deleting the right file.
b.rename():
This function is used to change a file's name.
Syntax:
It has the following syntax:
int rename(const char *old_filename, const char *new_filename);
Example:
#include <cstdio>
#include <iostream>
int main()
{
const char* old_filename = "old_file.txt";
const char* new_filename = "new_file.txt";
// Check if the old file exists before renaming it
if (std::FILE* file = std::fopen(old_filename, "r"))
{
std::fclose(file);
// Attempt to rename the file
if (std::rename(old_filename, new_filename) == 0)
{
std::cout<< "File renamed successfully.\n";
}
else
{
std::perror("Error renaming the file");
}
}
else
{
std::perror("Error opening the old file");
}
return 0;
}
Output:
Error opening the old file: No such file or directory
Explanation:
In this example, we'll rename a file called "old_file.txt" to "new_file.txt" that already exists. We attempt to open the old file in read mode ("r") before renaming it to see if it still exists. If the file already exists, we immediately shut it before renaming it with the rename() function.
The function returns 0, and we print a success message if the renaming procedure is successful. The method returns a non-zero number if there is a problem renaming the file, and we use the perror() function to output an error message.
c. feof():
With the feof() function, you may determine whether a file has reached the end of its storage space.
Syntax:
It has the following syntax:
int feof(FILE *stream);
Example:
#include <stdio.h>
int main()
{
FILE *file = fopen("example.txt", "r"); // Opening a file in read mode
if (file == NULL)
{
perror("Error opening the file");
return 1;
}
int character;
while ((character = fgetc(file)) != EOF)
{
// Process the character read from the file
putchar(character);
}
if (feof(file))
{
printf("\nEnd of file reached.\n");
}
else
{
printf("\nError while reading the file.\n");
}
fclose(file);
return 0;
}
Output:
Error opening the file: No such file or directory
Explanation:
In this example, the "example.txt" file is opened in read mode using the fopen() function and the characters are read from the file using a while loop and fgetc until an EOF is reached. We use the feof() function to determine if the file's end has been reached after reading it. If it is accurate, we print "End of file reached", and in the absence of which, we print "Error while reading the file".
d. perror():
This function is used to display a detailed error message to the standard error.
Syntax:
It has the following syntax:
void perror(const char *str);
Example:
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL)
{
// Print error message with the description
perror("Error");
// Print the specific error description
fprintf(stderr, "Error opening the file: %s\n", strerror(errno));
return 1;
}
// File processing code goes here...
fclose(file);
return 0;
}
Output:
ERROR!
Error: No such file or directory
Error opening the file: No such file or directory
Explanation:
In this example, we use the fopen() function to try and open a file called "nonexistent.txt" in read mode. The fopen() function will return a NULL pointer, which denotes an error because the file does not exist. After that, we print the error description and the error message "Error" to the standard error stream (stderr) using the perror() function. Additionally, we utilize the strerror function to obtain a more detailed error report based on the value of the global variable errno, which we print using fprintf() to stderr.
e. sprintf():
It is used to format data and saves it as a string rather than printing it to the standard output.
Syntax:
It has the following syntax:
int sprintf(char *buffer, const char *format, ...);
Example:
#include <cstdio>
int main()
{
char buffer[100]; // Buffer to store the formatted string
int number = 42;
float value = 3.14;
// Format the output and store it in the buffer
int chars_written = sprintf(buffer, "The number is %d and the value is %.2f", number, value);
if (chars_written>= 0)
{
printf("Formatted string: %s\n", buffer);
printf("Number of characters written: %d\n", chars_written);
}
else
{
printf("Error occurred while formatting.\n");
}
return 0;
}
Output:
Formatted string: The number is 42, and the value is 3.14
Number of characters written: 38
Explanation:
In this example, a string having an integer (number) and a floating-point value (value) with two decimal places is formatted using the sprint() function. After formatting, the output is saved in the buffer. We print the formatted string and the total number of characters written using the printf function after the sprintf function returns the number of characters written to the buffer.
Remember that the sprint() function doesn't conduct any bounds checking, so make sure the destination buffer is big enough to store the formatted string with the null terminator in it. The sprint() function can be dangerous since it may result in buffer overflows if the format string is generated dynamically or from an unreliable source. It is advised to utilize safer alternatives like snprintf, which enables the specification of the buffer size to prevent buffer overflows, to avoid similar problems.
f) sscanf():
With the sscanf() function, formatted data is read from a string as opposed to the standard input.
Syntax:
It has the following syntax:
int sscanf(const char *str, const char *format, ...);
Example:
#include <cstdio>
int main()
{
const char input[] = "John 25 75.50";
char name[50];
int age;
float height;
// Read data from the input string and store it in variables
int items_read = sscanf(input, "%s %d %f", name, &age, &height);
if (items_read == 3)
{
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
}
else
{
printf("Error occurred while reading.\n");
}
return 0;
}
Output:
Name: John
Age: 25
Height: 75.50
Explanation:
In this example, the data input is a C-string with the following formatting: ("Name Age Height"). The format string "%s%d%f" is used to guide the use of sscanf to read the data from the input string and store it in the variable's name, age, and height. The number of objects properly read and assigned is returned by the sscanf function, and in this case, it should be 3. After that, the values kept in the variables are printed.
Similar to scanf, employing sscanf can be dangerous if the input string is malformed or originates from an unreliable source because it could result in undefinable behavior. The input string must adhere to the format requirements, and any potential problems must be handled correctly.
Conclusion:
In this article, we discussed the cstdio header file in C++. The "cstdio" offers constants like BUFSIZ (buffer size) and NULL (null pointer) and macros like EOF (indicating the end-of-file value).
It should be noted that the C++ Standard Library advises using the similar header <cstdio> instead (without the ".h" extension). The same functionality is offered by both "cstdio" and "stdio.h", but using "cstdio" follows C++ name rules.
The "cstdio" additionally includes many utility functions and types for managing file input/output and data formatting in addition to these features.
It's important to remember that in contemporary C++, the cstdio header is a component of the C Standard Library, and C++ offers its substitute header named iostream. A more contemporary and C++-specific method of performing input and output operations utilizing streams (such as std::cout and std::cin) is provided by the iostream header. When building new C++ code, streams are typically preferred over the functions offered by "cstdio". Nevertheless, many people still utilize the "cstdio" routines, especially when interacting with C libraries or working with ancient code.