Advertisement
Guest User

File Size is Always Char Array Size...

a guest
Aug 22nd, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. int main() {
  6.   streampos begin, end;
  7.   // streampos type
  8.   /*
  9.  
  10.   streampos is a specific type used for buffer and file positioning.
  11.   It is the type returned by file.tellg(). Values of this type can
  12.   be safely subtracted from other values of the same type, and can
  13.   also be converted to an integer type large enough to contain the
  14.   size of the file.
  15.  
  16.   These stream positioning functions can use two particular types:
  17.   streampos and streamoff. These types are also defined as member
  18.   types of the stream class.
  19.  
  20.   */
  21.   ifstream myfile ("binary_file.bin", ios::binary);
  22.   begin = myfile.tellg(); // get the start position of the stream
  23.   myfile.seekg (0, ios::end);
  24.   // modifies the get postion to be ...
  25.   // 0 offset from the end of the stream
  26.   end = myfile.tellg(); // get the end position of the stream
  27.   if (end-begin == 0) {
  28.     ofstream outFile ("binary_file.bin", ios::binary);
  29.     char words[256] = {};
  30.     cout << "Enter a series of words into"
  31.     << " the file (enter: 'CTR+C' to terminate): \n";
  32.     while (cin.get(words, sizeof(words))) {
  33.       cout << "Writing [" << sizeof(words) << " bytes] to file...\n";
  34.       outFile.write(words, sizeof(words));
  35.     }
  36.     outFile.close();
  37.   } else {
  38.     myfile.close();
  39.     cout << "size is: " << (end-begin) << " bytes.\n";
  40.   }
  41.   return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement