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,否则读写会出错

   用read\write进行读写操作,而不能使用插入、提取运算符进行操作,否则会出错。

   使用eof()函数检测文件是否读结束,使用gcount()获得实际读取的字节数

关闭文件

  使用成员函数close,如:

  f.close(); 

  利用析构函数

  对象生命期结束时会检查文件是否关闭,对没有关闭的文件进行关闭操作。

随机读写

  通过移动文件读写指针,可在文件指定位置进行读写。

  seekg(绝对位置);      //绝对移动,    //输入流操作

  seekg(相对位置,参照位置);  //相对操作

  tellg();          //返回当前指针位置

  seekp(绝对位置);      //绝对移动,    //输出流操作

  seekp(相对位置,参照位置);  //相对操作   

  tellp();          //返回当前指针位置

  参照位置:

  ios::beg  = 0       //相对于文件头

  ios::cur  = 1       //相对于当前位置

  ios::end  = 2       //相对于文件尾

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

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

[cpp]view plaincopy

  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. typedef WCHAR NCHAR;
  9. //file
  10. #define NCHARfstream std::fstream
  11. #define NCHARifstream std::ifstream
  12. #define NCHARfostream std::ofstream
  13. #endif // ASCI || UTF-8

[cpp]view plaincopy

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

[cpp]view plaincopy

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