1
0
Fork 0
mirror of https://github.com/mfocko/blog.git synced 2025-05-08 12:22:58 +02:00

feat: don't reference FI MU subjects by their codes

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-11-24 16:00:45 +01:00
parent f81d3219e6
commit e1dea0cdbc
Signed by: mfocko
GPG key ID: 7C47D46246790496
232 changed files with 225 additions and 191 deletions

View file

View file

@ -0,0 +1,264 @@
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* If you want to see arrays before and after sorting, uncomment next line */
// #define DEBUG_OUTPUT
/**
* @brief Swaps two elements at given addresses of given size.
* @param left Pointer to the first element.
* @param right Pointer to the second element.
* @param size Size of the memory one element takes.
*/
void swap(void *left, void *right, size_t size)
{
/* TODO */
}
/**
* @brief Get index of biggest element in the array.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
* @param size Size of one element in the array.
* @param comp Comparator that is used to decide ordering of the elements.
* @returns Index of the biggest element given the ordering.
*/
size_t maximum(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
{
/* Pseudocode:
* ===========
* max_index <- 0
* FOR i <- 1 TO n - 1 DO
* IF A[i] > A[max_index] THEN
* max_index <- i
* FI
* OD
* RETURN max_index
*/
/* TODO */
return 0;
}
/**
* @brief Sort array in-situ using select-sort.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
* @param size Size of one element in the array.
* @param comp Comparator that is used to decide ordering of the elements.
*/
void select_sort(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
{
/* Pseudocode:
* ===========
* FOR i <- n - 1 DOWNTO 1 DO
* j <- MAXIMUM(A, i + 1)
* SWAP(A, i, j)
* OD
*/
/* TODO */
}
/**
* @brief Compares two integers that are given through generic pointers.
* @param x Pointer to the integer x.
* @param y Pointer to the integer y.
* @returns 0 if x == y, <0 if x < y, >0 otherwise.
*/
static int int_comparator(const void *x, const void *y)
{
/* TODO */
return 1;
}
/**
* @brief Compares two characters by ASCII value.
* @param x Pointer to the character x.
* @param y Pointer to the character y.
* @returns 0 if x == y, <0 if x < y, >0 otherwise.
*/
static int char_comparator(const void *x, const void *y)
{
char x_value = *(const char *) x;
char y_value = *(const char *) y;
return x_value - y_value;
}
/**
* @brief Compares two characters by ASCII value in a reversed order.
* @param x Pointer to the character x.
* @param y Pointer to the character y.
* @returns 0 if x == y, >0 if x < y, <0 otherwise.
*/
static int char_reversed_comparator(const void *x, const void *y)
{
char x_value = *(const char *) x;
char y_value = *(const char *) y;
return y_value - x_value;
}
// #pragma region TESTS
/**
* @brief Check if array is sorted.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
* @param size Size of one element in the array.
* @param comp Comparator that is used to decide ordering of the elements.
*/
static void check_if_sorted(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
{
char *left = ptr;
char *right = (char *) ptr + size;
for (size_t i = 0; i < count - 1; i++) {
assert(comp(left, right) <= 0);
left += size;
right += size;
}
}
#ifdef DEBUG_OUTPUT
/**
* @brief Print numbers from an array.
* @param array Pointer to the first element of the array.
* @param count Count of the elements in the array.
*/
static void print_numbers(int *array, size_t count)
{
for (size_t i = 0; i < count; i++) {
printf(" %d", array[i]);
}
}
#endif
/**
* @brief Run some basic tests on integer arrays.
*/
static void check_int_arrays()
{
/* You are free to add any other examples you like, in case you want to add
* array with more than 10 elements, please adjust the size.
*/
size_t examples_count = 5;
int examples[][10] = {
{ -1, 50, -10, 20, 30, 0, -100 },
{ -100, 0, 30, 20, -10, 50, -1 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
{ -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }
};
printf("[TEST] Integer arrays\n");
for (size_t i = 0; i < examples_count; i++) {
size_t count = sizeof(examples[i]) / sizeof(int);
#ifdef DEBUG_OUTPUT
printf("Before sorting:");
print_numbers(examples[i], count);
putchar('\n');
#endif
select_sort(examples[i], count, sizeof(int), int_comparator);
#ifdef DEBUG_OUTPUT
printf("After sorting:");
print_numbers(examples[i], count);
printf("\n\n");
#endif
check_if_sorted(examples[i], count, sizeof(int), int_comparator);
}
printf("[PASS] Tests passed.\n\n");
}
/**
* @brief Run some basic tests on strings. Also with reversed ordering.
*/
static void check_char_arrays()
{
#define MAX_SIZE 20
/* You are free to add any other examples you like, in case you want to add
* strings with more than 10 characters, please adjust the size.
* mind the terminator ;)
*/
const size_t examples_count = 5;
char examples[][MAX_SIZE] = {
"Hello World!",
"hi",
"aloha",
"LET US SORT",
"LeT uS sOrT"
};
printf("[TEST] Char arrays\n");
for (size_t i = 0; i < examples_count; i++) {
size_t count = strlen(examples[i]);
char temp_array[MAX_SIZE];
strncpy(temp_array, examples[i], MAX_SIZE);
select_sort(temp_array, count, 1, char_comparator);
#ifdef DEBUG_OUTPUT
printf("Before sorting: \"%s\"\n", examples[i]);
printf("After sorting: \"%s\"\n\n", temp_array);
#endif
check_if_sorted(temp_array, count, 1, char_comparator);
}
printf("[PASS] Tests passed.\n\n");
printf("[TEST] Char arrays reversed\n");
for (size_t i = 0; i < examples_count; i++) {
size_t count = strlen(examples[i]);
char temp_array[MAX_SIZE];
strncpy(temp_array, examples[i], MAX_SIZE);
select_sort(temp_array, count, 1, char_reversed_comparator);
#ifdef DEBUG_OUTPUT
printf("Before sorting: \"%s\"\n", examples[i]);
printf("After sorting: \"%s\"\n\n", temp_array);
#endif
check_if_sorted(temp_array, count, 1, char_reversed_comparator);
}
printf("[PASS] Tests passed.\n\n");
#undef MAX_SIZE
}
static void annotate(const char *description, bool result)
{
printf("[TEST] %s\n", description);
assert(result);
printf("[PASS] Test passed.\n\n");
}
static void check_int_comparator()
{
int a = 5, b = -10, c = -10;
annotate("Test comparator for: a > b", int_comparator(&a, &b) > 0);
annotate("Test comparator for: b < a", int_comparator(&b, &a) < 0);
annotate("Test comparator for: b = c", int_comparator(&b, &c) == 0);
annotate("Test comparator for: a = a", int_comparator(&a, &a) == 0);
annotate("Test comparator for: b = b", int_comparator(&b, &b) == 0);
annotate("Test comparator for: c = c", int_comparator(&c, &c) == 0);
}
// #pragma endregion TESTS
int main(void)
{
/* Neither of those tests check for bad behaviour, like overwriting array
* with elements satisfying ordering. **I** check those :scheming:
*/
check_int_comparator();
check_int_arrays();
check_char_arrays();
return 0;
}

View file

@ -0,0 +1,141 @@
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* If you want to see arrays before and after sorting, uncomment next line */
// #define DEBUG_OUTPUT
/**
* @brief Swaps two elements at given addresses.
* @param left Pointer to the first element.
* @param right Pointer to the second element.
*/
void swap(int *left, int *right)
{
/* TODO */
}
/**
* @brief Get index of biggest element in the array.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
* @returns Index of the biggest element given the ordering.
*/
size_t maximum(int *ptr, size_t count)
{
/* Pseudocode:
* ===========
* max_index <- 0
* FOR i <- 1 TO n - 1 DO
* IF A[i] > A[max_index] THEN
* max_index <- i
* FI
* OD
* RETURN max_index
*/
/* TODO */
return 0;
}
/**
* @brief Sort array in-situ using select-sort.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
*/
void select_sort(int *ptr, size_t count)
{
/* Pseudocode:
* ===========
* FOR i <- n - 1 DOWNTO 1 DO
* j <- MAXIMUM(A, i + 1)
* SWAP(A, i, j)
* OD
*/
/* TODO */
}
// #pragma region TESTS
/**
* @brief Check if array is sorted.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
*/
static void check_if_sorted(int *ptr, size_t count)
{
int *left = ptr;
int *right = ptr + 1;
for (size_t i = 0; i < count - 1; i++) {
assert(*left <= *right);
left++;
right++;
}
}
#ifdef DEBUG_OUTPUT
/**
* @brief Print numbers from an array.
* @param array Pointer to the first element of the array.
* @param count Count of the elements in the array.
*/
static void print_numbers(int *array, size_t count)
{
for (size_t i = 0; i < count; i++) {
printf(" %d", array[i]);
}
}
#endif
/**
* @brief Run some basic tests on integer arrays.
*/
static void check_int_arrays()
{
/* You are free to add any other examples you like, in case you want to add
* array with more than 10 elements, please adjust the size.
*/
size_t examples_count = 5;
int examples[][10] = {
{ -1, 50, -10, 20, 30, 0, -100 },
{ -100, 0, 30, 20, -10, 50, -1 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
{ -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }
};
printf("[TEST] Integer arrays\n");
for (size_t i = 0; i < examples_count; i++) {
size_t count = sizeof(examples[i]) / sizeof(int);
#ifdef DEBUG_OUTPUT
printf("Before sorting:");
print_numbers(examples[i], count);
putchar('\n');
#endif
select_sort(examples[i], count);
#ifdef DEBUG_OUTPUT
printf("After sorting:");
print_numbers(examples[i], count);
printf("\n\n");
#endif
check_if_sorted(examples[i], count);
}
printf("[PASS] Tests passed.\n\n");
}
// #pragma endregion TESTS
int main(void)
{
/* Neither of those tests check for bad behaviour, like overwriting array
* with elements satisfying ordering. **I** check those :scheming:
*/
check_int_arrays();
return 0;
}

View file

@ -0,0 +1,12 @@
CC=gcc
CFLAGS=-std=c99 -Wall -Wextra -Werror -Wpedantic
main:
$(CC) $(CFLAGS) main.c -o main
main_light:
$(CC) $(CFLAGS) main_light.c -o main_light
check: main main_light
valgrind ./main
valgrind ./main_light

View file

View file

@ -0,0 +1,25 @@
cmake_minimum_required(VERSION 3.0)
# Project configuration
project(seminar04-bonus-maze)
set(SOURCES maze.h maze.c)
set(EXECUTABLE maze)
# Executable
add_executable(maze ${SOURCES} main.c)
add_executable(test_maze ${SOURCES} cut.h test_maze.c)
# Configure compiler warnings
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
# using regular Clang, AppleClang or GCC
# Strongly suggested: neable -Werror
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
# using Visual Studio C++
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
endif()
if(MINGW)
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
endif()

View file

@ -0,0 +1,8 @@
#include "maze.h"
#include <stdio.h>
int main(void)
{
return 0;
}

View file

@ -0,0 +1,84 @@
#include "maze.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
/**
* @brief Checks if pointer points inside the memory specified by upper and lower
* bound.
* @param first Start of the allocated memory.
* @param last First address that is not included in the allocated memory.
* @param pos Pointer to memory.
* @returns <code>true</code> if pos points to the memory [first, last), <code>
* false</code> otherwise.
*/
static bool within_bounds(const char *first, const char *last, const char *pos)
{
/* TODO */
}
/**
* @brief Sets 2D coordinates of the pointer.
* @param map Start of the 2D memory.
* @param position Pointer to the map.
* @param width Width of one row of the map.
* @param row Output variable where the row is set.
* @param col Output variable where the column is set.
*/
static void set_coordinates(const char *map, char *position, size_t width, size_t *row, size_t *col)
{
/* TODO */
}
/**
* @brief Checks if indices are within bounds of the 2D map.
* @param width Width of the map.
* @param height Height of the map.
* @param row Row to be checked.
* @param col Column to be checked.
* @returns <code>true</code> if row,col are within bounds of the map,.<code>false
* </code> otherwise.
*/
static bool within_bounds_by_index(size_t width, size_t height, size_t row, size_t col)
{
/* TODO */
}
void print_maze(const char *map, char *position, char direction, size_t width, size_t height)
{
printf("Maze:\n");
for (size_t row = 0; row < height; row++) {
for (size_t col = 0; col < width; col++) {
const char *current = &map[row * width + col];
if (current == position) {
switch (direction) {
case '^':
putchar('N');
break;
case 'v':
putchar('S');
break;
case '>':
putchar('E');
break;
case '<':
putchar('W');
break;
}
continue;
}
putchar(*current);
}
putchar('\n');
}
putchar('\n');
}
enum end_state_t walk(const char *map, char *position, char direction, size_t width, size_t height)
{
/* TODO */
return NONE;
}

View file

@ -0,0 +1,33 @@
#include <stdlib.h>
enum end_state_t
{
NONE,
FOUND_KEY,
FOUND_TREASURE,
OUT_OF_BOUNDS,
INFINITE_LOOP,
};
/**
* @brief Prints maze and the robot within it.
* @param map Map of the maze.
* @param position Current position of the robot.
* @param direction Direction the robot is facing, one of "^v<>".
* @param width Width of the map.
* @param height Height of the map.
*/
void print_maze(const char *map, char *position, char direction, size_t width, size_t height);
/**
* @brief Get end state of the robot after his walk.
* @param map Map of the maze.
* @param position Initial position of the robot in the maze.
* @param direction Direction the robot is facing at the beginning. You can assume
* correctness of this value.
* @param width Width of the maze. You can assume correctness of this value.
* @param height Height of the maze. You can assume correctness of this value.
* @returns End state of the robot after his walk is finished or has been terminated
* manually.
*/
enum end_state_t walk(const char *map, char *position, char direction, size_t width, size_t height);

View file

@ -0,0 +1,246 @@
#include "maze.h"
#define CUT_MAIN
#include "cut.h"
static void check_result(char *map, size_t position, char direction, size_t width, size_t height, enum end_state_t expected)
{
enum end_state_t state = walk(map, &map[position], direction, width, height);
ASSERT(state == expected);
}
TEST(basic)
{
SUBTEST(spawns_on_treasure)
{
check_result(("T."
".."),
0,
'>',
2,
2,
FOUND_TREASURE);
}
SUBTEST(spawns_on_key)
{
check_result(("K."
".."),
0,
'^',
2,
2,
FOUND_KEY);
}
SUBTEST(spawns_on_treasure_in_middle)
{
check_result(("..."
".T."
"..."),
4,
'v',
3,
3,
FOUND_TREASURE);
}
}
TEST(some_walking)
{
SUBTEST(straight_up)
{
check_result((".T."
"..."
"..."),
7,
'^',
3,
3,
FOUND_TREASURE);
}
SUBTEST(down)
{
check_result(("..........................T"), 7, 'v', 1, 27, FOUND_TREASURE);
}
SUBTEST(to_right)
{
check_result(("..........................K"), 2, '>', 27, 1, FOUND_KEY);
}
SUBTEST(to_left)
{
check_result(("K.........................."), 15, '<', 27, 1, FOUND_KEY);
}
}
TEST(follows_directions)
{
SUBTEST(basic)
{
check_result((">..v"
"...."
"...K"
"^..<"),
12,
'>',
4,
4,
FOUND_KEY);
}
SUBTEST(no_way_to_avoid)
{
const char *directions = "<>^v";
for (size_t row = 0; row < 5; row++) {
for (size_t col = 0; col < 5; col++) {
for (size_t dir = 0; dir < 4; dir++) {
check_result((">>>>v"
"^>>vv"
"^^T<v"
"^^<<<"
"^<<<<"),
row * 5 + col,
directions[dir],
5,
5,
FOUND_TREASURE);
}
}
}
}
}
TEST(follows_directions_even_to_doom)
{
SUBTEST(to_right)
{
check_result((".>.."
"^KTK"
".TvT"
"...<"),
1,
'>',
4,
4,
OUT_OF_BOUNDS);
}
SUBTEST(to_up)
{
check_result((".>.."
"^KTK"
".TvT"
"...<"),
4,
'>',
4,
4,
OUT_OF_BOUNDS);
}
SUBTEST(to_down)
{
check_result((".>.."
"^KTK"
".TvT"
"...<"),
10,
'>',
4,
4,
OUT_OF_BOUNDS);
}
SUBTEST(to_left)
{
check_result((".>.."
"^KTK"
".TvT"
"...<"),
15,
'>',
4,
4,
OUT_OF_BOUNDS);
}
}
TEST(mean)
{
SUBTEST(out_of_bounds_at_the_beginning)
{
check_result((".."
".."),
4,
'v',
2,
2,
OUT_OF_BOUNDS);
check_result((".."
".."),
5,
'v',
2,
2,
OUT_OF_BOUNDS);
check_result((".."
".."),
(size_t) -1,
'v',
2,
2,
OUT_OF_BOUNDS);
check_result((">T<"
"..."
"^.^"),
10,
'^',
3,
3,
OUT_OF_BOUNDS);
}
}
TEST(infinite_bonus)
{
SUBTEST(easy)
{
check_result((">.v"
"..."
"^.<"),
0,
'v',
3,
3,
INFINITE_LOOP);
}
SUBTEST(medium)
{
check_result((">v"
"^<"),
2,
'v',
2,
2,
INFINITE_LOOP);
}
SUBTEST(hard)
{
check_result(("v.v"
"..."
"^.^"),
0,
'>',
3,
3,
INFINITE_LOOP);
}
SUBTEST(harder)
{
check_result((">.v.."
"....."
"^...<"
"....."
"..>.^"),
4,
'v',
5,
5,
INFINITE_LOOP);
}
}

View file

View file

@ -0,0 +1,25 @@
cmake_minimum_required(VERSION 3.0)
# Project configuration
project(seminar05-06-bonus-bmp)
set(SOURCES bmp.h bmp.c)
set(EXECUTABLE bmp)
# Executable
add_executable(bmp ${SOURCES} main.c)
add_executable(test_bmp ${SOURCES} cut.h test_bmp.c)
# Configure compiler warnings
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
# using regular Clang, AppleClang or GCC
# Strongly suggested: neable -Werror
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
# using Visual Studio C++
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
endif()
if(MINGW)
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
endif()

View file

@ -0,0 +1,153 @@
#include "bmp.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#define UNUSED(var) ((void) (var))
/**
* Return reversed string.
*
* Function returns a pointer to the reversed string, which has been created
* from the input parameter. If the input string is NULL or memory could not be
* allocated, function returns NULL.
*
* @param text input string
* @return reversed representation of input string, or NULL, if the string could
* not be created.
*/
char *reverse(const char *text)
{
/* TODO */
UNUSED(text);
return NULL;
}
/**
* @brief Checks if key is valid.
* @param key String that is used as a key
* @returns true, if key is valid; false otherwise
*/
static bool check_key(const char *key)
{
/* TODO */
UNUSED(key);
return false;
}
/**
* Function for encrypting the given plaintext by applying the Vigenère cipher.
*
* @param key Pointer to a string representing the key which will be used
* for encrypting the plaintext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text Pointer to a string representing the plaintext to be
* encrypted.
* @return the address of a copy of the ciphertext encrypted by the Vigenère
* cipher, or NULL if the encryption was not successful.
*/
char *vigenere_encrypt(const char *key, const char *text)
{
/* TODO */
UNUSED(key);
UNUSED(text);
return NULL;
}
/**
* Function for decrypting the given ciphertext by applying the Vigenère cipher.
*
* @param key Pointer to a string representing the key which has been used
* for encrypting the ciphertext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text Pointer to a string representing the ciphertext to be
* decrypted.
* @return the address of a copy of the plaintext decrypted by the Vigenère
* cipher, or NULL if the decryption was not successful.
*/
char *vigenere_decrypt(const char *key, const char *text)
{
/* TODO */
UNUSED(key);
UNUSED(text);
return NULL;
}
/**
* Function for bitwise encryption according to the following process:
* The character about to be encrypted is divided in half (4 bits + 4 bits).
* Subsequently, the bits in the left half are divided into two pairs and the
* values inside each pair are swapped. The four bits created by this way are
* then used in a bitwise XOR operation with the remaining 4 bits.
*
* @param text String representing the plaintext to be encrypted.
* @return a pointer to a newly created string containing the ciphertext
* produced by encrypting the plaintext, or NULL if the encryption was not
* successful.
*/
unsigned char *bit_encrypt(const char *text)
{
/* TODO */
UNUSED(text);
return NULL;
}
/**
* Function for bitwise decryption - it is the inverse of the bitwise encryption
* function.
*
* @param text String representing the ciphertext to be decrypted.
* @return a pointer to a newly created string containing the plaintext produced
* by decrypting the ciphertext, or NULL if the decryption was not successful.
*/
char *bit_decrypt(const unsigned char *text)
{
/* TODO */
UNUSED(text);
return NULL;
}
/**
* Function for encrypting the given plaintext by applying the BMP cipher.
* The process of encrypting by BMP:
* <ol>
* <li> the provided input string is encrypted by function reverse()
* <li> the acquired string is encrypted by function vigenere_encrypt()
* <li> function bit_encrypt() is applied on the resulting string
* </ol>
*
* @param key Pointer to a string representing the key which will be used
* for encrypting the plaintext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text String representing the plaintext to be encrypted.
* @return the address of a copy of the ciphertext encrypted by the BMP cipher,
* or NULL if the encryption was not successful.
*/
unsigned char *bmp_encrypt(const char *key, const char *text)
{
/* TODO */
UNUSED(key);
UNUSED(text);
return NULL;
}
/**
* Function for decrypting the given ciphertext by applying the BMP cipher.
* The process of decrypting by BMP is the opposite of BMP encryption.
*
* @param key Pointer to a string representing the key which has been used
* for encrypting the ciphertext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text String representing the ciphertext to be decrypted.
* @return the address of a copy of the plaintext decrypted by the BMP cipher,
* or NULL if the decryption was not successful.
*/
char *bmp_decrypt(const char *key, const unsigned char *text)
{
/* TODO */
UNUSED(key);
UNUSED(text);
return NULL;
}

View file

@ -0,0 +1,98 @@
#ifndef _BMP_H
#define _BMP_H
/**
* Return reversed string.
*
* Function returns a pointer to the reversed string, which has been created
* from the input parameter. If the input string is NULL or memory could not be
* allocated, function returns NULL.
*
* @param text input string
* @return reversed representation of input string, or NULL, if the string could
* not be created.
*/
char *reverse(const char *text);
/**
* Function for encrypting the given plaintext by applying the Vigenère cipher.
*
* @param key Pointer to a string representing the key which will be used
* for encrypting the plaintext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text Pointer to a string representing the plaintext to be
* encrypted.
* @return the address of a copy of the ciphertext encrypted by the Vigenère
* cipher, or NULL if the encryption was not successful.
*/
char *vigenere_encrypt(const char *key, const char *text);
/**
* Function for decrypting the given ciphertext by applying the Vigenère cipher.
*
* @param key Pointer to a string representing the key which has been used
* for encrypting the ciphertext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text Pointer to a string representing the ciphertext to be
* decrypted.
* @return the address of a copy of the plaintext decrypted by the Vigenère
* cipher, or NULL if the decryption was not successful.
*/
char *vigenere_decrypt(const char *key, const char *text);
/**
* Function for bitwise encryption according to the following process:
* The character about to be encrypted is divided in half (4 bits + 4 bits).
* Subsequently, the bits in the left half are divided into two pairs and the
* values inside each pair are swapped. The four bits created by this way are
* then used in a bitwise XOR operation with the remaining 4 bits.
*
* @param text String representing the plaintext to be encrypted.
* @return a pointer to a newly created string containing the ciphertext
* produced by encrypting the plaintext, or NULL if the encryption was not
* successful.
*/
unsigned char *bit_encrypt(const char *text);
/**
* Function for bitwise decryption - it is the inverse of the bitwise encryption
* function.
*
* @param text String representing the ciphertext to be decrypted.
* @return a pointer to a newly created string containing the plaintext produced
* by decrypting the ciphertext, or NULL if the decryption was not successful.
*/
char *bit_decrypt(const unsigned char *text);
/**
* Function for encrypting the given plaintext by applying the BMP cipher.
* The process of encrypting by BMP:
* <ol>
* <li> the provided input string is encrypted by function reverse()
* <li> the acquired string is encrypted by function vigenere_encrypt()
* <li> function bit_encrypt() is applied on the resulting string
* </ol>
*
* @param key Pointer to a string representing the key which will be used
* for encrypting the plaintext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text String representing the plaintext to be encrypted.
* @return the address of a copy of the ciphertext encrypted by the BMP cipher,
* or NULL if the encryption was not successful.
*/
unsigned char *bmp_encrypt(const char *key, const char *text);
/**
* Function for decrypting the given ciphertext by applying the BMP cipher.
* The process of decrypting by BMP is the opposite of BMP encryption.
*
* @param key Pointer to a string representing the key which has been used
* for encrypting the ciphertext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text String representing the ciphertext to be decrypted.
* @return the address of a copy of the plaintext decrypted by the BMP cipher,
* or NULL if the decryption was not successful.
*/
char *bmp_decrypt(const char *key, const unsigned char *text);
#endif

View file

@ -0,0 +1,8 @@
#include "playfair.h"
#include <stdio.h>
int main(void)
{
return 0;
}

View file

@ -0,0 +1,251 @@
#include "bmp.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define CUT_MAIN
#include "cut.h"
void test_reverse(const char *input, const char *output)
{
char *reversed = reverse(input);
// check if not NULL
ASSERT(reversed != NULL);
int result = strcmp(reversed, output);
if (result != 0) {
DEBUG_MSG("Expected: %s, but got: %s\n", output, reversed);
}
ASSERT(strcmp(reversed, output) == 0);
free(reversed);
}
TEST(REVERSE)
{
SUBTEST(ABCD)
{
test_reverse("ABCD", "DCBA");
}
SUBTEST(BADACAD)
{
test_reverse("BADACAD", "DACADAB");
}
SUBTEST(qqsfyCCDAADQWQLLLlccaasq)
{
test_reverse("qqsfyCCDAADQWQLLLlccaasq", "QSAACCLLLLQWQDAADCCYFSQQ");
}
SUBTEST(NULL)
{
ASSERT(reverse(NULL) == NULL);
}
SUBTEST(EMPTY)
{
char *result = reverse("");
ASSERT(result[0] == '\0');
free(result);
}
SUBTEST(RANDOM)
{
test_reverse("hello", "OLLEH");
test_reverse("malloc", "COLLAM");
test_reverse("calloc", "COLLAC");
test_reverse("realloc", "COLLAER");
test_reverse("everything", "GNIHTYREVE");
test_reverse("failing", "GNILIAF");
test_reverse("LOL", "LOL");
test_reverse("1273912739&^%$$*((", "((*$$%^&9372193721");
}
}
void test_bit(const char *input, const unsigned char *output, size_t length)
{
unsigned char *encrypted = bit_encrypt(input);
char *decrypted = bit_decrypt(encrypted);
for (size_t i = 0; i < length; i++) {
ASSERT(encrypted[i] == output[i]);
ASSERT(decrypted[i] == input[i]);
}
free(decrypted);
free(encrypted);
}
TEST(BIT)
{
SUBTEST(HELLO_WORLD)
{
const unsigned char output[] = { 0x80, 0x9c, 0x95, 0x95, 0x96, 0x11, 0xbc, 0x96, 0xb9, 0x95, 0x9d, 0x10 };
test_bit("Hello world!", output, 12);
}
SUBTEST(MALLOC)
{
const unsigned char output[] = { 0x94, 0x98, 0x95, 0x95, 0x96, 0x9a };
test_bit("malloc", output, 6);
}
SUBTEST(CALLOC)
{
const unsigned char output[] = { 0x9a, 0x98, 0x95, 0x95, 0x96, 0x9a };
test_bit("calloc", output, 6);
}
SUBTEST(REALLOC)
{
const unsigned char output[] = { 0xb9, 0x9c, 0x98, 0x95, 0x95, 0x96, 0x9a };
test_bit("realloc", output, 7);
}
SUBTEST(EVERYTHING)
{
const unsigned char output[] = { 0x9c, 0xbd, 0x9c, 0xb9, 0xb2, 0xbf, 0x91, 0x90, 0x97, 0x9e };
test_bit("everything", output, 10);
}
SUBTEST(FAILING)
{
const unsigned char output[] = { 0x9f, 0x98, 0x90, 0x95, 0x90, 0x97, 0x9e };
test_bit("failing", output, 7);
}
SUBTEST(LOL)
{
const unsigned char output[] = { 0x84, 0x87, 0x84 };
test_bit("LOL", output, 3);
}
SUBTEST(GARBAGE)
{
const unsigned char output[] = { 0x32, 0x31, 0x34, 0x30, 0x3a, 0x32, 0x31, 0x34, 0x30, 0x3a, 0x17, 0xa4, 0x14, 0x15, 0x15, 0x1b, 0x19, 0x19 };
test_bit("1273912739&^%$$*((", output, 18);
}
SUBTEST(HELLO_FI)
{
const unsigned char output[] = { 0x91, 0x9c, 0x95, 0x95, 0x96 };
test_bit("hello", output, 5);
}
SUBTEST(BYE_FI)
{
const unsigned char output[] = { 0x9b, 0xb2, 0x9c };
test_bit("bye", output, 3);
}
}
void test_vigenere(const char *key, const char *input, const char *output, size_t length)
{
char *encrypted = vigenere_encrypt(key, input);
char *decrypted = vigenere_decrypt(key, encrypted);
ASSERT(encrypted != NULL);
ASSERT(decrypted != NULL);
for (size_t i = 0; i < length; i++) {
ASSERT(encrypted[i] == output[i]);
ASSERT(decrypted[i] == toupper(input[i]));
}
free(encrypted);
free(decrypted);
}
TEST(VIGENERE)
{
SUBTEST(HELLO_WORLD)
{
test_vigenere("CoMPuTeR", "Hello world!", "JSXAI PSINR!", 12);
}
SUBTEST(MALLOC)
{
test_vigenere("fails", "malloc", "RATWGH", 6);
}
SUBTEST(CALLOC)
{
test_vigenere("fails", "calloc", "HATWGH", 6);
}
SUBTEST(REALLOC)
{
test_vigenere("fails", "realloc", "WEIWDTC", 7);
}
SUBTEST(EVERYTHING)
{
test_vigenere("FAILS", "everything", "JVMCQYHQYY", 10);
}
SUBTEST(FAILING)
{
test_vigenere("fails", "failing", "KAQWASG", 7);
}
SUBTEST(LOL)
{
test_vigenere("oopsie", "LOL", "ZCA", 3);
}
SUBTEST(GARBAGE)
{
test_vigenere("fi", "1273912739&^%$$*((", "1273912739&^%$$*((", 18);
}
SUBTEST(HELLO_FI)
{
test_vigenere("fi", "hello", "MMQTT", 5);
}
SUBTEST(BYE_FI)
{
test_vigenere("fi", "bye", "GGJ", 3);
}
}
void test_bmp(const char *key, const char *input, const unsigned char *encrypted_expected, const char *decrypted_expected, size_t length)
{
unsigned char *encrypted = bmp_encrypt(key, input);
char *decrypted = bmp_decrypt(key, encrypted);
ASSERT(encrypted != NULL);
ASSERT(decrypted != NULL);
for (size_t i = 0; i < length; i++) {
ASSERT(encrypted[i] == encrypted_expected[i]);
ASSERT(decrypted[i] == decrypted_expected[i]);
}
free(encrypted);
free(decrypted);
}
TEST(BMP)
{
SUBTEST(HELLO)
{
const unsigned char encrypted_expected[] = { 0xae, 0xae, 0xab, 0x85, 0x85 };
test_bmp("fi", "hello", encrypted_expected, "HELLO", 5);
}
SUBTEST(FI)
{
const unsigned char encrypted_expected[] = { 0xaa, 0x82 };
test_bmp("hello", "fi", encrypted_expected, "FI", 2);
}
SUBTEST(RANDOM)
{
const unsigned char encrypted_expected[] = { 0xa9, 0x87, 0xaf, 0x87, 0x89, 0xa2 };
test_bmp("garbage", "random", encrypted_expected, "RANDOM", 6);
}
SUBTEST(LETS)
{
const unsigned char encrypted_expected[] = { 0x83, 0xa2, 0x81, 0x8c };
test_bmp("see", "lets", encrypted_expected, "LETS", 4);
}
SUBTEST(how)
{
const unsigned char encrypted_expected[] = { 0x8d, 0x80, 0xaa };
test_bmp("it", "how", encrypted_expected, "HOW", 3);
}
SUBTEST(works)
{
const unsigned char encrypted_expected[] = { 0xa9, 0x8b, 0x89, 0xa8, 0x80 };
test_bmp("asjdljasdja", "works", encrypted_expected, "WORKS", 5);
}
SUBTEST(NOSPACES)
{
const unsigned char encrypted_expected[] = { 0x8d, 0x81, 0x82, 0x85, 0xae, 0xa0, 0x89, 0xa8, 0xa0, 0x85, 0x84, 0x89, 0x85, 0x84, 0x89, 0x8e, 0x8a, 0x84, 0x8e, 0xac, 0x84, 0xa9, 0xa8, 0xac, 0xa2 };
test_bmp("meh", "longerTextThatHasNoSpaces", encrypted_expected, "LONGERTEXTTHATHASNOSPACES", 25);
}
SUBTEST(ayaya)
{
const unsigned char encrypted_expected[] = { 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80 };
test_bmp("HUH", "ayayayayayayayayayayayayayayayaya", encrypted_expected, "AYAYAYAYAYAYAYAYAYAYAYAYAYAYAYAYA", 33);
}
}

View file

View file

@ -0,0 +1,24 @@
cmake_minimum_required(VERSION 3.0)
# Project configuration
project(seminar08-bonus)
set(SOURCES counting.c trees.c)
# Executable
add_executable(counting counting.c)
add_executable(trees trees.c)
# Configure compiler warnings
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
# using regular Clang, AppleClang or GCC
# Strongly suggested: neable -Werror
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
# using Visual Studio C++
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
endif()
if(MINGW)
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
endif()

View file

@ -0,0 +1,10 @@
check-counting:
python3 test-bonus.py test counting
check-counting-bonus:
python3 test-bonus.py test counting --no-global-config
check: check-counting check-counting-bonus
clean:
rm -rf test-*/*.out_produced

View file

@ -0,0 +1,60 @@
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define UNUSED(x) ((void) (x))
/**
* @brief Counts occurences of any substring in the file.
* @param file File where the substring is to be counted in.
* @param substring Substring to be counted.
* @returns Count of occurences of the substring the given file.
*/
long count_anything(FILE *file, const char *substring)
{
/* TODO */
UNUSED(file);
UNUSED(substring);
return 0;
}
/**
* @brief Counts ananas. Nothing more to it.
* @param file File where the ananas is to be counted in.
* @returns Count of occurences of ananas.
*/
long count_ananas(FILE *file)
{
return count_anything(file, "ananas");
}
/**
* @brief Writes given number to the file, character by character.
* @param file File where the number is supposed to be written.
* @param number Number to be written.
*/
void write_number(FILE *file, long number)
{
/* TODO */
UNUSED(file);
UNUSED(number);
}
/**
* @brief Main function of a program.
* @returns Exit code that denotes following:
* 0 in case of success
* 1 in case of invalid usage
* 2 in case of failure on input file
* 3 in case of failure on output file
*/
int main(int argc, char **argv)
{
if (argc < 3 || argc > 4) {
printf("Usage: %s <input-file> <output-file> [string-to-be-counted]\n", argv[0]);
return 1;
}
/* TODO */
return 0;
}

View file

@ -0,0 +1,4 @@
{
"args": ["{test_case}.in", "{test_case}.out_produced"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
../../test-bonus.py

View file

@ -0,0 +1 @@
ananas

View file

@ -0,0 +1 @@
1

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
1747627

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1,65 @@
FGETC(3) Linux Programmer's Manual FGETC(3)
NAME
fgetc, fgets, getc, getchar, ungetc - input of characters and strings
SYNOPSIS
#include <stdio.h>
int fgetc(FILE *stream);
char *fgets(char *s, int size, FILE *stream);
int getc(FILE *stream);
int getchar(void);
int ungetc(int c, FILE *stream);
DESCRIPTION
fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.
getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once.
getchar() is equivalent to getc(stdin).
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buf
fer. A terminating null byte ('\0') is stored after the last character in the buffer.
ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed.
Calls to the functions described here can be mixed with each other and with calls to other input functions from the stdio library for the same input stream.
For nonlocking counterparts, see unlocked_stdio(3).
RETURN VALUE
fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.
fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.
ungetc() returns c on success, or EOF on error.
ATTRIBUTES
For an explanation of the terms used in this section, see attributes(7).
┌──────────────────────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├──────────────────────────┼───────────────┼─────────┤
│fgetc(), fgets(), getc(), │ Thread safety │ MT-Safe │
│getchar(), ungetc() │ │ │
└──────────────────────────┴───────────────┴─────────┘
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, C89, C99.
It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associated with the input stream; the results will be undefined and very prob
ably not what you want.
SEE ALSO
read(2), write(2), ferror(3), fgetwc(3), fgetws(3), fopen(3), fread(3), fseek(3), getline(3), gets(3), getwchar(3), puts(3), scanf(3), ungetwc(3), unlocked_stdio(3), feature_test_macros(7)
COLOPHON
This page is part of release 5.07 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at
https://www.kernel.org/doc/man-pages/.
GNU 2017-09-15 FGETC(3)

View file

@ -0,0 +1,4 @@
{
"args": ["{test_case}.in", "{test_case}.out_produced", "getc"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
25

View file

@ -0,0 +1 @@
ananas bananas banana nanas nana

View file

@ -0,0 +1,4 @@
{
"args": ["{test_case}.in", "{test_case}.out_produced", "banana"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
2

View file

@ -0,0 +1,31 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi auctor euismod enim a sodales. Praesent efficitur pharetra mi, et finibus nulla pellentesque euismod. Sed fringilla sed mi in aliquet. Quisque eu nibh id arcu suscipit tempus. Mauris quam urna, volutpat id iaculis non, lobortis a orci. Quisque commodo lectus sit amet nisl mattis accumsan. Proin iaculis erat in elementum dapibus.
Aliquam commodo congue neque id porta. Aliquam dictum justo est, a vulputate diam ullamcorper ac. Etiam cursus augue eu porttitor sagittis. Fusce egestas tellus quis semper egestas. Nunc metus neque, accumsan non nulla in, fringilla tincidunt tellus. Aliquam in tempus eros. Donec ornare leo in neque pretium mattis. Morbi consequat lacus vitae justo auctor, eget interdum lorem tincidunt. Morbi at nisl lobortis, ultricies augue a, viverra libero. Phasellus sit amet magna aliquam, scelerisque lectus sit amet, euismod eros.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in ipsum dui. Maecenas euismod est a dui euismod tristique. Maecenas tincidunt diam ut velit rutrum, a bibendum ligula pellentesque. Maecenas sit amet turpis a mi tristique vulputate non vitae metus. Aenean ut lectus ut eros maximus hendrerit at sed arcu. Nulla condimentum velit non mauris consectetur tempor. Duis fringilla ligula aliquam massa malesuada dignissim. Suspendisse dignissim arcu et augue tristique vestibulum. Nam auctor vulputate dignissim. Integer eget ultrices elit. Vivamus placerat sit amet mauris et lacinia. Maecenas lacinia ipsum blandit justo efficitur congue. Aliquam erat volutpat. Vivamus risus enim, mattis ac lacus molestie, blandit volutpat elit.
Mauris id arcu vitae urna finibus scelerisque. Nullam dictum interdum lacinia. Nunc congue turpis malesuada velit maximus suscipit. Pellentesque quis interdum risus. Quisque leo massa, viverra in condimentum quis, pharetra ut est. Nullam vehicula tempus elit sit amet placerat. Integer elementum, mauris eget rhoncus sagittis, est massa laoreet felis, sed ultricies risus urna et mi. Proin commodo ut libero in commodo. Nullam consequat tellus non tellus cursus, eget luctus tellus tempor. Proin ante risus, convallis et ex ac, cursus auctor turpis. Integer et mauris ut enim suscipit laoreet. Nulla tortor augue, eleifend id faucibus sed, faucibus eu turpis. Sed vel nibh non tortor venenatis dignissim. Nunc vel maximus mauris.
Mauris porta nunc eros, vel mattis augue dignissim in. Nunc tempus ac purus dignissim dapibus. Nulla sit amet ipsum dapibus, viverra dolor eu, pharetra lectus. Sed maximus felis justo. Cras nec condimentum nisl. Donec vitae metus suscipit, auctor augue in, blandit purus. Pellentesque viverra non est id mollis. Aenean fermentum nisi sit amet urna tincidunt, eget accumsan mauris bibendum. In vestibulum consectetur erat, ac gravida odio ultrices eu. Nullam quam mi, sagittis a nisl quis, vestibulum ultrices est.
In ut tempus nibh. Morbi consectetur gravida feugiat. Morbi non eros ut dui faucibus sagittis. Duis euismod metus quis enim aliquet iaculis. Pellentesque pellentesque sed lorem vitae euismod. Aliquam luctus fringilla urna, eget hendrerit augue. Aliquam malesuada nisl id eros viverra aliquam id ut sem. Mauris vel arcu eget nisi finibus varius in vitae arcu. Maecenas aliquet gravida quam feugiat vestibulum. Maecenas id nunc sit amet nulla imperdiet pharetra quis eu lectus. In pellentesque mattis bibendum. Proin ultrices eget turpis eu accumsan. In porttitor ante eget odio mattis egestas.
Mauris lacinia lacus vel eleifend mattis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec eu quam orci. Vestibulum fermentum, odio iaculis porta semper, enim lorem faucibus nisl, eu vulputate enim turpis quis massa. Cras hendrerit pulvinar ante id mattis. Phasellus vitae neque lobortis, aliquam purus in, commodo ex. Aenean suscipit metus non sollicitudin porttitor. Maecenas a justo cursus, mattis ligula ut, vestibulum felis. Curabitur dapibus finibus lectus nec porttitor. Integer fringilla, dolor in varius sodales, purus risus bibendum tortor, in eleifend risus neque a elit. Phasellus placerat enim at nulla aliquam luctus. Nunc consequat placerat ornare. Suspendisse faucibus gravida arcu id ullamcorper.
Praesent dapibus mauris eu purus maximus vehicula. Nulla ultrices luctus eleifend. Etiam efficitur aliquam diam eu varius. Sed quis lacus volutpat, aliquet eros convallis, interdum erat. In auctor ipsum vitae massa rhoncus, nec sagittis purus gravida. Nullam condimentum fringilla euismod. Proin congue nisi ut est lacinia elementum.
Maecenas leo ex, mattis non neque ut, rutrum pulvinar enim. Morbi malesuada mollis risus, sed faucibus eros ultrices at. Aenean aliquet in odio sit amet rhoncus. Nulla nisi neque, vestibulum a sem sed, consectetur convallis neque. Nullam ac lectus vel eros luctus tincidunt rhoncus eu dui. Pellentesque vitae lorem congue, pretium felis vel, mattis velit. Nullam nulla elit, convallis eu congue sed, ultricies nec diam. Mauris et ligula dui. Praesent sit amet laoreet dolor. Aliquam erat volutpat. Nam feugiat iaculis vestibulum. Ut eget turpis at diam interdum finibus. Aliquam dictum fermentum dui, eget lobortis nibh interdum sagittis.
Nullam elit sapien, mollis sed convallis a, consectetur at ipsum. Integer viverra consequat turpis vel elementum. Aliquam tincidunt et est sit amet condimentum. Aenean nec sem semper, semper urna quis, aliquet ante. Duis malesuada, massa sit amet congue feugiat, sem diam accumsan lectus, at vestibulum dui libero non lectus. Maecenas nunc tortor, varius sed libero in, placerat consequat neque. Maecenas rutrum sem enim, vel hendrerit dolor luctus nec. Aliquam fringilla purus sagittis consequat pretium. Suspendisse iaculis pharetra est, eleifend elementum mauris viverra eu. Ut pellentesque tempus ipsum, ac maximus risus imperdiet ac. Nulla felis mauris, molestie eu aliquet non, pretium sit amet ante. Integer id cursus mauris. Nunc a mattis magna, nec luctus magna. Mauris sed vehicula nisi, id tincidunt mauris. Curabitur aliquam, eros vitae ultricies interdum, nunc felis placerat enim, eget maximus dui massa vel eros. Mauris turpis est, pretium ut fringilla at, lacinia non eros.
Mauris nulla massa, facilisis ut dui at, consequat dignissim felis. Pellentesque vitae nibh sed dui convallis faucibus a et risus. In id mauris ligula. Nunc nec ante sem. Curabitur purus eros, molestie ut nunc ut, cursus hendrerit est. Mauris bibendum viverra rhoncus. Nulla varius fringilla nulla, ac hendrerit neque tincidunt sed. Morbi malesuada bibendum elementum. In hac habitasse platea dictumst. Mauris at massa sed massa auctor pellentesque quis quis est. Fusce pharetra, sem nec malesuada consectetur, sapien nisl fermentum nisi, ac volutpat sapien sapien id ligula.
Mauris finibus ligula ac dolor feugiat, ac pellentesque felis venenatis. Cras scelerisque tempus libero, quis sollicitudin nunc pellentesque nec. Praesent pulvinar leo turpis, vel sagittis ligula dignissim ac. Nam ut bibendum diam. Etiam fermentum nunc tellus, sed ultrices neque porttitor a. Quisque placerat dignissim eros. Phasellus consectetur nisl erat, id luctus lacus scelerisque quis. Aenean mattis molestie mi, ac rhoncus felis congue id. Aliquam erat volutpat. Vestibulum ac accumsan dui. Phasellus a orci nec lacus rhoncus semper eu ac sapien.
Sed finibus, lectus eget interdum vehicula, lorem tortor ornare urna, id lacinia eros sem eu urna. Pellentesque consectetur vulputate arcu vitae aliquam. Aenean eleifend tempor dui. Mauris lectus diam, euismod vitae posuere et, pulvinar quis nulla. Donec sagittis vestibulum mi quis molestie. Sed eu lectus quis nunc vulputate tristique. Proin imperdiet nibh lectus. Nunc sagittis risus libero, sit amet dignissim ligula mollis a. Proin auctor, eros non condimentum fringilla, dolor neque consequat augue, quis ullamcorper velit nibh id nibh. Quisque mollis sit amet justo nec ultrices. Mauris vel commodo felis, porttitor rutrum turpis.
In et lacus quis ante commodo suscipit ac et leo. Nam in dui diam. Nulla molestie lacus ac nunc laoreet, vel lobortis nulla suscipit. Ut iaculis feugiat tincidunt. Vestibulum ut pharetra enim, vel pellentesque leo. Pellentesque sit amet rutrum mauris. Nullam ultricies augue id est interdum, sit amet consectetur eros eleifend.
Aliquam ac pretium arcu, quis viverra mi. Mauris tincidunt tincidunt libero, id aliquam ipsum scelerisque quis. Donec vitae purus et eros dapibus pulvinar. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis efficitur tempus tortor, et sodales augue ultricies sed. Phasellus nec finibus lacus, in aliquet turpis. Maecenas id turpis augue. Nunc finibus turpis purus, aliquam tempor magna ullamcorper ut. Morbi sit amet erat gravida, egestas metus vel, porttitor diam.

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1,31 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi auctor euismod enim a sodales. Praesent efficitur pharetra mi, et finibus nulla pellentesque euismod. Sed fringilla sed mi in aliquet. Quisque eu nibh id arcu suscipit tempus. Mauris quam urna, volutpat id iaculis non, lobortis a orci. Quisque commodo lectus sit amet nisl mattis accumsan. Proin iaculis erat in elementum dapibus.
Aliquam commodo congue neque id porta. Aliquam dictum justo est, a vulputate diam ullamcorper ac. Etiam cursus augue eu porttitor sagittis. Fusce egestas tellus quis semper egestas. Nunc metus neque, accumsan non nulla in, fringilla tincidunt tellus. Aliquam in tempus eros. Donec ornare leo in neque pretium mattis. Morbi consequat lacus vitae justo auctor, eget interdum lorem tincidunt. Morbi at nisl lobortis, ultricies augue a, viverra libero. Phasellus sit amet magna aliquam, scelerisque lectus sit amet, euismod eros.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in nananananananas dui. Maecenas euismod est a dui euismod tristique. Maecenas tincidunt diam ut velit rutrum, a bibendum ligula ananas. Maecenas sit amet turpis a mi tristique vulputate non vitae metus. Aenean ut lectus ut eros maximus hendrerit at sed arcu. Nulla condimentum velit non mauris consectetur tempor. Duis fringilla ligula aliquam massa malesuada dignissim. Suspendisse dignissim arcu et augue tristique vestibulum. Nam auctor vulputate dignissim. Integer eget ultrices elit. Vivamus placerat sit amet mauris et lacinia. Maecenas lacinia ipsum blandit justo efficitur congue. Aliquam erat volutpat. Vivamus risus enim, mattis ac lacus molestie, blandit volutpat elit.
Mauris id arcu vitae urna finibus scelerisque. Nullam dictum interdum lacinia. Nunc congue turpis malesuada velit maximus suscipit. Pellentesque quis interdum risus. Quisque leo massa, viverra in condimentum quis, pharetra ut est. Nullam vehicula tempus elit sit amet placerat. Integer elementum, mauris eget rhoncus sagittis, est massa laoreet felis, sed ultricies risus urna et mi. Proin commodo ut libero in commodo. Nullam consequat tellus non tellus cursus, eget luctus tellus tempor. Proin ante risus, convallis et ex ac, cursus auctor turpis. Integer et mauris ut enim suscipit laoreet. Nulla tortor augue, eleifend id faucibus sed, faucibus eu turpis. Sed vel nibh non tortor venenatis dignissim. Nunc vel maximus mauris.
Mauris porta nunc eros, vel mattis augue dignissim in. Nunc tempus ac purus dignissim dapibus. Nulla sit amet ipsum dapibus, viverra dolor eu, pharetra lectus. Sed maximus felis justo. Cras nec condimentum nisl. Donec vitae metus suscipit, auctor augue in, blandit purus. Pellentesque viverra non est id mollis. Aenean fermentum nisi sit amet urna tincidunt, eget accumsan mauris bibendum. In vestibulum consectetur erat, ac gravida odio ultrices eu. Nullam quam mi, sagittis a nisl quis, vestibulum ultrices est.
In ut tempus nibh. Morbi consectetur gravida feugiat. Morbi non eros ut dui ananas sagittis. Duis euismod metus quis enim aliquet iaculis. Pellentesque pellentesque sed lorem vitae euismod. Aliquam luctus fringilla urna, eget hendrerit augue. Aliquam malesuada nisl id eros viverra aliquam id ut sem. Mauris vel arcu eget nisi finibus varius in vitae arcu. Maecenas aliquet gravida quam feugiat vestibulum. Maecenas id nunc sit amet nulla imperdiet pharetra quis eu lectus. In pellentesque mattis bibendum. Proin ultrices eget turpis eu accumsan. In porttitor ante eget odio mattis egestas.
anans
Mauris lacinia lacus vel eleifend mattis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec eu aaaaaaaaaaaaaaaaaaaaaaaaaaaaananas orci. Vestibulum fermentum, odio iaculis porta semper, enim lorem faucibus nisl, eu vulputate enim turpis quis massa. Cras hendrerit pulvinar ante id mattis. Phasellus vitae neque lobortis, aliquam purus in, commodo ex. Aenean suscipit metus non sollicitudin porttitor. Maecenas a justo cursus, mattis ligula ut, vestibulum felis. Curabitur dapibus finibus lectus nec porttitor. Integer fringilla, dolor in varius sodales, purus risus bibendum tortor, in eleifend risus neque a elit. Phasellus placerat enim at nulla aliquam luctus. Nunc consequat placerat ornare. Suspendisse faucibus gravida arcu id ullamcorper.
ananas
Praesent dapibus mauris eu purus maximus vehicula. Nulla ultrices luctus eleifend. Etiam efficitur aliquam diam eu varius. Sed quis lacus volutpat, aliquet eros convallis, interdum erat. In auctor ipsum vitae massa rhoncus, nec sagittis purus gravida. Nullam condimentum fringilla euismod. Proin congue nisi ut est lacinia elementum.
Maecenas leo ex, mattis non neque ut, rutrum pulvinar enim. Morbi malesuada mollis risus, sed faucibus eros ultrices at. Aenean aliquet in aaaaaaaaaaaaaaaaaaaaaaaaaaaaananas sit amet rhoncus. Nulla nisi neque, vestibulum a sem sed, consectetur convallis neque. Nullam ac lectus vel eros luctus tincidunt rhoncus eu dui. Pellentesque vitae lorem congue, pretium felis vel, mattis velit. Nullam nulla elit, convallis eu congue sed, ultricies nec diam. Mauris et ligula dui. Praesent sit amet laoreet dolor. Aliquam erat volutpat. Nam feugiat iaculis vestibulum. Ut eget turpis at diam interdum finibus. Aliquam dictum fermentum dui, eget lobortis nibh interdum sagittis.
Nullam elit sapien, mollis sed convallis a, consectetur at ipsum. Integer viverra consequat turpis vel elementum. Aliquam tincidunt et est sit amet condimentum. Aenean nec sem semper, semper urna quis, aliquet ante. Duis malesuada, massa sit amet congue feugiat, sem diam accumsan lectus, at vestibulum dui libero non lectus. Maecenas nunc tortor, varius sed libero in, placerat consequat neque. Maecenas rutrum sem enim, vel hendrerit dolor luctus nec. Aliquam fringilla purus sagittis consequat pretium. Suspendisse iaculis pharetra est, eleifend elementum mauris viverra eu. Ut pellentesque tempus ipsum, ac maximus risus imperdiet ac. Nulla felis mauris, molestie eu aliquet non, pretium sit amet ante. Integer id cursus mauris. Nunc a mattis magna, nec luctus magna. Mauris sed vehicula nisi, id tincidunt mauris. Curabitur aliquam, eros vitae ultricies interdum, nunc felis placerat enim, eget maximus dui massa vel eros. Mauris turpis est, pretium ut fringilla at, lacinia non eros.
Mauris nulla massa, facilisis ut dui at, consequat dignissim felis. Pellentesque vitae nibh sed dui convallis faucibus a et risus. In id mauris ligula. Nunc nec ante sem. Curabitur purus eros, molestie ut nunc ut, cursus hendrerit est. Mauris bibendum viverra rhoncus. Nulla varius fringilla nulla, ac hendrerit neque tincidunt sed. Morbi malesuada bibendum elementum. In hac habitasse platea dictumst. Mauris at massa sed massa auctor pellentesque quis quis est. Fusce pharetra, sem nec malesuada consectetur, sapien nisl fermentum nisi, ac volutpat sapien sapien id ligula.
Mauris finibus ligula ac dolor feugiat, ac pellentesque felis venenatis. Cras anaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaanas tempus libero, quis sollicitudin nunc pellentesque nec. Praesent pulvinar leo turpis, vel sagittis ligula dignissim ac. Nam ut bibendum diam. Etiam fermentum nunc tellus, sed ultrices neque porttitor a. Quisque placerat dignissim eros. Phasellus consectetur nisl erat, id luctus lacus scelerisque quis. Aenean mattis molestie mi, ac rhoncus felis congue id. Aliquam erat volutpat. Vestibulum ac accumsan dui. Phasellus a orci nec lacus rhoncus semper eu ac sapien.
Sed finibus, lectus eget interdum vehicula, lorem tortor ornare urna, id lacinia eros sem eu urna. Pellentesque consectetur vulputate arcu vitae aliquam. Aenean eleifend tempor dui. Mauris lectus diam, euismod vitae posuere et, pulvinar quis nulla. Donec sagittis vestibulum mi quis molestie. Sed eu lectus quis nunc vulputate tristique. Proin imperdiet nibh lectus. Nunc sagittis risus libero, sit amet dignissim ligula mollis a. Proin auctor, eros non condimentum fringilla, dolor neque consequat augue, quis ullamcorper velit nibh id nibh. Quisque mollis sit amet justo nec ultrices. Mauris vel commodo felis, porttitor rutrum turpis.
ananas
In et lacus quis ante commodo suscipit ac et leo. Nam in dui diam. Nulla molestie lacus ac nunc laoreet, vel lobortis nulla suscipit. Ut iaculis feugiat tincidunt. Vestibulum ut pharetra enim, vel pellentesque leo. Pellentesque sit amet rutrum mauris. Nullam ultricies augue id est interdum, sit amet consectetur eros eleifend.
Aliquam ac pretium arcu, quis viverra mi. Mauris tincidunt tincidunt libero, id aliquam ipsum scelerisque quis. Donec vitae purus et eros dapibus pulvinar. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis efficitur tempus tortor, et sodales augue ultricies sed. Phasellus nec finibus lacus, in aliquet turpis. Maecenas id turpis augue. Nunc finibus turpis purus, aliquam tempor magna ullamcorper ut. Morbi sit amet erat gravida, egestas metus vel, porttitor diam.

View file

@ -0,0 +1 @@
7

View file

@ -0,0 +1,264 @@
MMAP(3P) POSIX Programmer's Manual MMAP(3P)
PROLOG
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be imple
mented on Linux.
NAME
mmap — map pages of memory
SYNOPSIS
#include <sys/mman.h>
void *mmap(void *addr, size_t len, int prot, int flags,
int fildes, off_t off);
DESCRIPTION
The mmap() function shall establish a mapping between an address space of a process and a memory object.
The mmap() function shall be supported for the following memory objects:
* Regular files
* Shared memory objects
* Typed memory objects
Support for any other type of file is unspecified.
The format of the call is as follows:
pa=mmap(addr, len, prot, flags, fildes, off);
The mmap() function shall establish a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off for len bytes. The value of pa
is an implementation-defined function of the parameter addr and the values of flags, further described below. A successful mmap() call shall return pa as its result. The address range starting at pa and continuing for len
bytes shall be legitimate for the possible (not necessarily current) address space of the process. The range of bytes starting at off and continuing for len bytes shall be legitimate for the possible (not necessarily current)
offsets in the memory object represented by fildes.
If fildes represents a typed memory object opened with either the POSIX_TYPED_MEM_ALLOCATE flag or the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, the memory object to be mapped shall be that portion of the typed memory object al
located by the implementation as specified below. In this case, if off is non-zero, the behavior of mmap() is undefined. If fildes refers to a valid typed memory object that is not accessible from the calling process, mmap()
shall fail.
The mapping established by mmap() shall replace any previous mappings for those whole pages containing any part of the address space of the process starting at pa and continuing for len bytes.
If the size of the mapped file changes after the call to mmap() as a result of some other operation on the mapped file, the effect of references to portions of the mapped region that correspond to added or removed portions of
the file is unspecified.
If len is zero, mmap() shall fail and no mapping shall be established.
The parameter prot determines whether read, write, execute, or some combination of accesses are permitted to the data being mapped. The prot shall be either PROT_NONE or the bitwise-inclusive OR of one or more of the other
flags in the following table, defined in the <sys/mman.h> header.
┌──────────────────┬──────────────────────────┐
│Symbolic Constant │ Description │
├──────────────────┼──────────────────────────┤
│PROT_READ │ Data can be read. │
│PROT_WRITE │ Data can be written. │
│PROT_EXEC │ Data can be executed. │
│PROT_NONE │ Data cannot be accessed. │
└──────────────────┴──────────────────────────┘
If an implementation cannot support the combination of access types specified by prot, the call to mmap() shall fail.
An implementation may permit accesses other than those specified by prot; however, the implementation shall not permit a write to succeed where PROT_WRITE has not been set and shall not permit any access where PROT_NONE alone
has been set. The implementation shall support at least the following values of prot: PROT_NONE, PROT_READ, PROT_WRITE, and the bitwise-inclusive OR of PROT_READ and PROT_WRITE. The file descriptor fildes shall have been
opened with read permission, regardless of the protection options specified. If PROT_WRITE is specified, the application shall ensure that it has opened the file descriptor fildes with write permission unless MAP_PRIVATE is
specified in the flags parameter as described below.
The parameter flags provides other information about the handling of the mapped data. The value of flags is the bitwise-inclusive OR of these options, defined in <sys/mman.h>:
┌──────────────────┬─────────────────────────┐
│Symbolic Constant │ Description │
├──────────────────┼─────────────────────────┤
│MAP_SHARED │ Changes are shared. │
│MAP_PRIVATE │ Changes are private. │
│MAP_FIXED │ Interpret addr exactly. │
└──────────────────┴─────────────────────────┘
It is implementation-defined whether MAP_FIXED shall be supported. MAP_FIXED shall be supported on XSI-conformant systems.
MAP_SHARED and MAP_PRIVATE describe the disposition of write references to the memory object. If MAP_SHARED is specified, write references shall change the underlying object. If MAP_PRIVATE is specified, modifications to the
mapped data by the calling process shall be visible only to the calling process and shall not change the underlying object. It is unspecified whether modifications to the underlying object done after the MAP_PRIVATE mapping
is established are visible through the MAP_PRIVATE mapping. Either MAP_SHARED or MAP_PRIVATE can be specified, but not both. The mapping type is retained across fork().
The state of synchronization objects such as mutexes, semaphores, barriers, and conditional variables placed in shared memory mapped with MAP_SHARED becomes undefined when the last region in any process containing the syn
chronization object is unmapped.
When fildes represents a typed memory object opened with either the POSIX_TYPED_MEM_ALLOCATE flag or the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, mmap() shall, if there are enough resources available, map len bytes allocated
from the corresponding typed memory object which were not previously allocated to any process in any processor that may access that typed memory object. If there are not enough resources available, the function shall fail. If
fildes represents a typed memory object opened with the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, these allocated bytes shall be contiguous within the typed memory object. If fildes represents a typed memory object opened with
the POSIX_TYPED_MEM_ALLOCATE flag, these allocated bytes may be composed of non-contiguous fragments within the typed memory object. If fildes represents a typed memory object opened with neither the POSIX_TYPED_MEM_ALLO
CATE_CONTIG flag nor the POSIX_TYPED_MEM_ALLOCATE flag, len bytes starting at offset off within the typed memory object are mapped, exactly as when mapping a file or shared memory object. In this case, if two processes map an
area of typed memory using the same off and len values and using file descriptors that refer to the same memory pool (either from the same port or from a different port), both processes shall map the same region of storage.
When MAP_FIXED is set in the flags argument, the implementation is informed that the value of pa shall be addr, exactly. If MAP_FIXED is set, mmap() may return MAP_FAILED and set errno to [EINVAL]. If a MAP_FIXED request is
successful, then any previous mappings or memory locks for those whole pages containing any part of the address range [pa,pa+len) shall be removed, as if by an appropriate call to munmap(), before the new mapping is estab
lished.
When MAP_FIXED is not set, the implementation uses addr in an implementation-defined manner to arrive at pa. The pa so chosen shall be an area of the address space that the implementation deems suitable for a mapping of len
bytes to the file. All implementations interpret an addr value of 0 as granting the implementation complete freedom in selecting pa, subject to constraints described below. A non-zero value of addr is taken to be a suggestion
of a process address near which the mapping should be placed. When the implementation selects a value for pa, it never places a mapping at address 0, nor does it replace any extant mapping.
If MAP_FIXED is specified and addr is non-zero, it shall have the same remainder as the off parameter, modulo the page size as returned by sysconf() when passed _SC_PAGESIZE or _SC_PAGE_SIZE. The implementation may require
that off is a multiple of the page size. If MAP_FIXED is specified, the implementation may require that addr is a multiple of the page size. The system performs mapping operations over whole pages. Thus, while the parameter
len need not meet a size or alignment constraint, the system shall include, in any mapping operation, any partial page specified by the address range starting at pa and continuing for len bytes.
The system shall always zero-fill any partial page at the end of an object. Further, the system shall never write out any modified portions of the last page of an object which are beyond its end. References within the ad
dress range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.
An implementation may generate SIGBUS signals when a reference would cause an error in the mapped object, such as out-of-space condition.
The mmap() function shall add an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. This reference shall be removed when there are no
more mappings to the file.
The last data access timestamp of the mapped file may be marked for update at any time between the mmap() call and the corresponding munmap() call. The initial read or write reference to a mapped region shall cause the file's
last data access timestamp to be marked for update if it has not already been marked for update.
The last data modification and last file status change timestamps of a file that is mapped with MAP_SHARED and PROT_WRITE shall be marked for update at some point in the interval between a write reference to the mapped region
and the next call to msync() with MS_ASYNC or MS_SYNC for that portion of the file by any process. If there is no such call and if the underlying file is modified as a result of a write reference, then these timestamps shall
be marked for update at some time after the write reference.
There may be implementation-defined limits on the number of memory regions that can be mapped (per process or per system).
If such a limit is imposed, whether the number of memory regions that can be mapped by a process is decreased by the use of shmat() is implementation-defined.
If mmap() fails for reasons other than [EBADF], [EINVAL], or [ENOTSUP], some of the mappings in the address range starting at addr and continuing for len bytes may have been unmapped.
RETURN VALUE
Upon successful completion, the mmap() function shall return the address at which the mapping was placed (pa); otherwise, it shall return a value of MAP_FAILED and set errno to indicate the error. The symbol MAP_FAILED is de
fined in the <sys/mman.h> header. No successful return from mmap() shall return the value MAP_FAILED.
ERRORS
The mmap() function shall fail if:
EACCES The fildes argument is not open for read, regardless of the protection specified, or fildes is not open for write and PROT_WRITE was specified for a MAP_SHARED type mapping.
EAGAIN The mapping could not be locked in memory, if required by mlockall(), due to a lack of resources.
EBADF The fildes argument is not a valid open file descriptor.
EINVAL The value of len is zero.
EINVAL The value of flags is invalid (neither MAP_PRIVATE nor MAP_SHARED is set).
EMFILE The number of mapped regions would exceed an implementation-defined limit (per process or per system).
ENODEV The fildes argument refers to a file whose type is not supported by mmap().
ENOMEM MAP_FIXED was specified, and the range [addr,addr+len) exceeds that allowed for the address space of a process; or, if MAP_FIXED was not specified and there is insufficient room in the address space to effect the map
ping.
ENOMEM The mapping could not be locked in memory, if required by mlockall(), because it would require more space than the system is able to supply.
ENOMEM Not enough unallocated memory resources remain in the typed memory object designated by fildes to allocate len bytes.
ENOTSUP
MAP_FIXED or MAP_PRIVATE was specified in the flags argument and the implementation does not support this functionality.
The implementation does not support the combination of accesses requested in the prot argument.
ENXIO Addresses in the range [off,off+len) are invalid for the object specified by fildes.
ENXIO MAP_FIXED was specified in flags and the combination of addr, len, and off is invalid for the object specified by fildes.
ENXIO The fildes argument refers to a typed memory object that is not accessible from the calling process.
EOVERFLOW
The file is a regular file and the value of off plus len exceeds the offset maximum established in the open file description associated with fildes.
The mmap() function may fail if:
EINVAL The addr argument (if MAP_FIXED was specified) or off is not a multiple of the page size as returned by sysconf(), or is considered invalid by the implementation.
The following sections are informative.
EXAMPLES
None.
APPLICATION USAGE
Use of mmap() may reduce the amount of memory available to other memory allocation functions.
Use of MAP_FIXED may result in unspecified behavior in further use of malloc() and shmat(). The use of MAP_FIXED is discouraged, as it may prevent an implementation from making the most effective use of resources. Most im
plementations require that off and addr are multiples of the page size as returned by sysconf().
The application must ensure correct synchronization when using mmap() in conjunction with any other file access method, such as read() and write(), standard input/output, and shmat().
The mmap() function allows access to resources via address space manipulations, instead of read()/write(). Once a file is mapped, all a process has to do to access it is use the data at the address to which the file was
mapped. So, using pseudo-code to illustrate the way in which an existing program might be changed to use mmap(), the following:
fildes = open(...)
lseek(fildes, some_offset)
read(fildes, buf, len)
/* Use data in buf. */
becomes:
fildes = open(...)
address = mmap(0, len, PROT_READ, MAP_PRIVATE, fildes, some_offset)
/* Use data at address. */
RATIONALE
After considering several other alternatives, it was decided to adopt the mmap() definition found in SVR4 for mapping memory objects into process address spaces. The SVR4 definition is minimal, in that it describes only what
has been built, and what appears to be necessary for a general and portable mapping facility.
Note that while mmap() was first designed for mapping files, it is actually a general-purpose mapping facility. It can be used to map any appropriate object, such as memory, files, devices, and so on, into the address space
of a process.
When a mapping is established, it is possible that the implementation may need to map more than is requested into the address space of the process because of hardware requirements. An application, however, cannot count on
this behavior. Implementations that do not use a paged architecture may simply allocate a common memory region and return the address of it; such implementations probably do not allocate any more than is necessary. References
past the end of the requested area are unspecified.
If an application requests a mapping that overlaps existing mappings in the process, it might be desirable that an implementation detect this and inform the application. However, if the program specifies a fixed address map
ping (which requires some implementation knowledge to determine a suitable address, if the function is supported at all), then the program is presumed to be successfully managing its own address space and should be trusted
when it asks to map over existing data structures. Furthermore, it is also desirable to make as few system calls as possible, and it might be considered onerous to require an munmap() before an mmap() to the same address
range. This volume of POSIX.12017 specifies that the new mapping replaces any existing mappings (implying an automatic munmap() on the address range), following existing practice in this regard. The standard developers also
considered whether there should be a way for new mappings to overlay existing mappings, but found no existing practice for this.
It is not expected that all hardware implementations are able to support all combinations of permissions at all addresses. Implementations are required to disallow write access to mappings without write permission and to
disallow access to mappings without any access permission. Other than these restrictions, implementations may allow access types other than those requested by the application. For example, if the application requests only
PROT_WRITE, the implementation may also allow read access. A call to mmap() fails if the implementation cannot support allowing all the access requested by the application. For example, some implementations cannot support a
request for both write access and execute access simultaneously. All implementations must support requests for no access, read access, write access, and both read and write access. Strictly conforming code must only rely on
the required checks. These restrictions allow for portability across a wide range of hardware.
The MAP_FIXED address treatment is likely to fail for non-page-aligned values and for certain architecture-dependent address ranges. Conforming implementations cannot count on being able to choose address values for
MAP_FIXED without utilizing non-portable, implementation-defined knowledge. Nonetheless, MAP_FIXED is provided as a standard interface conforming to existing practice for utilizing such knowledge when it is available.
Similarly, in order to allow implementations that do not support virtual addresses, support for directly specifying any mapping addresses via MAP_FIXED is not required and thus a conforming application may not count on it.
The MAP_PRIVATE function can be implemented efficiently when memory protection hardware is available. When such hardware is not available, implementations can implement such ``mappings'' by simply making a real copy of the
relevant data into process private memory, though this tends to behave similarly to read().
The function has been defined to allow for many different models of using shared memory. However, all uses are not equally portable across all machine architectures. In particular, the mmap() function allows the system as
well as the application to specify the address at which to map a specific region of a memory object. The most portable way to use the function is always to let the system choose the address, specifying NULL as the value for
the argument addr and not to specify MAP_FIXED.
If it is intended that a particular region of a memory object be mapped at the same address in a group of processes (on machines where this is even possible), then MAP_FIXED can be used to pass in the desired mapping address.
The system can still be used to choose the desired address if the first such mapping is made without specifying MAP_FIXED, and then the resulting mapping address can be passed to subsequent processes for them to pass in via
MAP_FIXED. The availability of a specific address range cannot be guaranteed, in general.
The mmap() function can be used to map a region of memory that is larger than the current size of the object. Memory access within the mapping but beyond the current end of the underlying objects may result in SIGBUS signals
being sent to the process. The reason for this is that the size of the object can be manipulated by other processes and can change at any moment. The implementation should tell the application that a memory reference is out
side the object where this can be detected; otherwise, written data may be lost and read data may not reflect actual data in the object.
Note that references beyond the end of the object do not extend the object as the new end cannot be determined precisely by most virtual memory hardware. Instead, the size can be directly manipulated by ftruncate().
Process memory locking does apply to shared memory regions, and the MCL_FUTURE argument to mlockall() can be relied upon to cause new shared memory regions to be automatically locked.
Existing implementations of mmap() return the value -1 when unsuccessful. Since the casting of this value to type void * cannot be guaranteed by the ISO C standard to be distinct from a successful value, this volume of
POSIX.12017 defines the symbol MAP_FAILED, which a conforming implementation does not return as the result of a successful call.
FUTURE DIRECTIONS
None.
SEE ALSO
exec, fcntl(), fork(), lockf(), msync(), munmap(), mprotect(), posix_typed_mem_open(), shmat(), sysconf()
The Base Definitions volume of POSIX.12017, <sys_mman.h>
COPYRIGHT
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7,
2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the
original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-
pages/reporting_bugs.html .
IEEE/The Open Group 2017 MMAP(3P)

View file

@ -0,0 +1,4 @@
{
"args": ["{test_case}.in", "{test_case}.out_produced", "mmap"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
38

View file

@ -0,0 +1 @@
Quisquam ananas quisquam dolor voluptatem quaerat ananas ipsum consectetur. ananasPorro quisquam est quisquam. Adipisci quaerat ananas ut voluptatem ut amet. Tempora ut non non. Tempora magnam porro nananason. Velit ananas ipsum numquam voluptatem magnananasam ananas ut consectetur magnam. Numquam sit ananas ipsum eius. Quiquia ananas amet labore consectetur ananas magnam. Est aliquam dolore numquam ananas

View file

@ -0,0 +1 @@
12

View file

@ -0,0 +1 @@
Ipsum consectetur aliquam ut sit quiquia. Numquam labore quiquia tempora labore magnam aliquam. Neque eius magnam eius adipisci labore numquam magnam. Quaerat numquam tempora labore. Eius quaerat est porro amet ut. Etincidunt etincidunt dolor labore adipisci. Etincidunt quiquia voluptatem numquam quiquia ut voluptatem neque. Velit dolor quiquia est. Quiquia dolor sed est quisquam quisquam. Est porro quiquia tempora numquam ipsum consectetur non. Dolore porro magnam dolorem dolore dolor ipsum. Aliquam quiquia quiquia modi quisquam eius. Dolorem tempora adipisci ut dolor dolorem. Sit quaerat ut est aliquam modi magnam. Eius dolore

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1 @@
Quiquia est dolore quisquam. Magnam voluptatem dolorem dolor quaerat sed. Est labore eius etincidunt. Dolore neque magnam quisquam. Labore amet velit ipsum dolorem quaerat sed modi. Numquam labore quaerat non dolor quaerat dolore. Magnam dolore porro amet porro. Dolorem quiquia adipisci dolor dolore numquam porro dolorem. Velit sit numquam sit. Modi tempora ut dolor numquam. Numquam porro eius quaerat ut. Amet sit eius etincidunt ipsum ipsum.

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1 @@
Eius dolore est ipsum neque. Tempoananasra dolorem est labore ananas aliquam neque consectetur ananas dolor. Ut sed aliquam ut. Ut consectetur quiquia modi eius ananas eius. Dolore sed maananasgnam etincidunt quisquam dolor. Quaerat etincidunt aliquam etincidunt dolor ananas consectetur quaerat. Numquam ananas amet numquam esananast dolorem ananasconsectetur quisquam neque. Quisquam voluptatem consectetur non modi adipisci labore quisquam. Quiquia porro nananaseque sed magnam sed magnam porro. ananas Aliquam amet quaerat dolore quaerat. Numquam porro magnam ipsum etincidunt adipisci quisquam adipisci.

View file

@ -0,0 +1 @@
11

View file

@ -0,0 +1,4 @@
{
"args": ["test-counting/fgetc.in", "{test_case}.out_produced", "stream"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
10

View file

@ -0,0 +1 @@
anananas

View file

@ -0,0 +1 @@
1

View file

@ -0,0 +1 @@
nananananananananananas aaaaaaaaaaaaaaaaaaaaaaaaaaananas ananassssssssssssssssssssss

View file

@ -0,0 +1 @@
3

View file

@ -0,0 +1,9 @@
4;3
2;2
0;1
-1;0
1;0
3;0
6;1
5;0
7;0

View file

@ -0,0 +1,15 @@
5;4
3;2
2;1
1;0
nil
4;0
8;3
6;1
nil
7;0
12;2
10;1
9;0
11;0
13;0

View file

@ -0,0 +1,11 @@
13;3
8;2
1;1
nil
6;0
11;0
17;2
15;0
25;1
22;0
27;0

View file

@ -0,0 +1,15 @@
8;4
5;3
3;2
2;1
1;0
nil
4;0
7;1
6;0
nil
11;2
10;1
9;0
nil
12;0

View file

@ -0,0 +1,11 @@
13;1
8;1
1;0
nil
6;0
11;0
17;1
15;0
25;0
22;0
27;0

View file

@ -0,0 +1 @@
nil

View file

@ -0,0 +1 @@
8;0

View file

@ -0,0 +1,3 @@
10;1
9;0
11;0

View file

@ -0,0 +1,3 @@
4;1
3;0
nil

View file

@ -0,0 +1,3 @@
4;1
nil
5;0

View file

@ -0,0 +1,7 @@
42;2
11;1
nil
33;0
314;1
171;0
981;0

View file

@ -0,0 +1,85 @@
#include <stdio.h>
#include <stdlib.h>
#define UNUSED(x) ((void) (x))
struct node
{
int key;
int rank;
struct node *left;
struct node *right;
};
struct tree
{
struct node *root;
};
/**
* @brief Creates new dynamically allocated node.
* @param key Key that node holds.
* @param rank Rank that node has.
* @returns Pointer to dynamically allocated node, NULL if allocation fails.
*/
struct node *
create_node(int key, int rank)
{
struct node *new_node = calloc(1, sizeof(struct node));
if (new_node == NULL) {
fprintf(stderr, "create_node: Cannot allocate memory for node.\n");
return NULL;
}
new_node->key = key;
new_node->rank = rank;
return new_node;
}
/**
* @brief Recursively frees node and its subtrees.
* @param node Root of the subtree to be freed.
*/
void free_node(struct node *node)
{
if (node == NULL) {
return;
}
free_node(node->left);
free_node(node->right);
free(node);
}
/**
* @brief Prettyprints given tree into the file.
* @param file File for output.
* @param tree Tree to be prettyprinted.
*/
void pretty_print_tree(FILE *file, const struct tree *tree)
{
UNUSED(file);
UNUSED(tree);
}
/**
* @brief Loads tree from a file and returns root of it.
* @param file File where the tree is saved.
* @returns Pointer to the loaded tree, NULL if error happens or no tree is in file.
*/
struct node *load_tree(FILE *file)
{
UNUSED(file);
}
int main(int argc, char **argv)
{
if (argc < 2 || argc > 3) {
printf("Usage: %s <input-file> [output-file]\n", argv[0]);
return 1;
}
/* TODO */
return 0;
}

View file

View file

@ -0,0 +1,24 @@
cmake_minimum_required(VERSION 3.0)
# Project configuration
project(seminar10-bonus)
set(SOURCES hangman.c main.c)
# Executable
add_executable(hangman hangman.c main.c)
add_executable(test_hangman test_hangman.c hangman.c)
# Configure compiler warnings
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
# using regular Clang, AppleClang or GCC
# Strongly suggested: neable -Werror
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
# using Visual Studio C++
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
endif()
if(MINGW)
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
endif()

View file

@ -0,0 +1,11 @@
check: check-unit check-functional
check-unit:
build/test_hangman
check-functional:
python3 test-bonus.py test hangman
python3 test-bonus.py test hangman --no-global-config
clean:
rm -rf test-*/*.out_produced

View file

@ -0,0 +1,233 @@
#include "hangman.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define MAX_LENGTH 50
#define ALPHABET_LENGTH 27
int get_word(const char *wordlist, char secret[])
{
FILE *fp = fopen(wordlist, "rb");
if (fp == NULL) {
fprintf(stderr, "No such file or directory: %s\n", wordlist);
return 1;
}
struct stat st;
stat(wordlist, &st);
long int size = st.st_size;
/* FIXME: Can fall into infinite loop... */
do {
long int random = (rand() % size) + 1;
fseek(fp, random, SEEK_SET);
int result = fscanf(fp, "%*s %20s", secret);
if (result != EOF)
break;
} while (1);
fclose(fp);
return 0;
}
static void print_word(const char *word)
{
for (size_t i = 0; word[i]; i++) {
printf(" %c", word[i]);
}
printf("\n");
}
bool word_guessed(const char secret[], const char letters_guessed[])
{
size_t l = strlen(secret), k=0;
for (size_t j = 0; letters_guessed[j]; j++) {
for (size_t i = 0; secret[i]; i++) {
if (secret[i] == letters_guessed[j]) {
k++;
}
}
}
return l <= k;
}
void censor_word(const char secret[], const char letters_guessed[], char guessed_word[])
{
size_t i;
for (i = 0; secret[i]; i++, guessed_word++) {
*guessed_word = secret[i];
bool guessed = false;
for (int j = 0; letters_guessed[j]; j++) {
if (secret[i] == letters_guessed[j]) {
guessed = true;
}
}
if (!guessed) {
*guessed_word = '_';
}
}
*guessed_word = '\0';
}
void get_available_letters(const char letters_guessed[],
char available_letters[])
{
size_t k = 0;
for (char letter = 'a'; letter <= 'z'; letter++) {
bool to_be_put = true;
for (size_t j = 0; letters_guessed[j]; j++) {
if (letters_guessed[j] == letter) {
to_be_put = false;
break;
}
}
if (to_be_put) {
available_letters[k++] = letter;
}
}
available_letters[k] = '\0';
}
static bool been_already_guessed(const char *guessed_letters,
const char letter)
{
for (size_t i = 0; guessed_letters[i]; i++) {
if (guessed_letters[i] == letter) {
return true;
}
}
return false;
}
static bool is_good_guess(const char secret[], char guessed_word[], const char letter)
{
bool result = false;
for (size_t i = 0; secret[i]; i++) {
if (secret[i] == letter) {
result = true;
break;
}
}
if (result) {
printf("Good guess:");
} else {
printf("Oops! That letter is not in my word:");
}
print_word(guessed_word);
return result;
}
static bool guessed_whole(const char *secret, const char *guess)
{
for (size_t i = 0; secret[i]; i++)
if (tolower(guess[i]) != secret[i]) {
return false;
}
return true;
}
static int get_guess(char *guess)
{
int result = scanf("%s", guess);
if (result == 1) {
*guess = tolower(*guess);
return result;
}
int ch = 0;
fprintf(stderr, "Input was not successful.\n");
while (ch != EOF && (ch = getchar()) != '\n')
;
return result;
}
void hangman(const char secret[])
{
printf("Welcome to the game, Hangman!\n");
size_t length_of_word = strlen(secret);
printf("I am thinking of a word that is %lu letters long.\n",
length_of_word);
int guesses = 8, no_of_guessed_letters = 0;
char available_letters[ALPHABET_LENGTH],
guessed_letters[ALPHABET_LENGTH] = { 0 };
char guess[MAX_LENGTH];
char guessed_word[MAX_LENGTH] = { 0 };
get_available_letters(guessed_letters, available_letters);
while (guesses > 0) {
printf("-------------\n");
if (word_guessed(secret, guessed_letters)) {
printf("Congratulations, you won!\n");
return;
}
printf("You have %d guesses left.\n", guesses);
printf("Available letters: %s\n", available_letters);
printf("Please guess a letter: ");
int read_status = get_guess(guess);
if (read_status == EOF) {
fprintf(stderr, "No more input to read.\n");
return;
} else if (read_status == 0) {
continue;
}
if (guess[1]) {
if (guessed_whole(secret, guess)) {
printf("Congratulations, you won!\n");
} else {
printf("Sorry, bad guess. The word was %s.\n", secret);
}
}
if (*guess < 'a' || *guess > 'z') {
printf("Oops! '%c' is not a valid letter:", *guess);
censor_word(secret, guessed_letters, guessed_word);
print_word(guessed_word);
continue;
}
if (been_already_guessed(guessed_letters, *guess)) {
printf("Oops! You've already guessed that letter:");
censor_word(secret, guessed_letters, guessed_word);
print_word(guessed_word);
continue;
}
guessed_letters[no_of_guessed_letters++] = *guess;
get_available_letters(guessed_letters, available_letters);
censor_word(secret, guessed_letters, guessed_word);
if (!is_good_guess(secret, guessed_word, *guess)) {
guesses--;
}
}
if (guesses == 0) {
printf("-------------\n");
printf("Sorry, you ran out of guesses. The word was %s.\n", secret);
}
}

View file

@ -0,0 +1,55 @@
#include <stdbool.h>
#define WORDLIST_FILENAME "words.txt"
/**
* Function detects, whether player guessed the secret word
* Based on the letters player used for guessing, this function detects,
* if it is possible to construct (and guess) the secret word from this set.
* If it is possible, function returns true. If not, returns false.
* @param secret the secret word lowercase
* @param letters_guessed the lowercase letters player already used in his guessing
* @return true, if word is guess; false otherwise.
*/
bool word_guessed(const char secret[], const char letters_guessed[]);
/**
* Function returns string representing the guessed word
* This string contains visible letters, which were guessed successfuly
* by player at their correct positions. If there are still some hidden
* letters, the character '_' will be used for their representation.
* @param secret the secret word lowercase
* @param letters_guessed the lowercase letters player already used in his guessing
* @param guessed_word the constructed string as result of this function (output parameter)
*/
void censor_word(const char secret[], const char letters_guessed[], char guessed_word[]);
/**
* Returns all letters, which were not used for guessing
* Function returns set of lowercase letters sorted in alphabetical order. This
* set will contain all letters from the alphabet, but it ommits those, which
* were already guessed.
* @param letters_guessed the lowercase letters player already used in his guessing
* @param available_letters set of lowercase not yet used letters
*/
void get_available_letters(const char letters_guessed[], char available_letters[]);
/**
* Starts interactive hangman game
*
* @param secret the secret word lowercase
*/
void hangman(const char secret[]);
/**
* Returns the random word
* Function opens the file with all the words and reads randomly one of them
* into the buffer pointed by secret. Word consists of lowercase letters.
* If there is some error with reading the file, 1 is returned.
* Don't forget to initialize the random numbers in your main() function will srand() call!
* Otherwise (everything is ok), 0 is returned.
* @param wordlist path to the file with words
* @param secret buffer, where random word will be read
* @return status code
*/
int get_word(const char *wordlist, char secret[]);

View file

@ -0,0 +1,5 @@
{
"args": ["{test_case}.words"],
"has_stdin": true,
"capture_stdout": true
}

View file

@ -0,0 +1,23 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "hangman.h"
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: %s path-to-wordlist\n", argv[0]);
return 1;
}
char secret[50];
srand(time(NULL));
if (get_word(argv[1], secret) != 0) {
return 1;
}
hangman(secret);
return 0;
}

View file

@ -0,0 +1 @@
../../test-bonus.py

View file

@ -0,0 +1 @@
!*.words

View file

@ -0,0 +1,2 @@
o
word

View file

@ -0,0 +1,10 @@
Welcome to the game, Hangman!
I am thinking of a word that is 4 letters long.
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: Good guess: _ o _ _
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnpqrstuvwxyz
Please guess a letter: Sorry, bad guess. The word was goal.

View file

@ -0,0 +1,3 @@
goal
goal
goal

View file

@ -0,0 +1,2 @@
e
ball

View file

@ -0,0 +1,10 @@
Welcome to the game, Hangman!
I am thinking of a word that is 4 letters long.
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ _
-------------
You have 7 guesses left.
Available letters: abcdfghijklmnopqrstuvwxyz
Please guess a letter: Congratulations, you won!

View file

@ -0,0 +1,3 @@
ball
ball
ball

View file

@ -0,0 +1,16 @@
l
e
d
a
U
u
s
p
r

View file

@ -0,0 +1,40 @@
Welcome to the game, Hangman!
I am thinking of a word that is 7 letters long.
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: Good guess: _ _ _ _ l _ _
-------------
You have 8 guesses left.
Available letters: abcdefghijkmnopqrstuvwxyz
Please guess a letter: Good guess: _ _ _ _ l e _
-------------
You have 8 guesses left.
Available letters: abcdfghijkmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ _ l e _
-------------
You have 7 guesses left.
Available letters: abcfghijkmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ _ l e _
-------------
You have 6 guesses left.
Available letters: bcfghijkmnopqrstuvwxyz
Please guess a letter: Good guess: _ u _ _ l e _
-------------
You have 6 guesses left.
Available letters: bcfghijkmnopqrstvwxyz
Please guess a letter: Oops! You've already guessed that letter: _ u _ _ l e _
-------------
You have 6 guesses left.
Available letters: bcfghijkmnopqrstvwxyz
Please guess a letter: Good guess: _ u _ _ l e s
-------------
You have 6 guesses left.
Available letters: bcfghijkmnopqrtvwxyz
Please guess a letter: Good guess: p u _ p l e s
-------------
You have 6 guesses left.
Available letters: bcfghijkmnoqrtvwxyz
Please guess a letter: Good guess: p u r p l e s
-------------
Congratulations, you won!

View file

@ -0,0 +1,3 @@
purples
purples
purples

View file

@ -0,0 +1,11 @@
a
e
@
h
N
hangman

View file

@ -0,0 +1,26 @@
Welcome to the game, Hangman!
I am thinking of a word that is 7 letters long.
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: Good guess: _ a _ _ _ a _
-------------
You have 8 guesses left.
Available letters: bcdefghijklmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ a _ _ _ a _
-------------
You have 7 guesses left.
Available letters: bcdfghijklmnopqrstuvwxyz
Please guess a letter: Oops! '@' is not a valid letter: _ a _ _ _ a _
-------------
You have 7 guesses left.
Available letters: bcdfghijklmnopqrstuvwxyz
Please guess a letter: Good guess: h a _ _ _ a _
-------------
You have 7 guesses left.
Available letters: bcdfgijklmnopqrstuvwxyz
Please guess a letter: Good guess: h a n _ _ a n
-------------
You have 7 guesses left.
Available letters: bcdfgijklmopqrstuvwxyz
Please guess a letter: Congratulations, you won!

View file

@ -0,0 +1,3 @@
hangman
hangman
hangman

View file

@ -0,0 +1,11 @@
a
e
b
c
q
w
p
l
m
x
z

View file

@ -0,0 +1,40 @@
Welcome to the game, Hangman!
I am thinking of a word that is 10 letters long.
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ _ _ _ _ _ _ _
-------------
You have 7 guesses left.
Available letters: bcdefghijklmnopqrstuvwxyz
Please guess a letter: Good guess: _ _ _ e _ e _ _ e _
-------------
You have 7 guesses left.
Available letters: bcdfghijklmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ e _ e _ _ e _
-------------
You have 6 guesses left.
Available letters: cdfghijklmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ e _ e _ _ e _
-------------
You have 5 guesses left.
Available letters: dfghijklmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ e _ e _ _ e _
-------------
You have 4 guesses left.
Available letters: dfghijklmnoprstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ e _ e _ _ e _
-------------
You have 3 guesses left.
Available letters: dfghijklmnoprstuvxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ e _ e _ _ e _
-------------
You have 2 guesses left.
Available letters: dfghijklmnorstuvxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ e _ e _ _ e _
-------------
You have 1 guesses left.
Available letters: dfghijkmnorstuvxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ e _ e _ _ e _
-------------
Sorry, you ran out of guesses. The word was undeserved.

View file

@ -0,0 +1,3 @@
undeserved
undeserved
undeserved

View file

@ -0,0 +1,4 @@
{
"args": [],
"capture_stdout": true
}

View file

@ -0,0 +1 @@
Usage: build/hangman path-to-wordlist

View file

@ -0,0 +1,64 @@
#include "hangman.h"
#include <stdbool.h>
#include <string.h>
#define CUT_MAIN
#include "cut.h"
TEST(word_guessed)
{
SUBTEST(example_not_guessed)
{
CHECK(!word_guessed("secret", "aeiou"));
}
SUBTEST(example_guessed)
{
CHECK(word_guessed("hi", "aeihoul"));
}
SUBTEST(multiple_letters)
{
CHECK(word_guessed("baba", "ba"));
}
}
TEST(censor_word)
{
SUBTEST(example)
{
char result[30];
censor_word("container", "arpstxgoieyu", result);
CHECK(strcmp(result, "_o_tai_er") == 0);
}
SUBTEST(bigger_example)
{
char result[30];
censor_word("underserved", "arpstxgoieyu", result);
CHECK(strcmp(result, "u__erser_e_") == 0);
}
}
TEST(get_available_letters)
{
SUBTEST(example)
{
char result[30];
get_available_letters("arpstxgoieyu", result);
CHECK(strcmp(result, "bcdfhjklmnqvwz") == 0);
}
SUBTEST(all) {
char result[30];
get_available_letters("", result);
CHECK(strcmp(result, "abcdefghijklmnopqrstuvwxyz") == 0);
}
SUBTEST(none) {
char result[30];
get_available_letters("abcdefghijklmnopqrstuvwxyz", result);
CHECK(strcmp(result, "") == 0);
}
}