├── LICENSE.txt ├── README.md ├── doc ├── README.md ├── articles.md ├── biblio.md ├── free_books.md ├── img │ └── pdf_doc.png ├── papers_talks.md ├── stds_and_refs.md └── unix_history.md └── src ├── C ├── Abstract_Data_Types │ ├── ADT_black_boxes │ │ ├── addresslist.c │ │ ├── addresslist.h │ │ ├── main.c │ │ └── makefile │ ├── ADT_stack │ │ ├── README.md │ │ ├── dynamic_vector │ │ │ ├── main.c │ │ │ ├── makefile │ │ │ ├── stack.c │ │ │ └── stack.h │ │ ├── fixed_length_vector │ │ │ ├── main.c │ │ │ ├── makefile │ │ │ ├── stack.c │ │ │ └── stack.h │ │ └── linked_list │ │ │ ├── main.c │ │ │ ├── makefile │ │ │ ├── stack.c │ │ │ └── stack.h │ ├── Buffer │ │ ├── buffer.c │ │ ├── buffer.h │ │ └── main.c │ └── CSV_library │ │ ├── csv.c │ │ ├── csv.h │ │ ├── main.c │ │ └── makefile ├── Algorithms_and_Data_Structures │ ├── algorithms │ │ ├── Knuth_Morris_Path │ │ │ ├── kmp.c │ │ │ ├── kmp.h │ │ │ └── main.c │ │ ├── hanoi │ │ │ ├── get.c │ │ │ ├── hanoi.h │ │ │ ├── main.c │ │ │ └── move.c │ │ ├── ordinamento │ │ │ ├── mergesort │ │ │ │ ├── main.c │ │ │ │ ├── merge.c │ │ │ │ ├── mergesort.c │ │ │ │ └── mergesort.h │ │ │ ├── quicksort │ │ │ │ └── full_example │ │ │ │ │ ├── find_pivot.c │ │ │ │ │ ├── main.c │ │ │ │ │ ├── partition.c │ │ │ │ │ ├── quicksort.c │ │ │ │ │ ├── quicksort.h │ │ │ │ │ └── wrt.c │ │ │ └── selection_sort │ │ │ │ ├── README │ │ │ │ ├── header.h │ │ │ │ ├── main.c │ │ │ │ └── selection-sort.c │ │ └── ricerca │ │ │ ├── ricerca_binaria │ │ │ └── binary_search.c │ │ │ └── ricerca_sequenziale │ │ │ ├── ricerca-sequenziale-1.c │ │ │ ├── ricerca-sequenziale-2.c │ │ │ └── ricerca-sequenziale-3.c │ └── data_structures │ │ ├── array │ │ ├── README.md │ │ ├── crivello_eratostene.c │ │ └── vectors_and_files.c │ │ ├── hash_table │ │ ├── hash_table.c │ │ └── markov_chain_algorithm.c │ │ ├── linked_list │ │ ├── address_book.c │ │ ├── giuseppe_flavio_problem.c │ │ ├── linear_linked_list │ │ │ ├── Makefile │ │ │ ├── linklinstruct.c │ │ │ ├── linklinstruct.h │ │ │ └── main.c │ │ ├── lista_concatenata.c │ │ ├── personLLS.c │ │ └── sorted_sequence_node │ │ │ ├── Makefile │ │ │ ├── main.c │ │ │ ├── sorted_sequence.c │ │ │ └── sorted_sequence.h │ │ ├── polish_stack │ │ ├── eval.c │ │ ├── fill.c │ │ ├── main.c │ │ ├── po_out │ │ ├── polish.h │ │ ├── stack.c │ │ └── wrt.c │ │ ├── queue │ │ └── linked_linear_structure_implementation │ │ │ ├── Makefile │ │ │ ├── main.c │ │ │ ├── type_queue.c │ │ │ └── type_queue.h │ │ ├── stack │ │ ├── c_declarations_parser │ │ │ ├── cdeclar.c │ │ │ ├── cdeclar.h │ │ │ └── main.c │ │ ├── linked_list_representation │ │ │ ├── main.c │ │ │ ├── stack.c │ │ │ └── stack.h │ │ └── vector_representation │ │ │ ├── stack_module │ │ │ ├── main.c │ │ │ ├── stack.c │ │ │ └── stack.h │ │ │ ├── stack_module2 │ │ │ ├── main.c │ │ │ ├── stack.c │ │ │ └── stack.h │ │ │ └── stack_with_vector.c │ │ └── tree │ │ ├── binary_tree │ │ └── binary_tree_1 │ │ │ ├── create.c │ │ │ ├── main.c │ │ │ ├── traversal.c │ │ │ └── tree.h │ │ └── general_tree │ │ ├── general_tree_1 │ │ ├── gtree.c │ │ ├── gtree.h │ │ ├── main.c │ │ ├── traversal.c │ │ └── wrt.c │ │ └── general_tree_2 │ │ ├── build.c │ │ ├── gtree.c │ │ ├── gtree.h │ │ ├── main.c │ │ ├── traversal.c │ │ └── wrt.c ├── C_lang │ ├── README.md │ ├── array │ │ ├── array_bidimensional.c │ │ ├── array_initialization.c │ │ ├── array_multidimentional.c │ │ ├── break_multidim_array_components.c │ │ ├── compound_literal.c │ │ ├── dynamic_vector.c │ │ ├── dynamic_vector_redefinition.c │ │ ├── find_duplicate_members.c │ │ ├── how_compiler_treats_array_access.c │ │ ├── jagged_array.c │ │ └── variable_length_array.c │ ├── dynamic_memory_allocation │ │ ├── README.md │ │ ├── calloc │ │ │ ├── alloc_func.c │ │ │ ├── calloc.c │ │ │ └── simulate_calloc.c │ │ ├── free │ │ │ ├── dangling_pointers.c │ │ │ ├── double_free.c │ │ │ ├── free.c │ │ │ └── null_to_freed_pointer.c │ │ ├── full_programs │ │ │ └── notes.c │ │ ├── malloc │ │ │ ├── concat_strings.c │ │ │ ├── idiom.c │ │ │ └── malloc.c │ │ ├── mem_family_functions │ │ │ ├── README.md │ │ │ ├── how_memset_memmove_memcpy_work.c │ │ │ ├── memcpy.c │ │ │ ├── memmove.c │ │ │ └── memset.c │ │ └── realloc │ │ │ ├── realloc.c │ │ │ ├── realloc_array_of_characters.c │ │ │ └── realloc_array_of_integers.c │ ├── error_handling │ │ └── inline_function.c │ ├── expressions │ │ └── generic_selections │ │ │ └── generic.c │ ├── functions │ │ ├── 01_functions_basic.c │ │ ├── 02_array_as_parameter.c │ │ ├── 03_array_multidim_as_parameter.c │ │ ├── compound_literals_as_parameter │ │ │ ├── README.md │ │ │ ├── array_parameter.c │ │ │ └── structure_parameter.c │ │ ├── functions_and_pointers │ │ │ ├── full_programs │ │ │ │ ├── get_max_min.c │ │ │ │ └── swap.c │ │ │ ├── function_pointer │ │ │ │ ├── README.md │ │ │ │ ├── array_of_function_pointers.c │ │ │ │ ├── declaring_function_pointer.c │ │ │ │ └── passing_and_returning_a_fp.c │ │ │ ├── functions_and_multidim_array │ │ │ │ ├── returning_an_array.c │ │ │ │ └── sum_cols_and_rows.c │ │ │ ├── functions_and_onedim_array │ │ │ │ ├── pointer_vs_array.c │ │ │ │ └── sum_each_array_elem.c │ │ │ ├── passing_pointer_as_parameter.c │ │ │ ├── passing_pointer_by_value.c │ │ │ ├── passing_pointer_to_const.c │ │ │ ├── passing_pointer_to_pointer.c │ │ │ └── returning_a_pointer.c │ │ ├── get_hash_string.c │ │ ├── higher_order_functions │ │ │ ├── README.md │ │ │ ├── callback_functions │ │ │ │ ├── README.md │ │ │ │ ├── data.sql │ │ │ │ ├── fail_and_done.c │ │ │ │ └── open_database.c │ │ │ ├── make_operations.c │ │ │ ├── multiplier.c │ │ │ └── qsort_basic.c │ │ ├── printhex.c │ │ ├── stack.c │ │ ├── variable_length_array_as_param.c │ │ └── variadic_functions │ │ │ ├── iterate.c │ │ │ └── variadic_functions.c │ ├── idioms │ │ └── 07_idioms.c │ ├── input_output │ │ ├── README.md │ │ ├── block_IO │ │ │ ├── README.md │ │ │ ├── how_fread_and_fwrite_work.c │ │ │ ├── read_write_array_to_file.c │ │ │ ├── read_write_multiple_data_to_file.c │ │ │ └── read_write_structure_to_file.c │ │ ├── copy_input_to_output_line_by_line.c │ │ ├── file_positioning │ │ │ ├── README.md │ │ │ ├── fsetpos_fgetpos.c │ │ │ └── reverse_with_fseek_ftell.c │ │ ├── fprintf_and_fscanf.c │ │ ├── freopen.c │ │ ├── full_programs │ │ │ ├── add_strings_to_file.c │ │ │ ├── concatenate_files.c │ │ │ ├── count_characters.c │ │ │ ├── date_to_log.c │ │ │ ├── double_space.c │ │ │ ├── get_strings_from_binary.c │ │ │ ├── input_chunks_more_simulation.c │ │ │ ├── realtime_file_to_hex_conversion.c │ │ │ ├── record.c │ │ │ ├── search_file.c │ │ │ ├── text_notes.c │ │ │ └── visible_chars.c │ │ ├── printf_width_precision.c │ │ ├── snprintf.c │ │ ├── stream_buffering │ │ │ └── setvbuf.c │ │ ├── ungetc.c │ │ ├── use_feof_correctly.c │ │ ├── write_data_to_ascii_file.c │ │ └── write_structure_to_ascii_file.c │ ├── logical_operators │ │ └── logical_operators.c │ ├── pointers │ │ ├── 01_pointer_variable.c │ │ ├── 02_address_of_operator.c │ │ ├── 03_indirection_operator.c │ │ ├── 04_print_address.c │ │ ├── 05_pointer_to_void.c │ │ ├── 06_pointer_sizeof.c │ │ ├── 07_pointer_and_const.c │ │ ├── README.md │ │ ├── casting.c │ │ ├── full_programs │ │ │ ├── find_and_delete_substring.c │ │ │ ├── find_first_occurence.c │ │ │ ├── palindrome.c │ │ │ └── sieve_of_eratosthenes.c │ │ ├── pointer_arithmetic │ │ │ ├── addition.c │ │ │ ├── alloc.c │ │ │ ├── ptr_comparison_1.c │ │ │ ├── ptr_comparison_2.c │ │ │ ├── ptr_comparison_3.c │ │ │ ├── subtraction_int.c │ │ │ └── subtraction_ptr.c │ │ ├── pointer_to_function_1.c │ │ ├── pointer_to_function_2_bubblesort.c │ │ ├── pointer_to_pointer.c │ │ ├── pointers_and_array │ │ │ ├── array_of_pointers │ │ │ │ ├── array_of_integer_pointers.c │ │ │ │ ├── copy_strings.c │ │ │ │ ├── lookup_string.c │ │ │ │ ├── print_addresses.c │ │ │ │ ├── print_array_of_pointers_to_strings.c │ │ │ │ ├── print_array_of_strings.c │ │ │ │ ├── ptr2str_and_arr2ptr2str.c │ │ │ │ ├── qsort_array_of_pointers_to_strings.c │ │ │ │ └── sort_array_of_pointers_to_strings.c │ │ │ ├── full_programs │ │ │ │ └── sorting_strings.c │ │ │ ├── multidimensional_array │ │ │ │ ├── get_only_the_first_row_elements.c │ │ │ │ ├── lvalue_rvalue.c │ │ │ │ ├── pointers_and_array_multidim_1.c │ │ │ │ └── pointers_and_array_multidim_2.c │ │ │ └── onedimensional_array │ │ │ │ ├── assign_array_to_pointer.c │ │ │ │ ├── init_each_element_to_zero.c │ │ │ │ ├── print_addresses.c │ │ │ │ ├── subscripts_and_indirection_1.c │ │ │ │ └── subscripts_and_indirection_2.c │ │ ├── pointers_and_compound_literals.c │ │ └── restricted_pointers.c │ ├── preprocessor │ │ ├── generic_selection.c │ │ ├── macro_arguments.c │ │ ├── macro_expansion.c │ │ ├── macro_replacement_1_stringization.c │ │ ├── macro_replacement_2_token_pasting.c │ │ ├── macro_replacement_3_token_pasting.c │ │ └── predefined_macro.c │ ├── regex │ │ ├── 01-regex.c │ │ └── full_programs │ │ │ └── mygrep.c │ ├── strings │ │ ├── 01_string_literals.c │ │ ├── 02_string_variable.c │ │ ├── 03_string_length.c │ │ ├── 04_string_output.c │ │ ├── 05_standard_library.c │ │ ├── 06_array_of_pointers_2.c │ │ ├── 06_vector_of_strings_1.c │ │ ├── compare_strings.c │ │ ├── const_string_as_compound_literal.c │ │ ├── find_and_replace_strings │ │ │ ├── find_and_replace_1.c │ │ │ ├── find_and_replace_2.c │ │ │ ├── find_word_in_text_1.c │ │ │ ├── find_word_in_text_2.c │ │ │ ├── find_word_in_text_3.c │ │ │ └── find_word_in_text_4.c │ │ ├── input_string.c │ │ ├── parse_with_sscanf.c │ │ ├── search_substring.c │ │ ├── simulate_standard_functions │ │ │ ├── main.c │ │ │ ├── my_strfunc.h │ │ │ ├── my_strncat.c │ │ │ └── my_strncpy.c │ │ ├── strcopy_with_pointers.c │ │ ├── strdup.c │ │ ├── string_is_a_pointer.c │ │ ├── string_to_linked_list │ │ │ ├── 01_string_to_list │ │ │ │ ├── list.h │ │ │ │ ├── main.c │ │ │ │ ├── makefile │ │ │ │ └── str_to_list.c │ │ │ ├── 02_string_to_list │ │ │ │ ├── list.h │ │ │ │ ├── main.c │ │ │ │ ├── makefile │ │ │ │ └── str_to_list.c │ │ │ ├── 03_string_to_list │ │ │ │ ├── list.c │ │ │ │ ├── list.h │ │ │ │ ├── main.c │ │ │ │ ├── makefile │ │ │ │ └── str_to_list.c │ │ │ └── 04_string_to_list │ │ │ │ ├── input │ │ │ │ ├── list.c │ │ │ │ ├── list.h │ │ │ │ ├── main.c │ │ │ │ ├── makefile │ │ │ │ ├── str_to_list.c │ │ │ │ └── wrt.c │ │ ├── strtok.c │ │ └── working_char_by_char │ │ │ ├── count_rows.c │ │ │ ├── get_line.c │ │ │ ├── getline.c │ │ │ ├── reading_char_by_char.c │ │ │ ├── squeeze.c │ │ │ └── wc_simulator.c │ ├── structures_and_unions │ │ ├── README.md │ │ ├── anonymous_structures.c │ │ ├── bitfield.c │ │ ├── copy_structures.c │ │ ├── full_programs │ │ │ ├── hardware_components.c │ │ │ ├── hardware_components.h │ │ │ ├── main.c │ │ │ ├── makefile │ │ │ ├── readline.c │ │ │ └── readline.h │ │ ├── offsetof.c │ │ ├── pointer_to_nested_structures.c │ │ ├── rgb_color.h │ │ ├── sizeof_structures.c │ │ ├── strtag.h │ │ ├── structures.c │ │ ├── structures_and_compund_literals.c │ │ ├── structures_as_function_parameter.c │ │ ├── typedef_structures.c │ │ ├── unions │ │ │ ├── get_individual_bytes_with_array.c │ │ │ ├── get_individual_bytes_with_struct.c │ │ │ ├── publisher.c │ │ │ ├── structure_union_bitfield.c │ │ │ └── unions.c │ │ └── vector_of_structures.c │ └── stuff │ │ ├── attributes_of_variables │ │ ├── README.md │ │ └── main.c │ │ ├── binary_constant_with_GNU_extension.c │ │ ├── how_much_memory_allocate.c │ │ ├── mathematics │ │ ├── 2nd_degree_equations │ │ │ └── 2nd_degree_equations.c │ │ └── complex_numbers │ │ │ └── complex_numbers.c │ │ ├── menu_and_options │ │ ├── how_to_manage_options.c │ │ └── parse_arguments.c │ │ ├── profiling │ │ ├── basic_profiler.c │ │ └── byte_frequency.c │ │ ├── sizeof.c │ │ └── variable_declarations_c89_c99.c ├── README.md ├── bitwise_hacks │ ├── README.md │ ├── bit_operators.c │ ├── bit_swap.c │ ├── bit_swap_on_array.c │ ├── check_integer_power_of_two │ │ └── is_pow_of_2.c │ ├── extract_the_integer_absolute_value │ │ └── main.c │ ├── extract_the_maximum │ │ └── main.c │ ├── extract_the_minimum │ │ └── main.c │ ├── from_decimal_to_binary.c │ ├── howto_change_a_bit_field.c │ ├── howto_check_a_bit.c │ ├── howto_clear_a_bit.c │ ├── howto_get_a_bit_field.c │ ├── howto_setup_a_bit.c │ ├── inetegers_opposite_signs │ │ └── main.c │ ├── mask.c │ ├── operations_on_rightmost_bit.c │ ├── pack_char.c │ ├── rotation.c │ ├── shifting.c │ ├── simulate_equals │ │ └── main.c │ ├── struct_bitfield.c │ ├── the_sign_of_an_integer │ │ └── main.c │ └── tips_and_tricks │ │ ├── any_bit_LSB_equals_one.c │ │ ├── any_bit_MSB_equals_zero.c │ │ ├── any_bit_equals_one.c │ │ ├── any_bit_equals_zero.c │ │ ├── any_odd_bit_is_one.c │ │ ├── arithmetic_shift.c │ │ ├── get_0xff.c │ │ └── get_rightmost_one.c ├── libraries │ ├── ImageMagick │ │ └── magickWand │ │ │ ├── README.md │ │ │ └── resize_image.c │ ├── OpenGL │ │ └── 01_intro.c │ ├── README.md │ ├── SDL │ │ ├── 00_init_the_library.c │ │ ├── 00_show_message_box.c │ │ ├── 01_window.c │ │ ├── 02_window_renderer.c │ │ ├── 03_surface.c │ │ └── README.md │ ├── SQLite │ │ ├── 00_version_management_functions.c │ │ ├── 01_library_initialization.c │ │ ├── 02_open_database_connection.c │ │ ├── 02_open_database_connection_v2.c │ │ ├── 03_prepared_statements.c │ │ ├── 04_insert_data_into_db.c │ │ ├── 05_extracting_records.c │ │ ├── 06_multiple_sql_statements.c │ │ ├── 07_storage_class_and_cols_info.c │ │ ├── 08_dynamic_query_with_asprintf.c │ │ ├── 09_bind_1_positional_parameters.c │ │ ├── 09_bind_2_numbered_parameters.c │ │ ├── 09_bind_3_named_parameters.c │ │ ├── 10_setup_global_configuration.c │ │ ├── 11_inserting_a_blob.c │ │ ├── 12_retrieve_blob.c │ │ ├── 12_retrieve_blob_incremental_IO.c │ │ ├── README.md │ │ ├── convenience_wrappers │ │ │ ├── 01_create_table_and_put_records.c │ │ │ ├── 02_read_db_with_callback.c │ │ │ ├── 02_read_db_with_sqlite3_get_table.c │ │ │ └── README.md │ │ ├── create_database_sqlite.tcl │ │ └── full_programs │ │ │ └── reading_and_writing_blob.c │ ├── X11 │ │ └── window.c │ ├── cairo │ │ ├── README.md │ │ ├── cairo_basics.c │ │ ├── lines │ │ │ ├── black_and_white_horizontal_stripes.c │ │ │ ├── black_and_white_vertical_stripes.c │ │ │ ├── horizontal_line.c │ │ │ ├── spiderweb_with_lines.c │ │ │ └── verticial_line.c │ │ ├── pdf │ │ │ ├── txt_to_pdf.c │ │ │ └── txt_to_pdf.pdf │ │ ├── rectangles │ │ │ ├── boardchess.c │ │ │ ├── full_black_rectangle.c │ │ │ └── full_white_rectangle.c │ │ └── text │ │ │ ├── README.md │ │ │ └── text_on_png_backend.c │ ├── cryptography │ │ ├── OpenSSL │ │ │ ├── HMAC_hash_string.c │ │ │ ├── README.md │ │ │ └── openssl_bt.c │ │ ├── bitwise_crypto │ │ │ ├── xor_crypto_1.c │ │ │ └── xor_crypto_2.c │ │ ├── caesar_cipher.c │ │ ├── check_crypto_fips.c │ │ ├── crypt │ │ │ └── crypt.c │ │ └── gpgme │ │ │ ├── compila.txt │ │ │ └── intro.c │ ├── cups │ │ ├── README.md │ │ └── list_available_printers.c │ ├── igraph │ │ └── README.md │ ├── libGlib │ │ └── linked_list.c │ ├── libconfig │ │ ├── libconfig_intro.c │ │ └── test.cfg │ ├── mysql │ │ └── first_mysql_query.c │ ├── nCurses │ │ ├── README.md │ │ ├── basics_menu.c │ │ ├── checker.c │ │ ├── formatting_text │ │ │ └── text_attributes.c │ │ └── input_output │ │ │ ├── 01_compile_ncurses.c │ │ │ ├── 02_writing_text_1_addch.c │ │ │ ├── 02_writing_text_2_addstr.c │ │ │ ├── 02_writing_text_3_addnstr.c │ │ │ ├── 03_formatting_text_with_printw.c │ │ │ ├── 04_reading_text_1_getch.c │ │ │ ├── 04_reading_text_2_getstr.c │ │ │ ├── 04_reading_text_3_getnstr.c │ │ │ └── 05_scanw.c │ └── pam │ │ └── authentication.c └── representing_information │ ├── addressing_and_byte_ordering │ ├── byte_representation.c │ ├── endianess │ │ ├── check_for_endianess.c │ │ ├── endianess.c │ │ ├── little_endian.c │ │ └── view_hexdump.c │ ├── expanding_bit_1_zero_extension.c │ ├── expanding_bit_2_sign_extension.c │ ├── get_bytes_with_pointer_to_char.c │ ├── get_most_significant_byte.c │ ├── makefile │ ├── print_byte.c │ ├── print_byte │ │ ├── main.c │ │ ├── utils.c │ │ └── utils.h │ ├── replace_byte.c │ ├── show_bytes.c │ ├── show_bytes.h │ └── view_memory_address.c │ ├── floating_point │ ├── casting.c │ ├── encoding.c │ ├── range.c │ └── scientific_notation.c │ └── integer │ ├── integer_arithmetic │ ├── C_puzzle.c │ ├── addition_2complement_overflow.c │ ├── addition_unsigned_overflow.c │ ├── comparision.c │ ├── division16.c │ ├── division_unsigned.c │ ├── multiplication_8bit_operands.c │ ├── multiplication_booth_algorithm.c │ ├── multiplication_overflow.c │ ├── multiplication_vs_shifting.c │ └── power_of_two.c │ └── integer_representations │ ├── README.md │ ├── data_type_overflow.c │ ├── extracting_values.c │ ├── get_signed_int_range.c │ ├── hexdump.c │ ├── integer_promotion.c │ ├── is_signed_or_unsigned_macro.c │ ├── range_data_types.c │ ├── signed_unsigned_casting.c │ ├── signed_unsigned_operations.c │ ├── tips_and_tricks │ ├── arithmetic_or_logical_shift.c │ └── get_maxint_from_unsignedlong.c │ └── truncating_numbers.c ├── Kernel_Hacking ├── LKM │ ├── Makefile │ ├── README.md │ ├── basic_module.c │ ├── intercept_sc.c │ ├── intercept_sc_param.c │ ├── nascondere_file.c │ └── parametri.c └── README.md ├── README.md └── Unix_Programming ├── Date_and_Time ├── README.md ├── bdt_to_string_1_asctime.c ├── bdt_to_string_2_strftime.c ├── bdt_to_time_1_mktime.c ├── calendar_time_1_time.c ├── calendar_time_2_time.c ├── ctime.c ├── gettimeoftheday.c ├── highest_time_t_values.c ├── strptime.c ├── time_to_bdt_1_gmtime.c └── time_to_bdt_2_localtime.c ├── Error_Handling ├── README.md ├── errno_variable.c ├── get_errno_macro.c └── strerror.c ├── File_Events_Monitoring ├── inotify_directory.c └── inotify_full_monitor.c ├── File_System ├── 01_stat_1.c ├── 02_umask_access.c ├── 03_chmod_functions.c ├── 04_chown_functions.c ├── 05_link_unlink.c ├── 06_remove_rename.c ├── 07_symbolic_link.c ├── 08_utime.c ├── 09_mkdir.c ├── 10_rmdir.c ├── 11_read_dir_1_stream.c ├── 11_read_dir_2_fdescriptor.c ├── 11_read_dir_3.c ├── 11_read_dir_4_scandir.c ├── 12_current_working_directory.c ├── 13_chroot.c ├── dirname_basename.c ├── full_programs │ ├── file_data_access.c │ ├── find_file_inside_dir.c │ ├── get_filesize.c │ ├── get_filesize_POSIX_compilant.c │ ├── ls_clone.c │ ├── reading_directory.c │ ├── removing_link.c │ └── statfile.c └── statvfs.c ├── IO_Advanced ├── README.md ├── dup_01.c ├── dup_02.c ├── dup_03.c ├── fcntl.c ├── ftruncate.c ├── pread_pwrite.c ├── temporary_file_1_tmpfile.c ├── temporary_file_2_mkstemp.c ├── temporary_file_3_tmpnam.c ├── temporary_file_4_tempnam.c ├── truncate.c └── writev.c ├── IO_Buffering_and_Buffer_Cache ├── force_output_with_fflush.c ├── purge_buffer_with_fpurge.c └── setvbuf.c ├── IO_Standard_Library ├── 01_fopen_open_stream.c ├── 02_rw_stream_1_getc_putc.c ├── 02_rw_stream_2_fgets_fputs.c ├── 02_rw_stream_3_copy_file.c ├── 02_rw_stream_4_copy_file.c ├── 02_rw_stream_5.c ├── 03_binary_IO_with_fread.c ├── 04_get_filesize_with_ftell.c ├── 04_position_stream_fseek_ftell.c └── 07_fileno.c ├── IO_Unbuffered ├── 01_open_1_intro.c ├── 01_open_2_flags.c ├── 02_read_1.c ├── 02_read_2.c ├── 02_read_3.c ├── 02_read_4.c ├── 03_write.c ├── 04_lseek-1.c ├── 04_lseek-2.c ├── 04_lseek-holes-1.c ├── 04_lseek-holes-2.c ├── 04_lseek-holes-3.c └── full_programs │ ├── copy_file_1.c │ ├── copy_file_2.c │ ├── read_file.c │ ├── realtime_lseek.c │ └── write_strings_to_file.c ├── IPC_InterProcess_Communication ├── fifo │ └── 01_fifo.c ├── file_locking │ ├── fcntl_locking.c │ ├── fcntl_locking_2.c │ ├── locking_record_file.c │ └── locking_with_maxtry.c ├── memory_mapped_files │ ├── 01_mapping_file.c │ └── 02_mapping_a_structure.c ├── pipe │ ├── 01_pipe_1_intro.c │ ├── 01_pipe_2_simil_pager.c │ ├── 01_pipe_3_trasferimento_messaggi.c │ ├── 01_pipe_4_messaggi_tra_processi.c │ ├── 01_pipe_5_dup2.c │ ├── 02_popen_pclose_1.c │ ├── 02_popen_pclose_2.c │ ├── 02_popen_pclose_3_mail.c │ ├── 03_convert_1.c │ ├── 03_convert_2_pipe.c │ └── 04_coprocesses.c └── shared_memory │ └── memoria-condivisa.c ├── Internetworking └── Socket │ ├── 01_intro_socket.c │ ├── 02_getprotobyname.c │ ├── 03_address_1_conversion.c │ ├── 03_address_2_gethostbyname.c │ ├── 03_address_3_gethostbyname.c │ ├── 04_socket_address.c │ ├── 05_binding_1.c │ ├── 05_binding_2_getsockname.c │ ├── 06_ports_and_services.c │ ├── IPV4-TCP-client-server │ ├── tcp_client.c │ └── tcp_echo_server.c │ └── byte_ordering │ └── network_byte_order.c ├── Link_Library ├── README.md ├── shared_library │ ├── README.md │ ├── main.c │ └── mymath.c └── static_library │ ├── README.md │ ├── main.c │ └── mymath.c ├── Memory_Allocation ├── 01_program_break_sbrk.c ├── 02_program_break_brk.c ├── 03_write_characters_on_heap.c ├── 04_free_memory.c ├── 05_sbrk_free.c ├── 06_anon_memory_mammping.c ├── README.md ├── glibc_malloc_debugging_monitoring │ ├── README.md │ └── malloc_stats.c └── malloc_implementations │ ├── README.md │ ├── dummy_malloc │ ├── basic_malloc.c │ ├── basic_malloc.h │ ├── main.c │ └── makefile │ ├── malloc_one │ ├── main.c │ ├── makefile │ ├── malloc_one.c │ └── malloc_one.h │ └── malloc_two │ ├── main.c │ ├── makefile │ ├── malloc_two.c │ └── malloc_two.h ├── Parsing_Command_Line_Options ├── getopt_1.c ├── getopt_2.c ├── getopt_long_1.c └── getopt_long_2.c ├── Process_Control ├── 02_fork_1.c ├── 02_fork_2.c ├── 02_fork_3.c ├── 02_fork_4_orphan_1.c ├── 02_fork_4_orphan_2.c ├── 02_fork_5_zombie.c ├── 03_vfork.c ├── 04_wait_1.c ├── 04_wait_2_termination_status.c ├── 04_wait_3.c ├── 05_waitpid_1.c ├── 05_waitpid_2.c ├── 05_waitpid_3.c ├── 05_waitpid_4.c ├── 06_exec_functions_1.c ├── 06_exec_functions_2_execl.c ├── 06_exec_functions_3_execv.c ├── 06_exec_functions_4_execle.c ├── 06_exec_functions_5_execve.c ├── 06_exec_functions_6_execlp.c ├── 06_exec_functions_7_execvp.c ├── 08_system_clone.c ├── 09_user_identification_getlogin.c ├── 10_process_times.c └── memory_layout_addresses.c ├── Process_Credentials ├── README.md ├── get_process_credentials.c └── setuid.c ├── Process_Environment ├── 01_process_termination.c ├── 02_command_line_arguments.c ├── 03_environment_list.c ├── 04_read_and_set_env_vars_1.c ├── 04_read_and_set_env_vars_2.c ├── 05_resource_limits.c ├── 06_setjmp_longjmp_1.c ├── 06_setjmp_longjmp_2.c ├── CPU_limit.c └── README.md ├── Process_Relationships ├── 01_process_groups.c ├── 02_sessions.c ├── 03_controlling_terminal.c ├── 04_job_control.c └── 05_orphaned_process_groups.c ├── README.md ├── Signals ├── 01_signal_concepts.c ├── 02_signal_1.c ├── 02_signal_2.c ├── 03_unreliable_signals.c ├── 04_reentrant_functions.c ├── 05_SIGCHLD.c ├── 06_reliable_signals.c ├── 07_kill.c ├── 07_kill_and_raise_1.c ├── 07_raise.c ├── 08_alarm_1.c ├── 08_alarm_2.c ├── 09_pause.c ├── 10_signal_sets.c ├── 11_sigprocmask.c ├── 12_sigpending.c ├── 13_sigaction_1.c ├── 13_sigaction_2.c ├── 13_sigaction_3_signal.c └── 14_sigsuspend.c ├── Standardization_and_System_Limits ├── feauture.c ├── get_libc_version.c ├── get_libc_version_with_confstr.c ├── system_limits_with_pathconf.c └── system_limits_with_sysconf.c ├── System_Informations └── uname_gethostname.c ├── Terminal_IO ├── ioctl_eject_cdrom.c └── password_input.c ├── Threads ├── 01_threads_support.c ├── 02_thread-ID_1.c ├── 02_thread-ID_2_confronto.c ├── 03_creation_1.c ├── 03_creation_2.c ├── 03_creation_3.c ├── 03_creation_4.c ├── 04_joining_1.c ├── 04_joining_2.c ├── 04_joining_3.c ├── 05_termination_1.c ├── 05_termination_2.c ├── 05_termination_3.c ├── 06_cleanup_handlers.c ├── 07_parametri_1.c ├── 07_parametri_2_multipli.c └── 08_sync_1_mutexes.c ├── Unix_Daemons └── 01_daemon_intro.c └── Users_and_Groups ├── full_programs ├── check_passwd.c ├── group_file_simulation.c ├── user_and_group_conversions │ ├── main.c │ ├── makefile │ ├── user_group_conversions.c │ └── user_group_conversions.h └── who_simulation.c ├── group_1_getgrgid_getgrnam.c ├── group_2_getgrent_setgrent.c ├── login_accounting.c ├── passwd_1_getpwnam_getpwuid.c ├── passwd_2_getpwent_setpwent.c ├── shadow_password_1_getspnam.c └── shadow_password_2_getspent.c /doc/README.md: -------------------------------------------------------------------------------- 1 | # UnixCentric Documentation 2 | 3 | The documentation is splitted into many sections, each of which is a single page, 4 | in such a way as to make the usability as fast as possible. 5 | 6 | UnixCentric covers everything inherent the UNIX Universe, however, as well as 7 | for the code, there are two main areas: the C language and Unix Systems 8 | Programming, but then in addition to the technical side we will talk about the 9 | Unix history as well. 10 | 11 | * [Articles](articles.md) `Articles and small tutorial` 12 | * [Bibliography](biblio.md) `Printed books` 13 | * [Free Books](free_books.md) `Free/Open (full) books` 14 | * [Papers and Talks](papers_talks.md) `Academic Papers and talks; from University, Conference and so on` 15 | * [Standards](stds_and_refs.md) `Standards, Standards de facto, Reference manuals` 16 | * [Unix_History](unix_history.md) `Unix History and Timeline` 17 | -------------------------------------------------------------------------------- /doc/img/pdf_doc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/b3h3moth/UnixCentric/4a8c4ce7cfef10e221ec2ac5e264afd1f9a82de8/doc/img/pdf_doc.png -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_black_boxes/addresslist.h: -------------------------------------------------------------------------------- 1 | #ifndef _ADDRESSLIST_H 2 | #define _ADDRESSLIST_H 3 | 4 | #define NAME_LEN 20 // Longest name 5 | #define ADDR_LEN 80 // Longest address 6 | #define MAIL_LEN 30 // Longest e-mail 7 | #define MAX_ADDR 5 // Max addresses allowed 8 | 9 | extern char name[MAX_ADDR][NAME_LEN]; 10 | extern char address[MAX_ADDR][ADDR_LEN]; 11 | extern char mail[MAX_ADDR][MAIL_LEN]; 12 | 13 | char const *lookup_addr(char const *name); 14 | char const *lookup_mail(char const *name); 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_black_boxes/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -pedantic -Wall -std=c11 3 | TARGET = blackboxes 4 | SOURCE = *.c 5 | OBJS = main.o addresslist.o 6 | 7 | $(TARGET): $(OBJS) 8 | @$(CC) $^ -o $@ 9 | @echo Executable: $(TARGET) 10 | 11 | $(OBJS): addresslist.h 12 | $(CC) $(CFLAGS) $(INCLS) -c $(SOURCE) 13 | 14 | clean: 15 | rm -rf $(OBJS) $(TARGET) 16 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_stack/README.md: -------------------------------------------------------------------------------- 1 | The Abstact Data Type (ADT) Stack implementation: 2 | 3 | * Fixed length vector; 4 | * Dynamic vector; 5 | * Linked list. 6 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_stack/dynamic_vector/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "stack.h" 4 | 5 | int main(void) { 6 | Stack st1, st2; 7 | int st_size = 10; 8 | 9 | // Imposta l'ampiezza massima di entrambi gli stack a 10 10 | st1 = create(st_size); 11 | st2 = create(st_size); 12 | 13 | // Riempie entrambi gli stack 14 | for (int i=0; i 5 | 6 | typedef int Item; 7 | typedef struct stack_type *Stack; 8 | 9 | Stack create(int size); 10 | void destroy(Stack s); 11 | void make_empty(Stack s); 12 | bool is_empty(Stack s); 13 | bool is_full(Stack s); 14 | void push(Stack s, Item val); 15 | Item pop(Stack s); 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_stack/fixed_length_vector/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -pedantic -Wall -std=c11 3 | TARGET = stack 4 | 5 | OBJS = main.o stack.o 6 | 7 | $(TARGET): $(OBJS) 8 | @echo "linking ..." 9 | @$(CC) $^ -o $@ 10 | 11 | $(OBJS): stack.h 12 | $(CC) $(CFLAGS) $(INCLS) -c $*.c 13 | 14 | relink: 15 | @echo "relinking ..." 16 | @$(CC) $(CFLAGS) -o $(TARGET) $(OBJS) $(LIBS) 17 | 18 | clean: 19 | rm -rf $(OBJS) $(TARGET) 20 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_stack/fixed_length_vector/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | #include 5 | 6 | typedef int Item; 7 | typedef struct stack_type *Stack; 8 | 9 | Stack create(void); 10 | void destroy(Stack s); 11 | void make_empty(Stack s); 12 | bool is_empty(Stack s); 13 | bool is_full(Stack s); 14 | void push(Stack s, Item val); 15 | Item pop(Stack s); 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_stack/linked_list/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "stack.h" 4 | 5 | int main(void) { 6 | Stack st1 = create(); 7 | 8 | for (int i=0; i<10; i++) 9 | push(st1, i); 10 | 11 | printf("pop: %d from stack\n", pop(st1)); 12 | printf("pop: %d from stack\n", pop(st1)); 13 | printf("pop: %d from stack\n", pop(st1)); 14 | printf("pop: %d from stack\n", pop(st1)); 15 | 16 | print_stack(st1); 17 | 18 | make_empty(st1); 19 | 20 | return(EXIT_SUCCESS); 21 | } 22 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_stack/linked_list/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -pedantic -Wall -std=c11 3 | OBJS = main.o stack.o 4 | TARGET = stack 5 | 6 | $(TARGET): $(OBJS) 7 | @echo "linking ..." 8 | @$(CC) $^ -o $@ 9 | 10 | $(OBJS): stack.h 11 | $(CC) $(CFLAGS) -c $*.c 12 | 13 | relink: 14 | @echo "relinking ..." 15 | @$(CC) $(CFLAGS) -o $(TARGET) $(OBJS) $(LIBS) 16 | 17 | clean: 18 | rm -rf $(OBJS) $(TARGET) 19 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/ADT_stack/linked_list/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | #include 5 | 6 | typedef int Item; 7 | typedef struct stack_type *Stack; 8 | 9 | Stack create(void); 10 | void destroy(Stack s); 11 | void make_empty(Stack s); 12 | bool is_empty(Stack s); 13 | bool is_full(Stack s); 14 | void push(Stack s, Item val); 15 | Item pop(Stack s); 16 | void print_stack(Stack s); 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/Buffer/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "buffer.h" 4 | 5 | int main(void) { 6 | Buffer *buf1 = buf_alloc(10, "test1"); 7 | Buffer *buf2 = buf_alloc(10, "test2"); 8 | Buffer *buf3 = buf_alloc(10, "test3"); 9 | Buffer *buf4 = buf_alloc(10, "test4"); 10 | 11 | init_random(buf1); 12 | print(buf1); 13 | 14 | init_str(buf2, "ABCDEFGHI"); 15 | print(buf2); 16 | 17 | buf_copy(buf3, buf2); 18 | print(buf3); 19 | 20 | Buffer *buf5 = buf_concatenate(buf1, buf2, "testconcat"); 21 | print(buf5); 22 | 23 | buf_inverse_copy(buf4, buf1); 24 | print(buf4); 25 | 26 | printf("buf1 has %d occurences of 'A'\n", count(buf1, 'A')); 27 | printf("buf2 has %d occurences of 'H'\n", count(buf2, 'H')); 28 | 29 | reset(buf2); 30 | 31 | 32 | buf_dealloc(buf1); 33 | buf_dealloc(buf2); 34 | buf_dealloc(buf3); 35 | buf_dealloc(buf4); 36 | buf_dealloc(buf5); 37 | 38 | return(EXIT_SUCCESS); 39 | } 40 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/CSV_library/csv.h: -------------------------------------------------------------------------------- 1 | #ifndef CSV_H 2 | #define CSV_H 3 | 4 | // legge la successiva linea di input 5 | extern char *csv_getline(FILE *f); 6 | // restituisce il campo n 7 | extern char *csv_field(int n); 8 | // restituisce il numero di campi 9 | extern int csv_nfield(void); 10 | 11 | // segnale di memoria esaurita 12 | enum { NOMEM = -2 }; 13 | 14 | // caratteri input 15 | static char *line = NULL; 16 | // copia linea usata per la suddivisione 17 | static char *sline = NULL; 18 | 19 | // dimensione di line[] e sline[] 20 | static int max_line = 0; 21 | // puntatori ai campi 22 | static char **field = NULL; 23 | // dimensione di field[] 24 | static int max_field = 0; 25 | // numero di campi in field[] 26 | static int nfield = 0; 27 | // caratteri di separazione tra i campi 28 | static char field_sep[] = ","; 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/CSV_library/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "csv.h" 4 | 5 | int main(int argc, char *argv[]) { 6 | char *line; 7 | 8 | while ((line = csv_getline(stdin)) != NULL) { 9 | printf("%s\n", line); 10 | for (int i=0; i file.csv 21 | $ make 22 | $ ./a.out < file.csv 23 | 24 | "CB", 86.25,"11/4/1998",14:39,-1234.89,876.798,+890.0, 789^2.91, 25 | main, +, -, {, }, [], =, ==, ++, --, exit(0);, 26 | "ROMA", 90.25,"08/3/1987",9:56AM,+1.0876,76.7228,33.9527,20.345,9823761 27 | */ 28 | -------------------------------------------------------------------------------- /src/C/Abstract_Data_Types/CSV_library/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -pedantic -Wall -std=c99 3 | TARGET = csv.out 4 | 5 | OBJS = main.o csv.o 6 | 7 | $(TARGET): $(OBJS) 8 | @echo "linking ... $(TARGET)" 9 | @$(CC) $^ -o $@ 10 | 11 | $(OBJS): csv.h 12 | $(CC) $(CFLAGS) -c $*.c 13 | 14 | relink: 15 | @echo "relinking ... $(TARGET)" 16 | @$(CC) $(CFLAGS) -o $(TARGET) $(OBJS) $(LIBS) 17 | 18 | clean: 19 | rm -rf $(OBJS) $(TARGET) 20 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/Knuth_Morris_Path/kmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "kmp.h" 4 | 5 | int kmp(char *p, char *s) { 6 | int m = 0; 7 | int i = 0; 8 | int t[strlen(p)]; 9 | 10 | while (s[m+i] != '\0' && p[i] != '\0') { 11 | if (s[m+i] == p[i]) { 12 | ++i; 13 | } else { 14 | m += i - t[i]; 15 | if (i > 0) 16 | i = t[i]; 17 | } 18 | } 19 | 20 | if (p[i] == '\0') 21 | return m; 22 | else 23 | return m + i; 24 | } 25 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/Knuth_Morris_Path/kmp.h: -------------------------------------------------------------------------------- 1 | #ifndef KMP_H 2 | #define KMP_H 3 | 4 | int kmp(char *p, char *s); 5 | 6 | #endif 7 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/Knuth_Morris_Path/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "kmp.h" 4 | 5 | int main(void) { 6 | char *string = "tale a walk on the wild side"; 7 | char *pattern = "alk"; 8 | 9 | printf("%s\n", kmp(pattern, string)); 10 | return(EXIT_SUCCESS); 11 | } 12 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/hanoi/get.c: -------------------------------------------------------------------------------- 1 | #include "hanoi.h" 2 | 3 | int get_n_from_user(void) 4 | { 5 | int n; 6 | 7 | printf("%s", 8 | "---\n" 9 | "TOWERS OF HANOI:\n" 10 | "\n" 11 | "There are three towers: A, B, and C.\n" 12 | "\n" 13 | "The disks on tower A must be moved to tower C. Only one\n" 14 | "disk can be moved at a time, and the order on each tower\n" 15 | "must be preserved at each step. Any of the towers A, B,\n" 16 | "or C can be used for intermediate placement of a disk.\n" 17 | "\n" 18 | "The problem starts with n disks on Tower A.\n" 19 | "\n" 20 | "Input n: "); 21 | if (scanf("%d", &n) != 1 || n < 1) { 22 | printf("\nERROR: Positive integer not found - bye!\n\n"); 23 | exit(1); 24 | } 25 | printf("\n"); 26 | return n; 27 | } 28 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/hanoi/hanoi.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | extern int cnt; /* count of the number of moves */ 6 | 7 | int get_n_from_user(void); 8 | void move(int n, char a, char b, char c); 9 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/hanoi/main.c: -------------------------------------------------------------------------------- 1 | #include "hanoi.h" 2 | 3 | int cnt = 0; /* count of the number of moves */ 4 | 5 | int main(void) 6 | { 7 | int n; /* number of disks */ 8 | 9 | n = get_n_from_user(); 10 | assert(n > 0); 11 | /* 12 | // Move n disks from tower A to tower C, 13 | // using tower B as an intermediate tower. 14 | */ 15 | move(n, 'A', 'B', 'C'); /* recursive fct */ 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/hanoi/move.c: -------------------------------------------------------------------------------- 1 | #include "hanoi.h" 2 | 3 | void move(int n, char a, char b, char c) 4 | { 5 | if (n == 1) { 6 | ++cnt; 7 | printf("%5d: %s%d%s%c%s%c.\n", cnt, 8 | "Move disk ", 1, " from tower ", a, " to tower ", c); 9 | } 10 | else { 11 | move(n - 1, a, c, b); 12 | ++cnt; 13 | printf("%5d: %s%d%s%c%s%c.\n", cnt, 14 | "Move disk ", n, " from tower ", a, " to tower ", c); 15 | move(n - 1, b, a, c); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/mergesort/main.c: -------------------------------------------------------------------------------- 1 | #include "mergesort.h" 2 | 3 | int main(void) 4 | { 5 | int i, key[] = { 4, 3, 1, 67, 55, 8, 0, 4, 6 | -5, 37, 7, 4, 2, 9, 1, -1 }; 7 | 8 | mergesort(key, KEYSIZE); 9 | printf("After mergesort:\n"); 10 | for (i = 0; i < KEYSIZE; ++i) 11 | printf("%4d", key[i]); 12 | putchar('\n'); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/mergesort/merge.c: -------------------------------------------------------------------------------- 1 | /* 2 | // Merge a[] of size m and b[] of size n into c[]. 3 | */ 4 | 5 | #include "mergesort.h" 6 | 7 | void merge(int a[], int b[], int c[], int m, int n) 8 | { 9 | int i = 0, j = 0, k = 0; 10 | 11 | while (i < m && j < n) 12 | if (a[i] < b[j]) 13 | c[k++] = a[i++]; 14 | else 15 | c[k++] = b[j++]; 16 | while (i < m) /* pick up any remainder */ 17 | c[k++] = a[i++]; 18 | while (j < n) 19 | c[k++] = b[j++]; 20 | } 21 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/mergesort/mergesort.c: -------------------------------------------------------------------------------- 1 | /* 2 | // Mergesort: Use merge() to sort an array of size n. 3 | */ 4 | 5 | #include "mergesort.h" 6 | 7 | void merge(int *, int *, int *, int, int); 8 | 9 | void mergesort(int key[], int n) 10 | { 11 | int j, k, m, *w; 12 | 13 | for (m = 1; m < n; m *= 2) 14 | ; 15 | if (m != n) { 16 | printf("ERROR: Size of the array is not a power of 2 - bye!\n"); 17 | exit(1); 18 | } 19 | w = calloc(n, sizeof(int)); /* allocate workspace */ 20 | for (k = 1; k < n; k *= 2) { 21 | for (j = 0; j < n - k; j += 2 * k) 22 | merge(key + j, key + j + k, w + j, k, k); /* merge into w */ 23 | for (j = 0; j < n; ++j) 24 | key[j] = w[j]; /* write w back into key */ 25 | } 26 | free(w); /* free the workspace */ 27 | } 28 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/mergesort/mergesort.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define KEYSIZE 16 5 | 6 | void merge(int a[], int b[], int c[], int m, int n); 7 | void mergesort(int key[], int n); 8 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/quicksort/full_example/find_pivot.c: -------------------------------------------------------------------------------- 1 | #include "quicksort.h" 2 | 3 | yes_no find_pivot(int *left, int *right, int *pivot_ptr) 4 | { 5 | int a, b, c, *p; 6 | 7 | a = *left; /* left value */ 8 | b = *(left + (right - left) / 2); /* middle value */ 9 | c = *right; /* right value */ 10 | o3(a, b, c); /* order these 3 values */ 11 | if (a < b) { /* pivot will be higher of 2 values */ 12 | *pivot_ptr = b; 13 | return yes; 14 | } 15 | if (b < c) { 16 | *pivot_ptr = c; 17 | return yes; 18 | } 19 | for (p = left + 1; p <= right; ++p) 20 | if (*p != *left) { 21 | *pivot_ptr = (*p < *left) ? *left : *p; 22 | return yes; 23 | } 24 | return no; /* all elements have the same value */ 25 | } 26 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/quicksort/full_example/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "quicksort.h" 3 | 4 | int main(void) { 5 | int a[N], i; 6 | 7 | // Seed the random number generator. 8 | srand(time(NULL)); 9 | 10 | // Put randomly distributed values in a[]. 11 | for (i = 0; i < N; ++i) 12 | a[i] = rand() % 1000; 13 | 14 | // Write a[] before and after sorting. 15 | wrt("Before", a, N); 16 | 17 | quicksort(a, a + N - 1); 18 | 19 | wrt("After", a, N); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/quicksort/full_example/partition.c: -------------------------------------------------------------------------------- 1 | #include "quicksort.h" 2 | 3 | int *partition(int *left, int *right, int pivot) 4 | { 5 | while (left <= right) { 6 | while (*left < pivot) 7 | ++left; 8 | while (*right >= pivot) 9 | --right; 10 | if (left < right) { 11 | swap(*left, *right); 12 | ++left; 13 | --right; 14 | } 15 | } 16 | return left; 17 | } 18 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/quicksort/full_example/quicksort.c: -------------------------------------------------------------------------------- 1 | #include "quicksort.h" 2 | 3 | void quicksort(int *left, int *right) 4 | { 5 | int *p, pivot; 6 | 7 | if (find_pivot(left, right, &pivot) == yes) { 8 | p = partition(left, right, pivot); 9 | quicksort(left, p - 1); 10 | quicksort(p, right); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/quicksort/full_example/quicksort.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define N 100 6 | 7 | #define swap(x, y) { int t; t = x; x = y; y = t; } 8 | #define order(x, y) if (x > y) swap(x, y) 9 | #define o2(x, y) order(x, y) 10 | #define o3(x, y, z) o2(x, y); o2(x, z); o2(y, z) 11 | 12 | typedef enum {yes, no} yes_no; 13 | 14 | yes_no find_pivot(int *left, int *right, int *pivot_ptr); 15 | int *partition(int *left, int *right, int pivot); 16 | void quicksort(int *, int *); 17 | void wrt(char *s, int *a, int n); 18 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/quicksort/full_example/wrt.c: -------------------------------------------------------------------------------- 1 | #include "quicksort.h" 2 | 3 | void wrt(char *s, int *a, int n) 4 | { 5 | int i; 6 | 7 | printf("\n%s\n%s%s\n", "---", s, ":"); 8 | for (i = 0; i < n; ++i) { 9 | if (i % 10 == 0) 10 | putchar('\n'); 11 | printf("%7d", a[i]); 12 | } 13 | if (n % 10 != 0) 14 | putchar('\n'); 15 | } 16 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/selection_sort/README: -------------------------------------------------------------------------------- 1 | Gli algoritmi sono implementati nei corrispettivi sorgenti .c, ciascun algoritmo 2 | peraltro e' facilmente identificabile poiche' ad ogni sorgente e' stato 3 | associato il nome dell'algoritmo stesso. 4 | 5 | Nel file header.h e' stata inserita sia l'implementazione del vettore sia i 6 | prototipi di ciascuna funzione. 7 | 8 | Il file main.c serve per esguire i test. 9 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/selection_sort/header.h: -------------------------------------------------------------------------------- 1 | #define MAX_VECT 10 2 | typedef int ElemTipoVettore; 3 | typedef ElemTipoVettore TipoVettore[MAX_VECT]; 4 | 5 | void SelectionSort(TipoVettore V, int n); 6 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/algorithms/ordinamento/selection_sort/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "header.h" 4 | 5 | int main(void) { 6 | TipoVettore vett = {100,90,95,30,60,80,45,35,15,55}; 7 | int i; 8 | 9 | printf("Selection sort (prima) -> "); 10 | 11 | for (i=0; i "); 16 | 17 | for (i=0; i 2 | #include 3 | #include "sorted_sequence.h" 4 | 5 | /* The purpose of "Sorted Sequence Node" (SSN) ADT is to keep all elements 6 | sorted all time. */ 7 | 8 | int main() { 9 | /* Initialize the SSN to NULL */ 10 | sorted_Sequence *ssn = init(); 11 | /* Add the first node */ 12 | ins_First(ssn, 15); 13 | 14 | /* For debugging purpose: print integer in the first node */ 15 | #ifdef DBG 16 | printf("%d\n", ssn->head->next->data); 17 | #endif 18 | 19 | ins_Sort(ssn, 20); 20 | #ifdef DBG 21 | printf("%d\n", ssn->head->next->data); 22 | #endif 23 | ins_Sort(ssn, 10); 24 | #ifdef DBG 25 | printf("%d\n", ssn->head->next->data); 26 | #endif 27 | 28 | return(EXIT_SUCCESS); 29 | } 30 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/linked_list/sorted_sequence_node/sorted_sequence.h: -------------------------------------------------------------------------------- 1 | #ifndef SORTED_SEQUENCE_H 2 | #define SORTED_SEQUENCE_H 3 | 4 | typedef struct sorted_Sequence_Node sorted_Sequence_Node; 5 | typedef struct sorted_Sequence sorted_Sequence; 6 | 7 | struct sorted_Sequence_Node { 8 | int data; 9 | sorted_Sequence_Node *next; 10 | }; 11 | 12 | struct sorted_Sequence { 13 | sorted_Sequence_Node *head; 14 | }; 15 | 16 | 17 | /* Sorted Sequence Node (alias SSN) 18 | - A pointer to sorted_Sequence_Node 'head' is a pointer to the generator node: 19 | - The generator node is the ever first SSN but it is not part of it, it only 20 | serves to manage the SSN. */ 21 | 22 | /* SSN initialization. It contains only the generator node. */ 23 | sorted_Sequence *init(void); 24 | 25 | /* Add a node in the first position of the SSN */ 26 | void ins_First(sorted_Sequence *s, int val); 27 | 28 | /* Add a node in the sorted sequence */ 29 | void ins_Sort(sorted_Sequence *s, int val); 30 | #endif 31 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/polish_stack/eval.c: -------------------------------------------------------------------------------- 1 | /* Evaluation of the Polish stack. */ 2 | 3 | #include "polish.h" 4 | 5 | int evaluate(stack *polish) 6 | { 7 | data d, d1, d2; 8 | stack eval; 9 | 10 | initialize(&eval); 11 | while (!empty(polish)) { 12 | d = pop(polish); 13 | switch (d.kind) { 14 | case value: 15 | push(d, &eval); 16 | break; 17 | case operator: 18 | d2 = pop(&eval); 19 | d1 = pop(&eval); 20 | d.kind = value; /* begin overwriting d */ 21 | switch (d.u.op) { 22 | case '+': 23 | d.u.val = d1.u.val + d2.u.val; 24 | break; 25 | case '-': 26 | d.u.val = d1.u.val - d2.u.val; 27 | break; 28 | case '*': 29 | d.u.val = d1.u.val * d2.u.val; 30 | } 31 | push(d, &eval); 32 | } 33 | } 34 | d = pop(&eval); 35 | return d.u.val; 36 | } 37 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/polish_stack/main.c: -------------------------------------------------------------------------------- 1 | /* Test the two-stack Polish evaluation algorithm. */ 2 | 3 | #include "polish.h" 4 | 5 | int main(void) 6 | { 7 | char str[] = "13, 4, -, 2, 3, *, +"; 8 | stack polish; 9 | 10 | printf("\n%s%s\n\n", 11 | "Polish expression: ", str); 12 | fill(&polish, str); /* fill stack from the string */ 13 | wrt_stack(&polish); /* wrt the stack on the screen */ 14 | printf("\n%s%d\n\n", 15 | "Polish evaluation: ", evaluate(&polish)); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/polish_stack/po_out: -------------------------------------------------------------------------------- 1 | 2 | Polish expression: 13, 4, -, 2, 3, *, + 3 | 4 | stack count: 7 kind: value val: 13 5 | stack count: 6 kind: value val: 4 6 | stack count: 5 kind: operator op: - 7 | stack count: 4 kind: value val: 2 8 | stack count: 3 kind: value val: 3 9 | stack count: 2 kind: operator op: * 10 | stack count: 1 kind: operator op: + 11 | stack count: 0 12 | 13 | Polish evaluation: 15 14 | 15 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/polish_stack/stack.c: -------------------------------------------------------------------------------- 1 | /* The basic stack routines. */ 2 | 3 | #include "polish.h" 4 | 5 | void initialize(stack *stk) 6 | { 7 | stk -> cnt = 0; 8 | stk -> top = NULL; 9 | } 10 | 11 | void push(data d, stack *stk) 12 | { 13 | elem *p; 14 | 15 | p = malloc(sizeof(elem)); 16 | p -> d = d; 17 | p -> next = stk -> top; 18 | stk -> top = p; 19 | stk -> cnt++; 20 | } 21 | 22 | data pop(stack *stk) 23 | { 24 | data d; 25 | elem *p; 26 | 27 | d = stk -> top -> d; 28 | p = stk -> top; 29 | stk -> top = stk -> top -> next; 30 | stk -> cnt--; 31 | free(p); 32 | return d; 33 | } 34 | 35 | data top(stack *stk) 36 | { 37 | return (stk -> top -> d); 38 | } 39 | 40 | boolean empty(const stack *stk) 41 | { 42 | return ((boolean) (stk -> cnt == EMPTY)); 43 | } 44 | 45 | boolean full(const stack *stk) 46 | { 47 | return ((boolean) (stk -> cnt == FULL)); 48 | } 49 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/polish_stack/wrt.c: -------------------------------------------------------------------------------- 1 | #include "polish.h" 2 | 3 | void wrt_data(data *dp) 4 | { 5 | switch (dp -> kind) { 6 | case operator: 7 | printf("%s%3c\n", 8 | "kind: operator op:", dp -> u.op); 9 | break; 10 | case value: 11 | printf("%s%3d\n", 12 | "kind: value val:", dp -> u.val); 13 | } 14 | } 15 | 16 | void wrt_stack(stack *stk) 17 | { 18 | data d; 19 | 20 | printf("stack count:%3d%s", 21 | stk -> cnt, (stk -> cnt == 0) ? "\n" : " "); 22 | if (!empty(stk)) { 23 | d = pop(stk); /* pop the data */ 24 | wrt_data(&d); /* print the data */ 25 | wrt_stack(stk); /* recursive call */ 26 | push(d, stk); /* push the data */ 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/queue/linked_linear_structure_implementation/Makefile: -------------------------------------------------------------------------------- 1 | LD = gcc 2 | CC = gcc 3 | OBJS = main.o type_queue.o 4 | TARGET = queue.out 5 | 6 | $(TARGET): $(OBJS) 7 | $(LD) -o $(TARGET) $(OBJS) 8 | 9 | main.o: main.c type_queue.h 10 | $(CC) -c main.c 11 | 12 | type_queue: type_queue.c type_queue.h 13 | $(CC) -c type_queue.c 14 | 15 | clean: 16 | rm -rf *.o $(TARGET) *.txt *.out *.core 17 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/queue/linked_linear_structure_implementation/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "type_queue.h" 4 | 5 | int main(void) { 6 | int i; 7 | int val = -1; 8 | typeQueue_LLS *myqq = init(); 9 | 10 | for (i = 1; i<10; i++) 11 | putElemToQueue(myqq, i*i); 12 | 13 | printQueue(*myqq); 14 | 15 | printf("\n"); 16 | 17 | for (i = 1; i<10; i++) { 18 | val = getElemFromQueue(myqq); 19 | printf("The first elemment of the queue is: %d\n", val); 20 | if (emptyQueue(*myqq)) { 21 | printf("The queue is empty\n"); 22 | break; 23 | } 24 | } 25 | 26 | free(myqq); 27 | 28 | return(EXIT_SUCCESS); 29 | } 30 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/queue/linked_linear_structure_implementation/type_queue.h: -------------------------------------------------------------------------------- 1 | #ifndef TYPE_QUEUE_H 2 | #define TYPE_QUEUE_H 3 | 4 | typedef struct node_LLS node_LLS; 5 | typedef struct typeQueue_LLS typeQueue_LLS; 6 | 7 | struct node_LLS { 8 | int data; 9 | node_LLS *next; 10 | }; 11 | 12 | struct typeQueue_LLS { 13 | node_LLS *head; 14 | node_LLS *tail; 15 | }; 16 | 17 | 18 | /* Queue data structure, Linked Linear Structure (LLS) implementation. 19 | - A pointer to node_LLS 'head' is a pointer to the generator node; 20 | - A pointer to node_LLS 'tail' is a pointer to the last node; 21 | - Each node (node_LLS) includes: 22 | - the filed data, to save an integer value: 23 | - the field next, a pointer to the next node of the queue. 24 | */ 25 | 26 | typeQueue_LLS *init(void); 27 | int emptyQueue(typeQueue_LLS q); 28 | void printQueue(typeQueue_LLS q); 29 | void putElemToQueue(typeQueue_LLS *q, int val); 30 | int getElemFromQueue(typeQueue_LLS *q); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/c_declarations_parser/cdeclar.h: -------------------------------------------------------------------------------- 1 | #ifndef CDECLAR_H 2 | #define CDECLAR_H 3 | 4 | #define MAX_TOKENS 100 5 | #define MAX_TOKENS_SIZE 64 6 | 7 | enum type_tag { IDENTIFIER, QUALIFIER, DATATYPE }; 8 | 9 | struct token { 10 | char type; 11 | char string[MAX_TOKENS_SIZE]; 12 | }; 13 | 14 | typedef struct token Token; 15 | 16 | // Function Prototypes 17 | enum type_tag check_string(void); 18 | void get_token(void); 19 | void read_first_id(void); 20 | void deal_with_arrays(void); 21 | void deal_with_functions(void); 22 | void deal_with_pointers(void); 23 | void deal_with_declarator(void); 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/c_declarations_parser/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "cdeclar.h" 4 | 5 | int main(void) { 6 | read_first_id(); 7 | deal_with_declarator(); 8 | printf("\n"); 9 | 10 | return(EXIT_SUCCESS); 11 | } 12 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/linked_list_representation/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "stack.h" 4 | 5 | int main(void) { 6 | for (int i=0; i<10; i++) 7 | push(i); 8 | 9 | // Rimuove 9 10 | pop(); 11 | // Rimuove 8 12 | pop(); 13 | // Rimuove 7 14 | pop(); 15 | 16 | print_stack_elements(); 17 | 18 | make_empty(); 19 | 20 | print_stack_elements(); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/linked_list_representation/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | #include 5 | 6 | void make_empty(void); 7 | bool is_empty(void); 8 | bool is_full(void); 9 | void print_stack_elements(void); 10 | void push(int val); 11 | int pop(void); 12 | 13 | #endif 14 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/vector_representation/stack_module/main.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | 3 | // Testing the stack implementation by reversing a string 4 | 5 | int main(void) { 6 | char str[] = "Take a walk on the wild side"; 7 | int i; 8 | 9 | // New stack 10 | stack s; 11 | 12 | // Initialize the stack 13 | reset(&s); 14 | 15 | printf("Default string: %s\n", str); 16 | 17 | for (i = 0; str[i] != '\0'; ++i) 18 | if (!full(&s)) 19 | // push a char on the stack 20 | push(str[i], &s); 21 | 22 | printf("From the stack: "); 23 | 24 | while (!empty(&s)) 25 | // pop a char off the stack 26 | putchar(pop(&s)); 27 | 28 | putchar('\n'); 29 | 30 | return(EXIT_SUCCESS); 31 | } 32 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/vector_representation/stack_module/stack.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | 3 | void reset(stack *stk) 4 | { 5 | stk -> top = EMPTY; 6 | } 7 | 8 | void push(char c, stack *stk) 9 | { 10 | stk -> top++; 11 | stk -> s[stk -> top] = c; 12 | } 13 | 14 | char pop(stack *stk) 15 | { 16 | return (stk -> s[stk -> top--]); 17 | } 18 | 19 | char top(const stack *stk) 20 | { 21 | return (stk -> s[stk -> top]); 22 | } 23 | 24 | _Bool empty(const stack *stk) 25 | { 26 | return ((_Bool) (stk -> top == EMPTY)); 27 | } 28 | 29 | _Bool full(const stack *stk) 30 | { 31 | return ((_Bool) (stk -> top == FULL)); 32 | } 33 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/vector_representation/stack_module/stack.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX_LEN 1000 5 | #define EMPTY -1 6 | #define FULL (MAX_LEN - 1) 7 | 8 | typedef struct stack { 9 | char s[MAX_LEN]; 10 | int top; 11 | } stack; 12 | 13 | void reset(stack *stk); 14 | void push(char c, stack *stk); 15 | char pop(stack *stk); 16 | char top(const stack *stk); 17 | _Bool empty(const stack *stk); 18 | _Bool full(const stack *stk); 19 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/vector_representation/stack_module2/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "stack.h" 4 | 5 | int main(void) { 6 | for (int i=0; i<10; i++) 7 | push(i); 8 | 9 | // Rimuove 9 10 | pop(); 11 | // Rimuove 8 12 | pop(); 13 | // Rimuove 7 14 | pop(); 15 | 16 | print_stack_elements(); 17 | 18 | make_empty(); 19 | 20 | print_stack_elements(); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/stack/vector_representation/stack_module2/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | void make_empty(void); 9 | bool is_empty(void); 10 | bool is_full(void); 11 | void print_stack_elements(void); 12 | void push(int val); 13 | int pop(void); 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/binary_tree/binary_tree_1/create.c: -------------------------------------------------------------------------------- 1 | #include "tree.h" 2 | 3 | /* 4 | // Create a linked binary tree from an array. 5 | */ 6 | 7 | BTREE create_tree(DATA a[], int i, int size) 8 | { 9 | if (i >= size) 10 | return NULL; 11 | else 12 | return (init_node(a[i], 13 | create_tree(a, 2 * i + 1, size), 14 | create_tree(a, 2 * i + 2, size))); 15 | } 16 | 17 | /* 18 | // Initialize a node in a binary tree. 19 | */ 20 | 21 | BTREE init_node(DATA d1, BTREE p1, BTREE p2) 22 | { 23 | BTREE t; 24 | 25 | t = new_node(); 26 | t -> d = d1; 27 | t -> left = p1; 28 | t -> right = p2; 29 | return t; 30 | } 31 | 32 | /* 33 | // Create a new node. 34 | */ 35 | 36 | BTREE new_node(void) 37 | { 38 | BTREE t; 39 | 40 | t = (BTREE) malloc(sizeof(NODE)); 41 | assert(t != NULL); 42 | return t; 43 | } 44 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/binary_tree/binary_tree_1/main.c: -------------------------------------------------------------------------------- 1 | #include "tree.h" 2 | 3 | int main(void) 4 | { 5 | BTREE t; 6 | DATA a[] = "GDIBFHJACE"; 7 | int size = 10; /* size of a[] */ 8 | 9 | t = create_tree(a, 0, size); 10 | printf("%s", 11 | "---\n" 12 | "Inorder binary tree traversal: "); 13 | inorder(t); 14 | printf("\n\n%s", 15 | "---\n" 16 | "Preorder binary tree traversal: "); 17 | preorder(t); 18 | printf("\n\n%s", 19 | "---\n" 20 | "Postorder binary tree traversal: "); 21 | postorder(t); 22 | printf("\n\n"); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/binary_tree/binary_tree_1/traversal.c: -------------------------------------------------------------------------------- 1 | #include "tree.h" 2 | 3 | /* 4 | // Inorder binary tree traversal. 5 | */ 6 | 7 | void inorder(BTREE root) 8 | { 9 | if (root != NULL) { 10 | inorder(root -> left); /* recur left */ 11 | printf("%c ", root -> d); 12 | inorder(root -> right); /* recur right */ 13 | } 14 | } 15 | 16 | /* 17 | // Preorder binary tree traversal. 18 | */ 19 | 20 | void preorder(BTREE root) 21 | { 22 | if (root != NULL) { 23 | printf("%c ", root -> d); 24 | preorder(root -> left); 25 | preorder(root -> right); 26 | } 27 | } 28 | 29 | /* 30 | // Postorder binary tree traversal. 31 | */ 32 | 33 | void postorder(BTREE root) 34 | { 35 | if (root != NULL) { 36 | postorder(root -> left); 37 | postorder(root -> right); 38 | printf("%c ", root -> d); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/binary_tree/binary_tree_1/tree.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef char DATA; 6 | 7 | struct node { 8 | DATA d; 9 | struct node *left; 10 | struct node *right; 11 | }; 12 | 13 | typedef struct node NODE; 14 | typedef NODE *BTREE; 15 | 16 | /* 17 | // Function prototypes. 18 | */ 19 | 20 | BTREE create_tree(DATA a[], int i, int size); 21 | BTREE init_node(DATA d1, BTREE p1, BTREE p2); 22 | BTREE new_node(void); 23 | 24 | void inorder(BTREE root); 25 | void preorder(BTREE root); 26 | void postorder(BTREE root); 27 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_1/gtree.c: -------------------------------------------------------------------------------- 1 | /* Create a new node. */ 2 | 3 | #include "gtree.h" 4 | 5 | GTREE new_gnode(void) 6 | { 7 | return (malloc(sizeof(NODE))); 8 | } 9 | 10 | GTREE init_gnode(DATA d, int num, GTREE sib) 11 | { 12 | GTREE tmp; 13 | 14 | tmp = new_gnode(); 15 | tmp -> d = d; 16 | tmp -> child_no = num; 17 | tmp -> sib = sib; 18 | return tmp; 19 | } 20 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_1/gtree.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef const char cchr; 6 | typedef char DATA; 7 | 8 | struct node { 9 | int child_no; 10 | DATA d; 11 | struct node *sib; 12 | }; 13 | 14 | typedef struct node NODE; 15 | typedef NODE *GTREE; 16 | 17 | /* 18 | // Function prototypes. 19 | */ 20 | 21 | GTREE init_gnode(DATA d, int num, GTREE sibs); 22 | GTREE new_gnode(void); 23 | void preorder_g(GTREE *t, int ind); 24 | void postorder_g(GTREE *t, int ind); 25 | void wrt_header(cchr *s); 26 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_1/traversal.c: -------------------------------------------------------------------------------- 1 | #include "gtree.h" 2 | 3 | /* 4 | // Preorder traversal of general trees. 5 | */ 6 | 7 | void preorder_g(GTREE *t, int ind) 8 | { 9 | GTREE tmp; /* tmp traverses the sibling list */ 10 | 11 | tmp = t[ind]; /* t[ind] is the root node */ 12 | while (tmp != NULL) { 13 | printf("%5c%5d\n", tmp -> d, tmp -> child_no); 14 | preorder_g(t, tmp -> child_no); 15 | tmp = tmp -> sib; 16 | } 17 | } 18 | 19 | /* 20 | // Postorder traversal of general trees. 21 | */ 22 | 23 | void postorder_g(GTREE *t, int ind) 24 | { 25 | GTREE tmp; /* tmp traverses the sibling list */ 26 | 27 | tmp = t[ind]; /* t[ind] is the root node */ 28 | while (tmp != NULL) { 29 | postorder_g(t, tmp -> child_no); 30 | printf("%5c%5d\n", tmp -> d, tmp -> child_no); 31 | tmp = tmp -> sib; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_1/wrt.c: -------------------------------------------------------------------------------- 1 | #include "gtree.h" 2 | 3 | void wrt_header(cchr *s) 4 | { 5 | printf("\n%s%s%s\n", 6 | "---\n", 7 | s, " general tree traversal:\n"); 8 | } 9 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_2/build.c: -------------------------------------------------------------------------------- 1 | /* 2 | // Function buildtree creates a tree from an array of edges. 3 | */ 4 | 5 | #include "gtree.h" 6 | 7 | void buildtree(PAIR edges[], DATA d[], int n, GTREE t[]) 8 | { 9 | int i; 10 | int x, y; /* points of edge */ 11 | 12 | t[0] = init_gnode(d[1], 1, NULL); /* t[0] takes node 1 as root */ 13 | for (i = 1; i <= n; ++i) 14 | t[i] = NULL; 15 | for (i = 0; i < n - 1; ++i) { 16 | x = edges[i].out; 17 | y = edges[i].in; 18 | t[x] = init_gnode(d[y], y, t[x]); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_2/gtree.c: -------------------------------------------------------------------------------- 1 | /* Create a new node. */ 2 | 3 | #include "gtree.h" 4 | 5 | GTREE new_gnode(void) 6 | { 7 | return (malloc(sizeof(NODE))); 8 | } 9 | 10 | GTREE init_gnode(DATA d, int num, GTREE sib) 11 | { 12 | GTREE tmp; 13 | 14 | tmp = new_gnode(); 15 | tmp -> d = d; 16 | tmp -> child_no = num; 17 | tmp -> sib = sib; 18 | return tmp; 19 | } 20 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_2/gtree.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef const char cchr; 6 | typedef char DATA; 7 | 8 | struct node { 9 | int child_no; 10 | DATA d; 11 | struct node *sib; 12 | }; 13 | 14 | struct pair { /* a pair represents an edge in a tree */ 15 | int out; 16 | int in; 17 | }; 18 | 19 | typedef struct pair PAIR; 20 | typedef struct node NODE; 21 | typedef NODE * GTREE; 22 | 23 | /* 24 | // Function prototypes. 25 | */ 26 | 27 | void buildtree(PAIR edges[], DATA d[], int n, GTREE t[]); 28 | GTREE init_gnode(DATA d, int num, GTREE sibs); 29 | GTREE new_gnode(void); 30 | void preorder_g(GTREE *t, int ind); 31 | void postorder_g(GTREE *t, int ind); 32 | void wrt_header(cchr *s); 33 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_2/traversal.c: -------------------------------------------------------------------------------- 1 | #include "gtree.h" 2 | 3 | /* 4 | // Preorder traversal of general trees. 5 | */ 6 | 7 | void preorder_g(GTREE *t, int ind) 8 | { 9 | GTREE tmp; /* tmp traverses the sibling list */ 10 | 11 | tmp = t[ind]; /* t[ind] is the root node */ 12 | while (tmp != NULL) { 13 | printf("%5c%5d\n", tmp -> d, tmp -> child_no); 14 | preorder_g(t, tmp -> child_no); 15 | tmp = tmp -> sib; 16 | } 17 | } 18 | 19 | /* 20 | // Postorder traversal of general trees. 21 | */ 22 | 23 | void postorder_g(GTREE *t, int ind) 24 | { 25 | GTREE tmp; /* tmp traverses the sibling list */ 26 | 27 | tmp = t[ind]; /* t[ind] is the root node */ 28 | while (tmp != NULL) { 29 | postorder_g(t, tmp -> child_no); 30 | printf("%5c%5d\n", tmp -> d, tmp -> child_no); 31 | tmp = tmp -> sib; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/C/Algorithms_and_Data_Structures/data_structures/tree/general_tree/general_tree_2/wrt.c: -------------------------------------------------------------------------------- 1 | #include "gtree.h" 2 | 3 | void wrt_header(cchr *s) 4 | { 5 | printf("\n%s%s%s\n", 6 | "---\n", 7 | s, " general tree traversal:\n"); 8 | } 9 | -------------------------------------------------------------------------------- /src/C/C_lang/README.md: -------------------------------------------------------------------------------- 1 | ## The c language 2 | 3 | The c ansi programming language (c11) 4 | 5 | ### List of arguments covered 6 | 7 | * Array 8 | * monodimensional 9 | * bidimensional 10 | * multidimensional 11 | * Dynamic memory allocation 12 | * Expressions 13 | * Generic selections (`_Generic`) 14 | * Logical operators 15 | * Functions 16 | * variadic functions 17 | * function and pointers 18 | * high order functions 19 | * Pointers 20 | * Structures and Unions 21 | * Vector of characters (strings) 22 | * Stuff 23 | * variable declarations in c11 24 | * width precision when using printf() 25 | -------------------------------------------------------------------------------- /src/C/C_lang/array/break_multidim_array_components.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Lo scopo del programma e' di spezzare un array multidimensionale nelle sue 5 | componenti individuali, in modo tale da rendere evidente la relazione che 6 | intercorre con i puntatori. */ 7 | 8 | int main(void) { 9 | int data[2][3][5]; 10 | int *p; 11 | int i=1; 12 | 13 | // Inizializza ciascun elemento dell'array utilizzando la variabile 'i' 14 | for (p = &data[0][0][0]; p <= &data[2-1][3-1][5-1]; p++, i++) 15 | *p = i; 16 | 17 | puts("\nArray initialized.\n"); 18 | 19 | int (*pa)[3][5] = data; 20 | int (*pb)[5] = data[1]; 21 | int *pc = data[2][3]; 22 | 23 | printf("%p\n", (void*)pa); 24 | printf("%p\n", (void*)pb); 25 | printf("%p\n", (void*)pc); 26 | 27 | return(EXIT_SUCCESS); 28 | } 29 | -------------------------------------------------------------------------------- /src/C/C_lang/array/dynamic_vector.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef int DataType; 5 | typedef DataType *VectorDataType; 6 | 7 | /* Lo scopo del programma e' di realizzare un vettore dinamico, il numero degli 8 | elementi pertanto sara' definito dall'utente a run-time. */ 9 | 10 | int main(int argc, char *argv[]) { 11 | int size, i; 12 | VectorDataType vec; 13 | 14 | printf("Enter vector size: "); 15 | scanf("%d", &size); 16 | 17 | // Allocazione della memoria definita dall'utente 18 | vec = malloc(size * sizeof(DataType)); 19 | 20 | // Inizializzazione del vettore 21 | printf("Inizializzazione vettore\n"); 22 | for (i=0; i 2 | #include 3 | 4 | void find_duplicates(int vec[], int size); 5 | 6 | /* Lo scopo del programma e' di scrivere una funzione che consenta di trovare 7 | elementi duplicati in un array */ 8 | 9 | int main(void) { 10 | int vector[] = {1,12,2,3,4,5,6,7,8,9,10,5,11,12,13,14,15,16,17,15,18,7}; 11 | 12 | find_duplicates(vector, sizeof(vector)/sizeof(vector[0])); 13 | 14 | return(EXIT_SUCCESS); 15 | } 16 | 17 | void find_duplicates(int vec[], int size) { 18 | for (int i=0; i 2 | #include 3 | 4 | int main(void) { 5 | /* I compilatori riscrivono l'accesso a un array mediante puntatori, ma 6 | attenzione, puntatori e array non sono la stessa cosa. 7 | 8 | arr[i] e' sempre riscritto come: *(val + i) 9 | arr[i][j] e' sempre riscritto come: *(*(val + i) + j) 10 | */ 11 | 12 | int val[] = {1,2,3,4,5,6,7,8,9,10}; 13 | 14 | for (int i=0; i 2 | #include 3 | 4 | /* I vettori a lunghezza variabile (Variable-length arrays) sono stati 5 | introdotti nello standard c99, essi consentono di specificare la lunghezza di 6 | un vettore mediante una espressione non costante */ 7 | 8 | int main(void) { 9 | int size; 10 | 11 | printf("Give di size of the array: "); 12 | scanf("%d", &size); 13 | 14 | /* La lunghezza del vettore e' impostata da un'espressione non costante, 15 | che nel caso specifico e' 'size' */ 16 | int vec[size]; 17 | 18 | printf("Initialize an array of %d elements:\n", size); 19 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | char *allocmem(char *buf, int size); 6 | 7 | int main(void) { 8 | char def_string[] = "C language programming"; 9 | char *buffer = NULL; 10 | int size = strlen(def_string)+1; 11 | 12 | buffer = allocmem(buffer, size); 13 | strcpy(buffer, def_string); 14 | 15 | /* Imposta il null character finale. */ 16 | *(buffer + --size) = '\0'; // Equivalente a buffer[--size] 17 | 18 | printf("strlen(default): %d - %s\n", size, def_string); 19 | printf(" strlen(copy): %d - %s\n", strlen(buffer), buffer); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | 24 | /* La funzione allocmem() ritorna l'indirizzo di memoria di grandezza utile 25 | a contenere esattamente un vettore di caratteri 'buf' di dimensioni 'size'. */ 26 | char *allocmem(char *buf, int size) { 27 | return buf = calloc(size, sizeof(char)); 28 | } 29 | -------------------------------------------------------------------------------- /src/C/C_lang/dynamic_memory_allocation/calloc/simulate_calloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define BYTE 10 6 | 7 | /* Lo scopo del sorgente e' di simulare la funzione calloc() mediante l'ausilio 8 | delle funzioni malloc() e memset(). Per simulazione s'intende l'ottenimento del 9 | medesimo risultato finale e non la realizzazione interna del programma. */ 10 | 11 | int main(void) { 12 | int *pval = malloc(BYTE * sizeof(int)); 13 | memset(pval, 0, BYTE * sizeof(int)); 14 | 15 | // Setto i primi cinque byte a 1 16 | *pval = *(pval + 1) = *(pval + 2) = *(pval + 3) = *(pval + 4) = 1; 17 | 18 | /* La stampa di ciascun elemento mostra i primi 5 elementi impostati ad 1 19 | e gli altri cinque settati a zero mediante memset() */ 20 | for (int i=0; i 2 | #include 3 | 4 | /* Double free; si verifica allorquando si tenta di rilasciare nuovamente 5 | della memoria gia' rilasciata precedentemente. */ 6 | 7 | int main(void) { 8 | int *ptr1, *ptr2; 9 | ptr1 = malloc(sizeof(int)); 10 | 11 | *ptr1 = 1234; 12 | 13 | // Copia l'indirizzo della memoria allocata 14 | ptr2 = ptr1; 15 | 16 | // Primo rilascio 17 | free(ptr1); 18 | 19 | /* Secondo rilascio, che tuttavia si riferisce al primo poiche' puntano 20 | alla medesima area di memoria, per cui vi sara' un errore non appena si 21 | provera' ad eseguire il programma - double free or corruption. 22 | */ 23 | free(ptr2); 24 | 25 | return(EXIT_SUCCESS); 26 | } 27 | -------------------------------------------------------------------------------- /src/C/C_lang/dynamic_memory_allocation/free/null_to_freed_pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | float *ptr; 6 | 7 | /* Alloca la memoria per contenere un tipo di dato float */ 8 | ptr = malloc(sizeof(float)); 9 | 10 | /* Lo spazio di memoria viene ora rilasciato */ 11 | free(ptr); 12 | 13 | /* Nessun cambiamento nel programma */ 14 | free(NULL); 15 | 16 | /* Si assegna NULL al puntatore rilasciato per evitare comportamenti 17 | indefiniti in futuro. E' una buona tecnica di programmazione 18 | conservativa. */ 19 | ptr = NULL; 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/C_lang/dynamic_memory_allocation/malloc/idiom.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | char str[] = "Take a walk on the wild side"; 6 | char *p; 7 | 8 | /* Così facendo si allochera' la memoria necessaria a contenere l'oggetto 9 | a cui 'p' puntera' */ 10 | p = malloc(sizeof(*p)); 11 | 12 | // Ora 'p' punta a 'str', pertanto saranno allocati sizeof(str) byte 13 | p = str; 14 | 15 | printf("%s\n", p); 16 | 17 | return(EXIT_SUCCESS); 18 | } 19 | -------------------------------------------------------------------------------- /src/C/C_lang/dynamic_memory_allocation/mem_family_functions/README.md: -------------------------------------------------------------------------------- 1 | ### mem* family functions 2 | 3 | - memset(); 4 | -------------------------------------------------------------------------------- /src/C/C_lang/dynamic_memory_allocation/mem_family_functions/how_memset_memmove_memcpy_work.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | enum { OFFSET = 3, MAX_BUF = 50 }; 6 | 7 | int main(void) { 8 | char string1[MAX_BUF] = "Take a walk on the wild side"; 9 | char string2[MAX_BUF] = "Rastaman vibration positive"; 10 | char buf[MAX_BUF]; 11 | 12 | // Testing memset() 13 | printf("%16s %s\n", "memset() Before:", string1); 14 | memset(string1 + OFFSET, 'X', 10); 15 | printf("%16s %s\n", "memset() After:",string1); 16 | 17 | // Testing memcpy(), no overlap 18 | strcpy(buf, string2); 19 | printf("%16s %s\n", "Default string:", buf); 20 | memcpy(buf + 2, buf + 12, 10); 21 | printf("%16s %s (%s)\n", "memcpy() After:", buf, "No overlap"); 22 | 23 | // Testing memcpy(), with overlap 24 | memcpy(buf, buf + 5, 10); 25 | printf("%16s %s (%s)\n", "memcpy() After:", buf, "with overlap"); 26 | 27 | return(EXIT_SUCCESS); 28 | } 29 | -------------------------------------------------------------------------------- /src/C/C_lang/dynamic_memory_allocation/mem_family_functions/memcpy.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | return(EXIT_SUCCESS); 6 | } 7 | -------------------------------------------------------------------------------- /src/C/C_lang/dynamic_memory_allocation/mem_family_functions/memmove.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | return(EXIT_SUCCESS); 6 | } 7 | -------------------------------------------------------------------------------- /src/C/C_lang/dynamic_memory_allocation/mem_family_functions/memset.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void stampa(char *s) { 6 | 7 | int main(void) { 8 | char stringa[] = "UNIX Programming with POSIX"; 9 | 10 | /* La memset puo' essere utilizzata, ad esempio, per azzerare un array, 11 | tuttavia c'e' una sottile considerazione da porre in essere: 12 | se si utilizza il numero 0 la stringa sara' effettivamente azzerata, se 13 | invece si utilizza il carattere 0 l'array sara' riempito di tanti zeri. */ 14 | int n_zero = 0; 15 | char c_zero = '0'; 16 | int size = strlen(stringa); 17 | 18 | /* Azzero l'array */ 19 | memset(stringa, c_zero, size); 20 | stampa(stringa); 21 | 22 | /* Inserisco per ogni byte uno zero */ 23 | memset(stringa, n_zero, size); 24 | stampa(stringa); 25 | 26 | return(EXIT_SUCCESS); 27 | } 28 | 29 | void stampa(char *s) { 30 | printf("output: %s\n", s); 31 | } 32 | -------------------------------------------------------------------------------- /src/C/C_lang/error_handling/inline_function.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Lo scopo del programma e' di utilizzare una funzione inline per la gestione 5 | degli eventuali errori */ 6 | 7 | static inline void err_msg(int status, const char *msg); 8 | 9 | int main(int argc, char *argv[]) { 10 | 11 | if (argc != 2) { 12 | err_msg(1, "Error Message."); 13 | } 14 | 15 | return(EXIT_SUCCESS); 16 | } 17 | 18 | static inline void err_msg(int status, const char *msg) { 19 | fprintf(stderr, "%s (exit status: %d)\n", msg, status); 20 | exit(status); 21 | } 22 | -------------------------------------------------------------------------------- /src/C/C_lang/functions/02_array_as_parameter.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define SIZE 10 5 | 6 | // Prototipo 7 | int sum(int data[], int length); 8 | 9 | /* L'array, sia nel prototipo sia nella dichiarazione della funzione, 10 | dev'essere inserito con l'operatore di subscript [], la lunghezza dello stesso 11 | invece non e' obbligatoria, tuttavia necessaria */ 12 | 13 | int main(void) { 14 | int my_data[SIZE] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; 15 | 16 | // Nell'invocazione della funzione l'operatore di subscript si puo' omettere 17 | int res = sum(my_data, SIZE); 18 | 19 | printf("Sum is: %d\n", res); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | 24 | // Somma ciascun elemento dell'array 25 | int sum(int data[], int length) { 26 | int result = data[0]; 27 | 28 | for (int i=0; i 2 | #include 3 | 4 | #define MAX_LEN 20 5 | 6 | struct db { 7 | int id; 8 | char gender; 9 | char name[MAX_LEN]; 10 | }; 11 | 12 | struct db init(struct db val); 13 | void print_data(struct db val); 14 | 15 | /* Lo scopo del programma e' di utilizzare un compund literal, 16 | nella fattispecie una struct, come argomento di una funzione. */ 17 | 18 | int main(void) { 19 | struct db data = init((struct db){0,'m', "behemoth"}); 20 | print_data(data); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | 25 | struct db init(struct db val) { 26 | struct db temp = val; 27 | temp.id = 1; 28 | 29 | return temp; 30 | } 31 | 32 | void print_data(struct db val) { 33 | printf(" id: %d\ngender: %c\tname: %s", val.id, val.gender, val.name); 34 | } 35 | -------------------------------------------------------------------------------- /src/C/C_lang/functions/functions_and_pointers/full_programs/swap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void swap(int *w, int *z); 5 | 6 | int main(void) { 7 | int x = 10, y = 20; 8 | printf("before swap() x=%d - y=%d\n", x, y); 9 | 10 | // Si passano i puntatori x ed y alla funzione, i rispettivi indirizzi 11 | swap(&x, &y); 12 | 13 | printf(" after swap() x=%d - y=%d\n", x, y); 14 | 15 | return (EXIT_SUCCESS); 16 | } 17 | 18 | /* La funzione swap() scambia i valori delle variabili j, k passate come 19 | parametro */ 20 | void swap(int *j, int *k){ 21 | int tmp = *j; 22 | *j = *k; 23 | *k = tmp; 24 | } 25 | -------------------------------------------------------------------------------- /src/C/C_lang/functions/functions_and_pointers/function_pointer/README.md: -------------------------------------------------------------------------------- 1 | ### Function Pointers 2 | 3 | Un puntatore a funzione e' un puntatore che immagazzina l'indirizzo di una funzione, 4 | ad esempio `int (*fp)();`, `fp` e' un puntatore a funzione che restituisce un 5 | intero e non ha argomenti. 6 | 7 | > **Warning**: le parentesi sono fondamentali altrimenti diventerebbe `int *fp();` 8 | ovvero la funzione ``fp()`` che restituisce un puntatore ad intero. 9 | 10 | Altre dichiarazioni possono essere: 11 | 12 | * `void (*fp)(int, int);`, `fp` e' un puntatore a funzione con due parametri 13 | interi, e ritorna void; 14 | * `int* (*fp)(char*);`, `fp` e' un puntatore a funzione con un parametro puntatore a char, 15 | e ritorna un puntatore a int. E cosi' via. 16 | 17 | > **Warning**: e' necessario porre particolare attenzione ai parametri del puntatore 18 | a funzione, poiche' il C non prevede la verifica degli stessi nel caso specifico. 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/C/C_lang/functions/functions_and_pointers/passing_pointer_as_parameter.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void sum(int *number, unsigned short esp); 5 | 6 | int main(void) { 7 | int val = 2; 8 | int *ptr = &val; 9 | 10 | /* Il puntatore 'ptr' passato come argomento alla funzione 'sum()' 11 | contiene l'indirizzo della variabile 'val', pertanto andra' a modificare 12 | il valore della variabile stessa. 13 | 14 | I puntatori sono lvalue, e come tali sono oggetti di assegnamento. */ 15 | 16 | sum(ptr, 3); 17 | printf("%d\n", val); 18 | 19 | /* Si sarebbe potuto passare alla funzione l'indirizzo della variabile 20 | 'val', ottenendo il medesimo risultato. */ 21 | 22 | sum(&val, 10); 23 | printf("%d\n", val); 24 | 25 | return(EXIT_SUCCESS); 26 | } 27 | 28 | void sum(int *number, unsigned short esp) { 29 | for (int i=1; i 2 | #include 3 | 4 | int sum(const int *n1, const int *n2); 5 | 6 | /* Lo scopo del programma e' di utilizzare come parametro di funzione un 7 | puntatore a const */ 8 | 9 | int main(void) { 10 | int val1 = 100; 11 | int val2 = 200; 12 | int res = sum(&val1, &val2); 13 | 14 | printf("Result is: %d\n", res); 15 | 16 | return(EXIT_SUCCESS); 17 | } 18 | 19 | int sum(const int *n1, const int *n2) { 20 | return *n1 + *n2; 21 | } 22 | 23 | /* Error: assignment of read-only location 24 | int sum(const int *n1, const int *n2) { 25 | return *n1 = *n1 + *n2; 26 | } 27 | */ 28 | -------------------------------------------------------------------------------- /src/C/C_lang/functions/get_hash_string.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define VEC_SIZE(x) (sizeof(x)/sizeof(x[0])) 5 | enum { 6 | A = 127, 7 | M = 96 8 | }; 9 | 10 | unsigned int hash(char *str); 11 | 12 | /* Lo scopo del programma e' di creare una funzione hash da utilizzare con 13 | le stringhe */ 14 | 15 | int main(void) { 16 | char *strings[] = { "take", "a", "walk", "on", "the", "wild", "side", 17 | "song", "composed", "by", "Lou", "Reed", "and", 18 | "Velvet", "undeground"}; 19 | 20 | for (int i=0; i Nota: Naturalmente le "Higher Order Functions" sono in strettissima relazione 14 | con i puntatori a funzione (Function Pointers), in realta' sono esse 15 | stesse dei puntatori a funzione, ma in questo caso si sta parlando di 16 | una proprieta' della programmazione e non di una caratteristica del 17 | linguaggio. Ad esempio il Perl ne fa largamente uso. 18 | -------------------------------------------------------------------------------- /src/C/C_lang/functions/higher_order_functions/callback_functions/data.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS oslist( 2 | id INTEGER PRIMARY KEY, 3 | name TEXT, 4 | year INTEGER 5 | ) WITHOUT ROWID; 6 | 7 | INSERT INTO oslist(id, name, year) VALUES (1, 'OpenBSD', 1910); 8 | INSERT INTO oslist(id, name, year) VALUES (2, 'FreeBSD', 1920); 9 | INSERT INTO oslist(id, name, year) VALUES (3, 'NetBSD', 1930); 10 | INSERT INTO oslist(id, name, year) VALUES (4, 'Debian', 1990); 11 | -------------------------------------------------------------------------------- /src/C/C_lang/functions/higher_order_functions/multiplier.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int somma(int (*f)(int), int start, int end); 6 | int moltiplica(int x); 7 | 8 | int main(void) { 9 | int n = somma(moltiplica, 1, 10); 10 | printf("\nThe result is: %d\n", n); 11 | 12 | return(EXIT_SUCCESS); 13 | } 14 | 15 | int moltiplica(int x) { 16 | return x * x; 17 | } 18 | 19 | /* La funzione somma() accetta 3 parametri: 20 | - il primo parametro e' la funzione 'int (*p)(int par)', ovvero un puntatore a 21 | funzione 'p' che accetta il parametro 'par' e che restituisce un intero. 22 | - il secondo parametro e' l'intero 'start', 23 | - il terzo parametro e' l'intero 'end'. 24 | */ 25 | int somma(int (*f)(int), int start, int end) { 26 | int val; 27 | int ris = 0; 28 | 29 | for (val=start; val 2 | #include 3 | 4 | enum { MAX_LINE = 64, }; 5 | 6 | void copy_line_by_line(FILE *fin, FILE *fout); 7 | 8 | /* Lo scopo del programma e' di creare una funzione compatta che cosenta una 9 | veloce redirezione dello standard input verso lo standard output; nel caso 10 | specifico il programma, dopo essere stato compilato, puo' essere lanciato in 11 | questo modo: 12 | 13 | $ copylinebyline < input_file.txt 14 | */ 15 | 16 | int main(void) { 17 | 18 | copy_line_by_line(stdin, stdout); 19 | 20 | return(EXIT_SUCCESS); 21 | } 22 | 23 | void copy_line_by_line(FILE *fin, FILE *fout) { 24 | char buf[MAX_LINE]; 25 | 26 | while (fgets(buf, MAX_LINE, fin) != NULL) 27 | fputs(buf, fout); 28 | } 29 | -------------------------------------------------------------------------------- /src/C/C_lang/input_output/file_positioning/README.md: -------------------------------------------------------------------------------- 1 | Lo standard C [ISO/IEC 9899:2011] definisce il comportamento relativo alla 2 | funzione fsetpos(); ovvero il solo valore per la fsetpos() deve essere cio' 3 | che sara' restituito dalla funzione fgetpos(), l'utilizzo di un valore diverso 4 | avra' comportamenti indefiniti. 5 | -------------------------------------------------------------------------------- /src/C/C_lang/input_output/printf_width_precision.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) { 6 | char *unix_skills[] = { "C99 lang", "C11 lang", "C++11 lang", "Perl lang", 7 | "Awk lang", "Python lang", "Bash scripting", 8 | "Zsh scripting", "System Administration", 9 | "Newtork Administration" }; 10 | 11 | int size = (sizeof(unix_skills) / sizeof(unix_skills[0])); 12 | 13 | for (int i=0; i 2 | #include 3 | #include 4 | 5 | /* Lo scopo del programma e' di convertire le cifre decimali ricevute in 6 | interi, dopodiche' stamparle sullo stdout. */ 7 | 8 | int main(void) { 9 | int ch, value; 10 | fputs("Write any integer do you want: ", stdout); 11 | 12 | while ((ch = fgetc(stdin)) != EOF && isdigit(ch)) { 13 | value *= 10; 14 | value += ch -'0'; 15 | fputc(ch, stdout); 16 | } 17 | 18 | // Riporta sullo stdin i caratteri che non sono cifre decimali 19 | ungetc(ch, stdin); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/01_pointer_variable.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | /* Un puntatore e' un indirizzo; una variabile puntatore e' una variabile 6 | in grado di memorizzare un indirizzo o locazione di memoria. 7 | 8 | La grandezza di un puntatore dipende dall'architettura della macchina 9 | (32bit, 64bit) e dal tipo di dato con cui e' stato dichiarato. */ 10 | int n = 0; 11 | int *ptr = &n; /* ptr e' una variabile puntatore in grado di puntare ad 12 | oggetti di tipo 'int' */ 13 | 14 | printf("*ptr is %d byte\n", sizeof(ptr)); 15 | 16 | /* Nota: E' buona norma leggere le dichiarazioni di puntatori da destra a 17 | sinistra. */ 18 | 19 | return(EXIT_SUCCESS); 20 | } 21 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/02_address_of_operator.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | /* Poiche' una variabile puntatore puo' contenere l'indirizzo di una 6 | locazione di memoria, si usa l'operatore indirizzo per assegnare 7 | l'indirizzo di memoria di una variabile al puntatore stesso*/ 8 | int n = 0; 9 | int *ptr = &n; 10 | 11 | /* L'operatore indirizzo ritorna l'indirizzo del suo operando. 12 | 13 | ptr e' una variabile puntatore ad un intero a cui si assegna l'indirizzo 14 | della variabile di tipo intero n; ora puntano alla stessa locazione di 15 | memoria. */ 16 | 17 | return(EXIT_SUCCESS); 18 | } 19 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/06_pointer_sizeof.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | int n = 10; 6 | int *ptr = &n; 7 | 8 | /* size_t e' un unsigned int, ed e' utilizzato per fornire un tipo di dato 9 | sicuro per la gestione delle grandezze dei puntatori. */ 10 | size_t ptr_size = sizeof(ptr); 11 | 12 | /* sizeof ritorna la grandezza di un tipo di dato, il suo valore di ritorno 13 | peraltro e' di tipo size_t; per la stampa i valori consigliabili sono, 14 | nell'ordine: */ 15 | 16 | printf("sizeof(ptr): %zu byte\n", ptr_size); 17 | printf("sizeof(ptr): %u byte\n", ptr_size); 18 | printf("sizeof(ptr): %lu byte\n", ptr_size); 19 | 20 | return(EXIT_SUCCESS); 21 | } 22 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/README.md: -------------------------------------------------------------------------------- 1 | #### *C arrays and pointers are not the same* 2 | 3 | ### List of arguments covered 4 | 5 | * Declare a pointer 6 | * Address of operator 7 | * Indirection operator 8 | * Relations between array and pointers 9 | * Relations between multidimensional array and pointers 10 | * Pointer arithmetics 11 | * Pointer and const 12 | * Dynamic Memory Allocation 13 | * Pointer to function 14 | * Pointer to pointer 15 | * Pointer to void 16 | * Restricted pointer 17 | * Pointers and compound literals 18 | * Pointer and array 19 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/full_programs/palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define BUF_SIZE 20 6 | 7 | /* Lo scopo del programma e' verificare se una stringa ricevuta in input e' 8 | palindroma o meno. */ 9 | 10 | int main(int argc, char *argv[]) { 11 | char *first, *last; 12 | size_t len; 13 | char *str = calloc(BUF_SIZE, sizeof(char)); 14 | 15 | fputs("entry string: ", stdout); 16 | scanf("%19s", str); 17 | 18 | len = strlen(str); 19 | 20 | first = str; 21 | last = &str[len-1]; 22 | 23 | while (first < last) { 24 | if (*first != *last) 25 | break; 26 | first++; 27 | last--; 28 | } 29 | 30 | if (first >= last) 31 | fputs("The string is Palindrome", stdout); 32 | 33 | return(EXIT_SUCCESS); 34 | } 35 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/pointer_arithmetic/ptr_comparison_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Lo scopo del programma e' di verificare l'aritmetica dei puntatori, nel caso 5 | di una comparazione tra gli stessi, nello specifico in un ciclo for */ 6 | 7 | int main(void) { 8 | int vec[] = { 100, 200, 300, 400, 500, 600, 700, 800, 900 }; 9 | int *ptr; 10 | 11 | /* Le similitudini tra puntatori ed array vengono fuori in 12 | tutta la loro essenza allorquando, nel ciclo for, sono messi 13 | a confronto gli indirizzi di memoria del puntatore 'ptr' e del 14 | vettore 'vec'. */ 15 | 16 | for (ptr = vec; ptr <= vec+8; ptr++) 17 | printf("%d, ", *ptr); 18 | 19 | return(EXIT_SUCCESS); 20 | } 21 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/pointer_arithmetic/ptr_comparison_3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | enum { MAXBUF=50 }; 6 | 7 | void reverse(char *string); 8 | 9 | /* Lo scopo del programma e' di invertire una stringa mediante l'aritmetica 10 | dei puntatori, nello specifico comparazione tra puntatori */ 11 | 12 | int main(void) { 13 | char buf[MAXBUF]; 14 | 15 | printf("Enter the string:\n"); 16 | fgets(buf, MAXBUF, stdin); 17 | reverse(buf); 18 | printf("Reversing:\n%s", buf); 19 | 20 | return (EXIT_SUCCESS); 21 | } 22 | 23 | void reverse(char *string) { 24 | char *left_ptr = string; 25 | char *right_ptr = &string[strlen(string) - 1]; 26 | char tmp; 27 | 28 | while (left_ptr < right_ptr) { 29 | tmp = *left_ptr; 30 | *left_ptr = *right_ptr; 31 | *right_ptr = tmp; 32 | left_ptr++; 33 | right_ptr--; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/pointers_and_array/array_of_pointers/array_of_integer_pointers.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | enum { ARR_SIZE = 5 }; 5 | 6 | /* The program's purpose is to declare and initialize an array of pointers 7 | to integers with dereference and subscript notations. */ 8 | 9 | int main(void) { 10 | int *array[ARR_SIZE]; 11 | int *arr[ARR_SIZE]; 12 | 13 | // Memory allocation and initilization for each array member 14 | 15 | // Subscript notation 16 | for (int i=0; i 2 | #include 3 | #include 4 | 5 | /* Lo scopo del programma e' di stampare ciascun elemento dell'array di 6 | stringhe */ 7 | 8 | int main(int argc, char *argv[]) { 9 | char *array[] = {"campobasso", 10 | "roma", "napoli", "venezia", 11 | "verona","torino", "milano", 12 | "genova","palermo","catania", 13 | "bari","firenze"}; 14 | 15 | /* Calcola il numero degli elementi presenti nel vettore di stringhe */ 16 | int len = sizeof(array) / sizeof(char *); 17 | 18 | for (int x=0; x 2 | #include 3 | 4 | /* Lo scopo del programma e' di stampare a video soltanto il primo elemento di 5 | ciascuna riga della matrice, utilizzando solo i puntatori e senza l'ausilio 6 | dei subscripts. */ 7 | 8 | int main(void) { 9 | int matrix[4][4] = { 10 | {10, 20, 30, 40}, 11 | {50, 60, 70, 80}, 12 | {90, 100, 110, 120}, 13 | {130, 140, 150, 160} 14 | }; 15 | 16 | // Dichiarazione di un puntatore ad array 17 | int (*mp)[4]; 18 | 19 | for (mp = matrix; mp<(matrix + 4); mp++) 20 | printf("%d\n", *(*mp) ); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/pointers_and_array/onedimensional_array/init_each_element_to_zero.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | enum { SIZE = 10 }; 5 | 6 | // Lo scopo del programma e' l'inizializzazione di array mediante puntatori. 7 | 8 | int main(void) { 9 | double arr[SIZE]; 10 | 11 | // Dal primo elemento all'ultimo 12 | for (double *ap = &arr[0]; ap < &arr[SIZE]; ap++) { 13 | *ap = 0; 14 | printf("%g, ", *ap); 15 | } 16 | 17 | // Dall'ultimo elemento al primo 18 | for (double *ap = &arr[SIZE]; ap > &arr[0]; ) { 19 | *--ap = 1; 20 | printf("%g, ", *ap); 21 | } 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | -------------------------------------------------------------------------------- /src/C/C_lang/pointers/pointers_and_compound_literals.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct db { 5 | int id; 6 | int year; 7 | }; 8 | 9 | int main(void) { 10 | // Inizializzazione del puntatore 'ptr' al primo elemento dell'array 11 | int *ptr = (int []){10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; 12 | 13 | while(*ptr > 0) { 14 | printf("%3d\n", *ptr); 15 | ptr++; 16 | } 17 | 18 | // Un compund literal per l'inizializzazione di un puntatore a struttura 19 | struct db *data = &(struct db){1, 2016}; 20 | 21 | printf("id: %d\tyear: %d\n", data->id, data->year); 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | -------------------------------------------------------------------------------- /src/C/C_lang/preprocessor/macro_arguments.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // MACRO PARAMETRICHE 5 | #define MAX(x,y) ((x)>(y)?(x):(y)) 6 | #define PRINT_INT(n) printf("%d\n", n); 7 | 8 | int main(void) { 9 | int n1 = 32; 10 | int n2 = 28; 11 | 12 | /* Il comportamento del preprocessore è controllato dalle direttive di 13 | preprocessamento; riguarda i comandi che iniziano con # 14 | 15 | E' utile pensare al preprocessore come un componente separato rispetto 16 | alla compilazione 17 | 18 | Per verificare in output le direttive si può immettere l'opzione 19 | gcc -E al compilatore */ 20 | 21 | printf("MAX %d\n", MAX(n1,n2)); 22 | PRINT_INT(n1); 23 | PRINT_INT(n2); 24 | 25 | return(EXIT_SUCCESS); 26 | } 27 | -------------------------------------------------------------------------------- /src/C/C_lang/preprocessor/macro_expansion.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Si utilizza la compilazione condizionale per inserire una macro. 5 | 6 | $ gcc -std=c11 -Wall -pedantic -DNUM file.c 7 | $ gcc -std=c11 -Wall -pedantic -DNUM=10 file.c 8 | $ gcc -std=c11 -Wall -pedantic -DNUM="10" file.c 9 | 10 | */ 11 | int main(void) { 12 | 13 | #ifdef NUM 14 | for (int i=NUM; i>0; i--) 15 | printf("%d, ", i); 16 | printf("\n"); 17 | #endif 18 | 19 | printf("Hello"); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/C_lang/preprocessor/macro_replacement_1_stringization.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define PRINT_CHAR(c) printf(#c " = '%c'(%d)\n", c, c) 6 | 7 | /* Le definizioni di macro possono contenere due operatori speciali: 8 | - '#' converte un argomento in una stringa, da cui 'stringization'; 9 | - '##' compatta/incolla assieme due token, da cui 'token pasting'; 10 | */ 11 | 12 | int main(void) { 13 | char football_team[] = "Juventus Footbal Club 1897"; 14 | 15 | for (int i=0; i 2 | #include 3 | 4 | #define MAIN(type) i ## n ##t m ##ain(type) 5 | 6 | MAIN(void) 7 | 8 | printf("It works\n"); 9 | 10 | exit(EXIT_SUCCESS); 11 | } 12 | 13 | 14 | /* Le definizioni di macro possono contenere due operatori speciali: 15 | - '#' converte un argomento in una stringa, da cui 'stringization'; 16 | - '##' compatta/incolla assieme due token, da cui 'token pasting'; */ 17 | -------------------------------------------------------------------------------- /src/C/C_lang/preprocessor/macro_replacement_3_token_pasting.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define v(a,b,c) a ## b ## c 5 | 6 | int main(void) { 7 | int numbers[] = { v(1,2,3), v(4,5,6), v(7,8,), v(9,,), v(,,10), v(,,) }; 8 | 9 | for (int i=0; i 2 | #include 3 | 4 | int main(void) { 5 | printf("Compiled (%s) at (%s)\n", __DATE__, __TIME__); 6 | printf("Line (%d) file (%s)\n", __LINE__, __FILE__); 7 | printf("Standard C version: %ld\n", __STDC_VERSION__); 8 | 9 | /* Queste macro sono probabilmente le piu' conosciute, ma ce ne sono tante 10 | altre aggiunte sia nello standard c99 sia nello standard c11 */ 11 | 12 | return(EXIT_SUCCESS); 13 | } 14 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/06_array_of_pointers_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char *get_day(int); 5 | void help(char *str); 6 | 7 | int main(int argc, char *argv[]) { 8 | int nday; 9 | char *day_of_week = NULL; 10 | 11 | help("Please, type"); 12 | scanf("%1d", &nday); 13 | 14 | if (nday < 1 || nday > 7) { 15 | help("Error, it was"); 16 | exit(EXIT_FAILURE); 17 | } 18 | 19 | day_of_week = get_day(nday); 20 | 21 | printf("%s\n", day_of_week); 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | 26 | char *get_day(int d) { 27 | char *days[7] = { 28 | "Monday", 29 | "Tuesday", 30 | "Wednesday", 31 | "Thursday", 32 | "Friday", 33 | "Saturday", 34 | "Sunday" 35 | }; 36 | 37 | if (d >= 1 && d <= 7) 38 | return days[d-1]; 39 | } 40 | 41 | void help(char *str) { 42 | printf("%s a number from 1 and 7\n", str); 43 | } 44 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/compare_strings.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) { 6 | char *str = "I Love C"; 7 | 8 | /* strcmp() returns 0 if the strings are identicals, but it could be 9 | a problem because when the comparision is part of a conditional statement 10 | a zero result indicates false. */ 11 | 12 | if (strcmp(str, "I Love C")) 13 | fputs("ops!", stdout); 14 | 15 | // The solution is simple, we have to negate it to get what we want 16 | if (!strcmp(str, "I Love C")) 17 | fputs("The strings are indenticals\n", stdout); 18 | 19 | // or we have to compare strcmp() instruction to zero 20 | if (strcmp(str, "I Love C") == 0) 21 | fputs("The strings are equals\n", stdout); 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/const_string_as_compound_literal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | /* Inizializzazione di una costante stringa, o meglio, di un puntatore 6 | a una costante carattere */ 7 | const char *str = (const char[]){"Take a Walk on The Wild Side"}; 8 | 9 | // Stampa l'intera stringa puntando al primo carattere 10 | printf("%s\n", str); 11 | 12 | // Stampa char by char 13 | while (*str != '\0') 14 | printf("%c", *str++); 15 | 16 | return(EXIT_SUCCESS); 17 | } 18 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/find_and_replace_strings/find_and_replace_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void remove_filename(char *url); 6 | 7 | int main(int argc, char *argv[]) 8 | { 9 | char str[] = "http://github.com/index.html"; 10 | printf("%s %d\n", str, strlen(str)); 11 | remove_filename(str); 12 | printf("%s %d\n", str, strlen(str)); 13 | 14 | return(EXIT_SUCCESS); 15 | } 16 | 17 | /* spezza la stringa, in questo caso un URL, all'ultimo slash, per cui elimina 18 | * nel caso specifico index.html */ 19 | void remove_filename(char *url) 20 | { 21 | int i = 0; 22 | int len_str = strlen(url); 23 | 24 | for (i=len_str; ; i--) 25 | { 26 | if (url[i] == 47) 27 | { 28 | url[i] = '\0'; 29 | break; 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/find_and_replace_strings/find_word_in_text_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | char *string_replace(char *original, char *pattern, char *replacement); 7 | 8 | int main(int argc, char *argv[]) { 9 | 10 | printf("%s\n", string_replace("Hello ciao", "ciao", "world")); 11 | 12 | return(EXIT_SUCCESS); 13 | } 14 | 15 | char *string_replace(char *original, char *pattern, char *replacement) 16 | { 17 | static char buffer[4096]; 18 | char *p_tmp; 19 | 20 | /* Se non vi sono corrispondenze sara' ritornata la stringa originale */ 21 | if(!(p_tmp = strstr(original, pattern))) 22 | return original; 23 | 24 | strncpy(buffer, original, p_tmp-original); 25 | buffer[p_tmp-original] = '\0'; 26 | 27 | sprintf(buffer+(p_tmp-original), "%s%s", replacement, p_tmp+strlen(pattern)); 28 | 29 | return buffer; 30 | } 31 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/find_and_replace_strings/find_word_in_text_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char *replace(char *pattern, char *replacement, char *original); 6 | 7 | int main(void) { 8 | char string[] = "ANSI C language programming on win$ system"; 9 | printf("%s\n", replace("win$", "unix", string)); 10 | 11 | return(EXIT_SUCCESS); 12 | } 13 | 14 | char *replace(char *pattern, char *replacement, char *original) { 15 | char *p_temp = original; 16 | 17 | if(strlen(replacement) > strlen(pattern)) { 18 | fprintf(stderr, "Failed, strings are not equals\n"); 19 | exit(EXIT_FAILURE); 20 | } 21 | 22 | while ((p_temp = strstr(p_temp, pattern))) { 23 | memcpy(p_temp, replacement, strlen(replacement)); 24 | memmove(p_temp + strlen(replacement), 25 | p_temp + strlen(pattern), 26 | strlen(p_temp+strlen(pattern))+1); 27 | } 28 | 29 | return original; 30 | } 31 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/input_string.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_BUF 50 6 | 7 | /* Lo scopo del programma e' di ricevere una stringa in input e costruirla 8 | come tale mediante un vettore di caratteri della medesima lunghezza */ 9 | 10 | int main(void) { 11 | char ch, buf[MAX_BUF]; 12 | unsigned i = 0; 13 | 14 | printf("Type a string: "); 15 | while ((ch = getchar()) != '\n') { 16 | if (i < MAX_BUF-1) 17 | buf[i++] = ch; 18 | else { 19 | printf("Sorry, the string is too large.\n"); 20 | exit(EXIT_FAILURE); 21 | } 22 | } 23 | 24 | printf("%s\n", buf); 25 | 26 | return(EXIT_SUCCESS); 27 | } 28 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/simulate_standard_functions/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "my_strfunc.h" 5 | 6 | int main(void) { 7 | char src[] = "Take a walk on the wild side"; 8 | char *dest = malloc(sizeof(src)+1); 9 | char skill_list[] = "C, C+,+ AWK, Perl, Networking, SysAdministration, "; 10 | char update_skill[] = "Network Security, Secure Coding."; 11 | 12 | my_strncpy(dest, src, strlen(src)+1); 13 | my_strncat(skill_list, update_skill, strlen(update_skill)+1); 14 | 15 | printf(" src: %s\n", src); 16 | printf("dest: %s\n", dest); 17 | 18 | printf("%s\n", skill_list); 19 | 20 | return(EXIT_SUCCESS); 21 | } 22 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/simulate_standard_functions/my_strfunc.h: -------------------------------------------------------------------------------- 1 | #ifndef MY_STRFUNC_H 2 | #define MY_STRFUNC_H 3 | 4 | #include 5 | 6 | void my_strncpy(char *dest, const char *src, size_t n); 7 | void my_strncat(char *dest, const char *src, size_t n); 8 | 9 | #endif 10 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/simulate_standard_functions/my_strncat.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "my_strfunc.h" 3 | 4 | void my_strncat(char *dest, const char *src, size_t n) { 5 | size_t i; 6 | size_t len_dest = strlen(dest); 7 | 8 | for (i=0; src[i] && (i < n-1) != '\0'; i++) 9 | dest[len_dest + i] = src[i]; 10 | 11 | // Add null-terminated character 12 | dest[len_dest + i] = '\0'; 13 | } 14 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/simulate_standard_functions/my_strncpy.c: -------------------------------------------------------------------------------- 1 | #include "my_strfunc.h" 2 | 3 | void my_strncpy(char *dest, const char *src, size_t n) { 4 | size_t i; 5 | 6 | for (i=0; i 2 | #include 3 | #include 4 | 5 | /* 6 | Prototipe: char *strdup(const char *str); 7 | 8 | La funzione strdup() e similari non fanno parte dello standard c ansi, tuttavia 9 | nei sistemi Unix e' ampiamente utilizzata. 10 | 11 | Lo scopo della funzione e' di duplicare la stringa 'str', restituendo un 12 | puntatore ad essa in caso di successo. 13 | 14 | Compilazione: 15 | $ gcc -Wall -pedantic -std=c11 -D_GNU_SOURCE file.c 16 | $ gcc -Wall -pedantic -std=c99 -D_GNU_SOURCE file.c 17 | 18 | */ 19 | 20 | int main(void) { 21 | char str[] = "Get up stand up, stand up for your rights"; 22 | char *dup_str; 23 | 24 | dup_str = strdup(str); 25 | 26 | printf("%s\n", dup_str); 27 | 28 | return(EXIT_SUCCESS); 29 | } 30 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_is_a_pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | 6 | /* E' possibile verificare che una stringa, in C, e' essa stessa un 7 | puntatore */ 8 | char *p = "A String in C is a Poiner itself"; 9 | 10 | for (int i = 0; *(p + i) != '\0'; ++i) 11 | printf("%c", *(p + i) ); 12 | 13 | // Non valido con un array numerico. 14 | 15 | return(EXIT_SUCCESS); 16 | } 17 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/01_string_to_list/list.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXLINE 100 6 | 7 | typedef char DATA; /* will use char in examples */ 8 | 9 | struct linked_list { 10 | DATA d; 11 | struct linked_list *next; 12 | }; 13 | 14 | typedef struct linked_list ELEMENT; 15 | typedef ELEMENT * LINK; 16 | 17 | LINK string_to_list(char s[]); 18 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/01_string_to_list/main.c: -------------------------------------------------------------------------------- 1 | #include "list.h" 2 | 3 | int main(void) 4 | { 5 | char line[MAXLINE]; 6 | LINK hp; /* hp = head pointer */ 7 | LINK p; 8 | 9 | printf("%s", 10 | "---\n" 11 | "Type in a line of text: "); 12 | assert(fgets(line, MAXLINE, stdin) != NULL); 13 | hp = string_to_list(line); 14 | printf("%s%s%s", 15 | "\n" 16 | "Here is the line you type in:\n" 17 | "\n" 18 | " ", line, 19 | "\n" 20 | "and here is what we get running down the linked list:\n" 21 | "\n" 22 | " "); 23 | for (p = hp; p != NULL; p = p -> next) 24 | putchar(p -> d); 25 | printf("\n"); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/01_string_to_list/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -v 3 | EXEC = a.out 4 | INCLS = 5 | LIBS = 6 | 7 | OBJS = main.o str_to_list.o 8 | 9 | $(EXEC): $(OBJS) 10 | @echo "linking ..." 11 | @$(CC) $(CFLAGS) -o $(EXEC) $(OBJS) $(LIBS) 12 | 13 | $(OBJS): list.h 14 | $(CC) $(CFLAGS) $(INCLS) -c $*.c 15 | 16 | relink: 17 | @echo "relinking ..." 18 | @$(CC) $(CFLAGS) -o $(EXEC) $(OBJS) $(LIBS) 19 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/01_string_to_list/str_to_list.c: -------------------------------------------------------------------------------- 1 | /* 2 | // List creation using recursion. 3 | */ 4 | 5 | #include "list.h" 6 | 7 | LINK string_to_list(char s[]) 8 | { 9 | LINK head; 10 | 11 | if (s[0] == '\0') /* base case */ 12 | return NULL; 13 | else { 14 | head = malloc(sizeof(ELEMENT)); 15 | head -> d = s[0]; 16 | head -> next = string_to_list(s + 1); 17 | return head; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/02_string_to_list/list.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXLINE 100 6 | 7 | typedef char DATA; /* will use char in examples */ 8 | 9 | struct linked_list { 10 | DATA d; 11 | struct linked_list *next; 12 | }; 13 | 14 | typedef struct linked_list ELEMENT; 15 | typedef ELEMENT * LINK; 16 | 17 | LINK s_to_l(char s[]); 18 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/02_string_to_list/main.c: -------------------------------------------------------------------------------- 1 | #include "list.h" 2 | 3 | int main(void) 4 | { 5 | char line[MAXLINE]; 6 | LINK hp; /* hp = head pointer */ 7 | LINK p; 8 | 9 | printf("%s", 10 | "---\n" 11 | "Type in a line of text: "); 12 | assert(fgets(line, MAXLINE, stdin) != NULL); 13 | hp = s_to_l(line); 14 | printf("%s%s%s", 15 | "\n" 16 | "Here is the line you type in:\n" 17 | "\n" 18 | " ", line, 19 | "\n" 20 | "and here is what we get running down the linked list:\n" 21 | "\n" 22 | " "); 23 | for (p = hp; p != NULL; p = p -> next) 24 | putchar(p -> d); 25 | printf("\n"); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/02_string_to_list/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -v 3 | EXEC = a.out 4 | INCLS = 5 | LIBS = 6 | 7 | OBJS = main.o str_to_list.o 8 | 9 | $(EXEC): $(OBJS) 10 | @echo "linking ..." 11 | @$(CC) $(CFLAGS) -o $(EXEC) $(OBJS) $(LIBS) 12 | 13 | $(OBJS): list.h 14 | $(CC) $(CFLAGS) $(INCLS) -c $*.c 15 | 16 | relink: 17 | @echo "relinking ..." 18 | @$(CC) $(CFLAGS) -o $(EXEC) $(OBJS) $(LIBS) 19 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/02_string_to_list/str_to_list.c: -------------------------------------------------------------------------------- 1 | /* 2 | // List creation using iteration. 3 | */ 4 | 5 | #include "list.h" 6 | 7 | LINK s_to_l(char s[]) 8 | { 9 | LINK head = NULL, tail; 10 | int i; 11 | 12 | if (s[0] != '\0') { /* first element */ 13 | head = malloc(sizeof(ELEMENT)); 14 | head -> d = s[0]; 15 | tail = head; 16 | for (i = 1; s[i] != '\0'; ++i) { /* add to tail */ 17 | tail -> next = malloc(sizeof(ELEMENT)); 18 | tail = tail -> next; 19 | tail -> d = s[i]; 20 | } 21 | tail -> next = NULL; /* end of list */ 22 | } 23 | return head; 24 | } 25 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/03_string_to_list/list.c: -------------------------------------------------------------------------------- 1 | #include "list.h" 2 | 3 | /* --- 4 | // Count a list recursively. 5 | */ 6 | 7 | int count(LINK head) 8 | { 9 | if (head == NULL) 10 | return 0; 11 | else 12 | return (1 + count(head -> next)); 13 | } 14 | 15 | /* --- 16 | // Count a list iteratively. 17 | */ 18 | 19 | int count_it(LINK head) 20 | { 21 | int cnt = 0; 22 | 23 | for ( ; head != NULL; head = head -> next) 24 | ++cnt; 25 | return cnt; 26 | } 27 | 28 | /* --- 29 | // Print a list recursively. 30 | */ 31 | 32 | void print_list(LINK head) 33 | { 34 | if (head == NULL) 35 | printf("NULL"); 36 | else { 37 | printf("%c --> ", head -> d); 38 | print_list(head -> next); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/03_string_to_list/list.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXLINE 100 6 | 7 | typedef char DATA; /* will use char in examples */ 8 | 9 | struct linked_list { 10 | DATA d; 11 | struct linked_list *next; 12 | }; 13 | 14 | typedef struct linked_list ELEMENT; 15 | typedef ELEMENT * LINK; 16 | 17 | int count(LINK head); 18 | int count_it(LINK head); 19 | void print_list(LINK head); 20 | LINK string_to_list(char s[]); 21 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/03_string_to_list/main.c: -------------------------------------------------------------------------------- 1 | #include "list.h" 2 | 3 | int main(void) 4 | { 5 | LINK hp; /* hp = head pointer */ 6 | 7 | hp = string_to_list("ABC"); 8 | printf("The resulting list is\n"); 9 | print_list(hp); 10 | printf("\nThis list has %d elements.\n", count(hp)); 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/03_string_to_list/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -v 3 | EXEC = a.out 4 | INCLS = 5 | LIBS = 6 | 7 | OBJS = main.o list.o str_to_list.o 8 | 9 | $(EXEC): $(OBJS) 10 | @echo "linking ..." 11 | @$(CC) $(CFLAGS) -o $(EXEC) $(OBJS) $(LIBS) 12 | 13 | $(OBJS): list.h 14 | $(CC) $(CFLAGS) $(INCLS) -c $*.c 15 | 16 | relink: 17 | @echo "relinking ..." 18 | @$(CC) $(CFLAGS) -o $(EXEC) $(OBJS) $(LIBS) 19 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/03_string_to_list/str_to_list.c: -------------------------------------------------------------------------------- 1 | /* 2 | // List creation using recursion. 3 | */ 4 | 5 | #include "list.h" 6 | 7 | LINK string_to_list(char s[]) 8 | { 9 | LINK head; 10 | 11 | if (s[0] == '\0') /* base case */ 12 | return NULL; 13 | else { 14 | head = malloc(sizeof(ELEMENT)); 15 | head -> d = s[0]; 16 | head -> next = string_to_list(s + 1); 17 | return head; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/04_string_to_list/input: -------------------------------------------------------------------------------- 1 | A is for apple or alphabet pie 2 | which all get a slice of, 3 | come taste it and try. 4 | 5 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/04_string_to_list/list.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXLINE 100 6 | 7 | typedef char DATA; /* will use char in examples */ 8 | 9 | struct linked_list { 10 | DATA d; 11 | struct linked_list *next; 12 | }; 13 | 14 | typedef struct linked_list ELEMENT; 15 | typedef ELEMENT * LINK; 16 | 17 | void concatenate(LINK a, LINK b); 18 | int count(LINK head); 19 | int count_it(LINK head); 20 | void delete_list(LINK head); 21 | void print_list(LINK head); 22 | LINK string_to_list(char s[]); 23 | void wrt_list(LINK hp); 24 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/04_string_to_list/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -v 3 | EXEC = a.out 4 | INCLS = 5 | LIBS = 6 | 7 | OBJS = main.o list.o str_to_list.o wrt.o 8 | 9 | $(EXEC): $(OBJS) 10 | @echo "linking ..." 11 | @$(CC) $(CFLAGS) -o $(EXEC) $(OBJS) $(LIBS) 12 | 13 | $(OBJS): list.h 14 | $(CC) $(CFLAGS) $(INCLS) -c $*.c 15 | 16 | relink: 17 | @echo "relinking ..." 18 | @$(CC) $(CFLAGS) -o $(EXEC) $(OBJS) $(LIBS) 19 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/04_string_to_list/str_to_list.c: -------------------------------------------------------------------------------- 1 | /* 2 | // List creation using recursion, 3 | // but replace each newline with 4 | // a blank space. 5 | */ 6 | 7 | #include "list.h" 8 | 9 | LINK string_to_list(char s[]) 10 | { 11 | DATA d; 12 | LINK head; 13 | 14 | if (s[0] == '\0') /* base case */ 15 | return NULL; 16 | else { 17 | head = malloc(sizeof(ELEMENT)); 18 | d = (s[0] == '\n') ? ' ' : s[0]; 19 | head -> d = d; 20 | head -> next = string_to_list(s + 1); 21 | return head; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/string_to_linked_list/04_string_to_list/wrt.c: -------------------------------------------------------------------------------- 1 | #include "list.h" 2 | 3 | void wrt_list(LINK hp) 4 | { 5 | LINK p; 6 | 7 | for (p = hp; p != NULL; p = p -> next) 8 | putchar(p -> d); 9 | } 10 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/working_char_by_char/getline.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | #include 3 | #include 4 | 5 | 6 | /* 7 | * Calcola e stampa su stdout la lunghezza di ciascuna riga del file puntato da 8 | * filename. 9 | */ 10 | 11 | int main (void) 12 | { 13 | FILE *fp; 14 | char *filename = "/etc/passwd"; 15 | char *setmode = "r"; 16 | char *line = NULL; 17 | size_t len = 0; 18 | unsigned int read; 19 | 20 | if ( (fp = fopen (filename, setmode)) == NULL) { 21 | fprintf(stderr, "%s: Open file\n", filename); 22 | exit(EXIT_FAILURE); 23 | } 24 | 25 | /* Legge dallo stream fp una linea, archivia il risultato in line */ 26 | while ((read = getline(&line, &len, fp)) != -1) 27 | printf ("(len: %u) %s", read, line); 28 | 29 | free (line); 30 | fclose(fp); 31 | 32 | return (EXIT_SUCCESS); 33 | } 34 | -------------------------------------------------------------------------------- /src/C/C_lang/strings/working_char_by_char/squeeze.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void squeeze(char str[], int ch); 5 | 6 | /* Lo scopo del programma e' di eliminare tutte le occorrenze di uno specifico 7 | carattere da una stringa, modificandola mediante la funzione squeeze() */ 8 | 9 | int main(void) { 10 | char my_str[] = "Takxxxex xaxxx xxxwxxaxxxlxxk onxx xthxxe wxilxd sxxidxe!"; 11 | int c = 'x'; 12 | 13 | squeeze(my_str, c); 14 | printf("%s\n", my_str); 15 | 16 | return(EXIT_SUCCESS); 17 | } 18 | 19 | /* La funzione squeeze() elimina tutte le occorrenze di 'ch' da 'str' */ 20 | void squeeze(char str[], int ch) { 21 | int i, j; 22 | 23 | for (i = j = 0; str[i] != '\0'; i++) 24 | if (str[i] != ch) 25 | str[j++] = str[i]; 26 | str[j] = '\0'; 27 | } 28 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/README.md: -------------------------------------------------------------------------------- 1 | ### List of arguments covered 2 | 3 | * Structures; 4 | * How to copy a structure; 5 | * Size of structure; 6 | * New type with typedef; 7 | * Pointer to nested structures; 8 | * Unions; 9 | * Bit fields; 10 | * vector of structures. 11 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/anonymous_structures.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Lo standard C11 ha inrodotto le 'anonymous structures and unions', mediante 5 | le quali e' lecito definire strutture e unioni prive sia di tag sia di 6 | variabili, dotate del solo specificatore 'struct' o 'union'. 7 | 8 | c11 standard definition: 9 | "A structure or union is defined without any named members". 10 | */ 11 | 12 | typedef struct { 13 | union { 14 | struct { 15 | int x; 16 | int y; 17 | int z; 18 | }; 19 | int a[2]; 20 | }; 21 | } v_t; 22 | 23 | int main(void) { 24 | v_t vec; 25 | 26 | printf("%d %d %d\n", vec.x = 10, vec.a[1] = 20, vec.z = 30); 27 | 28 | return(EXIT_SUCCESS); 29 | } 30 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/copy_structures.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "rgb_color.h" /* definizione della struttura */ 5 | 6 | int main(void) { 7 | struct RGB_color white; 8 | struct RGB_color my_copy; 9 | 10 | // Inizializzazione della variabile di tipo struct RGB_color white 11 | white.set_red = 255; 12 | white.set_green = 255; 13 | white.set_blu = 255; 14 | strncpy(white.set_name, "bianco", 7); 15 | 16 | /* Copia ciascun valore di 'white' in 'my_copy'. Operazione permessa 17 | perche' si tratta di strutture compatibili */ 18 | my_copy = white; 19 | 20 | printf("%s: RGB(%i,%i,%i)\n", my_copy.set_name, my_copy.set_red, \ 21 | my_copy.set_green, my_copy.set_blu); 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/full_programs/hardware_components.h: -------------------------------------------------------------------------------- 1 | #ifndef HARDWARE_COMPONENTS_H 2 | #define HARDWARE_COMPONENTS_H 3 | 4 | #define MAX_LEN 25 5 | #define MAX_COMPONENTS 100 // Componenti Hardware 6 | 7 | // La struttura di ciascuna voce del catalogo 8 | struct hw_item { 9 | int id; 10 | char name[MAX_LEN+1]; 11 | char model[MAX_LEN+1]; 12 | int quantity; 13 | }; 14 | 15 | typedef struct hw_item HardwareItem; 16 | 17 | // Prototipi di funzione 18 | int insert(void); 19 | void update(void); 20 | void search(void); 21 | void delete(void); 22 | void print(void); 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/full_programs/makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -std=c11 -Wall -pedantic 3 | OBJS = main.o hardware_components.o readline.o 4 | TARGET = hwcomponent.out 5 | VAR = $(wildcard *.c) 6 | 7 | $(TARGET): $(OBJS) 8 | $(CC) $(CFLAGS) $(VAR) -o $(TARGET) 9 | 10 | clean: 11 | rm -rf $(OBJS) $(TARGET) 12 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/full_programs/readline.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "readline.h" 4 | 5 | int read_line(char str[], int n) { 6 | int c, i = 0; 7 | 8 | // Salta gli spazi vuoti 9 | while (isspace(c = fgetc(stdin))) 10 | ; 11 | 12 | /* Legge il resto della riga, salva l'input nella stringa 'str' solo se 13 | e' minore di 'n' */ 14 | while (c != '\n' && c != EOF) { 15 | if (i < n) 16 | str[i++] = c; 17 | c = fgetc(stdin); 18 | } 19 | // Aggiunge il null-character di fine stringa 20 | str[i] = '\0'; 21 | 22 | // Restituisce il numero dei caratteri memorizzati nella stringa 'str' 23 | return i; 24 | } 25 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/full_programs/readline.h: -------------------------------------------------------------------------------- 1 | #ifndef READLINE_H 2 | #define READLINE_H 3 | 4 | int read_line(char str[], int n); 5 | 6 | #endif 7 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/rgb_color.h: -------------------------------------------------------------------------------- 1 | #ifndef RGB_COLOR 2 | #define RGB_COLOR 3 | 4 | #define MAX_STR 10 5 | 6 | struct RGB_color { 7 | int set_red; 8 | int set_green; 9 | int set_blu; 10 | char set_name[MAX_STR]; 11 | }; 12 | 13 | #endif 14 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/strtag.h: -------------------------------------------------------------------------------- 1 | #ifndef STRTAG_H 2 | #define STRTAG_H 3 | 4 | /* When a struct use a struct-tag, it doesn't allocate memory */ 5 | struct strtag { 6 | unsigned int year; 7 | unsigned int month; 8 | unsigned int dat; 9 | }; 10 | 11 | #endif 12 | 13 | /* 14 | Within a .c file we can include this file: 15 | #include "strtag.h" 16 | */ 17 | 18 | /* A good way to create a new type is: 19 | typedef struct strtag NewType; 20 | 21 | Then we can declare a new struct data type with: 22 | 23 | NewType data; 24 | 25 | Now the memory will be allocated. 26 | */ 27 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/structures_and_compund_literals.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_AUT_LEN 20 6 | #define MAX_TIT_LEN 40 7 | 8 | struct library { 9 | int id; 10 | char author[MAX_AUT_LEN]; 11 | char title[MAX_TIT_LEN]; 12 | }; 13 | 14 | int main(void) { 15 | // Inizializzazione di una struttura con un compound literals 16 | struct library data = (struct library){1, "XXlliam XXbson", "XXuromancer"}; 17 | 18 | printf("id: %d\tauthor: %s\ttitle: %s\n", data.id, data.author, data.title); 19 | 20 | /* Si provvedere alla riscrittura di 'author' e 'title', utilizzando 21 | questa volta i 'compund literals' come parametri della funzione strcpy() */ 22 | strcpy(data.author, (const char[]){"WIlliam Gibson"}); 23 | strcpy(data.title, (const char[]){"Neuromancer"}); 24 | 25 | printf("id: %d\tauthor: %s\ttitle: %s\n", data.id, data.author, data.title); 26 | 27 | return(EXIT_SUCCESS); 28 | } 29 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/typedef_structures.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX_BUF 20 5 | 6 | // Nuovo tipo di dato 'Book' 7 | typedef struct { 8 | char title[MAX_BUF]; // 20 byte + 9 | char sub_title[MAX_BUF]; // 20 byte + 10 | char author_name[MAX_BUF]; // 20 byte + 11 | char author_surname[MAX_BUF]; // 20 byte + 12 | unsigned short year; // 4 byte + 13 | unsigned int ID; // 4 byte + 14 | } Book; // 2 byte per l'allineamento corretto) 15 | // tot. 88 byte 16 | // Alias al tipo di dato 17 | typedef Book book; 18 | 19 | int main(void) { 20 | // Istruzioni equivalenti 21 | Book scifi; 22 | book horror; 23 | 24 | printf("sizeof Book = %d byte\n", sizeof(scifi)); 25 | printf("sizeof book = %d byte\n", sizeof(horror)); 26 | 27 | return(EXIT_SUCCESS); 28 | } 29 | -------------------------------------------------------------------------------- /src/C/C_lang/structures_and_unions/vector_of_structures.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define VEC_SIZE(x) (sizeof(x)/sizeof(x[0])) 5 | 6 | struct unix_systems { 7 | char *os_name; 8 | int year; 9 | }; 10 | 11 | int main(void) { 12 | // Inizializzazione del vettore di struttore 13 | const struct unix_systems list_of_unix_os[] = { 14 | {"OpenBSD", 1994}, {"FreeBSD", 1992}, 15 | {"Linux", 1991}, {"HP/UX", 1995}, 16 | {"AIX", 1994}, {"Open Solaris", 2005}, 17 | {"UnixWare", 1992}, {"Mac OS X", 2000}, 18 | {"NetBSD", 1992}, {"Sun OS", 1981}, 19 | {"Minix", 1987}, {"SCO Unix", 1983} 20 | }; 21 | 22 | for (int i=0; i 2 | #include 3 | 4 | /* Warning: Binary integer literals are a GNU extension 5 | per cui non e' Standard, quindi non portabile */ 6 | 7 | int main(void) { 8 | 9 | /* Una costante binaria puo' essere scritta utilizzando il prefisso 10 | '0b' oppure '0B', tuttavia non e' parte integrante dello standard. 11 | 12 | Sia GCC sia Clang lo supportano*/ 13 | 14 | int val1 = 0B00000001; // 1 15 | int val2 = 0b00000010; // 2 16 | int total = val1 + val2; 17 | int val3 = 0xF; 18 | int val4 = 0b00001111; 19 | 20 | printf("%d + %d = %d\n", val1, val2, total); 21 | 22 | if (val3 == val4) 23 | printf("They are both %d\n", val4); 24 | 25 | return(EXIT_SUCCESS); 26 | } 27 | -------------------------------------------------------------------------------- /src/C/C_lang/stuff/how_much_memory_allocate.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Lo scopo del programma e' di verificare quanta memoria, espressa in Mb, 5 | puo' essere allocata in un processo */ 6 | 7 | int main(void) { 8 | int mb = 0; 9 | 10 | while (malloc(1<<20)) 11 | ++mb; 12 | 13 | printf("Allocated %d Mb\n", mb); 14 | 15 | return(EXIT_SUCCESS); 16 | } 17 | -------------------------------------------------------------------------------- /src/C/C_lang/stuff/profiling/basic_profiler.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_LOOP 10000000 6 | 7 | // Lo scopo del programma e' di calcolare il tempo di esecuzione di un ciclo 8 | 9 | int main(void) { 10 | clock_t before; 11 | double after; 12 | 13 | before = clock(); 14 | for (int i=0; i 2 | #include 3 | #include 4 | #include 5 | 6 | unsigned long count[UCHAR_MAX+1]; 7 | 8 | /* Lo scopo del programma e' di visualizzare la frequenza dei byte. 9 | Uso: ./a.out < file */ 10 | 11 | int main(void) { 12 | int c; 13 | 14 | while ((c = getchar()) != EOF) 15 | count[c]++; 16 | 17 | for (c=0; c<= UCHAR_MAX; c++) 18 | if (count[c] != 0) 19 | printf("%.2x %c %lu\n", c, isprint(c) ? c : '-', count[c]); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/README.md: -------------------------------------------------------------------------------- 1 | ## Bitwise operators 2 | 3 | ### List of arguments covered 4 | 5 | * logical operators 6 | * & - bitwise AND 7 | * | - inclusive OR 8 | * ^ - exclusive OR (XOR) 9 | * shift operators 10 | * << - left-shift 11 | * >> - right-shift 12 | * ~ - one's complement 13 | * bit mask 14 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/bit_swap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void bit_swap(int *x, int *y); 5 | 6 | int main(void) { 7 | int a = 10; 8 | int b = 20; 9 | 10 | printf("before swapping - a = %d, b = %d\n", a, b); 11 | bit_swap(&a, &b); 12 | printf(" after swapping - a = %d, b = %d\n", a, b); 13 | 14 | return(EXIT_SUCCESS); 15 | } 16 | 17 | // Working with XOR and change each value 18 | void bit_swap(int *x, int *y) { 19 | *y = *x ^ *y; 20 | *x = *x ^ *y; 21 | *y = *x ^ *y; 22 | } 23 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/check_integer_power_of_two/is_pow_of_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* The program's purpose is to check if an integer is a power of two */ 5 | 6 | int main(void) { 7 | unsigned int values[] = {2, 26, 64, 78, 88, 100, 31, 34, 1024, 16}; 8 | _Bool result; 9 | int i; 10 | 11 | for (i=0; i 2 | #include 3 | #include 4 | 5 | void absolute_value(int val); 6 | 7 | // The program's purpose is to extract the absolute value of an integer 8 | 9 | int main(void) { 10 | int values[] = {0x0, -1, 0x00000001, 0xFFFFFF00, 0xFFFFFEFF, 10}; 11 | 12 | for (int i=0; i> 31 */ 23 | int const mask = val >> (sizeof(int) * CHAR_BIT - 1); 24 | unsigned int result = (val + mask) ^ mask; 25 | 26 | printf("absolute (abs) value of %d is %u\n", val, result); 27 | } 28 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/extract_the_maximum/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // The program's purpose is to extract the maximum value from two integers 5 | 6 | int main(void) { 7 | int val1 = 229; 8 | int val2 = 281; 9 | 10 | int result = val1 ^ ((val1 ^ val2) & -(val1 < val2)); 11 | 12 | printf("The maximum of %d and %d is: %d\n", val1, val2, result); 13 | 14 | return(EXIT_SUCCESS); 15 | } 16 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/extract_the_minimum/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // The program's purpose is to extract the minimum value from two integers 5 | 6 | int main(void) { 7 | int val1 = 567; 8 | int val2 = 987; 9 | 10 | int result = val2 ^ ((val1 ^ val2) & -(val1 < val2)); 11 | 12 | printf("The minimum of %d and %d is: %d\n", val1, val2, result); 13 | 14 | return(EXIT_SUCCESS); 15 | } 16 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/howto_change_a_bit_field.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | /* Modificare un campo di bit 6 | Si vogliono modificare i bit della variabile 'num' dal bit 4 al bit 6 */ 7 | unsigned int num = 0; 8 | num = (num & ~0x0070) | 0x0050; /* L'operatore bitwise AND '&' ha una 9 | precedenza maggiore rispetto all'operatore 10 | bitwise OR '|', quindi le parentesi in 11 | questo caso non sono necessarie, tuttavia 12 | inserirle per migliorare la leggibilita' 13 | sarebbe una buona idea */ 14 | printf("(dec.) %d - (hex) %#x\n", num, num); 15 | 16 | return(EXIT_SUCCESS); 17 | } 18 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/howto_check_a_bit.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | /* Controllare un bit 6 | Si controlla se il bit numero 6 della variabile 'num1' e' pari a 1 */ 7 | unsigned short num1 = 0x5A; // 0000000001011010 8 | unsigned short i = 0x40; // 0000000001000000 9 | 10 | if (num1 & i) 11 | printf("The 6th bit of num1 variable is '1'\n"); 12 | 13 | return(EXIT_SUCCESS); 14 | } 15 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/howto_clear_a_bit.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | /* Azzerare un bit 6 | Azzeramento del bit numero 6 della variabile 'num1' di tipo 7 | 'unsigned short' da 16 bit, mediante un AND e una maschera con il bit 8 | nella posizione 6 impostato a 0 e i restanti bit a 1. */ 9 | unsigned short num1 = 0xEE; // 0000000011101110 & (dec. 238) 10 | num1 &= ~0x0040; // 1111111110111111 = 11 | // 0000000010101110 (dec. 174) 12 | printf("%#x &= ~%#x - %#x\n", 0xEE, 0x40, num1); 13 | 14 | // Oppure con uno shift-left, azzerando il bit 'i'esimo. 15 | unsigned short num2 = 0xEE; 16 | unsigned short i = 6; 17 | 18 | num2 &= ~(1 << i); 19 | 20 | printf("%#x &= ~(%d << %d) - %#x\n", 0xEE, 1, i, num2); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/howto_get_a_bit_field.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | /* Recuperare un valore da un campo di bit 6 | In questo caso si recuperano i 3 bit meno significativi, ovvero 0,1,2 */ 7 | unsigned int num1 = 0xAF; // 10101111 8 | 9 | // num2 reecupera i 3 bit meno significativi e vale 00000111, 0x07 10 | unsigned int num2 = num1 & 0x07; 11 | 12 | // num3 recupera i bit 4,5,6 mediante shift, e vale 00000010, 0x02 13 | unsigned int num3 = (num1 >> 4) & 0x07; 14 | 15 | printf("num1:%#x num2:%#x num3:%#x\n", num1, num2, num3); 16 | 17 | return(EXIT_SUCCESS); 18 | } 19 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/howto_setup_a_bit.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | /* Settare un bit 6 | Modifica del bit numero 6 di una variabile di tipo 'unsigned short' da 16 7 | bit, mediante un OR e una maschera con il bit nella posizione 6 impostato a 8 | 1 e i restanti bit a 0. */ 9 | unsigned short num1 = 0x0030; // 0000000000110000 | (dec. 48) 10 | num1 |= 0x0040; // 0000000001000000 = (dec. 64) 11 | // 0000000001110000 (dec. 112) 12 | printf("0x%x |= 0x%x - 0x%x\n", 0x30, 0x40, num1); 13 | 14 | // Oppure con uno shift-left 15 | unsigned short num2 = 0x0030; 16 | unsigned short i = 6; 17 | 18 | num2 |= 1 << i; 19 | 20 | printf("%#x |= %d << %d - %#x\n", 0x00, 1, i, num2); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/inetegers_opposite_signs/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* The program's purpose is to verify if two integers have opposite signs. 5 | true (1) = opposite signs 6 | false (0) = opposite signs */ 7 | 8 | int main(void) { 9 | int x = 10; 10 | int y = 4; 11 | int z = -5; 12 | 13 | _Bool val1 = ((x ^ y) < 0); 14 | _Bool val2 = ((x ^ z) < 0); 15 | 16 | printf("%2d and %2d have opposite signs: %d (false)\n", x, y, val1); 17 | printf("%2d and %2d have opposite signs: %d (true)\n", x, z, val2); 18 | 19 | return(EXIT_SUCCESS); 20 | } 21 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/mask.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define LEN 10 5 | 6 | int main(void) { 7 | /* Una maschera e' una costante o una variabile, e' utilizzata per estrarre 8 | i bit desiderati da una variabile o da un'espressione */ 9 | 10 | int mask = 1; /* 00000000 00000000 00000000 00000001 */ 11 | int i; 12 | 13 | /* Si utilizza la maschera per determinare se il bit meno significativo 14 | e' 0 oppure 1 */ 15 | for (i=0; i 2 | #include 3 | 4 | int main(void) { 5 | unsigned char n = 200; /* 11001000 (0xc8) */ 6 | 7 | /* turn off the rightmost bit in a word */ 8 | unsigned char res = n & (n - 1); 9 | /* 10 | 11001000 & (11001000 - 00000001) 11 | 11001000 & 11000111 12 | 11000000 13 | */ 14 | printf("before: %d (0x%x)\nafter : %d (0x%x)\n", n, n, res, res); 15 | 16 | return(EXIT_SUCCESS); 17 | } 18 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/the_sign_of_an_integer/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* The program's purpose is to find the sign of a number, the result 6 | goes into 'result' variable. 7 | Positive is +1, Negative is -1 */ 8 | 9 | int main(void) { 10 | int value = -378; 11 | int result = +1 | (value >> (sizeof(int) * CHAR_BIT - 1)); 12 | 13 | printf("%d\n", result); 14 | 15 | return(EXIT_SUCCESS); 16 | } 17 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/tips_and_tricks/any_bit_LSB_equals_one.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | int val = 0xA1B1C1FF; // 10101010 01010101 10101010 11111111 7 | int mask = 0xFF; // 00000000 00000000 00000000 11111111 8 | 9 | // if any bit in the LSB (Least Significant Byte) of 'val' is 1, returns 1 10 | int result = !(~val & mask); 11 | 12 | // Logical operator '!' detects whether there is any nonzero bit in a word 13 | int res = !!(val & mask); 14 | 15 | assert(result == 1); 16 | assert(res == 1); 17 | 18 | printf("result: %d\n", result); 19 | printf("result: %d\n", res); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/tips_and_tricks/any_bit_MSB_equals_zero.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(void) { 7 | int val = 0x00FFFFFF; // 00000000 11111111 11111111 11111111 8 | int mask = 0xFF; // 00000000 00000000 00000000 11111111 9 | 10 | // if any bit in the MSB (Most Significant Byte) of 'val' is 0, returns 1 11 | int result = !(val & (mask << CHAR_BIT * 3)); 12 | 13 | // Logical operator '!' detects whether there is any nonzero bit in a word 14 | int res = !!(~val & mask); 15 | 16 | assert(result == 1); 17 | assert(res == 0); 18 | 19 | printf("result: %d\n", result); 20 | printf("result: %d\n", res); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/tips_and_tricks/any_bit_equals_one.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | int val = ~0; // 11111111 11111111 11111111 11111111 7 | int mask = ~0; // 11111111 11111111 11111111 11111111 8 | 9 | // if any bit of 'val' is 1, returns 1 10 | int result = !(val ^ mask); 11 | 12 | // Logical operator '!' detects whether there is any nonzero bit in a word 13 | int res = !!(val); 14 | 15 | assert(result == 1); 16 | assert(res == 1); 17 | 18 | printf("result: %d\n", result); 19 | printf("result: %d\n", res); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/tips_and_tricks/any_bit_equals_zero.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | int val = 0; 7 | int mask = 0xFFFFFFFF; // 11111111 11111111 11111111 11111111 8 | 9 | // if any bit of 'val' is 0, returns 0 10 | int result = !(val & mask); 11 | 12 | // Logical operator '!' detects whether there is any nonzero bit in a word 13 | int res = !!~val; 14 | 15 | assert(result == 1); 16 | assert(res == 1); 17 | 18 | printf("result: %d\n", result); 19 | printf("result: %d\n", res); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/tips_and_tricks/any_odd_bit_is_one.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define SIZE (sizeof(num) / sizeof(num[0])) 5 | 6 | int any_odd_is_one(unsigned val); 7 | 8 | int main(void) { 9 | int num[] = { 0xFF, 0xA, 0x14, 0x0100, 0xABC, 0x6600, 0x0200 }; 10 | 11 | for (int i=0; i 2 | #include 3 | 4 | int arithmetic_shifts(); 5 | 6 | int main(void) { 7 | if ( arithmetic_shifts() ) 8 | fputs("Machine with arithmetic shifts", stdout); 9 | else 10 | fputs("Machine with logical shifts", stdout); 11 | 12 | return(EXIT_SUCCESS); 13 | } 14 | 15 | int arithmetic_shifts() { 16 | // Imposta di ciascuno dei 32 bit a 1; 17 | int val = ~0; 18 | 19 | /* Se dopo lo shift di un bit a destra, 'val' sara' ancora uguale ad 1, 20 | allora sara' stato un shift aritmetico */ 21 | return (val >> 1) == val; 22 | } 23 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/tips_and_tricks/get_0xff.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | unsigned int val = (1 << 8) - 1; // 0xFF (hex), 255 (dec) 6 | 7 | printf("%#x (hex), %d (dec)\n", val, val); 8 | 9 | return(EXIT_SUCCESS); 10 | } 11 | -------------------------------------------------------------------------------- /src/C/bitwise_hacks/tips_and_tricks/get_rightmost_one.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int get_rightmost_one_bit(unsigned value); 5 | 6 | int main(void) { 7 | int values[] = { 0xFF, 0xA, 0x14, 0x0100, 0xABC, 0x6600, 0x0200}; 8 | int i; 9 | 10 | for (i=0; i 2 | #include 3 | #include 4 | 5 | // Lo scopo del programma e' di inizializzare la libreria SDL 6 | 7 | int main(int argc, char *argv[]) { 8 | 9 | // Inizializzazione della libreria SDL 10 | if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { 11 | fprintf(stderr, "Cannot initialize SDL: %s\n", SDL_GetError()); 12 | exit(EXIT_FAILURE); 13 | } 14 | 15 | puts("Success"); 16 | 17 | // Chiusura della libreria 18 | SDL_Quit(); 19 | 20 | return(EXIT_SUCCESS); 21 | } 22 | -------------------------------------------------------------------------------- /src/C/libraries/SDL/00_show_message_box.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Lo scopo del programma e' di visualizzare un semplice 'message box' 6 | 7 | int main(void) { 8 | // Inizializzazione della libreria SDL 9 | if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { 10 | fprintf(stderr, "Cannot initialize SDL: %s\n", SDL_GetError()); 11 | exit(EXIT_FAILURE); 12 | } 13 | 14 | SDL_ShowSimpleMessageBox( 15 | SDL_MESSAGEBOX_INFORMATION, \ 16 | "SDL Title", \ 17 | "Window Title", \ 18 | NULL); 19 | 20 | // Chiusura e pulizia della libreria 21 | SDL_Quit(); 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | -------------------------------------------------------------------------------- /src/C/libraries/SDL/README.md: -------------------------------------------------------------------------------- 1 | # Simple DirectMedia Layer (SDL) 2 | 3 | E' una libreria multimediale cross-platform di sviluppo che fornisce un accesso 4 | di basso livello all'hardware grafico via OpenGL e Direct3D, ad audio, 5 | keyboard, mouse, joystick, cdrom, threads, timers, etc. 6 | 7 | > E' ampiamente utilizzata principalmente per la scrittura di video games. 8 | 9 | ## Which API version we are using 10 | 11 | Version: 2.0.x 12 | 13 | ## How to Compile SDL programs 14 | 15 | With sdl2-config tool: 16 | 17 | `gcc program.c -std=c11 (or c99) -Wall -pedantic `sdl2-config --cflags --libs`` 18 | 19 | `clang program.c -std=c11 (or c99) -Wall -pedantic `sdl2-config --cflags --libs`` 20 | 21 | Linking the library directly: 22 | 23 | `gcc -std=c11 (or c99) -Wall -pedantic -lSDL2 program.c` 24 | 25 | `clang -std=c11 (or c99) -Wall -pedantic -lSDL2 program.c` 26 | 27 | ## How to get the library 28 | 29 | [dowanload](https://libsdl.org) source code from the main site. 30 | -------------------------------------------------------------------------------- /src/C/libraries/SQLite/00_version_management_functions.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* Lo scopo del programma e' la presentazione di alcune funzioni utili per 6 | esrapolare alcuni dati relativi alla libreria SQLite in uso */ 7 | 8 | int main(void) { 9 | printf( "SQLite library version: %s\n", sqlite3_libversion()); 10 | printf(" SQLite library number: %d\n", sqlite3_libversion_number()); 11 | printf("SQLite library sourceid: %s\n", sqlite3_sourceid()); 12 | 13 | return(EXIT_SUCCESS); 14 | } 15 | -------------------------------------------------------------------------------- /src/C/libraries/SQLite/convenience_wrappers/README.md: -------------------------------------------------------------------------------- 1 | ## Convenience functions - or convenience wrapper or convenience queries 2 | 3 | The `sqlite3_exec()` interface is a __convenience wrapper__ that carries out all four 4 | of the above steps with a single function call. A callback function passed into 5 | `sqlite3_exec()` is used to process each row of the result set. 6 | 7 | [An Introduction to the SQLite C/C++ interface](https://www.sqlite.org/cintro.html) 8 | 9 | > Convenience functions can be used to prepare, step, and finalize SQL statement 10 | in one call. 11 | 12 | These functions are not faster, doesn't support the use of bound parameters, so 13 | you're forced to use string manipulation to build SQL commands. They are 14 | acceptable for DDL commands (Data Definition Language) but for any type of DML 15 | command (Data Manipulation Language) is strongly reccomended using the prepared 16 | statements. 17 | 18 | > sqlite3_exec() should only be used for one time use queries. 19 | -------------------------------------------------------------------------------- /src/C/libraries/SQLite/create_database_sqlite.tcl: -------------------------------------------------------------------------------- 1 | #! /usr/bin/tclsh 2 | 3 | # How to create a 'logged entry' database by using SQLite Tcl extension 4 | 5 | package require sqlite3 6 | sqlite3 db $argv 7 | 8 | if {$argc != 1 } { 9 | puts "Usage: $argv0 " 10 | exit 11 | } 12 | 13 | db eval { 14 | CREATE TABLE logged_users( 15 | userPID INTEGER, 16 | login_name VARCHAR(30), 17 | access TIME, 18 | logout TIME 19 | ); 20 | } 21 | -------------------------------------------------------------------------------- /src/C/libraries/cairo/README.md: -------------------------------------------------------------------------------- 1 | ## Cairo is a 2D graphics library 2 | 3 | First of all install the cairo library on GNU/Linux: 4 | - on Debian and its derivatives: 5 | `# apt- get install libcairo2-dev` 6 | 7 | The proper header is: `#include ` 8 | 9 | ### How to compile 10 | 11 | $ clang main.c -std=c11 -Wall -pedantic -lcairo 12 | $ gcc main.c -std=c11 -Wall -pedantic -lcairo 13 | -------------------------------------------------------------------------------- /src/C/libraries/cairo/pdf/txt_to_pdf.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/b3h3moth/UnixCentric/4a8c4ce7cfef10e221ec2ac5e264afd1f9a82de8/src/C/libraries/cairo/pdf/txt_to_pdf.pdf -------------------------------------------------------------------------------- /src/C/libraries/cairo/text/README.md: -------------------------------------------------------------------------------- 1 | The best way to use text in cairo is Pango library (pangocairo) 2 | -------------------------------------------------------------------------------- /src/C/libraries/cryptography/OpenSSL/README.md: -------------------------------------------------------------------------------- 1 | ## Secure Sockets Layer toolkit - development files 2 | 3 | On *Debian GNU/Linux* and its derivatives you need to install **`libssl-dev`** 4 | package. 5 | 6 | This package is part of the OpenSSL project's implementation of the SSL and TLS 7 | cryptographic protocols for secure communication over the internet. It contains 8 | development libraries, header files, and manpages for libssl and libcrypto. 9 | [Description: `dpkg -s libssl-dev`] 10 | 11 | 12 | ## How To compile OpenSSL library 13 | 14 | Linking program with -l option and appropriate library. 15 | 16 | ``$ gcc file.c -std=c11 (c99) -Wall -pedantic -lcrypto -o prog_name`` 17 | 18 | ``$ clang file.c -std=c11 (c99) -Wall -pedantic -lcrypto -o prog_name`` 19 | -------------------------------------------------------------------------------- /src/C/libraries/cryptography/bitwise_crypto/xor_crypto_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define KEY '\\' 6 | 7 | /* Lo scopo del programma e' di eseguire uno XOR con una chiave su ciascun 8 | carattere di una stringa o di un file */ 9 | 10 | int main(void) { 11 | int original_char, new_char; 12 | 13 | while((original_char = getchar()) != EOF) { 14 | new_char = original_char ^ KEY; // XOR between 0 and KEY 15 | 16 | if (isprint(original_char) && isprint(new_char)) 17 | //putchar(new_char); 18 | printf("%c", new_char); 19 | else 20 | //putchar(original_char); 21 | printf("%c", original_char); 22 | } 23 | 24 | return(EXIT_SUCCESS); 25 | } 26 | 27 | /* 28 | Encrypt file.txt: 29 | $ ./a.out < file.txt > new_file.txt 30 | 31 | Decrypt new_file.txt: 32 | $ ./a.out < new_file.txt 33 | */ 34 | -------------------------------------------------------------------------------- /src/C/libraries/cryptography/check_crypto_fips.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define CRYPTO_FIPS "/proc/sys/crypto/fips_enabled" 5 | 6 | int main(int argc, char *argv[]) { 7 | FILE *fp; 8 | char c; 9 | 10 | if ( (fp = fopen( CRYPTO_FIPS, "r")) == NULL) { 11 | printf("The OS doesn't support kernel crypto module!\n"); 12 | return(EXIT_FAILURE); 13 | } 14 | 15 | if (fread(&c, sizeof(c), 1, fp) <= 0){ 16 | printf("failed to read from: %s\n", CRYPTO_FIPS); 17 | fclose( fp); 18 | return(EXIT_FAILURE); 19 | } 20 | 21 | printf("FIPS_MODE: %c\n", c); 22 | 23 | fclose(fp); 24 | 25 | return(EXIT_SUCCESS); 26 | } 27 | -------------------------------------------------------------------------------- /src/C/libraries/cryptography/crypt/crypt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_STR 256 6 | #define MAX_SALT 12 7 | 8 | /* La funzione utilizzata in ambiente UNIX per la cifratura delle password e' 9 | crypt - man 3 crypt - che implementa l'algoritmo di cifratura DES - Data 10 | Encryption Standard. 11 | */ 12 | 13 | int main(int argc, char *argv[]) { 14 | char password[MAX_STR]; 15 | char salt[MAX_SALT]; 16 | char *pass; 17 | 18 | printf("salt: "); 19 | scanf("%12s", salt); 20 | 21 | printf("password: "); 22 | scanf("%256s", password); 23 | 24 | if ((pass = crypt(password, salt)) == NULL) { 25 | fprintf(stderr, "Err. when (en)crypt password\n"); 26 | exit(EXIT_FAILURE); 27 | } else 28 | printf("Encrypt '%s'(%s)\n", password, pass); 29 | 30 | return(EXIT_SUCCESS); 31 | } 32 | 33 | /* 34 | Compila con: gcc -lcrypt crypt.c 35 | */ 36 | -------------------------------------------------------------------------------- /src/C/libraries/cryptography/gpgme/compila.txt: -------------------------------------------------------------------------------- 1 | intro.c `gpgme-config --cflags --libs` -D_FILE_OFFSET_BITS=64 2 | -------------------------------------------------------------------------------- /src/C/libraries/cryptography/gpgme/intro.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /* GPGME GnuPG Made Easy */ 7 | 8 | int main(int argc, char *argv[]) { 9 | /* Inizializza l'ambiente locale */ 10 | setlocale(LC_ALL, ""); 11 | gpgme_check_version(NULL); 12 | gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL)); 13 | 14 | 15 | return(EXIT_SUCCESS); 16 | } 17 | -------------------------------------------------------------------------------- /src/C/libraries/cups/README.md: -------------------------------------------------------------------------------- 1 | First of all is necessary to install the cups library package, on Debian 2 | GNU/Linux and Debian-based systems it is: ``libcups-dev``. 3 | 4 | ``# apt get install libcups-dev`` 5 | 6 | Compile the source: 7 | 8 | ``$ gcc -std=c11 -Wall -pedantic -lcups main.c`` 9 | ``$ clang -std=c11 -Wall -pedantic -lcups main.c`` 10 | -------------------------------------------------------------------------------- /src/C/libraries/cups/list_available_printers.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | int i; 7 | cups_dest_t *dests, *dest; 8 | int num_dests = cupsGetDests(&dests); 9 | 10 | for (i = num_dests, dest = dests; i>0; i--, dest++) { 11 | if (dest->instance) 12 | printf("%s/%s\n", dest->name, dest->instance); 13 | else 14 | fputs(dest->name, stdout); 15 | } 16 | 17 | return(EXIT_SUCCESS); 18 | } 19 | -------------------------------------------------------------------------------- /src/C/libraries/igraph/README.md: -------------------------------------------------------------------------------- 1 | ## igraph 2 | 3 | igraph is a collection of network analysis tools (directed acyclic graphs) 4 | 5 | 6 | ### Package and Header library 7 | 8 | On Debian GNU/Linux and its derivatives the package is `libigraph0`, the header to add is `` 9 | 10 | 11 | ### How to compile 12 | 13 | $ `gcc test.c -std=c11 -Wall -pedantic **-I/usr/local/igraph -L/usr/local/lib -ligraph**` 14 | 15 | or 16 | 17 | $ `gcc test.c -std=c11 -Wall -pedantic '**pkg-config --libs --cflags igraph**'` 18 | 19 | or 20 | 21 | $ `gcc test.c -std=c11 -Wall -pedantic **-ligraph**` 22 | -------------------------------------------------------------------------------- /src/C/libraries/libconfig/test.cfg: -------------------------------------------------------------------------------- 1 | business = 1.0; 2 | prova = true; 3 | filename = "Esempio basico del file di configurazione"; 4 | 5 | negozio = 6 | { 7 | libri = 8 | { 9 | titolo = "Libconfig programming tutorial"; 10 | autore = "B3h3m0th"; 11 | anno = 2013; 12 | }; 13 | 14 | pizzeria = 15 | { 16 | pizze_da_asporto = 17 | ( 18 | { nome = "margherita"; 19 | prezzo = 4.00; }, 20 | { nome = "capricciosa"; 21 | prezzo = 4.50; }, 22 | { nome = "4 stagioni"; 23 | prezzo = 5.00; } 24 | ); 25 | }; 26 | }; 27 | 28 | rete = { 29 | host = "unixgeek"; 30 | arch = "PPC"; 31 | kernel = 3.2; 32 | }; 33 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/README.md: -------------------------------------------------------------------------------- 1 | How to compile nCurses program: 2 | 3 | `$ gcc -std=c11 -Wall -pedantic -lcurses file.c` 4 | `$ clang -std=c11 -Wall -pedantic -lcurses file.c` 5 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/checker.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | int r,c; 7 | int cond = 1; 8 | 9 | initscr(); 10 | 11 | while (1) { 12 | for(r=0 ; r 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | initscr(); 7 | 8 | 9 | /* attron() turns on the named attributes without affecting any others */ 10 | attron(A_UNDERLINE); 11 | 12 | addstr("Text formatting with style\n"); 13 | 14 | /* attrset() sets the current attributes of the given window */ 15 | attrset(A_BOLD); 16 | 17 | addstr("nCurses library is a good way to learn UNIX programming\n"); 18 | 19 | /* it turns off all attributes */ 20 | attrset(0); 21 | 22 | addstr("I\'m working with a lot of nice functions\n"); 23 | 24 | /* attroff() turns off the named attributes without turning any other 25 | attributes on or off */ 26 | attroff(A_BOLD); 27 | 28 | refresh(); 29 | getch(); 30 | 31 | endwin(); 32 | exit(EXIT_SUCCESS); 33 | } 34 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/01_compile_ncurses.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* First of all include header. 6 | 7 | To compile program linking ncurses library: 8 | $ gcc program.c -lncurses */ 9 | 10 | /* Skeleton of typical ncurses program */ 11 | int main(void) { 12 | 13 | /* nCurses initialization, it creates both 'stdscr' and 'curstr' */ 14 | initscr(); 15 | 16 | /* ... source code goes here ... */ 17 | 18 | /* nCurses closing */ 19 | endwin(); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/02_writing_text_1_addch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* It writes a string (one characters at time) on the current screen 6 | 'curscr' */ 7 | 8 | int main(void) { 9 | char address[] = "San lorenzo avenue (type something to exit)"; 10 | char *pstr; 11 | pstr = address; 12 | 13 | initscr(); 14 | 15 | /* Loop the string 'address' and writes each character of the string 16 | with addch() function */ 17 | while(*pstr) { 18 | addch(*pstr); 19 | pstr++; 20 | } 21 | 22 | /* Update the screen */ 23 | refresh(); 24 | 25 | /* Wait until the user types something */ 26 | getch(); 27 | 28 | endwin(); 29 | exit(EXIT_SUCCESS); 30 | } 31 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/02_writing_text_2_addstr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* It writes a string on the current screen 'curscr' */ 6 | 7 | int main(void) { 8 | char address[] = "Fifth avenue NY "; 9 | char msg_to_text[] = "(type something to exit)"; 10 | 11 | initscr(); 12 | 13 | /* Write the two strings with addstr() function */ 14 | addstr(address); 15 | addstr(msg_to_text); 16 | 17 | /* Update the screen. Only now the strings get displayed */ 18 | refresh(); 19 | 20 | /* Wait until the user types something */ 21 | getch(); 22 | 23 | endwin(); 24 | exit(EXIT_SUCCESS); 25 | } 26 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/02_writing_text_3_addnstr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /* It writes a string on the current screen 'curscr' with addnstr() function. 7 | 8 | int addnstr(const char *str, int n); 9 | write a string large exaclty n characters. */ 10 | 11 | int main(void) { 12 | char message[] = "Unix addicted\n"; 13 | char msg_help[] = "(type something to exit)\n"; 14 | 15 | initscr(); 16 | 17 | addnstr(message, strlen(message)); 18 | addnstr(msg_help, strlen(msg_help)); 19 | 20 | refresh(); 21 | getch(); 22 | 23 | endwin(); 24 | 25 | exit(EXIT_SUCCESS); 26 | } 27 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/03_formatting_text_with_printw.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* The printw() function is the equivalent to the standard C printf() 6 | function. */ 7 | 8 | int main(void) { 9 | char version[] = "5.7"; 10 | char os_name[] = "OpenBSD"; 11 | size_t day = 1; 12 | size_t month = 6; 13 | size_t year = 2015; 14 | 15 | initscr(); 16 | printw("%s %s", os_name, version); 17 | printw(" - last update: %zu/%zu/%zu", month, day, year); 18 | refresh(); 19 | getch(); 20 | 21 | endwin(); 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/04_reading_text_1_getch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | char ch; 7 | 8 | initscr(); 9 | addstr("Please type x to quit"); 10 | refresh(); 11 | 12 | /* getch() returns a single character from the console */ 13 | while( (ch = getch()) != 'x') { 14 | printw("\ntyped: %c\n", ch); 15 | } 16 | 17 | endwin(); 18 | exit(EXIT_SUCCESS); 19 | } 20 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/04_reading_text_2_getstr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_STR 30 6 | 7 | int main(void) { 8 | char firstname[MAX_STR]; 9 | char lastname[MAX_STR]; 10 | 11 | /* getstr() get an input and save it into a buffer, in this case firstname 12 | and lastname. 13 | 14 | Note For security reasons is better to use getnstr() function instead */ 15 | initscr(); 16 | addstr("Firstname: "); 17 | refresh(); 18 | getstr(firstname); 19 | 20 | addstr("Lastname: "); 21 | refresh(); 22 | getstr(lastname); 23 | 24 | 25 | printw("Hi, %s, %s\n", firstname, lastname); 26 | refresh(); 27 | getch(); 28 | 29 | endwin(); 30 | exit(EXIT_SUCCESS); 31 | } 32 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/04_reading_text_3_getnstr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_STR 10 6 | 7 | int main(void) { 8 | char firstname[MAX_STR]; 9 | char lastname[MAX_STR]; 10 | 11 | /* getnstr(char *str, int n) 12 | reads from stdscr (default window) max 'n' characters, the resulting value 13 | is placed into the array of characters pointed by 'str' */ 14 | 15 | initscr(); 16 | addstr("Firstname: "); 17 | refresh(); 18 | getnstr(firstname, MAX_STR-1); 19 | 20 | addstr("Lastname: "); 21 | refresh(); 22 | getnstr(lastname, MAX_STR-1); 23 | 24 | 25 | printw("Hi, %s, %s\n", firstname, lastname); 26 | refresh(); 27 | getch(); 28 | 29 | endwin(); 30 | exit(EXIT_SUCCESS); 31 | } 32 | -------------------------------------------------------------------------------- /src/C/libraries/nCurses/input_output/05_scanw.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_STR 20 6 | 7 | int main(void) { 8 | char firstname[MAX_STR]; 9 | char lastname[MAX_STR]; 10 | 11 | initscr(); 12 | 13 | /* scanw() is analogous to the scanf() functions family. */ 14 | 15 | printw("Firstname: "); 16 | scanw("%s", firstname); 17 | 18 | printw("Lastname: "); 19 | scanw("%s", lastname); 20 | 21 | printw("Hi %s %s\n", firstname, lastname); 22 | 23 | refresh(); 24 | getch(); 25 | 26 | endwin(); 27 | 28 | exit(EXIT_SUCCESS); 29 | } 30 | -------------------------------------------------------------------------------- /src/C/libraries/pam/authentication.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /* How to compile the program: 7 | 8 | $ gcc -std=c11 -Wall -pedantic -lpam -lpam_misc authentication.c 9 | 10 | The program's purpose is to authenticate the logged user. 11 | */ 12 | 13 | int main(void) { 14 | pam_handle_t* pamh; 15 | struct pam_conv pamc; 16 | 17 | // Setup PAM conversation 18 | pamc.conv = &misc_conv; 19 | pamc.appdata_ptr = NULL; 20 | 21 | // New authentication session 22 | pam_start ("su", getenv("USER"), &pamc, &pamh); 23 | 24 | // User authentication 25 | if (pam_authenticate (pamh, 0) != PAM_SUCCESS) 26 | fprintf (stderr, "Ops, failed Authentication.\n"); 27 | else 28 | fprintf (stderr, "Authentication is ok. Hi %s\n", getenv("USER")); 29 | 30 | // Clean up any allocated data structures 31 | pam_end (pamh, 0); 32 | 33 | return(EXIT_SUCCESS); 34 | } 35 | -------------------------------------------------------------------------------- /src/C/representing_information/addressing_and_byte_ordering/endianess/little_endian.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Prototipo funzione 6 | int little_endian(void); 7 | 8 | int main(void) { 9 | if (little_endian()) 10 | printf("little-endian: %d\n", __LITTLE_ENDIAN); 11 | else 12 | printf("big-endian: %d\n", __BIG_ENDIAN); 13 | 14 | return(EXIT_SUCCESS); 15 | } 16 | 17 | /* Se il puntatore dereferenziato puntera' ad 1 la macchina avra' una 18 | architettura - ordinamento dei byte nello specifico -, di tipo little-endian, 19 | big-endian altrimenti */ 20 | int little_endian(void) { 21 | int number_one = 1; 22 | char *ptr = (char *)&number_one; 23 | return *ptr; 24 | } 25 | 26 | /* 27 | 0x00 0x08 0x10 0x18 28 | 00000000 00000000 00000000 00000001 29 | ptr -> 0x18 = 1 30 | */ 31 | -------------------------------------------------------------------------------- /src/C/representing_information/addressing_and_byte_ordering/expanding_bit_1_zero_extension.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "show_bytes.h" 4 | 5 | int main(void) { 6 | /* La conversione dal tipo 'unsigned' ad un tipo di maggior grandezza 7 | riempira' con diversi zero i bit iniziali (zero extension) */ 8 | 9 | unsigned short val1 = 12345; // unsigned short 2 byte 10 | unsigned val2 = val1; // unsigned 4 byte 11 | unsigned long long val3 = val1; // unsigned long long 8 byte 12 | 13 | printf("(val1=%d)\t", val1); 14 | show_bytes((byte_pointer) &val1, sizeof(unsigned short)); 15 | 16 | printf("(val2=%d)\t", val2); 17 | show_bytes((byte_pointer) &val2, sizeof(unsigned)); 18 | 19 | printf("(val3=%lld)\t", val3); 20 | show_bytes((byte_pointer) &val3, sizeof(unsigned long long)); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/C/representing_information/addressing_and_byte_ordering/get_bytes_with_pointer_to_char.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | int value; 6 | value = 0xAABBCCDD; 7 | 8 | printf("%#2x %#2x %#2x %#2x\n", 9 | *(char *) &value, 10 | *(((char *) &value) + 1), 11 | *(((char *) &value) + 2), 12 | *(((char *) &value) + 3)); 13 | } 14 | -------------------------------------------------------------------------------- /src/C/representing_information/addressing_and_byte_ordering/print_byte/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "utils.h" 5 | 6 | int main(void) { 7 | char list_of_char[] = {'a','b','c'}; 8 | int list_of_int[] = {123456, 234567, 891234}; 9 | 10 | printf("Characters: \n"); 11 | for (int i=0; i<3; i++) { 12 | print_bit((unsigned char *)&list_of_char[i], sizeof(char)); 13 | print_byte((unsigned char *)&list_of_char[i], sizeof(char)); 14 | } 15 | 16 | printf("Integers:\n"); 17 | for (int i=0; i<3; i++) { 18 | print_bit((unsigned char *)&list_of_int[i], sizeof(int)); 19 | print_byte((unsigned char *)&list_of_int[i], sizeof(int)); 20 | } 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/C/representing_information/addressing_and_byte_ordering/print_byte/utils.h: -------------------------------------------------------------------------------- 1 | extern void print_bit(unsigned char *ptr, unsigned int size); 2 | extern void print_byte(unsigned char *ptr, unsigned int size); 3 | 4 | -------------------------------------------------------------------------------- /src/C/representing_information/addressing_and_byte_ordering/replace_byte.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | unsigned replace_byte(unsigned def_num, int byte_pos, char new_byte) { 5 | int shift = byte_pos << 3; 6 | unsigned mask = 0xFF << shift; 7 | return (def_num & ~mask) | (new_byte << shift); 8 | } 9 | 10 | int main(void) { 11 | unsigned default_number = 0x11111111; 12 | char value = 0xEF; 13 | 14 | for (int i=0; i<4; i++) { 15 | unsigned result = replace_byte(default_number, i, value); 16 | printf("%#x\n", result); 17 | } 18 | 19 | return(EXIT_SUCCESS); 20 | } 21 | -------------------------------------------------------------------------------- /src/C/representing_information/addressing_and_byte_ordering/show_bytes.h: -------------------------------------------------------------------------------- 1 | #ifndef SHOW_BYTES_H 2 | #define SHOW_BYTES_H 3 | 4 | typedef unsigned char *byte_pointer; 5 | 6 | void show_bytes(byte_pointer start, int len); 7 | void show_int(int data); 8 | void show_float(float data); 9 | void show_pointer(void *data); 10 | void show_short(short data); 11 | void show_double(double data); 12 | void show_long(long data); 13 | void show_long_long(long long data); 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /src/C/representing_information/floating_point/encoding.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | 7 | printf("Property \tfloat \t\tdouble\t\t\tlong double\n"); 8 | printf("mantissa: \t%d \t\t%d \t\t\t%d\n", FLT_MANT_DIG, DBL_MANT_DIG, LDBL_MANT_DIG); 9 | printf("dec.digits:\t%d \t\t%d \t\t\t%d\n", FLT_DIG, DBL_DIG, LDBL_DIG); 10 | printf("max value: \t%9.5e \t%18.14e \t%22.17Le\n", FLT_MAX, DBL_MAX, LDBL_MAX); 11 | printf("min value: \t%9.5e \t%18.14e \t%22.17Le\n", FLT_MIN, DBL_MIN, LDBL_MIN); 12 | 13 | /* Write again with strings */ 14 | return(EXIT_SUCCESS); 15 | } 16 | -------------------------------------------------------------------------------- /src/C/representing_information/floating_point/range.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | 7 | printf("Single precision, data type \'float\'\n" 8 | "\tmin value: %f\n" 9 | "\texponential notation: %e\n" 10 | "\tmax value: %f\n" 11 | "\texponential notation: %e\n", 12 | FLT_MIN, FLT_MIN, FLT_MAX, FLT_MAX); 13 | 14 | printf("Double precision, data type \'double\'\n" 15 | "\tmin value: %f\n" 16 | "\texponential notation: %e\n" 17 | "\tmax value: %f\n" 18 | "\texponential notation: %e\n", 19 | DBL_MIN, DBL_MIN, DBL_MAX, DBL_MAX); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/C/representing_information/integer/integer_arithmetic/division16.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define DIV 16 5 | 6 | int div16(int num); 7 | 8 | int main(void) { 9 | // Ciascun numero relativo intero sara' diviso per DIV 10 | const int numbers[] = {165,-165,48,-48,32,-32,197,-197,1,-1,0,234,-234}; 11 | const int elem_of_numbers = sizeof(numbers) / sizeof(numbers[0]); 12 | 13 | for(int i=0; i= 0); 23 | '15' se (num < 0); 24 | */ 25 | int bias = (num >> 31) & 0xF; 26 | return (num + bias) >> 4; 27 | } 28 | -------------------------------------------------------------------------------- /src/C/representing_information/integer/integer_arithmetic/multiplication_8bit_operands.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Lo scopo della funzione e' di moltiplicare due operandi unsigned char da 5 | 8 bit e di ritornare un unsigned short da 16 bit */ 6 | 7 | unsigned short multip(unsigned char x, unsigned char y) { 8 | unsigned char i; 9 | unsigned short res = 0; 10 | 11 | for (i=0; i<8; i++) { 12 | if (y & 1) { 13 | res += x << i; 14 | } 15 | y >>= 1; 16 | } 17 | 18 | return res; 19 | } 20 | 21 | int main(void) { 22 | printf("%d\n", multip(255,255)); 23 | 24 | return(EXIT_SUCCESS); 25 | } 26 | -------------------------------------------------------------------------------- /src/C/representing_information/integer/integer_arithmetic/multiplication_overflow.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int check_overflow(int x, int y); 5 | 6 | int main(void) { 7 | int val1 = 900000000; 8 | int val2 = 2; 9 | int val3 = val2 + 1; 10 | 11 | int res1 = check_overflow(val1, val2); 12 | int res2 = check_overflow(val1, val3); 13 | 14 | if (res1) 15 | printf("%d * %d = %d\n", val1, val2, val1*val2); 16 | else 17 | printf("%d * %d = %d (Err: Integer Overflow)\n", val1, val2, val1*val2); 18 | 19 | if (res2) 20 | printf("%d * %d = %d\n", val1, val3, val1*val3); 21 | else 22 | printf("%d * %d = %d (Err: Integer Overflow)\n", val1, val3, val1*val3); 23 | 24 | return(EXIT_SUCCESS); 25 | } 26 | 27 | /* Verifica l'overflow */ 28 | int check_overflow(int x, int y) { 29 | int tot = x * y; 30 | 31 | return !x || tot/x == y; 32 | } 33 | -------------------------------------------------------------------------------- /src/C/representing_information/integer/integer_arithmetic/power_of_two.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* The function returns 1 if the argument is a power of two and 0 otherwise */ 5 | unsigned char power_of_two(unsigned char n) { 6 | return (n == 0) ? 0 : (n & (n - 1)) == 0; 7 | } 8 | 9 | int main(void) { 10 | unsigned char arr[] = {8, 16, 24, 13, 32, 65, 254}; 11 | int i; 12 | 13 | for (i = 0; i 2 | #include 3 | 4 | int foo(unsigned word); 5 | int bar(unsigned word); 6 | 7 | int main(void) { 8 | unsigned val1 = 0x00000076; 9 | unsigned val2 = 0x87654321; 10 | unsigned val3 = 0x000000c9; 11 | unsigned val4 = 0xEDCBA987; 12 | 13 | printf("%10s %12s\n", "foo()", "bar()"); 14 | 15 | printf("%#.8x - %#.8x\n", foo(val1), bar(val1)); 16 | printf("%#.8x - %#.8x\n", foo(val2), bar(val2)); 17 | printf("%#.8x - %#.8x\n", foo(val3), bar(val3)); 18 | printf("%#.8x - %#.8x\n", foo(val4), bar(val4)); 19 | 20 | return(EXIT_SUCCESS); 21 | } 22 | 23 | int foo(unsigned word) { 24 | // bit gestiti logicamente 25 | return (int) ((word << 24) >> 24); 26 | } 27 | 28 | int bar(unsigned word) { 29 | // bit gestiti aritmeticamente 30 | return ((int) word << 24) >> 24; 31 | } 32 | -------------------------------------------------------------------------------- /src/C/representing_information/integer/integer_representations/is_signed_or_unsigned_macro.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define IS_UNSIGNED(val) (val >= 0 && ~val >= 0) 5 | #define IS_SIGNED(type) ((type)0 - 1 > 0) 6 | 7 | int main(void) { 8 | signed int val = -10; 9 | 10 | if (IS_UNSIGNED(val) == 1) 11 | puts("unsigned int"); 12 | else 13 | puts("signed int"); 14 | 15 | if (IS_SIGNED(unsigned int) == 1) 16 | puts("unsigned int"); 17 | else 18 | puts("signed int"); 19 | 20 | return(EXIT_SUCCESS); 21 | } 22 | -------------------------------------------------------------------------------- /src/C/representing_information/integer/integer_representations/tips_and_tricks/arithmetic_or_logical_shift.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Si evince come eseguendo un right shift su un operando unsigned possa 5 | portare ad un undefined behavior */ 6 | 7 | int main(void) { 8 | // signed integer 9 | char buf[sizeof(3+1)]; 10 | int value = 0x80000000; 11 | int result = snprintf(buf, sizeof(buf), "%u", value >> 24); 12 | 13 | printf("S: %d %#x\n", value, value); 14 | printf("S: %d %#x\n", result, result); 15 | printf("S: %s\n", buf); 16 | 17 | // unsigned integer 18 | char buf2[sizeof(3+1)]; 19 | unsigned int value2 = 0x80000000; 20 | int result2 = snprintf(buf2, sizeof(buf2), "%u", value2 >> 24); 21 | 22 | printf("U: %d %#x\n", value2, value2); 23 | printf("U: %d %#x\n", result2, result2); 24 | printf("U: %s\n", buf2); 25 | 26 | return(EXIT_SUCCESS); 27 | } 28 | -------------------------------------------------------------------------------- /src/C/representing_information/integer/integer_representations/tips_and_tricks/get_maxint_from_unsignedlong.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* Assegnando ad una variabile di tipo 'unsigned long' il valore '-1', ciascun 6 | bit sara' impostato a 1, per cui essendo 'unsigned long' di 4 byte come 'int' 7 | si otterra' il valore massimo 'UINT_MAX' 'unsigned int'. Dovrebbe funzionare 8 | su quasi tutte le architetture. */ 9 | 10 | int main(void) { 11 | unsigned long ulval = -1; 12 | 13 | if (ulval == UINT_MAX) 14 | printf("%lu = %u\n", ulval, UINT_MAX); 15 | else 16 | fputs("Err.\n", stdout); 17 | 18 | return(EXIT_SUCCESS); 19 | } 20 | -------------------------------------------------------------------------------- /src/Kernel_Hacking/LKM/Makefile: -------------------------------------------------------------------------------- 1 | #obj-m += basic_module.o 2 | #obj-m += parametri.o 3 | #obj-m += intercept_sc.o 4 | #obj-m += intercept_sc_param.o 5 | obj-m += nascondere_file.o 6 | 7 | KERNELVERSION = $(shell uname -r) 8 | 9 | all: 10 | $(MAKE) -C /lib/modules/$(KERNELVERSION)/build M=$(PWD) modules 11 | clean: 12 | $(MAKE) -C /lib/modules/$(KERNELVERSION)/build M=$(PWD) clean 13 | -------------------------------------------------------------------------------- /src/Kernel_Hacking/LKM/README.md: -------------------------------------------------------------------------------- 1 | ## LKM Loadable Kernel Module - Kernel Linux 2 | 3 | Compile modules 4 | ``` 5 | $ make 6 | ``` 7 | 8 | Insert a module into the Linux Kernel 9 | ``` 10 | $ sudo insmod 11 | ``` 12 | 13 | Add modules from the linux Kernel 14 | ``` 15 | $ sudo modprobe 16 | ``` 17 | 18 | Open Kernel log 19 | ``` 20 | $ dmesg (made with KERN_ALERT) 21 | $ cat /var/log/messages (made with KERN_INFO) 22 | ``` 23 | 24 | Show information about a Linux Kernel module 25 | ``` 26 | $ modinfo 27 | ``` 28 | 29 | Show active modules 30 | ``` 31 | $ cat /proc/modules 32 | $ lsmod (as the previous command but formatted) 33 | ``` 34 | 35 | Show available modules 36 | ``` 37 | $ sudo modprobe -l (*.ko) 38 | ``` 39 | 40 | remove module 41 | ``` 42 | $ sudo rmmod 43 | ``` 44 | -------------------------------------------------------------------------------- /src/Kernel_Hacking/README.md: -------------------------------------------------------------------------------- 1 | ## Kernel Hacking 2 | 3 | -------------------------------------------------------------------------------- /src/README.md: -------------------------------------------------------------------------------- 1 | # C (c99, c11 standards) - Unix Systems Programming 2 | -------------------------------------------------------------------------------- /src/Unix_Programming/Date_and_Time/bdt_to_string_1_asctime.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | /* Lo scopo del programma e' di convertire un dato broken-down time in una 8 | stringa */ 9 | 10 | int main(void) { 11 | struct tm *ptm; 12 | time_t t; 13 | char *str_time; 14 | 15 | if ((t = time(NULL)) < 0) { 16 | fprintf(stderr, "Err.(%s) getting time\n", strerror(errno)); 17 | exit(EXIT_FAILURE); 18 | } 19 | 20 | if ((ptm = gmtime(&t)) == NULL) { 21 | fprintf(stderr, "Err.(%s) conversion gmtime()\n", strerror(errno)); 22 | exit(EXIT_FAILURE); 23 | } 24 | 25 | if ((str_time = asctime(ptm)) == NULL) { 26 | fprintf(stderr, "Err.(%s) str conversion: asctime()\n", strerror(errno)); 27 | exit(EXIT_FAILURE); 28 | } 29 | 30 | printf("%s", str_time); 31 | 32 | return(EXIT_SUCCESS); 33 | } 34 | -------------------------------------------------------------------------------- /src/Unix_Programming/Date_and_Time/calendar_time_2_time.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* Lo scopo del programma e' di stampare in output nella forma 'Calendar time' 6 | la data corrente e i secondi trascorsi da Epoch. */ 7 | 8 | int main(void) { 9 | time_t cur; 10 | 11 | /* Se si utilizza NULL come argomento della funzione non e' necessario 12 | verificare gli errori */ 13 | cur = time(NULL); 14 | 15 | printf("Seconds since the Epoch: %d\n", (unsigned int)cur); 16 | printf("%s\n", asctime(localtime(&cur))); 17 | 18 | return(EXIT_SUCCESS); 19 | } 20 | -------------------------------------------------------------------------------- /src/Unix_Programming/Date_and_Time/ctime.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | /* Lo scopo del programma e' di convertire un tipo time_t in una stringa 8 | mediante l'utilizzo della funzione ctime() */ 9 | 10 | int main(void) { 11 | time_t t; 12 | char *str_time; 13 | 14 | if (time(&t) < 0) { 15 | fprintf(stderr, "Err.(%s) getting time()\n", strerror(errno)); 16 | exit(EXIT_FAILURE); 17 | } 18 | 19 | /* La conversione in stringa, partendo da un valore di tipo time_t */ 20 | if ((str_time = ctime(&t)) == NULL) { 21 | fprintf(stderr, "Err.(%s) str conversion: ctime()\n", strerror(errno)); 22 | exit(EXIT_FAILURE); 23 | } 24 | 25 | printf("%s", str_time); 26 | 27 | return(EXIT_SUCCESS); 28 | } 29 | -------------------------------------------------------------------------------- /src/Unix_Programming/Date_and_Time/highest_time_t_values.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // How to get the highest value of time_t variable in hex. 8 | int main(void) { 9 | time_t highest_value = 0x7FFFFFFF; 10 | 11 | char *str_datec = ctime(&highest_value); 12 | 13 | if (str_datec == NULL) { 14 | fprintf(stderr, "Err. ctime() failed: %s\n", strerror(errno)); 15 | exit(EXIT_FAILURE); 16 | } 17 | 18 | printf(" Highest value (ctime): %s", str_datec); 19 | 20 | // Correct technique 21 | char *str_datea = asctime(gmtime(&highest_value)); 22 | 23 | if (str_datea == NULL) { 24 | fprintf(stderr, "Err. asctime() failed: %s\n", strerror(errno)); 25 | exit(EXIT_FAILURE); 26 | } 27 | 28 | printf("Highest value (asctime): %s\n", str_datea); 29 | 30 | return(EXIT_SUCCESS); 31 | } 32 | -------------------------------------------------------------------------------- /src/Unix_Programming/Date_and_Time/strptime.c: -------------------------------------------------------------------------------- 1 | #define _XOPEN_SOURCE 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | enum { LEN = 255 }; 9 | 10 | /* Lo scopo del programma e' di convertire una stringa di data in formato 11 | 'struct tm' mediante strptime(), successivamente salvarla in un buffer con la 12 | funzione strftime() */ 13 | 14 | int main(void) { 15 | struct tm tm; 16 | char buf[LEN]; 17 | 18 | memset(&tm, 0, sizeof(struct tm)); 19 | 20 | strptime("2016-12-24 20:30:05", "%Y-%m-%d %H:%M:%S", &tm); 21 | strftime(buf, sizeof(buf), "%d/%b/%Y %H:%M", &tm); 22 | 23 | printf("%s\n", buf); 24 | 25 | exit(EXIT_SUCCESS); 26 | } 27 | -------------------------------------------------------------------------------- /src/Unix_Programming/Date_and_Time/time_to_bdt_1_gmtime.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | /* Lo scopo del programma e' di convertire una data da time_t a Broken-down 8 | time UTC mediante la funzione gmtime(). */ 9 | 10 | int main(void) { 11 | time_t t; 12 | struct tm *local_gm; 13 | 14 | if ((t = time(NULL)) < 0) { 15 | fprintf(stderr,"Err.(%s) getting time\n", strerror(errno)); 16 | exit(EXIT_FAILURE); 17 | } 18 | 19 | local_gm = gmtime(&t); 20 | 21 | printf("%d/%d/%d - %d:%d:%d\n", \ 22 | local_gm->tm_mon, \ 23 | local_gm->tm_mday, \ 24 | local_gm->tm_year + 1900,\ 25 | local_gm->tm_hour, \ 26 | local_gm->tm_min, \ 27 | local_gm->tm_sec); 28 | 29 | return(EXIT_SUCCESS); 30 | } 31 | -------------------------------------------------------------------------------- /src/Unix_Programming/Date_and_Time/time_to_bdt_2_localtime.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | /* Lo scopo del programma e' di convertire una variabile di tipo time_t 8 | in una stringa di tipo broken-down time, espressa mediante ora legale */ 9 | 10 | int main(void) { 11 | time_t t; 12 | struct tm *local_time; 13 | 14 | if ((t = time(NULL)) < 0) { 15 | fprintf(stderr,"Err.(%s) getting time\n", strerror(errno)); 16 | exit(EXIT_FAILURE); 17 | } 18 | 19 | local_time = localtime(&t); 20 | 21 | printf("%d/%d/%d - %d:%d:%d\n", \ 22 | local_time->tm_mon + 1, \ 23 | local_time->tm_mday, \ 24 | local_time->tm_year + 1900, \ 25 | local_time->tm_hour, \ 26 | local_time->tm_min, \ 27 | local_time->tm_sec); 28 | 29 | return(EXIT_SUCCESS); 30 | } 31 | -------------------------------------------------------------------------------- /src/Unix_Programming/Error_Handling/README.md: -------------------------------------------------------------------------------- 1 | The Unix systems don't provide an unique error handling: 2 | - of the system calls about 60% return -1 on an error; 3 | - about 20% returning NULL, zero, SIG_ERR or somethiong else; 4 | - about 20% don't report errors at all. 5 | -------------------------------------------------------------------------------- /src/Unix_Programming/Error_Handling/get_errno_macro.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* L'argomento fornito in input fornira' informazioni sulla macro associata 6 | alla variabile 'errno'. */ 7 | 8 | int main(int argc, char *argv[]) { 9 | 10 | if (argc < 2) 11 | fprintf(stderr, "Uso: %s \n", argv[0]); 12 | else { 13 | errno = strtol(argv[1], 0, 10); 14 | perror(argv[1]); // medesimo risultato con perror(""); 15 | } 16 | 17 | return(EXIT_SUCCESS); 18 | } 19 | -------------------------------------------------------------------------------- /src/Unix_Programming/Error_Handling/strerror.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include /* strerror() */ 5 | 6 | /* La funzione strerror() - char *strerror(int errnum); - ritorna un puntatore 7 | ad una stringa che descrive il codice di errore ottenuto dall'argomento 8 | 'errnum'. */ 9 | 10 | /* Lo scopo del programma e' il tentativo di aprire il file /etc/passwd in 11 | scrittura, che se eseguito come utente causera' un errore, tale errore sara' 12 | descritto dalla funzione strerror(). */ 13 | 14 | int main(void) { 15 | FILE *passdb; 16 | 17 | if ( (passdb = fopen("/etc/passwd", "w")) == NULL) { 18 | fprintf(stderr, "EACCES %d: %s\n", EACCES, strerror(EACCES)); 19 | exit(EXIT_FAILURE); 20 | } 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/Unix_Programming/File_System/11_read_dir_3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | /* Lo scopo del programma e' la lista di una directory */ 8 | 9 | int main(void) { 10 | DIR * dir; 11 | struct dirent * ent; 12 | 13 | /* "." e' la directory corrente */ 14 | if (!(dir = opendir("."))) { 15 | fprintf(stderr,"Err.(%s) opendir() failed\n", strerror(errno)); 16 | exit(EXIT_FAILURE); 17 | } 18 | 19 | errno = 0; 20 | while ((ent = readdir(dir))) { 21 | puts(ent->d_name); 22 | errno = 0; 23 | } 24 | 25 | if (errno) { 26 | fprintf(stderr,"Err.(%s) readdir() failed\n", strerror(errno)); 27 | exit(EXIT_FAILURE); 28 | } 29 | 30 | closedir(dir); 31 | 32 | return(EXIT_SUCCESS); 33 | } 34 | -------------------------------------------------------------------------------- /src/Unix_Programming/File_System/dirname_basename.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /* Lo scopo del programma e' di verificare il risultato delle chiamate alle 7 | funzioni dirname() e basename() */ 8 | 9 | int main(int argc, char *argv[]) { 10 | int i; 11 | 12 | if (argc != 2) { 13 | fprintf(stderr, "Usage: %s \n", argv[0]); 14 | fprintf(stderr, "dirname: [], basename: ()\n"); 15 | exit(EXIT_FAILURE); 16 | } 17 | 18 | for (i=1; i 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // Stampa l'ora di accesso del file ricevuto in argomento 8 | 9 | int main(int argc, char *argv[]) { 10 | struct stat stbuf; 11 | 12 | if (argc < 2) { 13 | fprintf(stderr, "Uso: %s \n", argv[0]); 14 | exit(EXIT_FAILURE); 15 | } 16 | 17 | if (stat(argv[1], &stbuf) == -1) { 18 | fprintf(stderr, "Err.: fsize %s\n", argv[1]); 19 | exit(EXIT_FAILURE); 20 | } 21 | 22 | printf(" Last status change: %s", ctime(&stbuf.st_ctime)); 23 | printf(" Last file access: %s", ctime(&stbuf.st_atime)); 24 | printf("Last file modification: %s", ctime(&stbuf.st_mtime)); 25 | 26 | exit(EXIT_SUCCESS); 27 | } 28 | -------------------------------------------------------------------------------- /src/Unix_Programming/File_System/full_programs/get_filesize.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main(int argc, char *argv[]){ 8 | struct stat infobuf; 9 | 10 | if (argc != 2) { 11 | fprintf(stderr, "Usage: %s \n", argv[0]); 12 | exit(EXIT_FAILURE); 13 | } 14 | 15 | if (stat(argv[1], &infobuf) == -1 ) { 16 | fprintf(stderr, "Err. stat(): %s\n", strerror(errno)); 17 | exit(EXIT_FAILURE); 18 | } else 19 | printf("The size of %s is %ld K\n", argv[1], infobuf.st_size ); 20 | 21 | return(EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /src/Unix_Programming/File_System/full_programs/get_filesize_POSIX_compilant.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | /* Lo scopo del programma e' di restituire la grandezza di un file regolare in 9 | modo sicuro. Soluzione POSIX compilant. */ 10 | 11 | int main(int argc, char *argv[]) { 12 | struct stat stbuf; 13 | size_t size; 14 | int fd; 15 | 16 | fd = open(argv[1], O_RDONLY); 17 | if (fd == -1) { 18 | fprintf(stderr, "Err. Can't open file: %s\n", strerror(errno)); 19 | exit(EXIT_FAILURE); 20 | } 21 | 22 | if ((fstat(fd, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode))) { 23 | fprintf(stderr, "Err. Can't fstat file: %s\n", strerror(errno)); 24 | exit(EXIT_FAILURE); 25 | } 26 | 27 | size = stbuf.st_size; 28 | 29 | printf("The \'%s\' size is: %i byte\n", argv[1], size); 30 | 31 | return(EXIT_SUCCESS); 32 | } 33 | -------------------------------------------------------------------------------- /src/Unix_Programming/IO_Buffering_and_Buffer_Cache/purge_buffer_with_fpurge.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /* Lo scopo del programma e' di scartare l'output pendente mediante 7 | l'utilizzo della funzione __fpurge(). 8 | 9 | La funzione __fpurge() non e' ne' standard ne' portabile, e' stata introdotta 10 | in Solaris, presente nella libreria glibc.*/ 11 | 12 | int main(void) { 13 | 14 | /* A differenza della funzione fflush() che forza la scrittura del buffer 15 | cache, la funzione __fpurge() pulisce il buffer dello stream fornito. 16 | 17 | Nel caso specifico sara' scartato tutto l'output non ancora scritto, per 18 | cui la funzione printf() non produrra' alcunche' */ 19 | 20 | printf("Get-up stand-up, stand-up for your rights, by: "); 21 | __fpurge(stdout); 22 | write(1, "Bob Marley.\n", 12); 23 | 24 | return(EXIT_SUCCESS); 25 | } 26 | -------------------------------------------------------------------------------- /src/Unix_Programming/IO_Standard_Library/02_rw_stream_2_fgets_fputs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_BUF 516 7 | 8 | int main(int argc, char *argv[]) { 9 | FILE *fp; 10 | char buf[MAX_BUF]; 11 | char *input_file = "/etc/group"; 12 | 13 | if ((fp = fopen(input_file, "r")) == NULL) { 14 | fprintf(stderr, "Err(%d) %s: %s\n", errno, strerror(errno), input_file); 15 | exit(EXIT_FAILURE); 16 | } 17 | 18 | /* Si provvede alla lettura del file input_file linea per linea */ 19 | while ((fgets(buf, MAX_BUF, fp)) != NULL) { 20 | if (fputs(buf, stdout) == EOF) { 21 | fprintf(stderr, "Err(%d) %s: fputs()\n", errno, strerror(errno)); 22 | exit(EXIT_FAILURE); 23 | } 24 | } 25 | 26 | fclose(fp); 27 | 28 | return(EXIT_SUCCESS); 29 | } 30 | -------------------------------------------------------------------------------- /src/Unix_Programming/IO_Standard_Library/02_rw_stream_5.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_BUF 4096 7 | 8 | int main(int argc, char *argv[]) { 9 | FILE *fp_in; 10 | int c; 11 | 12 | if (argc != 2) { 13 | fprintf(stderr, "Uso: %s \n", argv[0]); 14 | exit(EXIT_FAILURE); 15 | } 16 | 17 | if ((fp_in = fopen(argv[1], "r")) == NULL) { 18 | fprintf(stderr, "Err(%d) %s: %s\n", errno, strerror(errno), argv[1]); 19 | exit(EXIT_FAILURE); 20 | } 21 | 22 | while (!feof(fp_in)) { 23 | if ((c = fgetc(fp_in)) != EOF) 24 | fputc(c, stdout); 25 | } 26 | 27 | if (ferror(fp_in)) { 28 | fprintf(stderr, "Err(%d) %s: stream error\n", errno, strerror(errno)); 29 | exit(EXIT_FAILURE); 30 | } 31 | 32 | fclose(fp_in); 33 | 34 | return(EXIT_SUCCESS); 35 | } 36 | -------------------------------------------------------------------------------- /src/Unix_Programming/IO_Unbuffered/02_read_3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /* Lo scopo del programma e' la lettura di un file ricevuto in input, stampando 7 | un carattere alla volta sullo stream di output. */ 8 | 9 | int main(int argc, char *argv[]) { 10 | int fd; 11 | ssize_t n; 12 | char buf; 13 | 14 | if (argc < 2) { 15 | fprintf(stderr,"Uso: %s \n", argv[0]); 16 | exit(EXIT_FAILURE); 17 | } 18 | 19 | if ( (fd = open(argv[1], O_RDONLY)) < 0) { 20 | fprintf(stderr, "Err. open file\n"); 21 | exit(EXIT_FAILURE); 22 | } 23 | 24 | /* Lettura del file un carattere alla volta e stampa immediata in output 25 | del carattere stesso. */ 26 | while ((n = read(fd, &buf, 1)) > 0) 27 | write(STDOUT_FILENO, &buf, n); 28 | 29 | close(fd); 30 | 31 | return(EXIT_SUCCESS); 32 | } 33 | -------------------------------------------------------------------------------- /src/Unix_Programming/IO_Unbuffered/03_write.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main(void) { 8 | char buf[] = "Take a Walk on the Wild Side"; 9 | 10 | /* Stampare sullo stdout mediante la system call di basso livello write() 11 | risulta essere piu' efficiente rispetto alla funzione di libreria printf() 12 | */ 13 | 14 | write(STDOUT_FILENO, buf, sizeof(buf)); 15 | 16 | printf("\n"); 17 | 18 | /* Stampa sullo stdout mediante la verifica di un'espressione condizionale 19 | per constatare la correttezza del buffer stesso. */ 20 | if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1) 21 | fprintf(stderr, "%d: %s err.\n", errno, strerror(errno)); 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | -------------------------------------------------------------------------------- /src/Unix_Programming/IO_Unbuffered/full_programs/read_file.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | char c; 8 | 9 | /* 10 | * Come si puo' notare, il parametro della read() che prevede la lunghezza 11 | * del buffer è impostato ad 1, ciò vuol dire che la lettura dell'input sarà 12 | * carattere per carattere. 13 | * 14 | * Codice estremamente efficiente 15 | */ 16 | while (read(0, &c, 1) > 0) 17 | write(STDOUT_FILENO, &c, sizeof(c)); 18 | 19 | return(EXIT_SUCCESS); 20 | } 21 | -------------------------------------------------------------------------------- /src/Unix_Programming/IPC_InterProcess_Communication/pipe/02_popen_pclose_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_BUF 512 7 | 8 | /* Sara' eseguito mediante una pipe il comando fornito da 'cmd' e copiato sullo 9 | standard output. */ 10 | 11 | int main(int argc, char *argv[]) 12 | { 13 | char *cmd = "ps ajf"; 14 | char buf[MAX_BUF]; 15 | FILE *fpipe; 16 | 17 | if (!(fpipe = popen(cmd, "r"))) { 18 | fprintf(stderr, "Err.: %d popen() - %s\n", errno, strerror(errno)); 19 | return 13; 20 | } 21 | 22 | /* Legge l'output del comando fornito mediante la pipe */ 23 | while (fgets(buf, MAX_BUF, fpipe) != 0) 24 | fputs(buf, stdout); 25 | 26 | if (pclose(fpipe)) { 27 | fprintf(stderr, "Err.: %d - pclose() %s\n", errno, strerror(errno)); 28 | return(EXIT_SUCCESS); 29 | } 30 | 31 | return(EXIT_SUCCESS); 32 | } 33 | -------------------------------------------------------------------------------- /src/Unix_Programming/Link_Library/README.md: -------------------------------------------------------------------------------- 1 | ## Link Library 2 | 3 | A link library contains precompiled object code. During linking, the linker uses 4 | the link library to complete the linking process. In Linux, there are two kinds 5 | of link libraries: 6 | 7 | 1) [static link library](./static_library) (also know as `archives`) for static linking; 8 | 9 | 2) [shared link library](./shared_library) for dynamic linking. 10 | 11 | ### References 12 | 13 | * [Stevanovic 2014](../../../doc/biblio.md#headBB6) 14 | * [Kerrisk 2010](../../../doc/biblio.md#headBB1a) `chapters 41, 42` 15 | * [Drepper 2011](../../../doc/free_books.md#headFB3) 16 | -------------------------------------------------------------------------------- /src/Unix_Programming/Link_Library/shared_library/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | int n1 = mul(10, 20); 6 | int n2 = sum(10, 20); 7 | 8 | printf("%d, %d\n", n1, n2); 9 | 10 | return(EXIT_SUCCESS); 11 | } 12 | -------------------------------------------------------------------------------- /src/Unix_Programming/Link_Library/shared_library/mymath.c: -------------------------------------------------------------------------------- 1 | int mul(int x, int y) { 2 | return x * y; 3 | } 4 | 5 | int sum(int x, int y) { 6 | return x + y; 7 | } 8 | -------------------------------------------------------------------------------- /src/Unix_Programming/Link_Library/static_library/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | int n1 = mul(10, 20); 6 | int n2 = sum(10, 20); 7 | 8 | printf("%d, %d\n", n1, n2); 9 | 10 | return(EXIT_SUCCESS); 11 | } 12 | -------------------------------------------------------------------------------- /src/Unix_Programming/Link_Library/static_library/mymath.c: -------------------------------------------------------------------------------- 1 | int mul(int x, int y) { 2 | return x * y; 3 | } 4 | 5 | int sum(int x, int y) { 6 | return x + y; 7 | } 8 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/README.md: -------------------------------------------------------------------------------- 1 | ### How to compile program 2 | 3 | With `MAP_ANON` and many other flags (*man mmap*) will be necessary `_GNU_SOURCE` 4 | (*feature test macros*) to compile the program: 5 | 6 | $ `gcc -std=c11 -Wall -pedantic -D_GNU_SOURCE prog.c` 7 | 8 | $ `clang -std=c11 -Wall -pedantic -D_GNU_SOURCE prog.c` 9 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/glibc_malloc_debugging_monitoring/README.md: -------------------------------------------------------------------------------- 1 | ## The GNU C Library 2 | 3 | The functions covered in this section are GNU extension (glibc), 4 | the interface offered by these vary across implementations, so they are not 5 | portable. 6 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/glibc_malloc_debugging_monitoring/malloc_stats.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(void) { 7 | char text[] = "The art of Unix Programming"; 8 | char *str = malloc(strlen(text)); 9 | 10 | malloc_stats(); 11 | 12 | return(EXIT_SUCCESS); 13 | } 14 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/README.md: -------------------------------------------------------------------------------- 1 | ## Malloc implementations 2 | 3 | The purpose of these alternative implementations is to understand how malloc() 4 | works in deep. 5 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/dummy_malloc/basic_malloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // sbrk() 4 | #include 5 | #include 6 | #include 7 | #include "basic_malloc.h" 8 | 9 | /* my malloc (a) 10 | utilizza la syscall sbrk() per la manipolazione dello heap; sbrk(0) ritorna un 11 | puntatore a 'break', ovvero in cima allo heap, sbrk(n) incrementa lo heap di 12 | 'n' byte e ritorna un puntatore al nuovo indirizzo. In caso di fallimento 13 | riorna (void *)-1, con il settaggio appropriato della variabile 'errno'. */ 14 | 15 | void *basic_malloc(size_t size) { 16 | void *ptr = sbrk(0); 17 | void *increment = sbrk(size); 18 | 19 | if (increment == (void *) - 1) { 20 | fprintf(stderr, "Err.(%d) sbrk(): %s\n", errno, strerror(errno)); 21 | exit(EXIT_FAILURE); 22 | } else { 23 | assert (ptr == increment); 24 | return ptr; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/dummy_malloc/basic_malloc.h: -------------------------------------------------------------------------------- 1 | #ifndef BASIC_MALLOC 2 | #define BASIC_MALLOC 3 | 4 | #include 5 | 6 | void *basic_malloc(size_t size); 7 | 8 | #endif 9 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/dummy_malloc/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "basic_malloc.h" 5 | 6 | int main(void) { 7 | const char *title = "The Unix Programming Environment"; 8 | const unsigned int size = strlen(title); 9 | char *ptr; 10 | 11 | // basic_malloc() testing function 12 | // Alloca 'size' byte sullo heap, dopodiche' copia e stampa la stringa 13 | ptr = basic_malloc(size); 14 | strcpy(ptr, title); 15 | printf("%s\n", ptr); 16 | 17 | /* Con la prima funzione per l'allocazione della memoria basic_malloc(), 18 | non puo' essere invocata free() per liberare la memoria, per cui si 19 | utilizza' un semplice puntatore a NULL, che peraltro dovrebbe essere una 20 | buona regola dopo la deallocazione della memoria. */ 21 | ptr = NULL; 22 | 23 | return(EXIT_SUCCESS); 24 | } 25 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/dummy_malloc/makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -pedantic -Wall -std=c11 -D_BSD_SOURCE -g 3 | TARGET = mallocs.out 4 | 5 | OBJS = main.o basic_malloc.o 6 | 7 | $(TARGET): $(OBJS) 8 | @echo "linking ... $(TARGET)" 9 | @$(CC) $^ -o $@ 10 | 11 | relink: 12 | @echo "relinking ... $(TARGET)" 13 | @$(CC) $(CFLAGS) -o $(TARGET) $(OBJS) $(LIBS) 14 | 15 | clean: 16 | rm -rf $(OBJS) $(TARGET) 17 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/malloc_one/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "malloc_one.h" 5 | 6 | int main(void) { 7 | const char *title = "The Unix Programming Environment"; 8 | const unsigned int size = strlen(title); 9 | 10 | // malloc_one() testing function 11 | //void *ptr = (char *)malloc_one(size); 12 | //strncpy(ptr, title, strlen(title)+1); 13 | 14 | //printf("%s\n", ptr); 15 | 16 | return(EXIT_SUCCESS); 17 | } 18 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/malloc_one/makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -pedantic -Wall -std=c11 -D_BSD_SOURCE -g 3 | TARGET = mallocs.out 4 | 5 | OBJS = main.o malloc_one.o 6 | 7 | $(TARGET): $(OBJS) 8 | @echo "linking ... $(TARGET)" 9 | @$(CC) $^ -o $@ 10 | 11 | relink: 12 | @echo "relinking ... $(TARGET)" 13 | @$(CC) $(CFLAGS) -o $(TARGET) $(OBJS) $(LIBS) 14 | 15 | clean: 16 | rm -rf $(OBJS) $(TARGET) 17 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/malloc_one/malloc_one.h: -------------------------------------------------------------------------------- 1 | #ifndef MALLOC_ONE_H 2 | #define MALLOC_ONE_H 3 | 4 | #include 5 | 6 | struct memory_block { 7 | int free; 8 | size_t size; 9 | }; 10 | 11 | // Prototipi 12 | void init_alloc(void); 13 | void free_mem(void *first_byte); 14 | void malloc_one(size_t size); 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/malloc_two/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "malloc_two.h" 5 | 6 | int main(void) { 7 | const char *title = "The Unix Programming Environment"; 8 | const unsigned int size = strlen(title); 9 | 10 | // xmalloc() testing function 11 | char *ptr; 12 | ptr = malloc_two(size); 13 | strncpy(ptr, title, strlen(title)+1); 14 | printf("%s\n", ptr); 15 | free_two(ptr); 16 | 17 | return(EXIT_SUCCESS); 18 | } 19 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/malloc_two/makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -pedantic -Wall -std=c11 -D_BSD_SOURCE -g 3 | TARGET = mallocs.out 4 | 5 | OBJS = main.o malloc_two.o 6 | 7 | $(TARGET): $(OBJS) 8 | @echo "linking ... $(TARGET)" 9 | @$(CC) $^ -o $@ 10 | 11 | relink: 12 | @echo "relinking ... $(TARGET)" 13 | @$(CC) $(CFLAGS) -o $(TARGET) $(OBJS) $(LIBS) 14 | 15 | clean: 16 | rm -rf $(OBJS) $(TARGET) 17 | -------------------------------------------------------------------------------- /src/Unix_Programming/Memory_Allocation/malloc_implementations/malloc_two/malloc_two.h: -------------------------------------------------------------------------------- 1 | #ifndef MALLOC_TWO_H 2 | #define MALLOC_TWO_H 3 | 4 | #include 5 | 6 | #define META_BLOCK_SIZE sizeof(struct mem_block) 7 | 8 | typedef struct mem_block *t_mem_block; 9 | 10 | struct mem_block { 11 | size_t size; 12 | t_mem_block next; 13 | int free; 14 | }; 15 | 16 | // Prototipi 17 | t_mem_block find_block(t_mem_block *last, size_t size); 18 | t_mem_block request_heap(t_mem_block last, size_t size); 19 | void *malloc_two(size_t size); 20 | void free_two(void *ptr); 21 | t_mem_block get_ptr_block(void *ptr); 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /src/Unix_Programming/Process_Control/memory_layout_addresses.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Su diverse implementazioni UNIX l'ambiente di programmazione C fornisce 5 | alcune variabili globali per ottenere l'indirizzo del successivo byte di 6 | specifici segmenti del layout della memoria di un processo. Essi sono: 7 | - etext, la fine del segmento 'text'; 8 | - edata, la fine del segmento 'data' (dati inizializzati); 9 | - end, la fine del segmento 'bss' (dati non inizializzati). 10 | */ 11 | 12 | extern char etext, edata, end; 13 | 14 | int main(void) { 15 | 16 | puts("Print the next byte past of some Segment Adresses"); 17 | 18 | printf(" \'program text\' (etest): %10p\n", (void*)&etext); 19 | printf(" \'initialized data\' (edata): %10p\n", (void*)&edata); 20 | printf("\'uninitialized data, bss\' (end): %10p\n", (void*)&end); 21 | 22 | return(EXIT_SUCCESS); 23 | } 24 | -------------------------------------------------------------------------------- /src/Unix_Programming/README.md: -------------------------------------------------------------------------------- 1 | ## The Art of Writing (C)ode in the UNIX Environment 2 | 3 | The purpose of this project is to create a repository with a lot of source 4 | code well documented, it is totally focused on the beautiful art of writing 5 | UNIX programs in C, c11 mainly. 6 | 7 | ### How to compile programs 8 | 9 | `$gcc -std=c11 -Wall -pedantic source.c` 10 | `$clang -std=c11 -Wall -pedantic source.c` 11 | 12 | Sometimes we need a macro like _BSD_SOURCE or _GNU_SOURCE to compile. 13 | 14 | A list of compilers and Unix-like Operating systems used: 15 | 16 | * OpenBSD (-current) on PowerPC Architecture (32 bit, big-endian) 17 | * gcc 4.2.1 18 | 19 | * Debian GNU/Linux (testing) (64 bit, little endian) 20 | * gcc (Debian 6.3.0-12) 6.3.0 21 | * clang version 3.8.1-18 22 | 23 | * OpenBSD (-current) (64 bit, little endian) 24 | * gcc 4.2.1 25 | * clang 26 | -------------------------------------------------------------------------------- /src/Unix_Programming/Standardization_and_System_Limits/get_libc_version.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* La libreria in questione, se trovata, fornira' la 6 | versione della librera GNU C. 7 | 8 | Nel caso specifico e' stata utilizzata una macchina con 9 | processore PPC, come si evince chiaramante dal path. */ 10 | 11 | int main(void) { 12 | const char *version = gnu_get_libc_version(); 13 | 14 | printf("%s\n", version); 15 | 16 | return(EXIT_SUCCESS); 17 | } 18 | -------------------------------------------------------------------------------- /src/Unix_Programming/Standardization_and_System_Limits/get_libc_version_with_confstr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main(int argc, char *argv[]) { 8 | char *buf; 9 | size_t n; 10 | 11 | n = confstr(_CS_GNU_LIBC_VERSION, NULL, (size_t) 0); 12 | 13 | buf = malloc(n); 14 | 15 | confstr(_CS_GNU_LIBC_VERSION, buf, n); 16 | printf("%s\n", buf); 17 | 18 | return(EXIT_SUCCESS); 19 | } 20 | -------------------------------------------------------------------------------- /src/Unix_Programming/Terminal_IO/ioctl_eject_cdrom.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | int main(int argc, char *argv[]) { 9 | int fd = open(argv[1], O_RDONLY); 10 | 11 | // Eject CDROM 12 | ioctl(fd, CDROMEJECT); 13 | 14 | close(fd); 15 | return(EXIT_SUCCESS); 16 | } 17 | -------------------------------------------------------------------------------- /src/Unix_Programming/Users_and_Groups/full_programs/user_and_group_conversions/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "user_group_conversions.h" 5 | 6 | int main(void) { 7 | uid_t uid = getuid(); 8 | char *my_user_name = username_from_userid(uid); 9 | uid_t my_uid = userid_from_username(my_user_name); 10 | char *my_group_name = groupname_from_groupid(111); 11 | gid_t my_gid = groupid_from_groupname(my_group_name); 12 | 13 | printf("My user name is: %s\n", my_user_name); 14 | printf("My user ID is: %d\n", my_uid); 15 | printf("My group name is: %s\n", my_group_name); 16 | printf("My group ID is: %d\n", my_gid); 17 | 18 | return(EXIT_SUCCESS); 19 | } 20 | -------------------------------------------------------------------------------- /src/Unix_Programming/Users_and_Groups/full_programs/user_and_group_conversions/makefile: -------------------------------------------------------------------------------- 1 | CC = cc 2 | CFLAGS = -pedantic -Wall -std=c11 3 | TARGET = conversions 4 | SOURCE = *.c 5 | OBJS = main.o user_group_conversions.o 6 | 7 | $(TARGET): $(OBJS) 8 | @$(CC) $^ -o $@ 9 | @echo Executable: $(TARGET) 10 | 11 | $(OBJS): user_group_conversions.h 12 | $(CC) $(CFLAGS) $(INCLS) -c $(SOURCE) 13 | 14 | clean: 15 | rm -rf $(OBJS) $(TARGET) 16 | -------------------------------------------------------------------------------- /src/Unix_Programming/Users_and_Groups/full_programs/user_and_group_conversions/user_group_conversions.h: -------------------------------------------------------------------------------- 1 | #ifndef USER_GROUP_CONVERSIONS 2 | #define USER_GROUP_CONVERSIONS 3 | 4 | #include 5 | 6 | char *username_from_userid(uid_t uid); 7 | uid_t userid_from_username(const char *username); 8 | char *groupname_from_groupid(gid_t gid); 9 | gid_t groupid_from_groupname(const char *groupname); 10 | 11 | #endif 12 | --------------------------------------------------------------------------------