ifstream junk output

This is a discussion on ifstream junk output within the C++ Programming forums, part of the General Programming Boards category; I've been trying to use ifstream to read a file and output it to the console but I get garbage ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    465

    ifstream junk output

    I've been trying to use ifstream to read a file and output it to the console but I get garbage for ouput instead of the file itself.

    This is the output that I get every time that I run the program:
    Code:
    p'+ 0+ n Platform=MCD PROCESSOR_ARCHITECTURE=x86 PROCESSOR_ARCHITEW6432=AMD64 PROCESSOR_IDENTIFIER=AMD64 Family 17 Model 3 Stepping 1, AuthenticAMD PROCESSOR_LEVEL=17 PROCESSOR_REVISION=0301 ProgramData=C:\ProgramData ProgramFiles=C:\Program Files (x86) Progra
    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main(){
    int length;
    char * buffer;
    ifstream file;
    file.open("books.txt", ios::binary);
    if ( !file.is_open() ) {
      cout<<"can't open.";
    }
    else{
    file.seekg(0, ios::end);
    length=file.tellg();
    buffer=new char[length];
    file.read(buffer,length);
    file.close();
    cout.write(buffer,length);
    }
    //cout<<"\n"<<length;
    delete[] buffer;
    cin.ignore();
    cin.get();    
    return 0;   
    }
    Does anyone know how I can fix this to output correctly?
    My computer is awesome.

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,263
    You seek to the end of the file to get its length, but you forget to seek back to the beginning again in order to read it.

    Had you bothered to check the error status after attempting to read, you would have seen that the read failed.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    I wasn't aware that there was a function to check the error status until just now. Thanks for pointing out my mistake.
    My computer is awesome.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help for my output array
    By qwertysingh in forum C Programming
    Replies: 1
    Last Post: 02-17-2009, 03:08 PM
  2. execl()/fork() output
    By tadams in forum C Programming
    Replies: 19
    Last Post: 02-04-2009, 03:29 PM
  3. n00b: junk output
    By Kudose in forum C Programming
    Replies: 7
    Last Post: 06-06-2008, 05:07 PM
  4. Formatting output into even columns?
    By Uncle Rico in forum C Programming
    Replies: 2
    Last Post: 08-16-2005, 06:10 PM
  5. Output problems with structures
    By Gkitty in forum C Programming
    Replies: 1
    Last Post: 12-16-2002, 05:27 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21