Regarding Text files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • flavourofbru
    New Member
    • May 2007
    • 48

    Regarding Text files

    Hi,

    I have a question. I know how to read text files using ifstream. Now I would like to append some data at the end of the file.

    I read a text file as follows:

    #include "stdafx.h"
    #include<string >
    #include<iostre am>
    #include<fstrea m>
    using namespace std;

    void main()
    {
    string line;
    ifstream test_file;
    test_file.open( "test.txt", ios::in);
    if(test_file.is _open())
    {
    while(!test_fil e.eof())
    {
    getline(test_fi le, line);
    cout<<line<<end l;
    }
    }
    }

    Now I would like to append some more data to the end of the text file. The data are numbers(int).

    How can I do that.

    Please Help.

    Thanks!!
  • niskin
    New Member
    • Apr 2007
    • 109

    #2
    You will need to include stdio.h to do this:

    Code:
    FILE *fp;
    fp=fopen("example.txt", "a");
    fprintf(fp, "This is text will be added to the end of the file");
    fclose(fp);

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Originally posted by niskin
      FILE *fp;
      fp=fopen("examp le.txt", "a");
      fprintf(fp, "This is text will be added to the end of the file");
      fclose(fp);
      This is C.

      In C++, just open your file to append:
      [code=cpp]
      ofstream test_file;
      test_file.open( "test.txt", ios::app);
      [/code]

      You can also use the same stream for input and output:

      [code=cpp]
      fstream test_file;
      test_file.open( "test.txt", ios_base::out |ios_base::app) ; //output
      test_file.open( "test.txt", ios_base::in |ios_base::beg) ; //input
      [/code]

      Comment

      • flavourofbru
        New Member
        • May 2007
        • 48

        #4
        Thnx for the help!!

        It solved my problem.

        Comment

        Working...