#include #include #include

int main() { std::fstream file("inout.dat", std::ios::binary | std::ios::in | std::ios::out);

// Write file size in bytes and gigabytes
file.seekp(0);
int fileSize = 1024; // example value
double fileSizeGB = fileSize / double(1024*1024*1024); // convert to GB
file.write(reinterpret_cast<char*>(&fileSize), sizeof(fileSize));
file.write(reinterpret_cast<char*>(&fileSizeGB), sizeof(fileSizeGB));

// Read and display file size
file.seekg(0);
int readFileSize;
double readFileSizeGB;
file.read(reinterpret_cast<char*>(&readFileSize), sizeof(readFileSize));
file.read(reinterpret_cast<char*>(&readFileSizeGB), sizeof(readFileSizeGB));
std::cout << "File size in bytes: " << readFileSize << std::endl;
std::cout << "File size in GB: " << readFileSizeGB << std::endl;

// Append string array
std::array<std::string, 3> poetry = {"Roses are red", "Violets are blue", "Sugar is sweet"};
file.seekp(0, std::ios::end); // move write pointer to end of file
for (const std::string& line : poetry) {
    file << line << std::endl;
}

// Read and display string array
file.seekg(0, std::ios::beg); // move read pointer to beginning of file
std::string line;
while (std::getline(file, line)) {
    std::cout << line << std::endl;
}

file.close();
return 0;

}

C++ Binary File Operations: Reading and Writing Data

原文地址: https://www.cveoy.top/t/topic/nwZH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录