This simple function, in C++17, changes a single character in a text file to a passed in tracking choice (0 or 1). The problem I'm having with this code is that the put statement is changing more than just the character position passed to it, it is changing the text file into a binary file. If I comment out the line with the put statement the function executes without effecting the file.
void changeTracking(int charPosition, char trackingChoice) {
try {
std::ofstream fileStream(rootPath + "/" + directoryName + "/" + fileName, std::ios::out);
if (fileStream.is_open()) {
fileStream.seekp(charPosition);
fileStream.put(trackingChoice);
if (fileStream.good()) {
fileStream.close();
std::cout << "Configuration file successfully modified and closed." << std::endl;
}
else {
throw std::runtime_error("Error writing to the configuration file.");
}
} else {
std::cerr << "Failed to modify and close the configuration file: " << fileName << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
Here is the file before running the function:
# HealthTrak v0.9.8 configuration file.
# This file uses UTF-8 encoding.
# Key/value pairs are used to manage HealthTrak configuration parameters.
# The version number of this configuration file.
0.9.8
# The vital sign types that are supported and their enabled status.
# weight
0
# blood_sugar
0
# hdl
0
# ldl
0
# triglycerides
0
# The end of file marker.
eof=eof
Here is the file after running the function:
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 31
IDE: Code::Blocks 20.03
OS: Manjaro Linux 5.13.19-2-MANJARO 64-bit rolling build
Hardware: Lenovo IdeaCentre 3
Processor: AMD Athlon Silver 3050U with Radeon™ Graphics × 2
std::ofstreamin thestd::ios::outmode (which is the default mode forstd::ofstreams anyway) means for output-only, i.e., destroying the existing contents. Perhaps take a look at mode combinations.1there. (All the positions before that1are just filled with zero bytes when you seek, because the newly created file is initially empty.)