Displaying content of a file in C++ -


  • i've made program using can add records in file order, displaying of file after adding record not working.
  • if add "|ios::app" in "ofstream fo" open file in append mode, displaying "fin" working.

  • why 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 added here,                                      // display fin below 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); // not working of //ios:: not added in ofstream fo     while(true)     {         fin.read((char *)&a,sizeof(a));         if(fin.eof()) break;         cout<<a.r<<endl;         puts(a.nm);     }     return 0; } 

this correct code closest 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. , 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; } 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -