最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c - Bash script not counting textbinary files correctly in WSL, despite individual file identification working - Stack Overflow

programmeradmin2浏览0评论

I have been trying to fix a problem in my code but I don´t know what I can even do anymore.

I'm working on a Bash script in WSL (Windows Subsystem for Linux) that's supposed to count the number of text and binary files within a specified directory and its subdirectories.

I have a C program (isText) that correctly identifies if a given file is text (outputs '1') or binary (outputs '0'). When I run this program directly on my test files, it works as expected.

My Bash script uses find to locate all regular files and then iterates through them, calling the isText program to determine the file type. The script captures the output of isText and uses if/elif conditions to increment counters for text and binary files. I've added extensive debugging output to the script, and it shows that for each file, isText is returning the correct type ('0' or '1').

However, despite this correct individual file identification, the final counts for binary and text files always remain zero. I've tried various debugging steps, including ensuring correct file paths, removing whitespace from the output of isText, and comparing the output as strings in the Bash script.

The script and the C program seem logically correct, and the debugging output confirms the individual file type detection. I suspect there might be a subtle issue with how the Bash script is interacting with the output of the C program within the loop or how variables are being updated in my specific WSL environment.

I'm looking for any insights or suggestions on why the counters might not be incrementing despite the correct individual file type detection.

I will put my codes here just in case.

C

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define CHUNK_SIZE 4096

int is_text_file(const char *filename) {
    FILE *file = fopen(filename, "rb");
    if (file == NULL) {
        fprintf(stderr, "Erro: não foi possível abrir o arquivo '%s'.\n", filename);
        return -1;  // Indica erro ao abrir arquivo
    }

    unsigned char buffer[CHUNK_SIZE];
    size_t bytes_read;

    while ((bytes_read = fread(buffer, 1, CHUNK_SIZE, file)) > 0) {
        for (size_t i = 0; i < bytes_read; i++) {
            unsigned char byte = buffer[i];
            if (byte != 9 && byte != 10 && byte != 13 && !(byte >= 32 && byte <= 126) && !(byte >= 160 && byte <= 255)) {
                fclose(file);
                return 0; // Arquivo binário (byte inválido encontrado)
            }
        }
    }

    fclose(file);
    return 1;  // Arquivo de texto
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Uso: %s <nome_do_arquivo>\n", argv[0]);
        return 1;
    }

    int tipo = is_text_file(argv[1]);

    if (tipo == -1) {
        return 1; // Erro ao abrir arquivo
    } else if (tipo == 0) {
        printf("0\n"); // Arquivo binário
    } else {
        printf("1\n"); // Arquivo de texto
    }

    return 0;
}

Bash

#!/bin/bash

# Compila o programa isText se o executável não existir
if [ ! -x "isText" ]; then
    gcc isText.c -o isText || {
        echo "Erro ao compilar isText. Saindo."
        exit 1
    }
fi

# Verifica se um diretório foi passado como argumento
if [ -z "$1" ]; then
    echo "Uso: $0 <diretorio>"
    exit 1
fi

main_directory="$1"
text_count=0
binary_count=0

# Encontra todos os arquivos regulares na sub-árvore do diretório especificado
while IFS= read -r -d $'\0' file; do
    echo "Analisando o arquivo: \"$file\""
    file_type=$( ("./isText" "$file") | tr -d '[:space:]' )
    echo "Tipo detectado para \"$file\": [$file_type]"
    if [ "$file_type" = "1" ]; then
        ((text_count++))
        echo "\"$file\" foi contado como TEXTO"
    elif [ "$file_type" = "0" ]; then
        ((binary_count++))
        echo "\"$file\" foi contado como BINÁRIO"
    else
        echo "Erro desconhecido ao analisar \"$file\""
    fi
done < <(find "$main_directory" -type f -print0)

echo "number of binary files: $binary_count"
echo "number of text files: $text_count"

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论