在CentOS系統中,可以使用readdir
函數來讀取目錄中的文件和子目錄。如果你想要對讀取到的文件進行加密和解密,你可以使用OpenSSL庫來實現。以下是一個簡單的示例,展示了如何在CentOS中使用readdir
函數以及OpenSSL庫來實現文件的加密和解密。
首先,確保已經安裝了OpenSSL庫。在CentOS終端中運行以下命令來安裝:
sudo yum install openssl-devel
接下來,創建一個名為encrypt_decrypt.c
的C文件,并添加以下代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#define KEY_SIZE 32
#define IV_SIZE 16
void encrypt_file(const char *input_file, const char *output_file) {
// 加密邏輯
}
void decrypt_file(const char *input_file, const char *output_file) {
// 解密邏輯
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
const char *dir_path = argv[1];
DIR *dir = opendir(dir_path);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // 只處理普通文件
char input_file[PATH_MAX], output_file[PATH_MAX];
snprintf(input_file, sizeof(input_file), "%s/%s", dir_path, entry->d_name);
snprintf(output_file, sizeof(output_file), "%s/encrypted_%s", dir_path, entry->d_name);
encrypt_file(input_file, output_file);
printf("Encrypted file: %s\n", output_file);
char decrypted_file[PATH_MAX];
snprintf(decrypted_file, sizeof(decrypted_file), "%s/decrypted_%s", dir_path, entry->d_name);
decrypt_file(output_file, decrypted_file);
printf("Decrypted file: %s\n", decrypted_file);
}
}
closedir(dir);
return 0;
}
在上面的代碼中,我們定義了兩個函數encrypt_file
和decrypt_file
,分別用于加密和解密文件。你需要使用OpenSSL庫來實現這兩個函數的邏輯。你可以參考OpenSSL文檔來了解如何使用AES加密算法。
編譯這個程序:
gcc encrypt_decrypt.c -o encrypt_decrypt -lcrypto
運行程序:
./encrypt_decrypt /path/to/directory
程序將會遍歷指定目錄中的所有文件,并對每個文件進行加密和解密操作。
請注意,這個示例僅用于演示目的,實際應用中可能需要更多的錯誤處理和優化。在使用加密和解密功能時,請確保正確處理密鑰和初始化向量(IV),并妥善保管它們。