Search code examples
c++fstreamostream

Deleting from a file C++


Alright so Here is the code I have currently for my delete function.

void classSchedule::deleteEntry(classSchedule schedule[], int numElems)
{
    string entryToDelete;
    cout << endl << "Enter the Teacher's Last Name of the Entry you want to delete: ";
    cin >> entryToDelete;

    int i, recordToDelete = -1;
    for (i = 0; i < numElems; i++)
    {
        if (schedule[i].teacherLastName == entryToDelete)
            recordToDelete = i;
    }
    if (recordToDelete != -1)
    {

    }

}

It essentially is like this: I have an array of classes that is called schedule[] each object has the following members: class department, class number, credit hours, teacher last name, teacher first name, room number, and current gpa. I started my function by asking them the teachers last name they want to delete, because all the rest could repeat. I searched my object for that last name.

I want to know how to delete the whole instance of that object from a file.

Is it possible for me to just overwrite it with the objects ahead or behind it.

i.e. they want to delete schedule[4] out of 10 instances could i just overwrite [4] with [5], [5] with [6] and so on?

Edit:

Here is the file that is being read wrote to(classes.txt):

ENG 112 3 Tetlof S S062 3.1

CST 280 3 Klingler T K114 3.4

LWA 220 2 Wesolak J M121 2.1

POL 103 4 Fortin B J122 4.1

ENG 111 2 Harood J K131 3.1

Edit2:

void classSchedule::outputToFile(classSchedule schedule[], int& numElems)
{
    ofstream fileOut;

    fileOut.open("classes.txt", ios::out | ios::app);

    fileOut << schedule[numElems - 1].classDepartment
            << " " << schedule[numElems - 1].creditHours
            << " " << schedule[numElems - 1].teacherLastName
            << " " << schedule[numElems - 1].teacherFirstName
            << " " << schedule[numElems - 1].roomWingAndNumber
            << " " << schedule[numElems - 1].currentGPA;
    fileOut.close();
}

Solution

  • You have three options: 1) Output the modified data to a new file; or 2) Mark records as deleted, but available for reuse; or 3) Move data "up" to the unused slots (like an array).

    Maybe you should be using a database instead.

    Many applications write the original and modified data to a new file. Data that is to be deleted is not written to the file. This is the simplest solution.

    If your file has fixed sized records, you could mark the deleted record as available so it can be used again. This may require adding a flag to the record that indicates whether it is dead or alive.

    An ugly method is to overwrite the deleted data with data that is forward of it. For example if I have a file containing 3 sentences and I delete sentence 2, I will read sentence 3 and write it to the position where sentence 2 started.