C++ File Handling and Formatting: Open, Read, Check Existence, and Format File Size
#include <fstream>
int main() {
std::ofstream out_file("D:/out.txt");
// ...
return 0;
}
#include <fstream>
int main() {
std::ifstream in_file;
in_file.open("x.json");
if (!in_file.is_open()) {
std::cout << "x.json does not exist" << std::endl;
return 1;
}
// ...
return 0;
}
#include <iostream>
#include <filesystem>
int main() {
std::filesystem::path file_path("x.json");
if (!std::filesystem::exists(file_path)) {
std::cout << "x.json does not exist" << std::endl;
return 1;
}
// ...
return 0;
}
#include <iostream>
#include <fstream>
#include <filesystem>
#include <iomanip>
int main() {
std::filesystem::path file_path("x.json");
if (!std::filesystem::exists(file_path)) {
std::cout << "x.json does not exist" << std::endl;
return 1;
}
std::uintmax_t file_size = std::filesystem::file_size(file_path);
std::ofstream out_file("D:/out.txt");
out_file << std::fixed << std::setprecision(1) << std::setw(5) << std::setfill('*') << static_cast<double>(file_size) / 1e9 << std::endl;
out_file << std::fixed << std::setprecision(2) << std::setw(6) << std::setfill('*') << static_cast<double>(file_size) / 1e9 << std::endl;
out_file << std::fixed << std::setprecision(3) << std::setw(7) << std::setfill('*') << static_cast<double>(file_size) / 1e9 << std::endl;
out_file << std::fixed << std::setprecision(4) << std::setw(8) << std::setfill('*') << static_cast<double>(file_size) / 1e9 << std::endl;
out_file << std::fixed << std::setprecision(5) << std::setw(9) << std::setfill('*') << static_cast<double>(file_size) / 1e9 << std::endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/nvzE 著作权归作者所有。请勿转载和采集!