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_fstream
13
14 // template <class charT, class traits>
15 // void swap(basic_fstream<charT, traits>& x, basic_fstream<charT, traits>& y);
16
17 #include <fstream>
18 #include <utility>
19 #include <cassert>
20 #include "test_macros.h"
21 #include "platform_support.h"
22
23
get_temp_file_names()24 std::pair<std::string, std::string> get_temp_file_names() {
25 std::pair<std::string, std::string> names;
26 names.first = get_temp_file_name();
27
28 // Create the file so the next call to `get_temp_file_name()` doesn't
29 // return the same file.
30 std::FILE *fd1 = std::fopen(names.first.c_str(), "w");
31
32 names.second = get_temp_file_name();
33 assert(names.first != names.second);
34
35 std::fclose(fd1);
36 std::remove(names.first.c_str());
37
38 return names;
39 }
40
main(int,char **)41 int main(int, char**)
42 {
43 std::pair<std::string, std::string> temp_files = get_temp_file_names();
44 std::string& temp1 = temp_files.first;
45 std::string& temp2 = temp_files.second;
46 assert(temp1 != temp2);
47 {
48 std::fstream fs1(temp1.c_str(), std::ios_base::in | std::ios_base::out
49 | std::ios_base::trunc);
50 std::fstream fs2(temp2.c_str(), std::ios_base::in | std::ios_base::out
51 | std::ios_base::trunc);
52 fs1 << 1 << ' ' << 2;
53 fs2 << 2 << ' ' << 1;
54 fs1.seekg(0);
55 swap(fs1, fs2);
56 fs1.seekg(0);
57 int i;
58 fs1 >> i;
59 assert(i == 2);
60 fs1 >> i;
61 assert(i == 1);
62 i = 0;
63 fs2 >> i;
64 assert(i == 1);
65 fs2 >> i;
66 assert(i == 2);
67 }
68 std::remove(temp1.c_str());
69 std::remove(temp2.c_str());
70 {
71 std::wfstream fs1(temp1.c_str(), std::ios_base::in | std::ios_base::out
72 | std::ios_base::trunc);
73 std::wfstream fs2(temp2.c_str(), std::ios_base::in | std::ios_base::out
74 | std::ios_base::trunc);
75 fs1 << 1 << ' ' << 2;
76 fs2 << 2 << ' ' << 1;
77 fs1.seekg(0);
78 swap(fs1, fs2);
79 fs1.seekg(0);
80 int i;
81 fs1 >> i;
82 assert(i == 2);
83 fs1 >> i;
84 assert(i == 1);
85 i = 0;
86 fs2 >> i;
87 assert(i == 1);
88 fs2 >> i;
89 assert(i == 2);
90 }
91 std::remove(temp1.c_str());
92 std::remove(temp2.c_str());
93
94 return 0;
95 }
96