Skip to content

Instantly share code, notes, and snippets.

@aliharis
Last active August 29, 2015 14:13
Show Gist options
  • Save aliharis/a1e62370ab5e51a2b4c6 to your computer and use it in GitHub Desktop.
Save aliharis/a1e62370ab5e51a2b4c6 to your computer and use it in GitHub Desktop.
Updates a record in a text file.
#include <iostream>
#include <fstream>
using namespace std;
bool updateRecord(string currentRecord, string newRecord)
{
ifstream inFile("Data.txt"); // File to read from
ofstream outFile("Temp.txt", ios::trunc); // Temporary file
if(!inFile || !outFile) {
cout << "An error occured while opening the files." << endl;
return false;
}
// Copy all the records to a temporary file while editing a record
string currentLine;
while (getline(inFile, currentLine)) {
if (currentLine == currentRecord)
currentLine = newRecord;
currentLine += "\n";
outFile << currentLine;
}
inFile.close();
outFile.close();
// Swap temp file to active file
ifstream tempFile("Temp.txt");
ofstream currentFile("Data.txt", ios::trunc);
// Loop temp file line by line
string currentLine;
while (getline(tempFile, currentLine))
// Copy contents of temp file to current file
currentFile << currentLine << "\n";
tempFile.close();
currentFile.close();
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment