DEV Community

Cover image for Copy Files via Command Line with C++
Marcos Oliveira
Marcos Oliveira

Posted on

Copy Files via Command Line with C++

🕸️ Your custom command, simple and fast!


How about the convenience of copying files via the command line? You can quickly create your own command with C++.

See the step-by-step guide below!


Dependencies

Example for distros that use APT as the package manager

Look for corresponding names for your distro.

sudo apt install build-essential libx11-dev libxcb1-dev libpng-dev
Enter fullscreen mode Exit fullscreen mode

Also compile and install clip

git clone https://github.com/dacap/clip
cd clip
cmake . -B build
cmake --build build
sudo cmake --install build
Enter fullscreen mode Exit fullscreen mode

Create the Code

Example: main.cpp

#include <clip.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <memory>

const auto use = [](){
  std::cerr << "Use: xclip++ <file> [file...]\n";
};

class Xclip {
  public:
    Xclip(int argc, char** argv){
      std::ostringstream buffer;

      for (int i = 1; i < argc; ++i) {
        std::ifstream file(argv[i], std::ios::binary);
        if (!file) {
          std::cerr << "Error opening: " << argv[i] << "\n";
          std::exit(1);
        }

        buffer << file.rdbuf();

        if(i + 1 < argc){
          buffer << '\n';
        }
      }

      clip::set_text(buffer.str());
    }
};

int main(int argc, char** argv){
  if(argc < 2){
    use();
    return 1;
  }

  auto xclip = std::make_unique<Xclip>(argc, argv);
}
Enter fullscreen mode Exit fullscreen mode

Compile and Install

g++ main.cpp -o xclip++ -lclip -lxcb -lX11 -lpng -pthread
sudo install -v xclip++ /usr/local/bin/
Enter fullscreen mode Exit fullscreen mode

Use Easily

xclip++ file.txt
# Or multiple files
xclip++ file1.txt file2.md file3.cpp # ...
Enter fullscreen mode Exit fullscreen mode

See also: Copy and Paste via Linux Command Line with xclip

Top comments (0)