Problem with getline C++

Discussion in 'C++' started by at_pradeep, Oct 17, 2008.

  1. at_pradeep

    at_pradeep New Member

    Joined:
    Oct 17, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I am having following code for reading and writing from an file....
    but when i directly read from file... it displays all the data..
    but when i do some write and the again read then it does not read any thing..
    getline returns without reading anything...
    and then file reaches to eof...
    Code:
    int main()
    {
    fstream tempFile;
    tempFile.open( "abc.txt" );
    
    if( !tempFile.is_open() )
    {
    printf("ERROR: Enable to Open File ");
    exit(0);
    }
    
    printf("Writting To file\n");
    string buffer = "I am in File";
    tempFile.write ( buffer.c_str(), buffer.size( ) );
    tempFile.write ( "\n", 1 );
    
    printf("Reading From file\n");
    string tempBuf;
    while( !tempFile.eof( ) )
    {
    getline( tempFile, tempBuf, '\n' );
    printf("Data %s\n", tempBuf.c_str() );
    tempBuf.clear();
    }
    
    
    return 0;
    }
    
    whats the problem am i missing any thing...
    please HELP! :confused:
     
  2. sun_kangane

    sun_kangane New Member

    Joined:
    Mar 20, 2007
    Messages:
    33
    Likes Received:
    0
    Trophy Points:
    0
    you have used

    tempFile.open( "abc.txt" );

    to open file
    you have not given read, write i. e. w, r, +w etc. mode of open file...
    i think by default it takes "w" mode which delete existing data of file and start writing it from 0th byte...........

    try by using "+w" mode..............................
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice