File handling in C++ involves creating, reading, writing, and updating files. This is essential for data persistence and sharing information between programs.
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
file << "Hello, world!";
file.close();
return 0;
}
In this example, we use ofstream
to create a file named "example.txt" and write "Hello, world!" to it. The file is then closed using file.close()
.
Console Output:
File created and written successfully.
To read from a file, we use the ifstream
class. This allows us to extract data from the file and store it in variables for processing.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("example.txt");
string content;
getline(file, content);
cout << content;
file.close();
return 0;
}
getline
to Read Data: The getline
function reads a line from the file and stores it in the content
variable, which is then printed to the console.
Console Output:
Hello, world!
To append data to a file, open it in ios::app
mode. This ensures new data is added to the end of the file without overwriting existing content.
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt", ios::app);
file << " Welcome to C++!";
file.close();
return 0;
}
In this code, " Welcome to C++!" is appended to "example.txt". The use of ios::app
prevents overwriting.
Console Output:
Data appended successfully.
Before performing file operations, it's often necessary to check if a file exists to prevent errors.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("example.txt");
if (file) {
cout << "File exists.";
} else {
cout << "File does not exist.";
}
file.close();
return 0;
}
This example uses a simple if statement to determine if "example.txt" exists, printing the result to the console.
Console Output:
File exists.
Binary files store data in a format that is not human-readable, which can be more efficient for certain types of data.
#include <fstream>
using namespace std;
int main() {
ofstream file("example.bin", ios::binary);
int num = 12345;
file.write(reinterpret_cast<char*>(&num), sizeof(num));
file.close();
return 0;
}
Here, an integer is written to a binary file using write()
, with data type casting to ensure correct binary format.
Console Output:
Binary file written successfully.
Reading from binary files involves extracting data in its original format, using read()
to convert it back to usable variables.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("example.bin", ios::binary);
int num;
file.read(reinterpret_cast<char*>(&num), sizeof(num));
cout << num;
file.close();
return 0;
}
This code reads an integer from "example.bin" and outputs it, demonstrating the use of read()
for binary data.
Console Output:
12345
File position indicators allow you to move the read/write pointer to specific locations in a file, useful for random access.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
fstream file("example.txt", ios::in | ios::out);
file.seekp(7);
file << "C++";
file.close();
return 0;
}
seekp()
: This example moves the write pointer to the 8th character in "example.txt" and writes "C++", demonstrating random access.
Console Output:
File updated with random access.
Proper error handling ensures your program can handle unexpected situations, such as missing files or permission issues.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("nonexistent.txt");
if (!file) {
cerr << "Error: File could not be opened.";
return 1;
}
file.close();
return 0;
}
This example checks if a file can be opened, and if not, outputs an error message to cerr
.
Console Output:
Error: File could not be opened.
File streams use buffers to optimize reading and writing operations, reducing the number of direct interactions with the filesystem.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file("example.txt");
file.rdbuf()->sputn("Buffered write.", 15);
file.close();
return 0;
}
This code demonstrates writing directly to a stream's buffer using sputn()
, which can enhance performance in certain scenarios.
Console Output:
Buffered write completed.
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies