string _delete_an_apiKey(int n)
{
string a;
string del;
int cnt = 0;
ofstream f1("tempAPIKeys.dat",ios::app); // Temporary file for executing deletion
ifstream f2(file,ios::in); // Main file containing all the keys
while(!f2.eof())
{
if(cnt != n)
{
f2 >> a;
f1 << a << endl;
}
else
{
f2 >> del;
}
++cnt;
}
f1.close();
f2.close();
remove(fileName);
rename("tempAPIKeys.dat",fileName);
return del;
}
n is basically like an index which is associated with each key
in this case n = 0, meaning delete the first key
In this code, I have partially succeeded in deleting the key of my choice but it gives an unexpected output. Let me give you an example by giving the contents of the file:
Before the execution :
x4pDtc3vI8yHFDar99GUdkPh
0RxLFwFhcyazoZ0zBKmPFR4q
4Haw6HSUQKDhNSxeD0JKMcFT
After the execution :
0RxLFwFhcyazoZ0zBKmPFR4q
4Haw6HSUQKDhNSxeD0JKMcFT
4Haw6HSUQKDhNSxeD0JKMcFT
The function also returns the deleted string.
Now you can easily tell that I have deleted the first key but I don't know why the last key is stored twice.