1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // <fstream>
10 
11 // template <class charT, class traits = char_traits<charT> >
12 // class basic_ofstream
13 
14 // template <class charT, class traits>
15 //   void swap(basic_ofstream<charT, traits>& x, basic_ofstream<charT, traits>& y);
16 
17 #include <fstream>
18 #include <utility>
19 #include <cassert>
20 #include "test_macros.h"
21 #include "platform_support.h"
22 
get_temp_file_names()23 std::pair<std::string, std::string> get_temp_file_names() {
24   std::pair<std::string, std::string> names;
25   names.first = get_temp_file_name();
26 
27   // Create the file so the next call to `get_temp_file_name()` doesn't
28   // return the same file.
29   std::FILE *fd1 = std::fopen(names.first.c_str(), "w");
30 
31   names.second = get_temp_file_name();
32   assert(names.first != names.second);
33 
34   std::fclose(fd1);
35   std::remove(names.first.c_str());
36 
37   return names;
38 }
39 
main(int,char **)40 int main(int, char**)
41 {
42     std::pair<std::string, std::string> temp_files = get_temp_file_names();
43     std::string& temp1 = temp_files.first;
44     std::string& temp2 = temp_files.second;
45     assert(temp1 != temp2);
46     {
47         std::ofstream fs1(temp1.c_str());
48         std::ofstream fs2(temp2.c_str());
49         fs1 << 3.25;
50         fs2 << 4.5;
51         swap(fs1, fs2);
52         fs1 << ' ' << 3.25;
53         fs2 << ' ' << 4.5;
54     }
55     {
56         std::ifstream fs(temp1.c_str());
57         double x = 0;
58         fs >> x;
59         assert(x == 3.25);
60         fs >> x;
61         assert(x == 4.5);
62     }
63     std::remove(temp1.c_str());
64     {
65         std::ifstream fs(temp2.c_str());
66         double x = 0;
67         fs >> x;
68         assert(x == 4.5);
69         fs >> x;
70         assert(x == 3.25);
71     }
72     std::remove(temp2.c_str());
73     {
74         std::wofstream fs1(temp1.c_str());
75         std::wofstream fs2(temp2.c_str());
76         fs1 << 3.25;
77         fs2 << 4.5;
78         swap(fs1, fs2);
79         fs1 << ' ' << 3.25;
80         fs2 << ' ' << 4.5;
81     }
82     {
83         std::wifstream fs(temp1.c_str());
84         double x = 0;
85         fs >> x;
86         assert(x == 3.25);
87         fs >> x;
88         assert(x == 4.5);
89     }
90     std::remove(temp1.c_str());
91     {
92         std::wifstream fs(temp2.c_str());
93         double x = 0;
94         fs >> x;
95         assert(x == 4.5);
96         fs >> x;
97         assert(x == 3.25);
98     }
99     std::remove(temp2.c_str());
100 
101   return 0;
102 }
103