Um utilitário para trocar dois arquivos

Aug 17 2020

Embora nunca tenha tido que trocar dois arquivos, sempre me perguntei se havia um comando para trocar dois arquivos e recentemente decidi ver se havia um. Eventualmente, descobri que não havia um e, como resultado, decidi criar um.

Aqui está o código:main.cc

#include <iostream>
#include <filesystem>
#include <cstring>
#include <cassert>

static auto print_help() -> void {
    std::cout << "Usage: swap [file1] [file2]\n";
    std::cout << "swaps the contents of file1 and file2\n";
    std::cout << "use swap --help to print this message\n";
}

static auto validate_files(const std::filesystem::path& file1_path, const std::filesystem::path& file2_path) -> void {
    {
        /* check if file exists */
        const auto file1_exists = std::filesystem::exists(file1_path);
        const auto file2_exists = std::filesystem::exists(file2_path);
        const auto exists = file1_exists && file2_exists;


        if (!exists) {
            if (!file1_exists) std::cerr << "cannot find file " << file1_path << '\n';
            if (!file2_exists) std::cerr << "cannot find file " << file2_path << '\n';
            exit(EXIT_FAILURE);
        }
    }

    {
        if (file1_path == file2_path) {
            std::cerr << "swaping the same two files does nothing\n";
            exit(EXIT_SUCCESS);
        }
    }
}

static auto get_temp_filename(char* template_name) -> void {
    /* tmpnam_s does not work on linux */
#if defined(WIN32) || defined(_WIN32)
    errno_t err = tmpnam_s(template_name, L_tmpnam);
    assert(!err);
#else
    int err = mkstemp(template_name);
    assert(err != -1);
#endif
}

int main(int argc, char** argv) {
    std::ios::sync_with_stdio(false);
    switch (argc) {
        case 2: {
            /* convert the second arg to upper case */
            std::transform(argv[1],
                argv[1] + strlen(argv[1]),
                argv[1],
                ::toupper);
            if (!strcmp(argv[1], "--HELP")) {
                print_help();
                return EXIT_SUCCESS;
            }
            else {
                std::cerr << "Invalid args see --help for usage\n";
                return EXIT_FAILURE;
            }
        }
        case 3:
            break;
        default: {
            std::cerr << "Invalid args see --help for usage\n";
            return EXIT_FAILURE;
        }
    }
    const auto file1_path = std::filesystem::path{ argv[1] };
    const auto file2_path = std::filesystem::path{ argv[2] };


    validate_files(file1_path, file2_path);
    char temp_filename[L_tmpnam] = "XXXXXX";
    get_temp_filename(temp_filename);
    const auto temp_filepath = std::filesystem::path{ temp_filename };
    /* move-swap the files instead of copy-swaping */
    /* renaming a file is the same as moving it */
    std::filesystem::rename(file1_path, temp_filepath);
    std::filesystem::rename(file2_path, file1_path);
    std::filesystem::rename(temp_filepath, file2_path);
}

Aqui está um exemplo de uso:

swap doc1.txt doc2.txt

Respostas

11 vnp Aug 17 2020 at 06:22
  • file1_path == file2_pathcertamente informa que os caminhos se referem ao mesmo arquivo. No entanto, mesmo que file1_path != file2_patheles ainda possam se referir ao mesmo arquivo.

  • file1_exists = std::filesystem::exists(file1_path);introduz uma condição de corrida TOC-TOU. O arquivo pode existir no momento do teste, mas desaparecer no momento do uso. Veja o próximo marcador.

  • std::filesystem::renamepode falhar. Você chama isso de três vezes. Se a segunda ou terceira chamada falhar (com uma exceção!), o sistema de arquivos terminará não exatamente no estado esperado. Use uma noexceptsobrecarga, teste error_codeapós cada chamada e reverta todas as ações anteriores à falha. Isso também cuidaria automaticamente dos caminhos inexistentes.

  • Não assert. É bom apenas para detectar bugs, não os problemas de tempo de execução. No código de produção (compilado com -DNDEBUG) ele não faz nada e seu programa não detectaria uma mkstempfalha.

  • O programa silenciosamente não faz nada se for chamado com, digamos, 4 argumentos. Também exige muito esforço se for chamado com 2 argumentos. Ligar print_help()a qualquer hora argc != 3é muito mais simples.

1 Razzle Aug 28 2020 at 20:26

Eu estou supondo que a 'pergunta' está pedindo críticas de código. Se eu estiver errado sobre isso, por favor, seja gentil .. LOL

Minha primeira impressão é a legibilidade de main. A chave de análise de argumentos grandes está escondendo a lógica mais importante.

Talvez facilite a leitura (objetos de string e comparações que não diferenciam maiúsculas de minúsculas?). Melhor ainda: relegue para um método auxiliar de limpeza.

(Também: às vezes simplista é bom. Se você não receber dois argumentos de nome de arquivo, poderá cuspir imediatamente a ajuda, em vez de dizer ao usuário para pedir ajuda explicitamente.)