0
  • I've made a program using which we can add records in a file is an order, but the displaying of the file after adding the record is not working.
  • If I add "|ios::app" in "ofstream fo" to open the file in append mode, the displaying by "fin" is working.

  • Why is it so? I'm using mingw4.8.1


#include<fstream>
#include<iostream>
#include<stdio.h>
class c{
    public:
    int r;
    char nm[20];
};

using namespace std;

int main()

{

    c a,b;
    ifstream fi("old.txt",ios::binary);
    ofstream fo("new.txt",ios::binary); // if |ios::app is added here, the 
                                    // display by fin below is working fine

    cout<<"Enter roll\t";
    cin>>b.r;
    cout<<"Enter name\t";
    fflush(stdin);
    gets(b.nm);
    int w=0;
    while(true)
    {
        fi.read((char *)&a,sizeof(a));
        if(fi.eof()) break;
        if(b.r<a.r&&w==0)
        {
            fo.write((char *)&b,sizeof(b));
            w++;
        }
        else
            fo.write((char *)&a,sizeof(a));
    }

    ifstream fin("new.txt",ios::binary); // this is not working of the //ios:: is not added in the ofstream fo
    while(true)
    {
        fin.read((char *)&a,sizeof(a));
        if(fin.eof()) break;
        cout<<a.r<<endl;
        puts(a.nm);
    }
    return 0;
}
Tuesday
  • 55
  • 1
  • 7
  • If you do not give us a [minimal complete example](http://stackoverflow.com/help/mcve), we must do extra work before we can even *try* to help you. – Beta Jul 18 '15 at 05:38

2 Answers2

1

This is the correct code closest to what you want

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

struct c {
    int roll;
    string name;
};

int main() {
    c a, b;
    ifstream fi("old.txt");
    ofstream fo("new.txt");
    cout << "Enter roll no. and name" << endl;
    cin >> b.roll >> b.name;
    while (fi >> a.roll >> a.name) {
        if (b.roll < a.roll)
            fo << b.roll << " " << b.name << endl;
        else
            fo << a.roll << " " << a.name << endl;
    }
    fi.close();
    fo.close();
    ifstream fin("new.txt");
    while (fin >> a.roll >> a.name)
        cout << a.roll << " " << a.name << endl;
    fin.close();
    return 0;
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
0

It is my understanding that if you use ios::app you must also indicate ios::out try ios::app | ios::out | ios::binary and see if that helps.

ydobonebi
  • 240
  • 2
  • 11
  • yea, it's working, but I don't actually want to append any data, rather I'm adding a record in between(in increasig roll. no. order) and the code to display the records isn't working, thanks :) – Tuesday Jul 18 '15 at 07:47