Xenon
Xenon

Reputation: 1

How can I edit data in file without the other data being overwritten?

I have a file that has the following information

123 abc 52 23
234 bcd 14 53

After I've done editing (the ID int the top row), it become like this

12345 abc 52 23
bcd 14 53

The code doing this is:

if (choiceSecond == 1)
{
    cout << "Enter new ID: ";
    cin >> ToyInformation[choiceFirst].ID;
    outfile << ToyInformation[choiceFirst].ID << " "
            << ToyInformation[choiceFirst].Name << " "
            << ToyInformation[choiceFirst].Price << " "
            << ToyInformation[choiceFirst].Quantity << " " << endl;
}

Structure:

    struct toys
{
    int ID;
    char Name[31];
    float Price;
    int Quantity;
};

I'msure i'm doing something wrong here. Can anyone help?

Upvotes: 0

Views: 63

Answers (4)

Kristopher Johnson
Kristopher Johnson

Reputation: 82535

It's hard to tell exactly what's going on without seeing the rest of your code, but my guess is that you start with a file containing this:

123 abc 52 23 \n234 bcd 14 53 \n

then, my guess is that after reading the file, you re-open it or rewind the file pointer to the beginning and write "12345 abc 52 23 \n". Those new characters overwrite the existing characters in the first part of your file, but leave the remaining characters as-is, leaving you with this in your file:

12345 abc 52 23 \nbcd 14 53 \n

You probably don't want to be overwriting the first part of the next line. So what you need to do is read the entire file (maybe into a vector or list of strings), update the line you want in memory, and then write them all back out. Or as you are reading in the file, you update the line(s) you want as you write them each back out to another file, and the swap the new output with the old output.

Upvotes: 1

Slava
Slava

Reputation: 44238

You want to change some data in a file without changing the rest. General answer it is not possible. You may only replace some bytes to others, but if your editing involves inserting or removing bytes, you have to overwrite the rest of the file.

Upvotes: 0

jdc
jdc

Reputation: 339

When you define outfile, you can use the mode ofstream::app, like that

ofstream outfile (fileName, ofstream::app);

Upvotes: 0

john
john

Reputation: 87944

When you open the file use ios_base::app

ofstream outfile("myfilename", ios_base::app);

This will cause all output to be appended to the end of the file (which I'm guessing is what you want).

Upvotes: 0

Related Questions