ファイル実行C++読書ノートのファイルとストリームファイルの読み書き操作ポインタでファイルサイズを取得

13845 ワード

時間が緊張して、まず1筆覚えて、後続の最適化と完備.
本ルーチンでは、ファイルの基本的な読み書き操作だけでなく、ファイルの大きさをどのように得るか、getlineとcinにもかかわる.getlineの違い、stringクラスの文字列がどのようにcスタイルの文字列に変換されるかという問題は、次のブログで紹介します.まずプログラムの実行結果を見て、実行結果は以下の通りです.
/**********************************プログラムの実行結果は以下の通りである:Writing to the file Enter your name:wangshihui Enter your age:22 Reading from the file wangshihui 22 wangshihui 22 To recap,the three main objectives in the Mystery Method are:To attract a woman To establish comfort,trust, and connection             To structure the opportunity to be seduced A woman's number-one emotional priority is safety and security. TheMisteryMethod.txt size is: 294 bytes. Process returned 0 (0x0)   execution time : 13.100 s Press any key to continue. ***********************************/
    
    
#include <fstream>
#include <iostream>
using namespace std;
void test_write_read_cin_getline()
{
    char data[100];
    // open a file in write mode.
    ofstream outfile;
    outfile.open("TheMisteryMethod.txt");
    cout << "Writing to the file" << endl;
    cout << "Enter your name: ";
    cin.getline(data, 100);
    // write inputted data into the file.
    outfile << data << endl;
    cout << "Enter your age: ";
    cin >> data;
    cin.ignore();
    // again write inputted data into the file.
    outfile << data << endl;
    // close the opened file.
    outfile.close();
    // open a file in read mode.
    ifstream infile;
    infile.open("TheMisteryMethod.txt");
    cout << "Reading from the file" << endl;
    infile >> data;
    // write the data at the screen.
    cout << data << endl;
    // again read the data from the file and display it.
    infile >> data;
    cout << data << endl;
    // close the opened file.
    infile.close();
}
void test_write()
{
  ofstream myfile;
  myfile.open ("TheMisteryMethod.txt",ios::app);
  if(myfile.is_open())
  {
     myfile <<
            "
To recap, the three main objectives in the Mystery Method are:
\ To attract a woman
\ To establish comfort, trust, and connection
\ To structure the opportunity to be seduced
"; myfile.close(); } else cout<<" !
"; } void test_write_read_getline() { string str; //Creates an instance of ofstream, and opens TheMisteryMethod.txt ofstream a_file ( "TheMisteryMethod.txt",ios::app );// // Outputs to TheMisteryMethod.txt through a_file if(a_file.is_open()) { a_file<<"A woman's number-one emotional priority is safety and security."; // Close the file stream explicitly a_file.close(); } else cout << "Unable to open file
"; //Opens for reading the file ifstream b_file ( "TheMisteryMethod.txt",ios::app ); //Reads one string from the file b_file>> str; // to cout<< str <<"
"; getline(b_file,str,'\0');// cout<< str <<"
"; cin.get(); // wait for a keypress // b_file is closed implicitly here } void GetSizeOfFile(string filename) { long begin,end; ifstream myfile (filename.c_str());// c begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout <<filename<<" size is: " << (end-begin) << " bytes.
"; } int main () { test_write_read_cin_getline(); test_write(); test_write_read_getline(); string file("TheMisteryMethod.txt"); GetSizeOfFile(file); return 0; } /********************************** : Writing to the file Enter your name: wangshihui Enter your age: 22 Reading from the file wangshihui 22 wangshihui 22 To recap, the three main objectives in the Mystery Method are: To attract a woman To establish comfort, trust, and connection To structure the opportunity to be seduced A woman's number-one emotional priority is safety and security. TheMisteryMethod.txt size is: 294 bytes. Process returned 0 (0x0) execution time : 13.100 s Press any key to continue. ***********************************/

    C++ has two basic classes to handle files, ifstream and ofstream. To use them, include the header file fstream. Ifstream handles file input (reading from files), and ofstream handles file output (writing to files). The way to declare an instance of the ifstream or ofstream class is:
ifstream a_file;

    or
ifstream a_file ( "filename" );

    
    
 
    
    The constructor for both classes will actually open the file if you pass the name as an argument. As well, both classes have an open command (a_file.open()) and a close command (a_file.close()). You aren't required to use the close command as it will automatically be called when the program terminates, but if you need to close the file long before the program ends, it is useful. 
    
    The beauty of the C++ method of handling files rests in the simplicity of the actual functions used in basic input and output operations. Because C++ supports overloading operators, it is possible to use << and >> in front of the instance of the class as if it were cout or cin. In fact, file streams can be used exactly the same as cout and cin after they are opened.
    
    
Input/Output with files
    C++ provides the following classes to perform output and input of characters to/from files:
    
  • ofstream: Stream class to write on files
  • ifstream: Stream class to read from files
  • fstream: Stream class to both read and write from/to files.

  •     
    Open a file
         In order to open a file with a stream object we use its member function open(): open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, andmode is an optional parameter with a combination of the following flags:
        
    ios::in
    Open for input operations.
    ios::out
    Open for output operations.
    ios::binary
    Open in binary mode.
    ios::ate
    Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file.
    ios::app
    All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
    ios::trunc
    If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.
    毎日同じ理屈
    生命が荘厳な城だとすれば、生命が青々とした大木だとすれば、生命が飛ぶ海鳥だとすれば.では、信念はあのドームの梁柱で、あの深く刺さった木の根で、あの扇動の翼です.信念がなければ、生命の動力は消えてしまう.信念がなければ、生命の美しさは茫然として西へ行く.(線を引くところで他の言葉を変えることができます)
         All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the fileexample.bin in binary mode to add data we could do it by the following call to member functionopen():
    1 2 
    ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); 

    Each one of the open() member functions of the classes ofstream,ifstream andfstream has a default mode that is used if the file is opened without a second argument:
        
    class
    default mode parameter
    ofstream
    ios::out
    ifstream
    ios::in
    fstream
    ios::in | ios::out
         For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to theopen() member function. The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.
        
        To check if a file stream was successful opening a file, you can do it by calling to memberis_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:
     
    if (myfile.is_open()) { /* ok, proceed with output */ }

    Closing a file
        When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member functionclose(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:
     
    myfile.close();

    Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.
        
        
    get and put stream pointers
        All i/o streams objects have, at least, one internal stream pointer: ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation. ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written. Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream). These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:
        
    tellg() and tellp()
        These two member functions have no parameters and return a value of the member typepos_type, which is an integer data type representing the current position of the get stream pointer (in the case oftellg) or the put stream pointer (in the case of tellp).
        
    seekg() and seekp()
        These functions allow us to change the position of the get and put stream pointers. Both functions are overloaded with two different prototypes. The first prototype is: seekg ( position ); seekp ( position ); Using this prototype the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is the same as the one returned by functionstellg andtellp: the member type pos_type, which is an integer value. The other prototype for these functions is: seekg ( offset, direction ); seekp ( offset, direction ); Using this prototype, the position of the get or put pointer is set to an offset value relative to some specific point determined by the parameterdirection.offset is of the member type off_type, which is also an integer type. Anddirection is of typeseekdir, which is an enumerated type (enum) that determines the point from where offset is counted from, and that can take any of the following values:
        
    ios::beg
    offset counted from the beginning of the stream
    ios::cur
    offset counted from the current position of the stream pointer
    ios::end
    offset counted from the end of the stream
        ==============================================================
        The default mode for opening a file with ofstream's constructor is to create it if it does not exist, or delete everything in it if something does exist in it. If necessary, you can give a second argument that specifies how the file should be handled. They are listed below:
    ios::app   -- Append to the file
    ios::ate   -- Set the current position to the end
    ios::trunc -- Delete everything in the file

        For example:
    ofstream a_file ( "test.txt", ios::app );

        This will open the file without destroying the current contents and allow you to append new data. When opening files, be very careful not to use them if the file could not be opened. This can be tested for very easily:
    ifstream a_file ( "example.txt" );
    
    if ( !a_file.is_open() ) 
    {
      // The file could not be opened
    }
    else 
    {
      // Safely use the file stream
    }

        
    文章が终わってみんなに次のプログラマーのいくつかのジョークの语录を分かち合います:PCのソフトウェアの体积が大きいのは、1つのPCのソフトウェアの机能が往々にして多いためで、あなたの1つの方面の需要を満たすことができて、1つのiphoneのソフトウェアは往々にして何行のコードがなくて、1件のとても小さい事をして、自然に必要とするソフトウェアは多いです.スイカを食べるのと瓜を食べるのとで数を比べるように、単位が違いますね.