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 // void swap(basic_fstream& rhs); 15 16 #include <fstream> 17 #include <utility> 18 #include <cassert> 19 #include "test_macros.h" 20 #include "platform_support.h" 21 22 std::pair<std::string, std::string> get_temp_file_names() { 23 std::pair<std::string, std::string> names; 24 names.first = get_temp_file_name(); 25 26 // Create the file so the next call to `get_temp_file_name()` doesn't 27 // return the same file. 28 std::FILE *fd1 = std::fopen(names.first.c_str(), "w"); 29 30 names.second = get_temp_file_name(); 31 assert(names.first != names.second); 32 33 std::fclose(fd1); 34 std::remove(names.first.c_str()); 35 36 return names; 37 } 38 39 int main(int, char**) 40 { 41 std::pair<std::string, std::string> temp_files = get_temp_file_names(); 42 std::string& temp1 = temp_files.first; 43 std::string& temp2 = temp_files.second; 44 assert(temp1 != temp2); 45 { 46 std::fstream fs1(temp1.c_str(), std::ios_base::in | std::ios_base::out 47 | std::ios_base::trunc); 48 std::fstream fs2(temp2.c_str(), std::ios_base::in | std::ios_base::out 49 | std::ios_base::trunc); 50 fs1 << 1 << ' ' << 2; 51 fs2 << 2 << ' ' << 1; 52 fs1.seekg(0); 53 fs1.swap(fs2); 54 fs1.seekg(0); 55 int i; 56 fs1 >> i; 57 assert(i == 2); 58 fs1 >> i; 59 assert(i == 1); 60 i = 0; 61 fs2 >> i; 62 assert(i == 1); 63 fs2 >> i; 64 assert(i == 2); 65 } 66 std::remove(temp1.c_str()); 67 std::remove(temp2.c_str()); 68 69 #ifndef TEST_HAS_NO_WIDE_CHARACTERS 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 fs1.swap(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 #endif 94 95 return 0; 96 } 97