Code:
outfile.open(filename, ios::in);
- An attempt at opening the file for reading. ios::in here means that data will be read from the file. iosut means data will be written to the file. Can you see the contrast?
outfile here is a variable of the fstream class' data type, just like infile. The different is that outfile is being used to read, not write data, from the file. When you start learning about inheritance and polymorphism, you will learn an alternate route to writing files, without using the fstream class to define variables.
Code:
if (outfile.fail())
{
cout<<"Could not open in read mode!";
}
- pretty self-explanatory
Code:
else
{
outfile.read(reinterpret_cast<char*>(&time), sizeof(account));
- Very similar to the write line explained earlier. This time, the function read reads the exact number of bytes from the disk that the file was written to earlier. The read function is able to discern where on the disk that block of data lies, because it has a character pointer (char*) passed to it by dereferencing the time variable. In C programming, using an ampersand (& infront of a variable, passes the pointer location in memory (volatile or non-volatile) that the data it contains resides. You will need to read up on pointers for more details on that.
Code:
while(!outfile.eof())
{
cout<<time.programid<<""<<time.programname;
outfile.read((reinterpret_cast<char*>(&time), sizeof(account));
}
- Now that the file is open, continue to read to the very end of the file, outputting the names of all the programs written to the file. Since the write command writes a fixed byte size of data to the file, the read command will only read that fixed block of data back into memory to be printed on your screen. So if for argument's sake, your account struct was 50 bytes in size, the read command will continue to read contiguous 50 byte blocks into memory, until it reaches the end of file marker (designated by a null char* pointer value).
Code:
outfile.close();
}
return 0;
}
- Close the file and end the main function.