From d0a0e3bdef4aeefd41675790a20d6afe6a9f26e9 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 12 Jun 2023 20:36:16 +0300 Subject: [PATCH] Userspace: Add u8sum This program caluculates the sum of bytes in file mod 256 --- userspace/CMakeLists.txt | 1 + userspace/u8sum/CMakeLists.txt | 16 ++++++++++++++++ userspace/u8sum/main.cpp | 29 +++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 userspace/u8sum/CMakeLists.txt create mode 100644 userspace/u8sum/main.cpp diff --git a/userspace/CMakeLists.txt b/userspace/CMakeLists.txt index 0ce1bf16..efefef74 100644 --- a/userspace/CMakeLists.txt +++ b/userspace/CMakeLists.txt @@ -10,6 +10,7 @@ set(USERSPACE_PROJECTS ls Shell test + u8sum yes ) diff --git a/userspace/u8sum/CMakeLists.txt b/userspace/u8sum/CMakeLists.txt new file mode 100644 index 00000000..20fa7354 --- /dev/null +++ b/userspace/u8sum/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.26) + +project(u8sum CXX) + +set(SOURCES + main.cpp +) + +add_executable(u8sum ${SOURCES}) +target_compile_options(u8sum PUBLIC -O2 -g) +target_link_libraries(u8sum PUBLIC libc) + +add_custom_target(u8sum-install + COMMAND cp ${CMAKE_CURRENT_BINARY_DIR}/u8sum ${BANAN_BIN}/ + DEPENDS u8sum +) diff --git a/userspace/u8sum/main.cpp b/userspace/u8sum/main.cpp new file mode 100644 index 00000000..c33a7ad8 --- /dev/null +++ b/userspace/u8sum/main.cpp @@ -0,0 +1,29 @@ +#include +#include + +int main(int argc, char** argv) +{ + for (int i = 1; i < argc; i++) + { + FILE* fp = fopen(argv[i], "r"); + if (fp == nullptr) + { + perror("nullptr"); + continue; + } + + uint8_t sum = 0; + + uint8_t buffer[1024]; + while (size_t ret = fread(buffer, 1, sizeof(buffer), fp)) + for (int j = 0; j < ret; j++) + sum += buffer[j]; + + if (ferror(fp)) + perror("fread"); + else + printf("%s: %02x\n", argv[i], sum); + + fclose(fp); + } +}