C++文件操作 (fstream)

  我们在编写程序的时候,最密不可分的就是对文件进行相应的操作,我们可以从文件中读取数据,可以将数据保存到文件,可以……        

        文件在进行读写操作之前要先打开,使用完毕要关闭。所谓打开文件,实际上是建立文件的各种有关信息,并使文件指针指向该文件,以便进行其它操作。关闭文件则断开指针与文件之间的联系,也就禁止再对该文件进行操作。 

        总而言之,言而总之,一言以蔽之,对文件的操作是非常重要的,下面我们就来介绍一下C++中是如何对文件进行操作的。


        在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,对文件的操作是通过stream的子类fstream(file stream)来实现的,所以,要用这种方式操作文件,就必须加入头文件fstream.h。


打开文件
  文件名
    注意路径名中的斜杠要双写,如:
    "D:\MyFiles\ReadMe.txt"
  文件打开方式选项:
    ios::in    = 0x01, //供读,文件不存在则创建(ifstream默认的打开方式)
    ios::out    = 0x02, //供写,文件不存在则创建,若文件已存在则清空原内容(ofstream默认的打开方式)
    ios::ate    = 0x04, //文件打开时,指针在文件最后。可改变指针的位置,常和in、out联合使用
    ios::app    = 0x08, //供写,文件不存在则创建,若文件已存在则在原文件内容后写入新的内容,指针位置总在最后
    ios::trunc   = 0x10, //在读写前先将文件长度截断为0(默认)
    ios::nocreate = 0x20, //文件不存在时产生错误,常和in或app联合使用
    ios::noreplace = 0x40, //文件存在时产生错误,常和out联合使用
    ios::binary  = 0x80  //二进制格式文件
  文件保护方式选择项:
    filebuf::openprot;   //默认的兼容共享方式
    filebuf::sh_none;    //独占,不共享
    filebuf::sh_read;    //读共享
    filebuf::sh_write;   //写共享
  打开文件的方法
    调用构造函数时指定文件名和打开模式
    ifstream f("d:\12.txt",ios::nocreate);         //默认以 ios::in 的方式打开文件,文件不存在时操作失败
    ofstream f("d:\12.txt");                //默认以 ios::out的方式打开文件
    fstream f("d:\12.dat",ios::in|ios::out|ios::binary); //以读写方式打开二进制文件
    使用Open成员函数
    fstream f;
    f.open("d:\12.txt",ios::out);             //利用同一对象对多个文件进行操作时要用到open函数


检查是否成功打开
  成功:
    if(f){...}       //对ifstream、ofstream对象可用,fstream对象不可用。
    if(f.good()){...}
  失败:
    if(!f){...}       // !运算符已经重载
    if(f.fail()){...}


读写操作
  使用<<,>>运算符
  只能进行文本文件的读写操作,用于二进制文件可能会产生错误。
  使用函数成员 get、put、read、write等
  经常和read配合使用的函数是gcount(),用来获得实际读取的字节数。
注意事项
          打开方式中必须指定ios::binary,否则读写会出错
          用readwrite进行读写操作,而不能使用插入、提取运算符进行操作,否则会出错。
          使用eof()函数检测文件是否读结束,使用gcount()获得实际读取的字节数


关闭文件
  使用成员函数close,如:
  f.close(); 
  利用析构函数
  对象生命期结束时会检查文件是否关闭,对没有关闭的文件进行关闭操作。


随机读写
  通过移动文件读写指针,可在文件指定位置进行读写。
  seekg(绝对位置);      //绝对移动,    //输入流操作
  seekg(相对位置,参照位置);  //相对操作
  tellg();          //返回当前指针位置
  seekp(绝对位置);      //绝对移动,    //输出流操作
  seekp(相对位置,参照位置);  //相对操作   
  tellp();          //返回当前指针位置
  参照位置:
  ios::beg  = 0       //相对于文件头
  ios::cur  = 1       //相对于当前位置
  ios::end  = 2       //相对于文件尾


        基于以上,我们就可以对文件流进行封装了。新建一个AL_File类,对所有操作进行封装。

       稍微注意下字节问题(指ASCII字符(单字节)和Unicode字符(宽字节)。前者占一个字节,后者占两个字节)

  1. #define (UNICODE) || (_UNICODE)  
  2. typedef char NCHAR;  
  3. //file  
  4. #define NCHARfstream    std::wfstream  
  5. #define NCHARifstream   std::wifstream  
  6. #define NCHARfostream   std::wofstream  
  7. #else //UNICODE || _UNICODE  
  8.   
  9. typedef WCHAR NCHAR;  
  10.   
  11. //file  
  12. #define NCHARfstream    std::fstream  
  13. #define NCHARifstream   std::ifstream  
  14. #define NCHARfostream   std::ofstream  
  15.   
  16. #endif // ASCI || UTF-8  

  1. /** 
  2.   @file         AL_File.h  
  3.   @brief        AL_File File operations 
  4.   @author   arvin 
  5.   @version  1.0   2013/03/14 
  6.  */  
  7.   
  8. #ifndef CXX_AL_FILE_H  
  9. #define CXX_AL_FILE_H  
  10.   
  11. #include <fstream>  
  12.   
  13. typedef long AL_ERROR;  
  14.   
  15. class AL_File  
  16. {  
  17. public:  
  18.     enum FILE_REFERENCE_POS;  
  19.   
  20.     /** 
  21.     * Construction 
  22.     * 
  23.     * @param 
  24.     * @return 
  25.     */  
  26.     AL_File();  
  27.   
  28.     /** 
  29.     * Construction 
  30.     * 
  31.     * @param        <IN> const NCHAR* cpFilePath 
  32.     * @param        <IN> WORD wOpenModel 
  33.     static const WORD MODEL_IN          = std::ios::in;         // 0x01, for reading the file does not exist, create (ifstream Open default) 
  34.     static const WORD MODEL_OUT         = std::ios::out;        // 0x02, for writing, the file does not exist, to create, if the file already exists, clear the original content (ofstream default Open) 
  35.     static const WORD MODEL_ATE         = std::ios::ate;        // 0x04, when the file is opened, the pointer in the file last. Can change the position of the pointer, often used in combination and in, out 
  36.     static const WORD MODEL_APP         = std::ios::app;        // 0x08, for writing, the file does not exist, to create, to write new content after the original contents of the file if the file already exists, the total in the final pointer position 
  37.     static const WORD MODEL_TRUNC       = std::ios::trunc;      // 0x10, length of the file read and write before first truncated to 0 (default) 
  38.     static const WORD MODEL_NOCREATE    = std::ios::_Nocreate;  // 0x20, file does not exist error, often used in combination and in or app 
  39.     static const WORD MODEL_NOREPLACE   = std::ios::_Noreplace; // 0x40, file exists generates an error when used in combination, often and out 
  40.     static const WORD MODEL_BINARY      = std::ios::binary;     // 0x80, binary format file 
  41.     * @param        <IN> WORD wAccess 
  42.     static const WORD ACCESS_ORDINARY   = 0;                    // 0: ordinary files, open access 
  43.     static const WORD ACCESS_READONLY   = 1;                    // 1: read-only file 
  44.     static const WORD ACCESS_HIDDEN     = 2;                    // 2: hidden file 
  45.     static const WORD ACCESS_SYSTEM     = 4;                    // 4: System Files 
  46.     * @return 
  47.     * @note 
  48.     * @attention    The default way to open a file to open the binary file reading and writing 
  49.                     The default file ordinary files, open access 
  50.     */  
  51.     AL_File(const NCHAR* cpFilePath, WORD wOpenModel = MODEL_IN|MODEL_OUT|MODEL_BINARY, WORD wOpenAccess = ACCESS_ORDINARY);  
  52.   
  53.     /** 
  54.     * Destruction 
  55.     * 
  56.     * @param 
  57.     * @return 
  58.     */  
  59.     ~AL_File(VOID);  
  60.   
  61.     ///////////////////////////////////Open the file///////////////////////////////////////  
  62.     /** 
  63.     * Open (Open the file) 
  64.     * 
  65.     * @param        <IN> const NCHAR* cpFilePath 
  66.     * @param        <IN> WORD wOpenModel 
  67.                         static const WORD MODEL_IN          = std::ios::in;         // 0x01, for reading the file does not exist, create (ifstream Open default) 
  68.                         static const WORD MODEL_OUT         = std::ios::out;        // 0x02, for writing, the file does not exist, to create, if the file already exists, clear the original content (ofstream default Open) 
  69.                         static const WORD MODEL_ATE         = std::ios::ate;        // 0x04, when the file is opened, the pointer in the file last. Can change the position of the pointer, often used in combination and in, out 
  70.                         static const WORD MODEL_APP         = std::ios::app;        // 0x08, for writing, the file does not exist, to create, to write new content after the original contents of the file if the file already exists, the total in the final pointer position 
  71.                         static const WORD MODEL_TRUNC       = std::ios::trunc;      // 0x10, length of the file read and write before first truncated to 0 (default) 
  72.                         static const WORD MODEL_NOCREATE    = std::ios::_Nocreate;  // 0x20, file does not exist error, often used in combination and in or app 
  73.                         static const WORD MODEL_NOREPLACE   = std::ios::_Noreplace; // 0x40, file exists generates an error when used in combination, often and out 
  74.                         static const WORD MODEL_BINARY      = std::ios::binary;     // 0x80, binary format file 
  75.     * @param        <IN> WORD wAccess 
  76.                         static const WORD ACCESS_ORDINARY   = 0;                    // 0: ordinary files, open access 
  77.                         static const WORD ACCESS_READONLY   = 1;                    // 1: read-only file 
  78.                         static const WORD ACCESS_HIDDEN     = 2;                    // 2: hidden file 
  79.                         static const WORD ACCESS_SYSTEM     = 4;                    // 4: System Files 
  80.     * @return VOID 
  81.     * @note         Note the slash in the path name to dual-write, such as: "\MyFiles\ReadMe.txt" 
  82.     * @attention    The default way to open a file to open the binary file reading and writing 
  83.                     The default file ordinary files, open access 
  84.     */  
  85.     VOID Open(const NCHAR* cpFilePath, WORD wOpenModel = MODEL_IN|MODEL_OUT|MODEL_BINARY, WORD wOpenAccess = ACCESS_ORDINARY);  
  86.   
  87. ////////////////////////////////Check if successfully opened//////////////////////////////////////////  
  88.     /** 
  89.     * Good (Check if successfully opened) 
  90.     * 
  91.     * @param VOID 
  92.     * @return BOOL 
  93.     * @note 
  94.     * @attention 
  95.     */  
  96.     BOOL Good(VOID);  
  97.   
  98.     /** 
  99.     * Fail (Check if successfully opened) 
  100.     * 
  101.     * @param VOID 
  102.     * @return BOOL 
  103.     * @note 
  104.     * @attention 
  105.     */  
  106.     BOOL Fail(VOID);  
  107.   
  108.     /** 
  109.     * IsOpen (Check if successfully opened) 
  110.     * 
  111.     * @param VOID 
  112.     * @return BOOL 
  113.     * @note         Generally use this method to determine if a file is open successfully 
  114.     * @attention 
  115.     */  
  116.     BOOL IsOpen(VOID);  
  117.   
  118. /////////////////////////////////Reading and writing binary files/////////////////////////////////////////  
  119.     /** 
  120.     * Put (Reading and writing binary files) 
  121.     * 
  122.     * @param        <IN> NCHAR ch 
  123.     * @return VOID 
  124.     * @note         put () function to write to the stream a character prototype ofstream & put (char ch),  
  125.                     the use of relatively simple, such as file1.put ('c'); is to write to the stream a character 'c'. 
  126.     * @attention 
  127.     */  
  128.     VOID Put(NCHAR ch);  
  129.       
  130.     /** 
  131.     * Get (Reading and writing binary files) 
  132.     * 
  133.     * @param        <OUT> NCHAR& ch 
  134.     * @return VOID 
  135.     * @note         put () corresponds to the form: ifstream & get (char & ch); function is to read a single character  
  136.                     from the stream, and the result is stored in the reference ch, if the end of the file, and returns  
  137.                     a null character. As file2.get (x); represents a character read from the file, and read characters  
  138.                     stored in x. 
  139.     * @attention 
  140.     */  
  141.     VOID Get(NCHAR& ch);  
  142.   
  143.     /** 
  144.     * Get (Reading and writing binary files) 
  145.     * 
  146.     * @param        <OUT> NCHAR* pStr 
  147.     * @param        <IN> DWORD dwGetNum 
  148.     * @param        <IN> NCHAR chEndChar 
  149.     * @return VOID 
  150.     * @note         ifstream & get (char * buf, int num, char delim = ' n'); this form to read characters into the  
  151.                     array pointed to by buf until reads num characters or encounter characters specified by delim,  
  152.                     ifdelim this parameter will use the default value of the newline character ' n'. For example: 
  153.                     file2.get (str1, 127, 'A') ;/ / read characters from a file into a string str1 terminate when  
  154.                     to encounter characters 'A' or read 127 characters. 
  155.     * @attention 
  156.     */  
  157.     VOID Get(NCHAR* pStr, DWORD dwGetNum, NCHAR chEndChar);  
  158.   
  159.   
  160.     /** 
  161.     * Read (Reading and writing binary files) 
  162.     * 
  163.     * @param        <OUT> NCHAR* buf 
  164.     * @param        <IN> DWORD dwNum 
  165.     * @return BOOL 
  166.     * @note         Prototype: read (unsigned char * buf, int num); read () num characters to read from the file  
  167.                     cache buf points to the end of the file has not been read into the num characters can use member  
  168.                     functionsint gcount (); to get the actual number of characters read 
  169.     * @attention 
  170.     */  
  171.     VOID Read(NCHAR* buf, DWORD dwNum);  
  172.   
  173.     /** 
  174.     * Write (Reading and writing binary files) 
  175.     * 
  176.     * @param        <IN> NCHAR* buf 
  177.     * @param        <IN> DWORD dwNum 
  178.     * @return BOOL 
  179.     * @note         Prototype: write (const unsigned char * buf, int num); write () from buf points to the cache  
  180.                     write num characters to the file, it is noteworthy cache type is unsigned char *, may sometimes 
  181.                     be necessary type conversion. 
  182.     * @attention 
  183.     */  
  184.     VOID Write(const NCHAR* buf, DWORD dwNum);  
  185.   
  186.     /** 
  187.     * Eof End of file is read (Reading and writing binary files) 
  188.     * 
  189.     * @param VOID 
  190.     * @return BOOL 
  191.     * @note 
  192.     * @attention 
  193.     */  
  194.     BOOL Eof(VOID);  
  195.   
  196.     /** 
  197.     * Gcount The actual number of bytes read (Reading and writing binary files) 
  198.     * 
  199.     * @param VOID 
  200.     * @return DWORD 
  201.     * @note 
  202.     * @attention 
  203.     */  
  204.     DWORD Gcount(VOID);  
  205.   
  206.   
  207.     /** 
  208.     * Seekg Absolutely move (Reading and writing binary files) 
  209.     * 
  210.     * @param        <IN> DWORD dwSeek absolute move position 
  211.     * @return VOID 
  212.     * @note 
  213.     * @attention    Input stream operation 
  214.     */  
  215.     VOID Seekg(DWORD dwSeek);  
  216.   
  217.     /** 
  218.     * Seekg Relatively move (Reading and writing binary files) 
  219.     * 
  220.     * @param        <IN> DWORD dwSeek relatively move position 
  221.     * @param        <IN> FILE_REFERENCE_POS eFileRefPos file reference position 
  222.                         FILE_REFERENCE_POS_BEG = std::ios :: beg,   // 0: relative to the file header 
  223.                         FILE_REFERENCE_POS_CUR = std::ios :: cur,   // 1: relative to the current position 
  224.                         FILE_REFERENCE_POS_END = std::ios :: end,   // 2: relative to the end of the file 
  225.     * @return VOID 
  226.     * @note 
  227.     * @attention    Input stream operation 
  228.     */  
  229.     VOID Seekg(DWORD dwSeek, FILE_REFERENCE_POS eFileRefPos);  
  230.   
  231.     /** 
  232.     * Tellg Returns the current pointer position (Reading and writing binary files) 
  233.     * 
  234.     * @param VOID 
  235.     * @return VOID 
  236.     * @note 
  237.     * @attention    Input stream operation 
  238.     */  
  239.     VOID Tellg(VOID);  
  240.   
  241.     /** 
  242.     * Seekp Absolutely move (Reading and writing binary files) 
  243.     * 
  244.     * @param        <IN> DWORD dwSeek absolute move position 
  245.     * @return VOID 
  246.     * @note 
  247.     * @attention    Output stream operation 
  248.     */  
  249.     VOID Seekp(DWORD dwSeek);  
  250.   
  251.     /** 
  252.     * Seekp Relatively move (Reading and writing binary files) 
  253.     * 
  254.     * @param        <IN> DWORD dwSeek relatively move position 
  255.     * @param        <IN> FILE_REFERENCE_POS eFileRefPos file reference position 
  256.                         FILE_REFERENCE_POS_BEG = std::ios :: beg,   // 0: relative to the file header 
  257.                         FILE_REFERENCE_POS_CUR = std::ios :: cur,   // 1: relative to the current position 
  258.                         FILE_REFERENCE_POS_END = std::ios :: end,   // 2: relative to the end of the file 
  259.     * @return VOID 
  260.     * @note 
  261.     * @attention    Output stream operation 
  262.     */  
  263.     VOID Seekp(DWORD dwSeek, FILE_REFERENCE_POS eFileRefPos);  
  264.   
  265.     /** 
  266.     * Tellp Returns the current pointer position (Reading and writing binary files) 
  267.     * 
  268.     * @param VOID 
  269.     * @return VOID 
  270.     * @note 
  271.     * @attention    Output stream operation 
  272.     */  
  273.     VOID Tellp(VOID);  
  274.   
  275.   
  276. /////////////////////////////////////Close the file/////////////////////////////////////  
  277.     /** 
  278.     * Close (Close the file) 
  279.     * 
  280.     * @param VOID 
  281.     * @return VOID 
  282.     * @note 
  283.     * @attention 
  284.     */  
  285.     VOID Close(VOID);  
  286.   
  287. protected:  
  288. private:  
  289.     /** 
  290.     *Copy Construct 
  291.     * 
  292.     * @param const AL_File& cAL_File 
  293.     * @return 
  294.     */  
  295.     AL_File(const AL_File& cAL_File);  
  296.   
  297.     /** 
  298.     *Assignment 
  299.     * 
  300.     * @param const AL_File& cAL_File 
  301.     * @return AL_File& 
  302.     */  
  303.     AL_File &operator =(const AL_File& cAL_File);  
  304.   
  305.   
  306. public:  
  307.     ////////////////////////////open model//////////////////////////////////////////////  
  308.     static const WORD MODEL_IN          = std::ios::in;         // 0x01, for reading the file does not exist, create (ifstream Open default)  
  309.     static const WORD MODEL_OUT         = std::ios::out;        // 0x02, for writing, the file does not exist, to create, if the file already exists, clear the original content (ofstream default Open)  
  310.     static const WORD MODEL_ATE         = std::ios::ate;        // 0x04, when the file is opened, the pointer in the file last. Can change the position of the pointer, often used in combination and in, out  
  311.     static const WORD MODEL_APP         = std::ios::app;        // 0x08, for writing, the file does not exist, to create, to write new content after the original contents of the file if the file already exists, the total in the final pointer position  
  312.     static const WORD MODEL_TRUNC       = std::ios::trunc;      // 0x10, length of the file read and write before first truncated to 0 (default)  
  313.     static const WORD MODEL_NOCREATE    = std::ios::_Nocreate;  // 0x20, file does not exist error, often used in combination and in or app  
  314.     static const WORD MODEL_NOREPLACE   = std::ios::_Noreplace; // 0x40, file exists generates an error when used in combination, often and out  
  315.     static const WORD MODEL_BINARY      = std::ios::binary;     // 0x80, binary format file  
  316.   
  317.     ////////////////////////////open access//////////////////////////////////////////////  
  318.     static const WORD ACCESS_ORDINARY   = 0;                    // 0: ordinary files, open access  
  319.     static const WORD ACCESS_READONLY   = 1;                    // 1: read-only file  
  320.     static const WORD ACCESS_HIDDEN     = 2;                    // 2: hidden file  
  321.     static const WORD ACCESS_SYSTEM     = 4;                    // 4: System Files  
  322.   
  323.     //////////////////////////////////////////////////////////////////////////  
  324.     enum FILE_REFERENCE_POS  
  325.     {  
  326.         FILE_REFERENCE_POS_BEG = std::ios :: beg,   // 0: relative to the file header  
  327.         FILE_REFERENCE_POS_CUR = std::ios :: cur,   // 1: relative to the current position  
  328.         FILE_REFERENCE_POS_END = std::ios :: end,   // 2: relative to the end of the file  
  329.     };  
  330.   
  331. protected:  
  332. private:  
  333.     NCHARfstream*   m_pfstream;  
  334. };  
  335.   
  336. #endif // CXX_AL_FILE_H  
  337. /* EOF */  
  338.       

  1. /** 
  2.   @file         AL_File.h  
  3.   @brief        AL_File File operations 
  4.   @author   arvin 
  5.   @version  1.0   2013/03/14 
  6.  */  
  7. #include "stdafx.h"  
  8.   
  9. #ifndef CXX_AL_FILE_H  
  10. #include "AL_File.h"  
  11. #endif  
  12.   
  13. #ifndef CXX_AL_ERROR_H  
  14. #include "AL_Error.h"  
  15. #endif  
  16.   
  17. /** 
  18. * Construction 
  19. * 
  20. * @param 
  21. * @return 
  22. */  
  23. AL_File::AL_File():  
  24. m_pfstream(NULL)  
  25. {  
  26.     m_pfstream = new NCHARfstream;  
  27. }  
  28.   
  29. /** 
  30. * Construction 
  31. * 
  32. * @param        <IN> const NCHAR* cpFilePath 
  33. * @param        <IN> WORD wOpenModel 
  34. static const WORD MODEL_IN          = std::ios::in;         // 0x01, for reading the file does not exist, create (ifstream Open default) 
  35. static const WORD MODEL_OUT         = std::ios::out;        // 0x02, for writing, the file does not exist, to create, if the file already exists, clear the original content (ofstream default Open) 
  36. static const WORD MODEL_ATE         = std::ios::ate;        // 0x04, when the file is opened, the pointer in the file last. Can change the position of the pointer, often used in combination and in, out 
  37. static const WORD MODEL_APP         = std::ios::app;        // 0x08, for writing, the file does not exist, to create, to write new content after the original contents of the file if the file already exists, the total in the final pointer position 
  38. static const WORD MODEL_TRUNC       = std::ios::trunc;      // 0x10, length of the file read and write before first truncated to 0 (default) 
  39. static const WORD MODEL_NOCREATE    = std::ios::_Nocreate;  // 0x20, file does not exist error, often used in combination and in or app 
  40. static const WORD MODEL_NOREPLACE   = std::ios::_Noreplace; // 0x40, file exists generates an error when used in combination, often and out 
  41. static const WORD MODEL_BINARY      = std::ios::binary;     // 0x80, binary format file 
  42. * @param        <IN> WORD wAccess 
  43. static const WORD ACCESS_ORDINARY   = 0;                    // 0: ordinary files, open access 
  44. static const WORD ACCESS_READONLY   = 1;                    // 1: read-only file 
  45. static const WORD ACCESS_HIDDEN     = 2;                    // 2: hidden file 
  46. static const WORD ACCESS_SYSTEM     = 4;                    // 4: System Files 
  47. * @return 
  48. * @note 
  49. * @attention    The default way to open a file to open the binary file reading and writing 
  50.                 The default file ordinary files, open access 
  51. */  
  52. AL_File::AL_File(const NCHAR* cpFilePath, WORD wOpenModel, WORD wOpenAccess):  
  53. m_pfstream(NULL)  
  54. {  
  55.     m_pfstream = new NCHARfstream;  
  56.     Open(cpFilePath, wOpenModel, wOpenAccess);  
  57. }  
  58.   
  59. /** 
  60. * Destruction 
  61. * 
  62. * @param 
  63. * @return 
  64. */  
  65. AL_File::~AL_File(VOID)  
  66. {  
  67.     if (NULL == m_pfstream) {  
  68.         delete m_pfstream;  
  69.         m_pfstream = NULL;  
  70.     }  
  71. }  
  72.   
  73. ///////////////////////////////////Open the file///////////////////////////////////////  
  74. /** 
  75. * Open (Open the file) 
  76. * 
  77. * @param        <IN> const NCHAR* cpFilePath 
  78. * @param        <IN> WORD wOpenModel 
  79.                     static const WORD MODEL_IN          = std::ios::in;         // 0x01, for reading the file does not exist, create (ifstream Open default) 
  80.                     static const WORD MODEL_OUT         = std::ios::out;        // 0x02, for writing, the file does not exist, to create, if the file already exists, clear the original content (ofstream default Open) 
  81.                     static const WORD MODEL_ATE         = std::ios::ate;        // 0x04, when the file is opened, the pointer in the file last. Can change the position of the pointer, often used in combination and in, out 
  82.                     static const WORD MODEL_APP         = std::ios::app;        // 0x08, for writing, the file does not exist, to create, to write new content after the original contents of the file if the file already exists, the total in the final pointer position 
  83.                     static const WORD MODEL_TRUNC       = std::ios::trunc;      // 0x10, length of the file read and write before first truncated to 0 (default) 
  84.                     static const WORD MODEL_NOCREATE    = std::ios::_Nocreate;  // 0x20, file does not exist error, often used in combination and in or app 
  85.                     static const WORD MODEL_NOREPLACE   = std::ios::_Noreplace; // 0x40, file exists generates an error when used in combination, often and out 
  86.                     static const WORD MODEL_BINARY      = std::ios::binary;     // 0x80, binary format file 
  87. * @param        <IN> WORD wAccess 
  88.                     static const WORD ACCESS_ORDINARY   = 0;                    // 0: ordinary files, open access 
  89.                     static const WORD ACCESS_READONLY   = 1;                    // 1: read-only file 
  90.                     static const WORD ACCESS_HIDDEN     = 2;                    // 2: hidden file 
  91.                     static const WORD ACCESS_SYSTEM     = 4;                    // 4: System Files 
  92. * @return VOID 
  93. * @note         Note the slash in the path name to dual-write, such as: "\MyFiles\ReadMe.txt" 
  94. * @attention    The default way to open a file to open the binary file reading and writing       
  95. */  
  96. VOID   
  97. AL_File::Open(const NCHAR* cpFilePath, WORD wOpenModel, WORD wOpenAccess)  
  98. {  
  99.     if (NULL == m_pfstream) {  
  100.         return;  
  101.     }  
  102.     m_pfstream->open(cpFilePath, wOpenModel, wOpenAccess);  
  103. }  
  104.   
  105. ////////////////////////////////Check if successfully opened//////////////////////////////////////////  
  106. /** 
  107. * Good (Check if successfully opened) 
  108. * 
  109. * @param VOID 
  110. * @return BOOL 
  111. * @note 
  112. * @attention 
  113. */  
  114. BOOL   
  115. AL_File::Good(VOID)  
  116. {  
  117.     if (NULL == m_pfstream) {  
  118.         return FALSE;  
  119.     }  
  120.     return m_pfstream->good();  
  121.   
  122. }  
  123.   
  124. /** 
  125. * Fail (Check if successfully opened) 
  126. * 
  127. * @param VOID 
  128. * @return BOOL 
  129. * @note 
  130. * @attention 
  131. */  
  132. BOOL   
  133. AL_File::Fail(VOID)  
  134. {  
  135.     if (NULL == m_pfstream) {  
  136.         return FALSE;  
  137.     }  
  138.     return m_pfstream->fail();  
  139. }  
  140.   
  141. /** 
  142. * IsOpen (Check if successfully opened) 
  143. * 
  144. * @param VOID 
  145. * @return BOOL 
  146. * @note         Generally use this method to determine if a file is open successfully 
  147. * @attention 
  148. */  
  149. BOOL   
  150. AL_File::IsOpen(VOID)  
  151. {  
  152.     if (NULL == m_pfstream) {  
  153.         return FALSE;  
  154.     }  
  155.     return m_pfstream->is_open();  
  156.   
  157. }  
  158.   
  159. /////////////////////////////////Reading and writing binary files/////////////////////////////////////////  
  160. /** 
  161. * Put (Reading and writing binary files) 
  162. * 
  163. * @param        <IN> NCHAR ch 
  164. * @return VOID 
  165. * @note         put () function to write to the stream a character prototype ofstream & put (char ch),  
  166.                 the use of relatively simple, such as file1.put ('c'); is to write to the stream a character 'c'. 
  167. * @attention 
  168. */  
  169. VOID   
  170. AL_File::Put(NCHAR ch)  
  171. {  
  172.     if (NULL == m_pfstream) {  
  173.         return;  
  174.     }  
  175.     m_pfstream->put(ch);  
  176. }  
  177.   
  178. /** 
  179. * Get (Reading and writing binary files) 
  180. * 
  181. * @param        <OUT> NCHAR& ch 
  182. * @return VOID 
  183. * @note         put () corresponds to the form: ifstream & get (char & ch); function is to read a single character  
  184.                 from the stream, and the result is stored in the reference ch, if the end of the file, and returns  
  185.                 a null character. As file2.get (x); represents a character read from the file, and read characters  
  186.                 stored in x. 
  187. * @attention 
  188. */  
  189. VOID   
  190. AL_File::Get(NCHAR& ch)  
  191. {  
  192.     if (NULL == m_pfstream) {  
  193.         return;  
  194.     }  
  195.     m_pfstream->get(ch);  
  196. }  
  197.   
  198. /** 
  199. * Get (Reading and writing binary files) 
  200. * 
  201. * @param        <OUT> NCHAR* pStr 
  202. * @param        <IN> DWORD dwGetNum 
  203. * @param        <IN> NCHAR chEndChar 
  204. * @return VOID 
  205. * @note         ifstream & get (char * buf, int num, char delim = ' n'); this form to read characters into the  
  206.                 array pointed to by buf until reads num characters or encounter characters specified by delim,  
  207.                 ifdelim this parameter will use the default value of the newline character ' n'. For example: 
  208.                 file2.get (str1, 127, 'A') ;/ / read characters from a file into a string str1 terminate when  
  209.                 to encounter characters 'A' or read 127 characters. 
  210. * @attention 
  211. */  
  212. VOID   
  213. AL_File::Get(NCHAR* pStr, DWORD dwGetNum, NCHAR chEndChar)  
  214. {  
  215.     if (NULL == m_pfstream) {  
  216.         return;  
  217.     }  
  218.     m_pfstream->get(pStr, dwGetNum, chEndChar);  
  219. }  
  220.   
  221.   
  222. /** 
  223. * Read (Reading and writing binary files) 
  224. * 
  225. * @param        <OUT> NCHAR* buf 
  226. * @param        <IN> DWORD dwNum 
  227. * @return BOOL 
  228. * @note         Prototype: read (unsigned char * buf, int num); read () num characters to read from the file  
  229.                 cache buf points to the end of the file has not been read into the num characters can use member  
  230.                 functionsint gcount (); to get the actual number of characters read 
  231. * @attention 
  232. */  
  233. VOID   
  234. AL_File::Read(NCHAR* buf, DWORD dwNum)  
  235. {  
  236.     if (NULL == m_pfstream) {  
  237.         return;  
  238.     }  
  239.     m_pfstream->read(buf, dwNum);  
  240. }  
  241.   
  242. /** 
  243. * Write (Reading and writing binary files) 
  244. * 
  245. * @param        <IN> NCHAR* buf 
  246. * @param        <IN> DWORD dwNum 
  247. * @return BOOL 
  248. * @note         Prototype: write (const unsigned char * buf, int num); write () from buf points to the cache  
  249.                 write num characters to the file, it is noteworthy cache type is unsigned char *, may sometimes 
  250.                 be necessary type conversion. 
  251. * @attention 
  252. */  
  253. VOID   
  254. AL_File::Write(const NCHAR* buf, DWORD dwNum)  
  255. {  
  256.     if (NULL == m_pfstream) {  
  257.         return;  
  258.     }  
  259.     m_pfstream->write(buf, dwNum);  
  260. }  
  261.   
  262. /** 
  263. * Eof End of file is read (Reading and writing binary files) 
  264. * 
  265. * @param VOID 
  266. * @return BOOL 
  267. * @note 
  268. * @attention 
  269. */  
  270. BOOL   
  271. AL_File::Eof(VOID)  
  272. {  
  273.     if (NULL == m_pfstream) {  
  274.         return FALSE;  
  275.     }  
  276.     return m_pfstream->eof();  
  277. }  
  278.   
  279. /** 
  280. * Gcount The actual number of bytes read (Reading and writing binary files) 
  281. * 
  282. * @param VOID 
  283. * @return DWORD 
  284. * @note 
  285. * @attention 
  286. */  
  287. DWORD   
  288. AL_File::Gcount(VOID)  
  289. {  
  290.     if (NULL == m_pfstream) {  
  291.         return FALSE;  
  292.     }  
  293.     return m_pfstream->gcount();  
  294. }  
  295.   
  296. /** 
  297. * Seekg Absolutely move (Reading and writing binary files) 
  298. * 
  299. * @param        <IN> DWORD dwSeek absolute move position 
  300. * @return VOID 
  301. * @note 
  302. * @attention    Input stream operation 
  303. */  
  304. VOID   
  305. AL_File::Seekg(DWORD dwSeek)  
  306. {  
  307.     if (NULL == m_pfstream) {  
  308.         return;  
  309.     }  
  310.     m_pfstream->seekg(dwSeek);  
  311. }  
  312.   
  313. /** 
  314. * Seekg Relatively move (Reading and writing binary files) 
  315. * 
  316. * @param        <IN> DWORD dwSeek relatively move position 
  317. * @param        <IN> FILE_REFERENCE_POS eFileRefPos file reference position 
  318.                     FILE_REFERENCE_POS_BEG = std::ios :: beg,   // 0: relative to the file header 
  319.                     FILE_REFERENCE_POS_CUR = std::ios :: cur,   // 1: relative to the current position 
  320.                     FILE_REFERENCE_POS_END = std::ios :: end,   // 2: relative to the end of the file 
  321. * @return VOID 
  322. * @note 
  323. * @attention    Input stream operation 
  324. */  
  325. VOID   
  326. AL_File::Seekg(DWORD dwSeek, FILE_REFERENCE_POS eFileRefPos)  
  327. {  
  328.     if (NULL == m_pfstream) {  
  329.         return;  
  330.     }  
  331.     m_pfstream->seekg(dwSeek, eFileRefPos);  
  332. }  
  333.   
  334. /** 
  335. * Tellg Returns the current pointer position (Reading and writing binary files) 
  336. * 
  337. * @param VOID 
  338. * @return VOID 
  339. * @note 
  340. * @attention    Input stream operation 
  341. */  
  342. VOID   
  343. AL_File::Tellg(VOID)  
  344. {  
  345.     if (NULL == m_pfstream) {  
  346.         return;  
  347.     }  
  348.     m_pfstream->tellg();  
  349. }  
  350.   
  351. /** 
  352. * Seekp Absolutely move (Reading and writing binary files) 
  353. * 
  354. * @param        <IN> DWORD dwSeek absolute move position 
  355. * @return VOID 
  356. * @note 
  357. * @attention    Output stream operation 
  358. */  
  359. VOID   
  360. AL_File::Seekp(DWORD dwSeek)  
  361. {  
  362.     if (NULL == m_pfstream) {  
  363.         return;  
  364.     }  
  365.     m_pfstream->seekp(dwSeek);  
  366. }  
  367.   
  368. /** 
  369. * Seekp Relatively move (Reading and writing binary files) 
  370. * 
  371. * @param        <IN> DWORD dwSeek relatively move position 
  372. * @param        <IN> FILE_REFERENCE_POS eFileRefPos file reference position 
  373.                     FILE_REFERENCE_POS_BEG = std::ios :: beg,   // 0: relative to the file header 
  374.                     FILE_REFERENCE_POS_CUR = std::ios :: cur,   // 1: relative to the current position 
  375.                     FILE_REFERENCE_POS_END = std::ios :: end,   // 2: relative to the end of the file 
  376. * @return VOID 
  377. * @note 
  378. * @attention    Output stream operation 
  379. */  
  380. VOID   
  381. AL_File::Seekp(DWORD dwSeek, FILE_REFERENCE_POS eFileRefPos)  
  382. {  
  383.     if (NULL == m_pfstream) {  
  384.         return;  
  385.     }  
  386.     m_pfstream->seekp(dwSeek, eFileRefPos);  
  387. }  
  388.   
  389. /** 
  390. * Tellp Returns the current pointer position (Reading and writing binary files) 
  391. * 
  392. * @param VOID 
  393. * @return VOID 
  394. * @note 
  395. * @attention    Output stream operation 
  396. */  
  397. VOID   
  398. AL_File::Tellp(VOID)  
  399. {  
  400.     if (NULL == m_pfstream) {  
  401.         return;  
  402.     }  
  403.     m_pfstream->tellp();  
  404. }  
  405.   
  406.   
  407. /////////////////////////////////////Close the file/////////////////////////////////////  
  408. /** 
  409. * Close (Close the file) 
  410. * 
  411. * @param VOID 
  412. * @return VOID 
  413. * @note 
  414. * @attention 
  415. */  
  416. VOID   
  417. AL_File::Close(VOID)  
  418. {  
  419.     if (NULL == m_pfstream) {  
  420.         return;  
  421.     }  
  422.     m_pfstream->close();  
  423. }  
  424.   
  425. /* EOF */  

        附其它几篇相关文章:

                http://www.iteye.com/topic/383903

                http://blog.csdn.net/mak0000/article/details/3230199

     文件路径函数 
        ExpandFileName() 返回文件的全路径(含驱动器、路径) 
        ExtractFileExt() 从文件名中抽取扩展名 
        ExtractFileName() 从文件名中抽取不含路径的文件名 
        ExtractFilePath() 从文件名中抽取路径名 
        ExtractFileDir() 从文件名中抽取目录名 
        ExtractFileDrive() 从文件名中抽取驱动器名 
        ChangeFileExt() 改变文件的扩展名 
        ExpandUNCFileName() 返回含有网络驱动器的文件全路径 
        ExtractRelativePath() 从文件名中抽取相对路径信息 
        ExtractShortPathName() 把文件名转化为DOS的8·3格式 
        MatchesMask() 检查文件是否与指定的文件名格式匹配
        tellp();                                        //返回当前指针位置
        参照位置:
        ios::beg        = 0                         //相对于文件头
        ios::cur        = 1                         //相对于当前位置
        ios::end        = 2                         //相对于文件尾

     文件管理函数 

        这类函数包括设置和读取驱动器、子目录和文件的有关的各种操作,下表列出这类操作常用的函数及其功能。

        函数 功能 
        CreateDir() 创建新的子目录 
        DeleteFile() 删除文件 
        DirectoryExists() 判断目录是否存在 
        DiskFree() 获取磁盘剩余空间 
        DiskSize() 获取磁盘容量 
        FileExists() 判断文件是否存在 
        FileGetAttr() 获取文件属性 
        FileGetDate() 获取文件日期 
        GetCurrentDir() 获取当前目录 
        RemoveDir() 删除目录 
        SetCurrentDir() 设置当前目录

        ⑴CreateDir() 
        原型:extern PACKAGE bool __fastcall CreateDir(const System::AnsiString Dir);


        功能:建立子目录,如果成功返回true,否则返回false


        参数:Dir:要建立的子目录的名字


        例:Create("ASM");//在当前目录下建立一个名为ASM的子目录


        ⑵DeleteFile() 
        原型:extern PACKAGE bool __fastcall DeleteFile(const System::AnsiString FileName);


        功能:删除文件,如果成功返回true,否则返回false


        参数:FileName:要删除的文件名


        例:if(OpenDialog1->Execute())DeleteFile(OpenDialog1->FileName);


        ⑶DirectoryExists() 
        原型:extern PACKAGE bool __fastcall DirectoryExists(const System:: AnsiString Name);


        功能:检测目录是否存在,如果存在返回true,否则返回false


        参数:Name:要检测的目录名


        例:if(!DirectoryExists("ASM"))CreateDir("ASM");//如果ASM这个目录不存在则创建之


        ⑷DiskFree() 
        原型:extern PACKAGE __int64 __fastcall DiskFree(Byte Drive);


        功能:检测磁盘剩余空间,返回值以字节为单位,如果指定的磁盘无效,返回-1


        参数:Drive:磁盘的代号,0表示当前盘, 1=A,2=B,3=C 以此类推


        例:ShowMessage(DiskFree(0));//显示当前盘的剩余空间


        ⑸DiskSize() 
        原型:extern PACKAGE __int64 __fastcall DiskSize(Byte Drive);


        功能:检测磁盘容量,返回值以字节为单位,如果指定的磁盘无效,返回-1


        参数:Drive:磁盘的代号,0表示当前盘, 1=A,2=B,3=C 以此类推


        例:ShowMessage(DiskFree(0));//显示当前盘的容量


        ⑹FileExists() 
        原型:extern PACKAGE bool __fastcall FileExists(const AnsiString FileName);


        功能:检测文件是否存在,如果存在返回true,否则返回false


        参数:FileName:要检测的文件名


        例:if(FileExists("AAA.ASM"))DeleteFile("AAA.ASM");


        ⑺FileGetAttr() 
        原型:extern PACKAGE int __fastcall FileGetAttr(const AnsiString FileName);


        功能:取得文件属性,如果出错返回-1


        返回值如下表,如果返回$00000006表示是一个具有隐含和系统属性的文件(4+2)


        常量 值 含义 
        faReadOnly $00000001 只读文件 
        faHidden $00000002 隐含文件 
        faSysFile $00000004 系统文件 
        faVolumeID $00000008 卷标 
        faDirectory $00000010 目录 
        faArchive $00000020 归档文件


        例:if(FileGetAttr("LLL.TXT")&0x2)ShowMessage("这是一个有隐含属性的文件");


        与此对应的有FileSetAttr() ,请自已查阅帮助系统




        ⑻FileGetDate() 
        原型:extern PACKAGE int __fastcall FileGetDate(int Handle);


        功能:返回文件的建立时间到1970-1-1日0时的秒数


        参数:Handle:用FileOpen()打开的文件句柄。


        例:


        int i=FileOpen("C://autoexec.bat",fmOpenRead); 
        ShowMessage(FileGetDate(i)); 
        FileClose(i);


        与此对应的有FileSetDate(),请自已查阅帮助系统


        ⑼GetCurrentDir() 
        原型:extern PACKAGE AnsiString __fastcall GetCurrentDir();


        功能:取得当前的目录名


        例:ShowMessage(GetCurrentDir());


        ⑽RemoveDir() 
        原型:extern PACKAGE bool __fastcall RemoveDir(const AnsiString Dir);


        功能:删除目录,如果成功返回true,否则返回false


        参数:Dir:要删除的目录名


        例:if(DiectoryExists("ASM"))RemoveDir("ASM");


        ⑾SetCurrentDir() 
        原型:extern PACKAGE bool __fastcall SetCurrentDir(const AnsiString Dir);


        功能:设置当前目录,如果成功返回true,否则返回false


        参数:Dir:要切换到的目录名


        例:SetCurrentDir("C://WINDOWS");


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
以后的笔记潇汀会尽量详细讲解一些相关知识的,希望大家继续关注我的博客。
本节笔记到这里就结束了。


潇汀一有时间就会把自己的学习心得,觉得比较好的知识点写出来和大家一起分享。
编程开发的路很长很长,非常希望能和大家一起交流,共同学习,共同进步。
如果文章中有什么疏漏的地方,也请大家指正。也希望大家可以多留言来和我探讨编程相关的问题。

最后,谢谢你们一直的支持~~~

from:http://blog.csdn.net/xiaoting451292510/article/details/8677867

极简,专注,速度,极致
原文地址:https://www.cnblogs.com/simplelifestyle/p/3761921.html