Michael
Michael

Reputation: 50

How do I read from a file and print to the console without using a variable using C++?

In my code I have

for (int i = 0; i < 5; i++) {
    ranInts= rand();//generate a random integer, store in ranInts
    cout << ranInts<< " ";//Print out ints
    binaryFile.write(reinterpret_cast <char *>(&ranInts), sizeof(int))//Write to file
        }

The code to read is

binaryFile.seekg(ios::beg);//Set the pointer in file to beginning
for (int i = 0; i < 5; i++) {
    binaryFile.read(reinterpret_cast <char *>(&ranInts), sizeof(int));
    //reading each int moves the file pointer down 4 bytes, ready to get the next one

    //display
    cout << ranInts<< endl;
}

This works fine. What I want to do is go from the disk to the screen and leave the variable out of the loop.

Is this possible?

Upvotes: 2

Views: 184

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Yes, it is possible. Call std::copy to copy an std::istream_iterator based on your file into an std::ostream_iterator based on cout:

std::ifstream file("myinput.txt");  // Open your input file
file.unsetf(std::ios_base::skipws); // Make sure whitespace is not skipped
std::copy(                          // Call std:copy to copy the content
    std::istream_iterator<char>(file)
,   std::istream_iterator<char>()
,   std::ostream_iterator<char>(std::cout, "")
);

Upvotes: 2

Phoenixcomm
Phoenixcomm

Reputation: 45

if you want to go from disk to the screen (two different devices ) its really not a problem.

  1. open the disk for reading the file
  2. test for the end of file indicator.
    code: z = open( the file on the disk ) // returns a ID for (,,){ // this is a forever loop it could be written as: FOREVER { if you #define FOREVER for(;;) this should go in you header file. or you could use do{....}while ( z > 0 ); read( from z , buffer) you should test the buffer to make sure your buffer is not empty or did you reach the end of the file.
    fprintf( print the buffer contents )

note with this strategy you must know the lenth of the buffer. char buffer[50] make shure you add one for the eol char \n"

have fun.

Upvotes: 0

Related Questions