File: dedup.cpp 1 /* 2 The MIT License (MIT) 3 4 Copyright © 2020-2025 pacman64 5 6 Permission is hereby granted, free of charge, to any person obtaining a copy of 7 this software and associated documentation files (the “Software”), to deal 8 in the Software without restriction, including without limitation the rights to 9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 10 of the Software, and to permit persons to whom the Software is furnished to do 11 so, subject to the following conditions: 12 13 The above copyright notice and this permission notice shall be included in all 14 copies or substantial portions of the Software. 15 16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 SOFTWARE. 23 */ 24 25 /* 26 dedup [files...] 27 28 DEDUPlicate lines, emitting each distinct line from standard-input only once. 29 */ 30 31 // g++ -Wall -O2 -s -o dedup dedup.cpp 32 33 #include <fstream> 34 #include <iostream> 35 #include <set> 36 #include <string> 37 38 using namespace std; 39 40 void handle_input(istream& in, string& line, set<string>& seen) { 41 while (getline(in, line)) { 42 if (seen.find(line) != seen.end()) { 43 continue; 44 } 45 46 // cout.write(line.c_str(), line.size()); 47 // cout.write("\n", 1); 48 // cout.flush(); 49 cout << line << endl; 50 51 if (cout.eof()) { 52 break; 53 } 54 55 seen.insert(line); 56 } 57 } 58 59 bool handle_file(const char* path, string& line, set<string>& seen) { 60 ifstream f(path); 61 if (!f.is_open()) { 62 const auto msg = "can't open file named"; 63 cerr << "\x1b[31m" << msg << " '" << path << "'\x1b[0m" << endl; 64 return false; 65 } 66 67 handle_input(f, line, seen); 68 return true; 69 } 70 71 int main(int argc, char** argv) { 72 string line; 73 set<string> seen; 74 75 cin.tie(NULL); 76 ios_base::sync_with_stdio(false); 77 78 size_t errors = 0; 79 for (int i = 1; i < argc && !cout.eof(); i++) { 80 if (argv[i][0] == '-' && argv[i][1] == 0) { 81 handle_input(cin, line, seen); 82 continue; 83 } 84 if (!handle_file(argv[i], line, seen)) { 85 errors++; 86 } 87 } 88 89 if (argc < 2) { 90 handle_input(cin, line, seen); 91 } 92 return errors; 93 }