Last active
August 29, 2015 14:13
-
-
Save aliharis/a1e62370ab5e51a2b4c6 to your computer and use it in GitHub Desktop.
Updates a record in a text 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
#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