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
23std::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(filename: names.first.c_str(), modes: "w");
30
31 names.second = get_temp_file_name();
32 assert(names.first != names.second);
33
34 std::fclose(stream: fd1);
35 std::remove(filename: names.first.c_str());
36
37 return names;
38}
39
40int 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(x&: fs1, y&: 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(filename: 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(filename: temp2.c_str());
73
74#ifndef TEST_HAS_NO_WIDE_CHARACTERS
75 {
76 std::wofstream fs1(temp1.c_str());
77 std::wofstream fs2(temp2.c_str());
78 fs1 << 3.25;
79 fs2 << 4.5;
80 swap(x&: fs1, y&: fs2);
81 fs1 << ' ' << 3.25;
82 fs2 << ' ' << 4.5;
83 }
84 {
85 std::wifstream fs(temp1.c_str());
86 double x = 0;
87 fs >> x;
88 assert(x == 3.25);
89 fs >> x;
90 assert(x == 4.5);
91 }
92 std::remove(filename: temp1.c_str());
93 {
94 std::wifstream fs(temp2.c_str());
95 double x = 0;
96 fs >> x;
97 assert(x == 4.5);
98 fs >> x;
99 assert(x == 3.25);
100 }
101 std::remove(filename: temp2.c_str());
102#endif
103
104 return 0;
105}
106

source code of libcxx/test/std/input.output/file.streams/fstreams/ofstream.assign/nonmember_swap.pass.cpp