CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2003
    Posts
    30

    Reading a file, unwanted chars at the end

    Hi,

    I`m reading chars to a char *buffer

    Code:
    ifstream datafile;
    int length;
    char * buffer;
    
    try
    {	
     datafile.open(filename, ios::binary );
     if(!datafile.is_open())
      return false;
    
     char * buffer;
     datafile.seekg (0, ios::end);
     length = datafile.tellg();
     datafile.seekg (0, ios::beg);
     // allocate memory:
     buffer = new char [length];
     // read data as a block:
     datafile.read(buffer,length);
     // close file	
     datafile.close();
    
    }
    catch(...)
    {
     cout<<"\n\nError occurred while reading file\n\n";
    }

    the contents of the test.txt file
    Code:
    ksjdhafkjasnbdfkjhsdfjbsvdkjsdhgkjdshg
    asdasd
    asdasd
    asdasd
    g
    g
    and this is what the buffer contains
    Code:
    ksjdhafkjasnbdfkjhsdfjbsvdkjsdhgkjdshg
    asdasd
    asdasd
    asdasd
    g
    gH=.;%D
    How do I fix the code to get rid of that rubbish in the end?

  2. #2
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,150
    replace
    buffer = new char [length];
    with
    buffer = new char [length+1];
    and add a
    buffer[length]=0;
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured