Created
January 20, 2022 20:07
-
-
Save stungeye/1d28132dc9e242c8f6da61ef37d6d800 to your computer and use it in GitHub Desktop.
Reading and Writing Strings From a Binary File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ExploringFiles.cpp : This file contains the 'main' function. Program execution begins and ends there. | |
// | |
#include <iostream> | |
#include <filesystem> | |
#include <fstream> | |
#include <vector> | |
#include <string> | |
void writeString(std::string string, std::ofstream& out) { | |
size_t lengthOfString = string.length(); | |
out.write(reinterpret_cast<char*>(&lengthOfString), sizeof(size_t)); | |
out.write(string.c_str(), sizeof(char) * lengthOfString); | |
} | |
std::string readString(std::ifstream& in) { | |
size_t lengthOfString; | |
std::string string; | |
in.read(reinterpret_cast<char*>(&lengthOfString), sizeof(size_t)); | |
string.resize(lengthOfString); | |
in.read(&string[0], sizeof(char) * lengthOfString); | |
return string; | |
} | |
int main() { | |
std::ofstream outputFile{"data.bin", std::ios_base::binary}; | |
std::string outputString{"This is a test string."}; | |
writeString(outputString, outputFile); | |
std::getline(std::cin, outputString); | |
writeString(outputString, outputFile); | |
outputFile.close(); | |
std::ifstream inputFile{"data.bin", std::ios_base::binary}; | |
std::cout << "First String: " << readString(inputFile) << "\n"; | |
std::cout << "Second String: " << readString(inputFile) << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment