1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // <fstream> 11 12 // template <class charT, class traits = char_traits<charT> > 13 // class basic_fstream 14 15 // void swap(basic_fstream& rhs); 16 17 #include <fstream> 18 #include <utility> 19 #include <cassert> 20 #include "platform_support.h" 21 get_temp_file_names()22std::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 main()39int main() 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 std::wfstream fs1(temp1.c_str(), std::ios_base::in | std::ios_base::out 70 | std::ios_base::trunc); 71 std::wfstream fs2(temp2.c_str(), std::ios_base::in | std::ios_base::out 72 | std::ios_base::trunc); 73 fs1 << 1 << ' ' << 2; 74 fs2 << 2 << ' ' << 1; 75 fs1.seekg(0); 76 fs1.swap(fs2); 77 fs1.seekg(0); 78 int i; 79 fs1 >> i; 80 assert(i == 2); 81 fs1 >> i; 82 assert(i == 1); 83 i = 0; 84 fs2 >> i; 85 assert(i == 1); 86 fs2 >> i; 87 assert(i == 2); 88 } 89 std::remove(temp1.c_str()); 90 std::remove(temp2.c_str()); 91 } 92