C++ File Handling: Open, Read, and Get File Size with Examples
C++ File Handling: Open, Read, and Get File Size
This tutorial provides examples on how to perform basic file operations in C++, including opening files for writing and reading, checking file existence, and getting the file size.
1. Open a File for Writing (ofstream)
#include <fstream>
int main() {
std::ofstream out('D:\out.txt');
// Write to file
out.close();
return 0;
}
2. Open a File for Reading (ifstream)
#include <fstream>
int main() {
std::ifstream in;
in.open('x.json');
// Read from file
in.close();
return 0;
}
3. Check if a File Exists
#include <fstream>
#include <iostream>
int main() {
std::ifstream in('x.json');
if (!in.is_open()) {
std::cout << 'x.json does not exist' << std::endl;
return 0;
}
// Read from file
in.close();
return 0;
}
4. Get the File Size using std::filesystem::file_size
#include <fstream>
#include <iostream>
#include <filesystem>
int main() {
namespace fs = std::filesystem;
fs::path filePath('x.json');
if (!fs::exists(filePath)) {
std::cout << 'x.json does not exist' << std::endl;
return 0;
}
std::uintmax_t fileSize = fs::file_size(filePath);
std::ofstream out('D:\out.txt');
out << std::fixed;
out << std::setprecision(1) << std::setw(5) << std::setfill('*') << fileSize / 1e9 << ' GB' << std::endl;
out << std::setprecision(2) << std::setw(6) << std::setfill('*') << fileSize / 1e9 << ' GB' << std::endl;
out << std::setprecision(3) << std::setw(7) << std::setfill('*') << fileSize / 1e9 << ' GB' << std::endl;
out << std::setprecision(4) << std::setw(8) << std::setfill('*') << fileSize / 1e9 << ' GB' << std::endl;
out << std::setprecision(5) << std::setw(9) << std::setfill('*') << fileSize / 1e9 << ' GB' << std::endl;
out.close();
return 0;
}
These examples demonstrate fundamental C++ file handling techniques. You can build upon these to create more complex file manipulation programs.
原文地址: https://www.cveoy.top/t/topic/nvz0 著作权归作者所有。请勿转载和采集!