c++编写打开文件进行读写的函数

怼烎@ 2022-09-18 14:55 163阅读 0赞
  1. /*
  2. 编写打开文件用于输入输出的函数
  3. */
  4. #include <iostream>
  5. #include <string>
  6. #include <fstream>
  7. using namespace std;
  8. //编写open_in_file函数打开文件用于输入
  9. ifstream& open_in_file(ifstream &in,const string &file)
  10. {//利用引用传递可以改变实参,string类型利用const的引用不改变实参,提高效率
  11. //in为ifstream流对象
  12. //防止该流已经打开,所以在打开文件前关闭该流对象
  13. in.close();
  14. //清空流对象
  15. in.clear();
  16. in.open(file.c_str(),ifstream::in);
  17. return in;
  18. }
  19. //编写函数open_file1打开文件用于输出
  20. ofstream& open_out_file(ofstream &out,const string &file)
  21. {
  22. out.close();
  23. out.clear();
  24. out.open(file.c_str(),ofstream::out | ofstream::app);
  25. return out;
  26. }
  27. int main()
  28. {
  29. ifstream infile;
  30. open_in_file(infile,"map_file.txt");
  31. if(!infile)
  32. {
  33. //报错
  34. }
  35. else
  36. {
  37. string s;
  38. while(!infile.eof())
  39. {
  40. getline(infile,s);
  41. cout << s << endl;
  42. }
  43. infile.close();
  44. }
  45. ofstream outfile;
  46. if(!outfile)
  47. {
  48. //报错
  49. }
  50. else
  51. {
  52. open_out_file(outfile,"map_file.txt");
  53. outfile << "111 2222" <<endl;
  54. }
  55. outfile.close();
  56. return 0;
  57. }

在应用中,我们常常都要打开给定的文件用于输入和输出,所以在此我把两个常用的函数写出来,供大家参考。

发表评论

表情:
评论列表 (有 0 条评论,163人围观)

还没有评论,来说两句吧...

相关阅读