0
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.

  • 3
    As a side note, your usage of `while(!f2.eof())` looks [wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) and you should check before readings are successful before using what are "read". – MikeCAT Nov 02 '20 at 14:23
  • `_delete_an_apiKey` That name is reserved for the language implementation in the global namespace. If you define such function, the behaviour of the program will be undefined. You should use another name for the function. – eerorika Nov 02 '20 at 14:25
  • @eerorika I am so sorry about the function naming, I will correct that once it starts running – GhostVaibhav Nov 02 '20 at 14:26

2 Answers2

1

Your order of operations is wrong. What you do:

  • check if read was EOF
  • read from file
  • use the result

As a consequence when when EOF is reached, you use the last result again.

The correct order:

  • read from file
  • check if read was EOF
  • use the result only if result was not EOF

Furthermore, you don't check for cases where read fails for other reasons.

eerorika
  • 181,943
  • 10
  • 144
  • 256
0

The reason you see last key twice is because the iostream::eof is raised after reading the end of the stream, it does not mean that the next read will be end of file.

Use inputStream >> data in the while loop, which guarantee entering the loop if the read was successful, like:

while(f2 >> a) 
{
  if(cnt != n) 
  {
    f1 << a << endl;
  }
  else
  {
    del = a;
  }
  ++cnt;
}       
Tarun
  • 76
  • 6