language
large_string
text
string
C
#ifndef _PLUGIN_API_H #define _PLUGIN_API_H #include <stdio.h> #include <getopt.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <regex.h> #define PATTERN "^[0-9]{0,3}.[0-9]{0,3}.[0-9]{0,3}.[0-9]{0,3}$" /* Структура, описывающая опцию, поддерживаемую плагином. */ struct plugin_option { /* Опция в формате, поддерживаемом getopt_long (man 3 getopt_long). */ struct option opt; /* Описание опции, которое предоставляет плагин. */ const char *opt_descr; }; /* Структура, содержащая информацию о плагине. */ struct plugin_info { /* Название плагина */ const char *plugin_name; /* Длина списка опций */ size_t sup_opts_len; /* Список опций, поддерживаемых плагином */ struct plugin_option *sup_opts; }; /* Функция, позволяющая получить информацию о плагине. Аргументы: ppi - адрес структуры, которую заполняет информацией плагин. Возвращаемое значение: 0 - в случае успеха, 1 - в случае неудачи (в этом случае продолжать работу с этим плагином нельзя). */ int plugin_get_info(struct plugin_info* ppi) { if (ppi == NULL) { return 1; } ppi->plugin_name = "ipv4"; ppi->sup_opts_len = 1; struct plugin_option *ip_option = malloc(sizeof(struct plugin_option) * ppi->sup_opts_len); ip_option->opt_descr = "Searches ip address"; struct option *ip_opt = malloc(sizeof(struct option)); ip_opt->name = "ipv4-addr"; ip_opt->has_arg = required_argument; ip_opt->flag = NULL; ip_opt->val = 0; ip_option->opt = *ip_opt; //ppi->sup_opts = ip_option; ppi->sup_opts = malloc(sizeof(struct plugin_option)); ppi->sup_opts->opt.name = "ipv4-addr"; ppi->sup_opts->opt.has_arg = required_argument; ppi->sup_opts->opt.flag = NULL; ppi->sup_opts->opt.val = 0; return 0; }; /* Фунция, позволяющая выяснить, отвечает ли файл заданным критериям. Аргументы: in_opts - список опций (критериев поиска), которые передаются плагину. struct option { const char *name; int has_arg; int *flag; int val; }; Поле name используется для передачи имени опции, поле flag - для передачи значения опции (в виде строки). Если у опции есть аргумент, поле has_arg устанавливается в ненулевое значение. in_opts_len - длина списка опций. out_buff - буфер, предназначенный для возврата данных от плагина. В случае ошибки в этот буфер, если в данном параметре передано ненулевое значение, копируется сообщение об ошибке. out_buff_len - размер буфера. Если размера буфера оказалось недостаточно, функция завершается с ошибкой. Возвращаемое значение: 0 - файл отвечает заданным критериям, > 0 - файл НЕ отвечает заданным критериям, < 0 - в процессе работы возникла ошибка (код ошибки). */ int plugin_process_file(const char *fname, struct option *in_opts[], size_t in_opts_len, char *out_buff, size_t out_buff_len) { FILE *current_file; //printf("-- %s\n", fname); if (strstr(fname, "share") != NULL) { return 10; } //printf(" %s\n", fname); //printf("11++\n"); current_file = fopen(fname, "r"); //printf("11++\n"); //printf("--- %p\n", current_file); //printf("11++\n"); if (current_file == NULL) { fclose(current_file); return -1; } //printf ("--%s\n", fname); //printf("%s\n", in_opts[0]->flag); if (in_opts[0]->flag == NULL) { printf("Error: missing argument\n"); fclose(current_file); return -1; } char *ip1 = (char *) in_opts[0]->flag; //printf("%s\n", ip1); //mstrcpy(ip, regex_t preg; int err,regerr; err = regcomp (&preg, PATTERN, REG_EXTENDED); if (err != 0) { char buff[512]; regerror(err, &preg, buff, sizeof(buff)); printf("%s\n", buff); } regmatch_t pm; regerr = regexec (&preg, ip1, 0, &pm, 0); if (regerr == 0) { //printf("true\n"); } else { //printf("false\n"); char errbuf[512]; regerror(regerr, &preg, errbuf, sizeof(errbuf)); //printf("%s\n", errbuf); printf("Error: invalid syntax of IP address\n"); strcpy(out_buff, "invalid syntax"); //out_buff = "invalid syntax"; return -1; } char *s; s = malloc(sizeof(char) * 255); if (s == NULL) { return 10; } if (strlen(s) > 255) { return 10; } //printf("--\n"); //printf("%s\n", fname); int i = 0; while (feof(current_file) == 0) { i++; if (i > 400) { fclose(current_file); return -1; } //printf("%s\n", fname); //printf("--\n"); int yy; //printf("-->\n"); yy = fscanf(current_file, "%s", s); //printf("-->\n"); //printf("== %p\n", s); if (yy == 0) { return 10; } if (strlen(s) > 255) { return 10; } if (s == NULL) { return 0; } //printf("%s\n", s); //printf("-- %s\n", s); if (strstr(s, ip1) != NULL) { fclose(current_file); return 0; } } fclose(current_file); return 10; }; #endif
C
/* * double_linked_list.c * * Created on: 19 Nov 2019 * Author: billy */ #include "double_linked_list.h" #include "streams.h" DoubleListNode *AllocateDoubleListNode (const double64 value) { DoubleListNode *node_p = (DoubleListNode *) AllocMemory (sizeof (DoubleListNode)); if (node_p) { InitListItem (& (node_p -> dln_node)); node_p -> dln_value = value; } return node_p; } void FreeDoubleListNode (ListItem * const node_p) { DoubleListNode *double_node_p = (DoubleListNode *) node_p; FreeMemory (double_node_p); } LinkedList *AllocateDoubleLinkedList (void) { return AllocateLinkedList (FreeDoubleListNode); } bool AddDoubleegerToDoubleLinkedList (LinkedList *list_p, const double64 value) { bool success_flag = false; DoubleListNode *node_p = AllocateDoubleListNode (value); if (node_p) { LinkedListAddTail (list_p, & (node_p -> dln_node)); success_flag = true; } return success_flag; }
C
#include <stdarg.h> // varargs.h has been deprecated #include <stdio.h> // https://en.wikipedia.org/wiki/Variadic_function // passing number of variable arguments 'count' is possible idiom // but not at all enforced by the language double average(int count, ...) { va_list ap; // variable arguments list int j; double sum = 0; // initialize variable arguments list va_start(ap, count); // Requires the last parameter before ellipsis '...' for (j = 0; j < count; j++) { // scan variable arguments list sum += va_arg(ap, int); /* Increments ap to the next argument. */ } // clean up va_end(ap); return sum / count; } int main(int argc, char const *argv[]) { printf("average(1, 2, 3) = %f\n", average(3, 1, 2, 3) ); printf("average(1, 2, 3, 4, 0) = %f\n", average(5, 1, 2, 3, 4, 0) ); return 0; }
C
/* * Jacopo Del Granchio * #047 26.11.2019 * * Figura composta. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <locale.h> #include <stdarg.h> // Prototipi void chiedi(char *, char *, ...); // Funzioni int main() { setlocale(LC_ALL, ""); float a, b, r; chiedi("Inserisci la base del rettangolo: ", "%f", &a); chiedi("Inserisci l'altezza del rettangolo: ", "%f", &b); chiedi("Inserisci il raggio del cerchio: ", "%f", &r); printf("L'area totale è %.2f\n", a * b + 3.14 * r * r); // getchar(); // system("pause"); return 0; } void chiedi(char *msg, char *format, ...) { printf(msg); va_list list; va_start(list, format); vscanf(format, list); va_end(list); }
C
/** \file \brief Declaration of external system states. \details This files contain extern declaration and definition of static state structs for all external states. External states mean that these states might be requested from the system. Consequently, if any states are to be output from the system, they should be added here. The file also contain an initialization function to fill up some arrays of states structs. This initialization function must be called before the arrays are used. This should eventually be replaced by some code generating script which explicitly declear the arrays. \authors John-Olof Nilsson, Isaac Skog \copyright Copyright (c) 2011 OpenShoe, ISC License (open source) */ /** \addtogroup control_tables @{ */ #include "control_tables.h" ///\cond // IMU measurements extern vec3 accelerations_in; extern vec3 angular_rates_in; extern vec3 imu_temperaturs; extern precision imu_supply_voltage; // Filtering states extern vec3 position; extern vec3 velocity; extern quat_vec quaternions; extern bool zupt; // System states extern uint32_t interrupt_counter; // "Other" states extern vec3 accelerometer_biases; ///\endcond /// \name External state information /// Structs containing information and pointers to the externally accessible system states. //@{ static state_t_info specific_force_sti = {SPECIFIC_FORCE_SID, (void*) accelerations_in, sizeof(vec3)}; static state_t_info angular_rate_sti = {ANGULAR_RATE_SID, (void*) angular_rates_in, sizeof(vec3)}; static state_t_info imu_temperaturs_sti = {IMU_TEMPERATURS_SID, (void*) imu_temperaturs, sizeof(vec3)}; static state_t_info imu_supply_voltage_sti = {IMU_SUPPLY_VOLTAGE_SID, (void*) &imu_supply_voltage, sizeof(precision)}; static state_t_info position_sti = {POSITION_SID, (void*) position, sizeof(vec3)}; static state_t_info velocity_sti = {VELOCITY_SID, (void*) velocity, sizeof(vec3)}; static state_t_info quaternions_sti = {QUATERNION_SID, (void*) quaternions, sizeof(quat_vec)}; static state_t_info zupt_sti = {ZUPT_SID, (void*) &zupt, sizeof(bool)}; static state_t_info interrupt_counter_sti = {INTERRUPT_COUNTER_SID, (void*) &interrupt_counter, sizeof(uint32_t)}; static state_t_info accelerometer_biases_sti = {ACCELEROMETER_BIASES_SID, (void*) &accelerometer_biases, sizeof(vec3)}; //@} // Array of state data type struct pointers const static state_t_info* state_struct_array[] = {&interrupt_counter_sti, &specific_force_sti, &angular_rate_sti, &imu_temperaturs_sti, &imu_supply_voltage_sti, &position_sti, &velocity_sti, &quaternions_sti, &zupt_sti, &accelerometer_biases_sti}; state_t_info* state_info_access_by_id[SID_LIMIT]; void system_states_init(void){ for(int i = 0;i<(sizeof(state_struct_array)/sizeof(state_struct_array[0])); i++){ state_info_access_by_id[state_struct_array[i]->id] = state_struct_array[i];} } //@}
C
/** * crypter.h * * Author : Ourdia Oualiken and Jérémy LAMBERT * Date : 08/11/2017 * Description : functions needed for encryption / decryption */ #ifndef CRYPTER_H_ #define CRYPTER_H_ typedef struct message { int length; unsigned char* array; } message_t; /** * Returns the value of the nth bit of the given char * @param char num * @param int bit , the bit index */ char get_bit(char num, int bit); /** * Operates a single bit operation in the matrix multiplication */ unsigned char bit_add(int index, unsigned char message); /** * Splits the message into the correct amount of values for encryption. Returns 0 if the split failed. * @param size_t key_length * @param unsigned char * message , the message matrix * @param size_t message_length * @param unsigned char * result , pointer to the result matrix (should already be allocated) * @return 1 if success, 0 if fail */ int split_message(size_t key_length, unsigned char * message, size_t message_length, unsigned char * result); /** * Multiply the matrix message by the matrix key and fills the matrix result with the result. Returns -1 if the multiplication is impossible. * @param unsigned char * key , the matrix key * @param size_t key_length * @param unsigned char message * @return the result, -1 if fail */ unsigned char multiply_matrix(unsigned char message); /** * Encrypts the matrix message by the matrix key and fills the matrix result with the result. Return 0 if the encryption failed. * @param unsigned char * message , the message matrix * @param size_t message_length * @param message_t * res , the result message */ void encrypt(unsigned char * message, size_t message_length, message_t * res); /** * Decrypts the matrix message by the matrix key and fills the matrix result with the result. Return 0 if the decryption failed. * @param unsigned char * message , the message matrix * @param size_t message_length * @param message_t * res , the result message */ void decrypt(unsigned char * message, size_t message_length, message_t * res); /** * Sorts the given key. Returns 1 if it's a success, 0 if the key is invalid. * @param unsigned char* key * @return 1 if it's a success, 0 if the key is invalid. */ int sort_key(unsigned char* key); /** * Finds the column which is supposed to be at the j index in an ordered key matrix. * @param unsigned char* key * @param int j * @return int index */ int find_col(unsigned char* key, int j); /** * Swaps two columns of the matrix key. * @param unsigned char * key * @param int col1 * @param int col2 */ void swap_col(unsigned char * key, int col1, int col2); #endif /* CRYPTER_H_ */
C
/*! * @file main.c * @brief Hall Current 16 Click example * * # Description * This example demonstrates the use of Hall Current 16 click board * by reading and displaying the current measurements. * * The demo application is composed of two sections : * * ## Application Init * The initialization of SPI module and log UART. * After driver initialization, the app sets the default configuration. * * ## Application Task * The app reads the current measurements [A] and displays the results. * Results are being sent to the UART Terminal, where you can track their changes. * * @author Nenad Filipovic * */ #include "board.h" #include "log.h" #include "hallcurrent16.h" static hallcurrent16_t hallcurrent16; static log_t logger; void application_init ( void ) { log_cfg_t log_cfg; /**< Logger config object. */ hallcurrent16_cfg_t hallcurrent16_cfg; /**< Click config object. */ /** * Logger initialization. * Default baud rate: 115200 * Default log level: LOG_LEVEL_DEBUG * @note If USB_UART_RX and USB_UART_TX * are defined as HAL_PIN_NC, you will * need to define them manually for log to work. * See @b LOG_MAP_USB_UART macro definition for detailed explanation. */ LOG_MAP_USB_UART( log_cfg ); log_init( &logger, &log_cfg ); log_info( &logger, " Application Init " ); // Click initialization. hallcurrent16_cfg_setup( &hallcurrent16_cfg ); HALLCURRENT16_MAP_MIKROBUS( hallcurrent16_cfg, MIKROBUS_1 ); if ( SPI_MASTER_ERROR == hallcurrent16_init( &hallcurrent16, &hallcurrent16_cfg ) ) { log_error( &logger, " Communication init." ); for ( ; ; ); } Delay_ms ( 100 ); if ( HALLCURRENT16_ERROR == hallcurrent16_default_cfg ( &hallcurrent16 ) ) { log_error( &logger, " Default configuration." ); for ( ; ; ); } log_info( &logger, " Application Task " ); log_printf( &logger, " -------------------- \r\n" ); Delay_ms ( 100 ); } void application_task ( void ) { static float current = 0.0; if ( HALLCURRENT16_OK == hallcurrent16_get_current( &hallcurrent16, &current ) ) { log_printf( &logger, " Current : %.3f A \r\n", current ); } log_printf( &logger, " -------------------- \r\n" ); Delay_ms( 1000 ); } void main ( void ) { application_init( ); for ( ; ; ) { application_task( ); } } // ------------------------------------------------------------------------ END
C
/* server setup */ #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include <arpa/inet.h> #include<stdlib.h> #include<netdb.h> #include<string.h> #include"cserver.h" struct SPeer { char PID[2]; char PADDRESS[20]; char PNUM[7]; }peers[10]; static int peerCount = 0; int main(int argc, char *argv[]) { for(LoopI=0;LoopI<10;LoopI++) memset(peers[LoopI].PID,'\0',2); if ((serverFD = socket(AF_INET, SOCK_STREAM, 0))< 0) perror("Fail to open socket"); bzero((char *) &serverAddr, sizeof(serverAddr)); portNum = 9999; serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_port = htons(portNum); if (bind(serverFD, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) perror("Fail to bind"); listen(serverFD,10); Length = sizeof(clientAddr); puts("Trying to connect with peers ...."); while(1) { FD_ZERO(&readfds); FD_SET(serverFD, &readfds); IsActive = select( 10 , &readfds , NULL , NULL , NULL); if(IsActive < 0) printf("Error in Activity"); if (FD_ISSET(serverFD, &readfds)) { if ((sockFD = accept(serverFD, (struct sockaddr *) &clientAddr, &Length)) < 0) perror("Fail to accept"); bzero(Message,500); read(sockFD, Message, 500); strtok_r(Message, ";", &breakage); // breakage has remaining Message values in it i.e Message's right puts("Requested Peer Added to Network"); strcpy(peers[peerCount].PID,breakage); strcpy(peers[peerCount].PNUM,Message); copy = (char *)inet_ntoa(clientAddr.sin_addr); strcpy(peers[peerCount].PADDRESS, copy); if(peerCount == 0) { bzero(Message,500); strcpy(Message,"Connected to N/w"); write(sockFD, Message, 30); } else { bzero(Message, 500); Rand_var = random()%10; // Select clients from server in random way. while (peers[Rand_var].PID[0] == '\0' || Rand_var == peerCount) Rand_var = random()%10; strcpy(Message, "0");strcat(Message, ",");strcat(Message, peers[Rand_var].PID); strcat(Message, ",");strcat(Message, peers[Rand_var].PNUM); strcat(Message, ",");strcat(Message, peers[Rand_var].PADDRESS); write(sockFD, Message, 500); } peerCount++; } } }
C
/* ============================================================================ Name : tp_2.c Author : Bianca Gimenez Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> #include "input.h" #include "empleado.h" #define TAM 1000 #define MAX 10 #define TAMHARD 50 #define TAMSEC 6 #define LIBRE 0 #define OCUPADO 1 int main(void) { int opcion; //int flag = 0; int indice; int idAuto = 105;//---AUTO INCREMENTAL ID int auxID; int ordenElegido; float salarioTotal = 0; float salarioPromedio = 0; char respuesta = 's'; Employee listaEmpleados[TAM]; Sector sectores[TAMSEC] = { {1, "Recursos Humanos"}, {2, "Administracion"}, {3, "Sistemas"}, {4, "Comunicacion"}, {5, "Contable"}, {6, "Informes"}, }; if(initEmployees(listaEmpleados, TAM) == 0){ printf("La lista se inicializo Corecctamente\n"); }else{ printf("Ocurrio un error al Inicializar la lista\n"); } HardcodearEmpleados(listaEmpleados, TAMHARD); idAuto+= TAMHARD; do{ cartel(); utn_pedirNumero(&opcion, "Ingrese una opcion ", "opcion Invalida", 1, 5); switch(opcion){ case 1: cargarEmpleado(listaEmpleados, TAM, &idAuto); break; case 2: mostrarListaEmpleados(listaEmpleados, TAM, sectores, TAMSEC); if(utn_pedirNumero(&auxID,"\nIngrese ID del Empleado que desea modificar: \n","\nID invalido",0,1000) == 0) { indice = buscarIDempleado(listaEmpleados, TAM, auxID); if( indice >= 0 && modificarEmpleado(listaEmpleados, TAM, indice)== 0) { printf("\nModificacion exitosa\n"); break; } else { printf("No se pudo realizar la Modificacion\n"); } } break; case 3: mostrarListaEmpleados(listaEmpleados, TAM, sectores, TAMSEC); if(utn_pedirNumero(&auxID,"\nIngrese ID del Empreado a Eliminar \n","\nID invalido",0,1000) == 0){ indice = buscarIDempleado(listaEmpleados, TAM, auxID); if(indice >= 0 && removeEmployee(listaEmpleados, TAM, sectores, indice)== 0){ printf("\nBaja realizada con exito\n"); } } break; case 4: menuInfo(); utn_pedirNumero(&ordenElegido, "Ingrese una opcion", "Error,opcion incorrecta", 1, 5); if (ordenElegido == 1){ // Descenddientee ordenarPorNombre(listaEmpleados,TAM,ordenElegido); mostrarListaEmpleados(listaEmpleados, TAM, sectores, TAMSEC); } else if (ordenElegido == 2){ // Ascendenteee ordenarPorNombre(listaEmpleados,TAM,ordenElegido); mostrarListaEmpleados(listaEmpleados, TAM, sectores, TAMSEC); } else if (ordenElegido == 3){ salarioPromedioTotal(&salarioTotal, &salarioPromedio,listaEmpleados,TAM); } else if (ordenElegido == 4){ if (&salarioPromedio >=0){ saberSuledoMasAlto(&salarioPromedio, listaEmpleados,TAM ,sectores, TAMSEC); } else{ printf("\nNecesitas calcular el salario promedio primero.\n"); } } break; case 5: respuesta = 'n'; } }while(respuesta == 's'); return EXIT_SUCCESS; }
C
/** * Because of stupid trimpots */ #include <avr/io.h> #include <avr/sleep.h> #include <avr/interrupt.h> #include <util/delay.h> #include "../iocompat.h" // Frequency adjustment, results in ~25kHz PWM. #define FREQ_ADJ 160 #define PWM_MAX 0.9*FREQ_ADJ // Max PWM (of 255) allowed for fan = 90% #define PWM_MIN 0.1*FREQ_ADJ // And min // Restrict (clamp) value #define CLAMP(val,max,min) ((val<min)? min : (val>max)? max : val) void init() { // Setup PWM with non-prescaled clock source // TCCR1A = TIMER1_PWM_INIT; // Enables OCR1A TCCR1B |= _BV(CS11); GTCCR = _BV(PWM1B) | _BV(COM1B1); // Enables OCR1B // Set PWM duty cycle to 50% OCR1B = TIMER1_TOP / 2; // Set PWM frequency (kinda) OCR1C = FREQ_ADJ; // Enable PWM output DDROC = _BV(PB4); // Enable ADC pin pullup resistor PORTB = _BV(3); // Enable ADC ADCSRA = _BV(ADEN); // Initialise (take first reading) ADCSRA |= _BV(ADSC); // Enable free running mode ADCSRA |= _BV(ADATE); // x128 Prescaler for ADC clock ADCSRA |= _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0); // Select correct ADC input ADMUX = _BV(MUX0) | _BV(MUX1); } int main(int argc, char const *argv[]) { uint16_t voltage; init(); // Update speed every second. // Yes this could be done better using interrupts, but this took 2 seconds. for (;;) { voltage = ADCL; voltage |= ADCH << 8; // Get a duty cycle (0..0xFF) from a relative val (0..0x3FF) OCR1B = CLAMP(voltage >> 2, PWM_MAX, PWM_MIN); _delay_ms(1000); } return 0; }
C
/* ** EPITECH PROJECT, 2021 ** exec_unsetenv.c ** File description: ** exec_unsetenv.c */ #include "c_functions.h" #include "mysh.h" #include "mysh_macros.h" #include "mysh_structures.h" int error_handling_unsetenv(char **command) { if (my_str_arr_length(command) == 1) { my_putstr(UNSETENV_TOO_FEW); return (ERROR); } return (SUCCESSFUL); } int exec_unsetenv(char **command, t_minishell *minishell) { int index = 0; if (error_handling_unsetenv(command) == ERROR) return (SUCCESSFUL); for (int i = 1; command[i]; i++) { index = get_index_of_var(minishell->env, command[i]); if (index != -1) minishell->env = delete_index(minishell->env, index); } return (SUCCESSFUL); }
C
#include "header_files/SHT/SHT.h" #define FILENAME "hash_file.txt" #define SECONDARY_FILENAME "secondary_hash_file.txt" int main(void) { HT_info *info; BF_Init(); if ((HT_CreateIndex(FILENAME, 'i', "id", sizeof(int), 6)) < 0) { fprintf(stderr, "[!] Error in creating hash_file in main()\n"); return -1; } if ((info = HT_OpenIndex(FILENAME)) == NULL) { fprintf(stderr, "[!] Error in opening hash_file in main()\n"); HT_CloseIndex(info); return -1; } SHT_info *sht_info; if ((SHT_CreateSecondaryIndex(SECONDARY_FILENAME, "surname", sizeof(char *), 3, FILENAME)) < 0) { fprintf(stderr, "[!] Error in creating secondary index in main()."); return -1; } if ((sht_info = SHT_OpenSecondaryIndex(SECONDARY_FILENAME)) == NULL) { fprintf(stderr, "[!] Error in opening secondary hash file in main()."); SHT_CloseSecondaryIndex(sht_info); exit(EXIT_FAILURE); } SHT_InsertEntries(info, sht_info); printf("============================================================\n"); printf("INSERT DONE FOR BOTH HT AND SHT\n"); printf("============================================================\n"); printf("Get All Entries for HT:\n"); int value_ht = 4; int blocks_read; if ((blocks_read = HT_GetAllEntries(*info, &value_ht)) < 0) { fprintf(stderr, "[!] Error in getting all the entries in main()\n"); return -1; } printf("Blocks read for HT = %d\n", blocks_read); printf("============================================================\n"); printf("Get All Entries for SHT:\n"); char value_sht[40] = "surname_4980"; blocks_read = SHT_SecondaryGetAllEntries(*sht_info, *info, value_sht); printf("Blocks read for SHT= %d\n", blocks_read); printf("============================================================\n"); printf("Statistics for Primary Hash Table: \n"); HashStatistics(FILENAME); printf("============================================================\n"); printf("Statistics for Secondary Hash Table: \n"); SHT_HashStatistics(SECONDARY_FILENAME); return 0; // program terminated successfully. }
C
#ifndef FUNCIONES_H_INCLUDED #define FUNCIONES_H_INCLUDED struct fecha{ int dia; int mes; int anio; }; struct paciente{ int dni; char nombre[30]; char apellido[30]; char genero; fecha f; int obrasocial; bool estado; }; ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| int buscar_paciente(int codigo){ FILE *p; p = fopen("pacientes.dat", "rb"); if (p == NULL){ exit(1); } paciente a; int i=0; while(fread(&a, sizeof(paciente), 1, p)){ if (codigo == a.dni){ if (a.estado==false){ return -10; } fclose(p); return i; } i++; } fclose(p); return -1; } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| paciente leer_paciente(int pos){ paciente reg; FILE *p; p = fopen("pacientes.dat", "rb"); if (p==NULL){ reg.obrasocial = -1; return reg; } fseek(p, sizeof(paciente)*pos, SEEK_SET); bool leyo=fread(&reg, sizeof(paciente), 1, p); if (leyo == false){ reg.obrasocial = -1; } fclose(p); return reg; } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| void mostrar_pacientes(paciente a){ if (a.estado==true){ cout << "DNI:"; cout << a.dni << endl; cout << "NOMBRE: "; cout << a.nombre << endl; cout << "APELLIDO: "; cout << a.apellido << endl; cout << "GENERO: "; cout << a.genero << endl; cout << "FECHA: "; cout << a.f.dia<<"/"<<a.f.mes<<"/"<<a.f.anio << endl; cout << "OBRA SOCIAL: "; cout << a.obrasocial << endl; cout << endl; } } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| bool guardar_paciente(paciente a){ FILE *p; p = fopen("pacientes.dat", "ab"); if (p == NULL){ return false; } bool i=fwrite(&a, sizeof(paciente), 1, p); fclose(p); return i; } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| void listar_pacientes(){ paciente a; FILE *p; p = fopen("pacientes.dat", "rb"); if (p == NULL){ cout << "ERROR AL ABRIR EL ARCHIVO..."<<endl; return; } while(fread(&a, sizeof(paciente), 1, p) == 1){ mostrar_pacientes(a); cout << endl; } fclose(p); } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| void listar_paciente_x_dni(){ int codigo; int pos; cout << "DNI DEL PACIENTE: "; cin >> codigo; pos = buscar_paciente(codigo); if (pos >= 0){ paciente reg; reg = leer_paciente(pos); mostrar_pacientes(reg); } else{ cout << "NO EXISTE EL REGISTRO..."<<endl; } } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| bool sobreescribir_paciente(paciente reg, int pos){ FILE *p; p = fopen("pacientes.dat", "rb+"); if (p == NULL){ return false; } fseek(p, sizeof(paciente)*pos, 0); bool i=fwrite(&reg, sizeof(paciente), 1, p); fclose(p); return i; } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| void modificar_paciente(){ int codigo; int pos; cout << "DNI DEL PACIENTE A MODIFICAR: "; cin >> codigo; pos = buscar_paciente(codigo); if (pos >= 0){ paciente reg; reg = leer_paciente(pos); if(reg.estado==true){ mostrar_pacientes(reg); cout << endl << "NUEVO NUMERO DE OBRA SOCIAL: "; cin >> reg.obrasocial; while (reg.obrasocial<1||reg.obrasocial>50){ cout << "INGRESE UN NUMERO DE OBRA SOCIAL VALIDO (1 a 50)"<<endl; cin >>reg.obrasocial; } if (sobreescribir_paciente(reg, pos) == true){ cout << endl << "PACIENTE MODIFICADO."<<endl; } } else{ cout << "NO EXISTE EL PACIENTE" << endl; } } } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| void eliminar_paciente(){ int codigo; int pos; cout << "DNI DEL PACIENTE A ELIMINAR: "; cin >> codigo; pos = buscar_paciente(codigo); if (pos >= 0){ paciente reg; reg = leer_paciente(pos); mostrar_pacientes(reg); cout << endl << "ELIMINANDO PACIENTE... "<<endl; reg.estado=false; if (sobreescribir_paciente(reg, pos) == true){ cout << endl << "PACIENTE ELIMINADO."<<endl; } } else{ cout << "NO EXISTE EL PACIENTE."<<endl; } } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| void recuperar_paciente(int codigo){ int pos; bool x=true; cout << "DNI DEL PACIENTE A RECUPERAR: "<<codigo<<endl; while (x==true){ pos = buscar_paciente(codigo); if (pos == -1){ cout << "EL DNI INGRESADO NO EXISTE" << endl; } else { x=false; } } pos=buscar_paciente(codigo); paciente reg; reg = leer_paciente(pos); mostrar_pacientes(reg); cout << endl << "RECUPERANDO PACIENTE... "<<endl; reg.estado=true; if (sobreescribir_paciente(reg, pos) == true){ cout << endl << "PACIENTE RECUPERADO."<<endl; } else{ cout << "NO EXISTE EL PACIENTE."<<endl; } } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| void backup_pacientes (){ FILE *p, *p1; paciente a; fecha f; p=fopen("pacientes.dat","rb"); if(p==NULL){ cout << "ERROR DE ARCHIVO PACIENTES" << endl; return; } p1=fopen("pacientes.bkp", "wb"); if (p1==NULL){ cout << "ERROR DE ARCHIVO PACIENTES" << endl; return; } while(fread(&a,sizeof (paciente), 1, p)==1){ fwrite(&a, sizeof (paciente), 1, p1); } fclose(p1); fclose(p); } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| void backup_pacientes_restaurar (){ FILE *p, *p1; paciente a; fecha f; p=fopen("pacientes.bkp","rb"); if(p==NULL){ cout << "ERROR DE ARCHIVO PACIENTES" << endl; return; } p1=fopen("pacientes.dat", "wb"); if (p1==NULL){ cout << "ERROR DE ARCHIVO PACIENTES" << endl; return; } while(fread(&a,sizeof (paciente), 1, p)==1){ fwrite(&a, sizeof (paciente), 1, p1); } fclose(p1); fclose(p); } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| int restricciones_dni_pacientes(int x){ FILE *p; paciente a; fecha f; int s=3,ss=3; p=fopen("pacientes.dat","rb"); if(p==NULL){ fopen("pacientes.dat","ab"); } while(fread(&a,sizeof (paciente),1,p)==1){ if(a.dni==x&&a.estado==false){ return 1; s=1; } else{ if(a.dni==x&&a.estado==true){ return -1; ss=2; } } } fclose(p); if(s==3&&ss==3){ return 0; } } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| bool cargar_nuevo_paciente(paciente *a){ int punteroDNI; int y; char recuperar; bool z=true; while(z==true){ cout<<"INGRESE EL DNI: "; cin>>punteroDNI; y=restricciones_dni_pacientes(punteroDNI); cout<<"VALOR DE PUNTERO DNI: "<<punteroDNI<<endl; cout<<"VALOR DE Y: "<<y<<endl; cout<<"Y=0 (NUEVO)| Y=1 (ELIMINADO)| Y=-1 (ACTIVO) "<<endl; if(y==0){ a->dni=punteroDNI; z=false; } else { if(y==1){ cout<<"PACIENTE DADO DE BAJA. RECUPERAR? (S/N)"<<endl; cin>>recuperar; if(recuperar=='S'){ recuperar_paciente(punteroDNI); y=1; z=false; return true; } else z=false; } else { cout<<"EL PACIENTE YA EXISTE."<<endl; cout<<endl; cout<<"VOLVER A INGRESAR UN DNI"<<endl;} } } ///cout<<"esto es y "<<y<<endl; if(y==0){ cin.ignore(); z=true; while(z==true){ cout<<"INGRESE EL APELLIDO: "; cin.getline(a->apellido, 50); if(strlen(a->apellido)==0){ cout<<"EL APELLIDO NO PUEDE ESTAR VACIO"<<endl; } else { z=false; } } z=true; while(z==true){ cout<<"INGRESE EL NOMBRE: "; cin.getline(a->nombre, 50); if(strlen(a->nombre)==0){ cout<<"EL NOMBRE NO PUEDE ESTAR VACIO"<<endl; } else { z=false; } } z=true; while(z==true){ cout<<"INGRESE EL GENERO: "; cin>>a->genero; if(a->genero=='F'||a->genero=='M'||a->genero=='O'){ z=false; } else cout<<"INGRESE UN GENERO CORRECTO..."<<endl; } z=true; while (z==true){ cout << "INGRESE EL DIA: "; cin >> a->f.dia; cout << "INGRESE EL MES: "; cin >> a->f.mes; cout << "INGRESE EL ANIO: "; cin >> a->f.anio; if(a->f.dia>=1 && a->f.dia<=31 && a->f.mes>=1 && a->f.mes<=12 && a->f.anio>=1){ z=false; } else cout << "INGRESE UNA FECHA VALIDA" << endl; } z=true; while(z==true){ cout<<"INGRESE EL NUMERO DE OBRA SOCIAL"<<endl; cin>>a->obrasocial; if(a->obrasocial>=1&&a->obrasocial<=50){ z=false; } else cout<<"NUMERO DE OBRA SOCIAL DEBE SER ENTRE 1 Y 50"<<endl; } a->estado=true; return true; } return false; } ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ///|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| #endif // FUNCIONES_H_INCLUDED
C
#include <stdio.h> #include<stdlib.h> int main(void){ int tamanho = 100; int posicao[tamanho]; int i; int soma = 0; int media = 0; for(i = 0; i<tamanho; i++){ printf("Digite o %d. valor: ", i+1); scanf("\n%d", &posicao[i]); } for(i = 0; i<tamanho; i++){ soma = soma + posicao[i]; media = soma / 99; } for(i = 0; i<tamanho; i++){ printf("\nPosição[%d] = %d", i+1, posicao[i]); } printf("\nSoma: %d\n", soma); printf("\nA media é: %d\n", media); return 0; }
C
/* Problem 7: For loop in C. Easy Approach: Steps: 1) Take two integer inputs and apply for loop through the values. eg- input of a and b. make loop for (a to b) in which b is also included(Hint. use <= for b). 2) With the help of if-else statements check values upto 9. 3) later on check for even(i%2==0), otherwise odd respectively. 4) I type ("\n ") to give line break after execution. */ #include <stdio.h> int main(){ int a, b; scanf("%d %d",&a, &b); for(int i=a;i<=b;i++){ if(i==1){printf("%s","one\n");} else if(i==2){printf("%s","two\n");} else if(i==3){printf("%s","three\n");} else if(i==4){printf("%s","four\n");} else if(i==5){printf("%s","five\n");} else if(i==6){printf("%s","six\n");} else if(i==7){printf("%s","seven\n");} else if(i==8){printf("%s","eight\n");} else if(i==9){printf("%s","nine\n");} else if(i>9 && i%2==0){printf("%s","even\n");} else{ printf("%s","odd\n"); } } return 0; } // Thank You By: Harsh Udai.
C
/** * Define a macro swap(t, x, y) that interchanges two arguments of type t. * (Block structure will help) */ #include <stdio.h> #define swap(t, x, y) { t temp; temp = x, x = y, y = temp; } int main() { int x = 1; int y = 2; swap(int, x, y); printf("x: %i\ny: %i\n", x, y); }
C
#ifndef lint static char sccsid[] = "%W% %G% %U%"; #endif #include <stdio.h> #include <stdlib.h> #include <string.h> /************************************************************************/ /* getenv_lf: */ /* Get the value of an environment variable as a double. */ /* Return 1 on success, 0 on failure. */ /************************************************************************/ int getenv_lf (var, pval) char *var; double *pval; { char *str; if (str = getenv(var)) { char *p; double val; val = strtod (str, &p); if (*p == '\0') { *pval = val; return(1); } } return (0); } /************************************************************************/ /* getenv_f: */ /* Get the value of an environment variable as a float. */ /* Return 1 on success, 0 on failure. */ /************************************************************************/ int getenv_f (var, pval) char *var; float *pval; { char *str; if (str = getenv(var)) { char *p; double val; val = (float)strtod (str, &p); if (*p == '\0') { *pval = val; return(1); } } return (0); } /************************************************************************/ /* getenv_d: */ /* Get the value of an environment variable as a int. */ /* Return 1 on success, 0 on failure. */ /************************************************************************/ int getenv_d (var, pval) char *var; int *pval; { char *str; if (str = getenv(var)) { char *p; int val; val = strtol (str, &p, 10); if (*p == '\0') { *pval = val; return(1); } } return (0); } /************************************************************************/ /* getenv_s: */ /* Get the value of an environment variable as a string. */ /* Return 1 on success, 0 on failure. */ /************************************************************************/ int getenv_s (var, pval) char *var; char **pval; { char *str; if (str = getenv(var)) { *pval = str; return(1); } return (0); }
C
#include <stdio.h> media(){ float x,y,z; float peso1,peso2,peso3; scanf("%f %f %f",&x,&y,&z); scanf("%f %f %f",&peso1,&peso2,&peso3); float media; media=(x*peso1+y*peso2+z*peso3)/(peso1+peso2+peso3); printf("A media final foi:%f\n",media); } main(){ media(); }
C
int myMax(int i, int j){ if(i >= j) return i; else return j; }
C
int bitwiseComplement(int N) { int c = 1; while (c < N) { c = (c << 1) | 1; printf("%d\n",c); } return N ^ c; } int bitwiseComplement(int N) { int m = 1; while (m < N) { m = m << 1 | 1; } return N ^ m; } /** C++ class Solution { public: int bitwiseComplement(int N) { if (N==0) return 1; int n = helper(N); cout<<n; return (~N) & n; } int helper(int N) { int n = 0; while (N) { n++; N >>= 1; } return pow(2, n) - 1; } };
C
#include <stdio.h> #include <stdlib.h> typedef struct grafo { int n; /* N�mero de n�s */ int **mat; /* Matriz (a ser alocada dinamicamente) */ } Grafo; void cria_grafo(Grafo* g, int n) { g->n = n; g->mat = malloc(n * sizeof (int)); for (int i = 0; i < n; ++i) g->mat[i] = calloc(n, sizeof (int)); } void inserir_grafo(Grafo* g, int u, int v) { g->mat[u][v] = g->mat[v][u] = 1; } void remover_grafo(Grafo* g, int u, int v) { g->mat[u][v] = g->mat[v][u] = 0; } int n, a, b, componete[MAXN]; vector< int > aresta[MAXN]; void dfs(int n){ for(int i = 0; i < n; i++){ int v = aresta[0][i]; if(componete[v] == 0){ dfs(v); } } } int main() { Grafo *g = malloc(sizeof(Grafo)); cria_grafo(g, 3); inserir_grafo(g, 1, 2); inserir_grafo(g, 0, 1); //remover_grafo(g, 0, 1); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { printf("%i ", g->mat[i][j]); } printf("\n"); } printf("Ola"); return 0; }
C
/* Week 2 Assignment 2 John McCormack */ #include <stdio.h> #include <limits.h> void main(void) { int counter = 1, largest = INT_MIN, number = 0; // largest_number value set to lowest possible value for INT printf("Please Enter 10 numbers. At the end the largest will be displayed\n"); while(counter <= 10){ printf("Please Enter Number %d\n", counter); scanf("%d", &number); if (number > largest) largest = number; counter++; }; printf("The Largest Number Entered was = %d\n", largest); getch(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <time.h> #include <unistd.h> #include <math.h> int **Matrix; int FirstRow,FirstColumn,SecondRow,SecondColumn,TotalRow,TotalColumn; int i,Row,Column; int **FirstMatrix; int **SecondMatrix; int **Multiplication; //this is for passing more than one arguments to thread function struct arg_struct { int thread_row; int thread_column; }; void print_matrix(int rows, int cols, int **mat){ int i=0,j=0; for(i=0; i<rows; i++){ /* Iterate of each row */ for(j=0; j<cols; j++){ /* In each row, go over each col element */ printf("%d ",mat[i][j]); /* Print each row element */ } printf("\n"); } } void free_matrix(int rows, int **mat){ int i=0; for(i=0;i<rows;i++) free(mat[i]); free(mat); } void* multiply_matrix(void *arguments) { struct arg_struct *args = arguments; int thread_sum=0;//store the calculation result in this thread. //calculate the multiplication of the current row of first matrix and column of second matrix. for (i = 0; i < SecondRow; i++) { thread_sum = thread_sum + (FirstMatrix[args -> thread_row][i]*SecondMatrix[i][args -> thread_column]); } //store the result to the Multiplication matrix . Multiplication[args -> thread_row][args -> thread_column] = thread_sum; pthread_exit(NULL); return NULL; } int main(int argc,char* argv[]) { /////////////// read input matrixes FILE *fp; pthread_t *threads;//to generate an array of thread. struct arg_struct *args; args=( struct arg_struct *) malloc((FirstRow*SecondColumn)* sizeof( struct arg_struct)); if (argc != 2) { fprintf(stderr, "Usage: %s file.txt\n", argv[0]); exit(1); } if (!(fp = fopen(argv[1], "r"))) { perror(argv[1]); exit(1); } for(i=1;i<=2;i++) { /////////////////////read matrix//////////// fscanf(fp, "%d%d",&TotalRow,&TotalColumn); printf("Input Matrix%d : Row= %d,Column= %d\n",i,TotalRow,TotalColumn); //setup 2D array to store input matrix Matrix = (int **) malloc(sizeof(int *)*TotalRow); for(Row=0; Row<TotalRow; Row++) Matrix[Row] = (int *) malloc(sizeof(int)*TotalColumn); // read a matrix for (Row = 0; Row < TotalRow; Row++) for (Column = 0; Column < TotalColumn; Column++) fscanf(fp,"%d", &Matrix[Row][Column]); /////////////////////////end read matrix////// if(i==1) { FirstMatrix=Matrix; FirstRow=TotalRow; FirstColumn=TotalColumn; print_matrix(FirstRow,FirstColumn,FirstMatrix); } else { SecondMatrix=Matrix; SecondRow=TotalRow; SecondColumn=TotalColumn; print_matrix(SecondRow,SecondColumn,SecondMatrix); } } fclose(fp); ///////////////finish read input matrixes //setup 2D array to store the result after multiplication Multiplication = (int **) malloc(sizeof(int *)*FirstRow); for(Row=0; Row<FirstRow; Row++) Multiplication[Row] = (int *) malloc(sizeof(int)*SecondColumn); //setup an array of threads with the same size as Multiplication threads = (pthread_t *) malloc((FirstRow*SecondColumn)* sizeof(pthread_t)); //setup an array of the arguments of thread functions with the same size as Multiplication args=( struct arg_struct *) malloc((FirstRow*SecondColumn)* sizeof( struct arg_struct)); int num_of_thread=0;//indicate num of thread. //measure elapsed time . /* double micros = 0.0; float millis = 0.0; clock_t start, end; start = clock(); */ //multiply two matrixes for (Row = 0; Row < FirstRow; Row++) { for (Column = 0; Column < SecondColumn; Column++) { //record the current row of first matrix and column of second matrix so as to pass these data to thread function. args[num_of_thread].thread_row = Row; args[num_of_thread].thread_column = Column; if(pthread_create(&threads[num_of_thread], NULL, multiply_matrix,(void *)&args[num_of_thread] ) <0) { perror("Could not create thread!"); return 1; } num_of_thread++;//increase the index of threads and args. } } //block main thread until all the treads come to an end. for (i = 0; i < (FirstRow*SecondColumn); i++) { pthread_join(threads[i], NULL); } //measure elapsed time . /* end = clock(); micros = end - start; millis = micros / 1000000.0; printf("\nFinished in %f seconds.\n\n", millis); */ ///////////////////// //print calculation result printf("Product of entered matrices: Row= %d,Column= %d\n",FirstRow,SecondColumn); print_matrix(FirstRow,SecondColumn,Multiplication); printf("\n"); //write the result to an output file. fp = fopen( "output_matrix.txt", "w" ); // Open file for writing fprintf(fp, "%d %d\n",FirstRow,SecondColumn ); for (Row = 0; Row < FirstRow; Row++) { for (Column = 0; Column < SecondColumn; Column++) fprintf(fp,"%d ", Multiplication[Row][Column]); fprintf(fp, "\n" ); } fclose(fp); //end writing the result ot an output file. free_matrix( TotalRow, Matrix);/* Free the matrix */ free_matrix( FirstRow, Multiplication);/* Free the result matrix */ FirstMatrix=NULL;//point FirstMatrix pointer to NULL to disable the pointer SecondMatrix=NULL;//point SecondMatrix pointer to NULL to disable the pointer Matrix=NULL;//point Matrix pointer to NULL to disable the pointer Multiplication=NULL;//point Multiplication pointer to NULL to disable the pointer return 0; }
C
#include "queue.h" #include "type.h" int main(){ // print_function = print_type; // Queue queue = new_queue_with_type(getType()); // push(queue, new_item( new_type(1) )); // push(queue, new_item( new_type(2) )); // push(queue, new_item( new_type(3) )); // push(queue, new_item( new_type(4) )); // print(queue); Queue queue = new_queue_string(); push(queue, new_item("Ciao")); push(queue, new_item("come")); push(queue, new_item("va")); push(queue, new_item("?")); print(queue); Queue queue2 = new_queue(); push(queue2, new_item("Ciao")); push(queue2, new_item("come")); push(queue2, new_item("va")); push(queue2, new_item("?")); print(queue2); pop(queue); Item i = pop(queue2); delete_Queue(queue); printf("\n\nInformazione = %s\n\n\n", get_info(i)); print(queue2); delete_Queue(queue2); return 0; }
C
#include "monitor-info-restaurantes.h" /* * t_dictionary: * <char* restaurante, t_info_restaurante info> */ t_dictionary* info_restaurantes; pthread_mutex_t mutex; void monitor_info_restaurantes_init(){ info_restaurantes = dictionary_create(); pthread_mutex_init(&mutex, NULL); } void monitor_info_restaurantes_destroy(){ pthread_mutex_destroy(&mutex); dictionary_destroy_and_destroy_elements(info_restaurantes, (void*)info_restaurante_destroy); } bool monitor_info_restaurantes_has_key(char* restaurante){ bool result = false; pthread_mutex_lock(&mutex); result = dictionary_has_key(info_restaurantes, restaurante); pthread_mutex_unlock(&mutex); return result; } void monitor_info_restaurantes_put(char* restaurante, t_info_restaurante* info_restaurante){ pthread_mutex_lock(&mutex); dictionary_put(info_restaurantes, restaurante, info_restaurante); pthread_mutex_unlock(&mutex); } t_info_restaurante* monitor_info_restaurantes_get(char* restaurante){ t_info_restaurante* info_restaurante = NULL; pthread_mutex_lock(&mutex); info_restaurante = dictionary_get(info_restaurantes, restaurante); pthread_mutex_unlock(&mutex); return info_restaurante; } t_list* monitor_info_restaurantes_get_all(){ t_list* info_restaurantes_list = list_create(); void add_restaurante_to_list(char* key, void* value){ t_info_restaurante* info_restaurante = (t_info_restaurante*) value; list_add(info_restaurantes_list, info_restaurante); } pthread_mutex_lock(&mutex); dictionary_iterator(info_restaurantes, add_restaurante_to_list); pthread_mutex_unlock(&mutex); return info_restaurantes_list; } void monitor_info_restaurantes_remove(char* restaurante){ pthread_mutex_lock(&mutex); dictionary_remove_and_destroy(info_restaurantes, restaurante, (void*)info_restaurante_destroy); pthread_mutex_unlock(&mutex); }
C
/** * project: 163 final project * * Conner Short * CMPE 163 * December 2017 * * sim.c: Simulation control functions **/ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "sim.h" struct timed_func_node { void (*function_ptr)(); double tick_rate; double interp_factor; int persistent; struct timespec l_tick; struct timed_func_node* next; }; struct timed_func_node* root = NULL; struct timed_func_node* last = NULL; int num_timed_functions = 0; void end_sim() { struct timed_func_node* i = root; struct timed_func_node* j; while(i != NULL) { j = i; i = i->next; free(j); } } void init_sim() { atexit(end_sim); } double diff_timespec(struct timespec* t0, struct timespec* t1) { double d_t0 = (double)t0->tv_sec + (double)t0->tv_nsec / 1000000000.0; double d_t1 = (double)t1->tv_sec + (double)t1->tv_nsec / 1000000000.0; return d_t1 - d_t0; } int sim_main() { int view_needs_updating = 0; struct timed_func_node* i = root; struct timespec c_time; clock_gettime(CLOCK_MONOTONIC, &c_time); while(i != NULL) { double d = diff_timespec(&(i->l_tick), &c_time); if(d > (1.0 / i->tick_rate)) { i->l_tick.tv_sec = c_time.tv_sec; i->l_tick.tv_nsec = c_time.tv_nsec; if(i->persistent) { /* If persistence is desired, step the function until it is caught up * with the elapsed time since the last run. */ while(d > (1.0 / i->tick_rate)) { d -= (1.0 / i->tick_rate); i->function_ptr(); } i->interp_factor = d * i->tick_rate; } else { /* Otherwise, just call it once. */ i->function_ptr(); } view_needs_updating = 1; } i = i->next; } return view_needs_updating; } int sim_register_periodic_function(void (*callback)(), double tick_rate, int persistent) { struct timed_func_node* n = malloc(sizeof(struct timed_func_node)); if(n == NULL) { perror("sim_register_periodic_function"); exit(EXIT_FAILURE); } clock_gettime(CLOCK_MONOTONIC, &(n->l_tick)); n->function_ptr = callback; n->tick_rate = tick_rate; n->persistent = persistent; n->next = NULL; if(root == NULL) { root = n; last = n; } else { last->next = n; last = n; } num_timed_functions++; return num_timed_functions - 1; } double get_interp_factor(int func_id) { struct timed_func_node* i = root; while(i != NULL && func_id > 0) { i = i->next; func_id--; } return (i == NULL) ? 0.0 : i->interp_factor; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "computeFlux.h" #include "macroDefinition.h" #include "updateFlux.h" #include "visual.h" #include "computeTimeStep.h" void printMatrixf(int n_grid, double *matrix) { for (int x = 0; x < n_grid; ++x) { for (int y = 0; y < n_grid; ++y) { printf("matrix[%d][%d]: %lf\t",x,y, matrix[x*n_grid + y] ); } printf("\n"); } } int main(int argc, char **argv) { /* initial value set up */ int cellsize = 1; int n_grid = 50; int length = n_grid * cellsize; int totalNumberofTimeStep = 1000; int plottingStep = 1; int LTS_levels = 5; /* LTS level: 1->GTS, LTS: 2,3 */ int level_A, level_B; int idum; double dt0 = 0.1; // double dt_dx = dt0/cellsize; double crmax; const char *szProblem; szProblem = "result"; /* Initialisation & memory allocation */ // double amax; double *h, *u, *v, *F, *G, *U, *dt, *lambdaf, *lambdag; int *levelf, *levelg, *levelc; h = malloc(n_grid*n_grid*sizeof(double)); u = malloc(n_grid*n_grid*sizeof(double)); v = malloc(n_grid*n_grid*sizeof(double)); dt = malloc(n_grid*n_grid*sizeof(double)); lambdag = malloc((n_grid + 1)*n_grid*sizeof(double)); lambdaf = malloc((n_grid + 1)*n_grid*sizeof(double)); F = malloc((n_grid+1)*n_grid*3*sizeof(double)); G = malloc((n_grid+1)*n_grid*3*sizeof(double)); U = malloc(n_grid*n_grid*3*sizeof(double)); levelc = malloc(n_grid*n_grid*sizeof(int)); levelf = malloc((n_grid+1)*n_grid*sizeof(int)); levelg = malloc((n_grid+1)*n_grid*sizeof(int)); /* initialisation */ for (int x = 0; x < n_grid; ++x) { for (int y = 0; y < n_grid; ++y) { h[x*n_grid + y] = 0.1; u[x*n_grid + y] = 0.0; v[x*n_grid + y] = 0.0; U[ (x*n_grid + y)*3] = h[x*n_grid + y]; U[ (x*n_grid + y)*3 + 1] = u[x*n_grid + y] * h[x*n_grid + y]; U[ (x*n_grid + y)*3 + 2] = v[x*n_grid + y] * h[x*n_grid + y]; levelc[x*n_grid + y] = LTS_levels*1; dt[x*n_grid + y] = dt0; } } /*initialise h*/ for (int x = 0; x < 6; ++x) { for (int y = n_grid - 6; y < n_grid; ++y) { h[x*n_grid + y] = 1.0; U[ (x*n_grid + y)*3] = h[x*n_grid + y]; } } for (int x = 0; x < n_grid + 1; ++x) { for (int y = 0; y < n_grid; ++y) { levelf[x*n_grid + y] = LTS_levels*1; lambdaf[x*n_grid + y] = 0.0; for (int i = 0; i < 3; ++i) { F[ (x*n_grid + y)*3 + i ] = 0.0; } } } for (int x = 0; x < n_grid; ++x) { for (int y = 0; y < n_grid + 1; ++y) { levelg[x*(n_grid+1) + y] = LTS_levels*1; lambdag[x*(n_grid+1) + y] = 0.0; for (int i = 0; i < 3; ++i) { G[ (x*(n_grid+1) + y)*3 + i ] = 0.0; } } } /* start simulation */ level_B = LTS_levels; for (int i = 1; i <= totalNumberofTimeStep; ++i) { level_A = level_B; /* initialise different level */ if ((i-1)%2 == 0) { level_B = 1; }else{ for (int j = 1; j <= LTS_levels; ++j) { idum = (int)pow(2,j-1); if (i%idum == 0) { level_B = j; } } } // printf("level_A: %d\n", level_A); /* compute fluxes*/ computeFlux(U, F, G, levelf, levelg, lambdaf, lambdag, n_grid, level_A); /* Assign LTS levels & calculate timestepping*/ if (level_A == LTS_levels) { calculateTimeStep(lambdaf, lambdag, dt, levelc, levelf, levelg, LTS_levels, cellsize, n_grid, dt0, &crmax); } // for (int x = 0; x < n_grid + 1; ++x) // { // for (int y = 0; y < n_grid; ++y) // { // printf("levelf[%d][%d]: %d\t",x,y, levelf[x*n_grid + y] ); // } // printf("\n"); // } // for (int x = 0; x < n_grid; ++x) // { // for (int y = 0; y < n_grid + 1; ++y) // { // printf("levelg[%d][%d]: %d\t",x,y, levelg[x*(n_grid+1) + y] ); // } // printf("\n"); // } // for (int x = 0; x < n_grid; ++x) // { // for (int y = 0; y < n_grid; ++y) // { // printf("levelc[%d][%d]: %d\t",x,y, levelc[x*n_grid + y] ); // } // printf("\n"); // } // for (int x = 0; x < n_grid; ++x) // { // for (int y = 0; y < n_grid; ++y) // { // printf("dt[%d][%d]: %lf\t",x,y, dt[x*n_grid + y] ); // } // printf("\n"); // } // printMatrixf(n_grid, levelf); /* updating the fluxes*/ updateFlux(U, F, G, levelc, n_grid, dt, level_B); // for (int i = 0; i < 3; ++i) // { // for (int x = 0; x < n_grid; ++x) // { // for (int y = 0; y < n_grid; ++y) // { // printf("U: %lf \t", U[(x*n_grid + y)*3 + i]); // } // printf("\n"); // } // printf("\n"); // } //printf("Time Step = %d, amax = %lf \n", i, amax); printf("Time Step = %d, Courant Number = %lf, level_B: %d \n", i, crmax, level_B); // /* write vtk file*/ // if(i % plottingStep == 0){ // write_vtkFile(szProblem, i, length, n_grid, n_grid, cellsize, cellsize, U, dt); // } } /* memory deallocation */ free(h); free(u); free(v); free(F); free(G); free(U); free(levelf); free(levelc); free(levelg); free(lambdag); free(lambdaf); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include<float.h> #include<time.h> #include <stdint.h> int main(){ int real1, real2, img1, img2, soma1, soma2; printf("Digite a parte real"); scanf("%d", &real1); printf("Digite a parte img"); scanf("%d", &img1); printf("Digite a parte real2"); scanf("%d", &real2); printf("Digite a parte img2"); scanf("%d", &img2); soma1=real1+real2; soma2=img1+img2; printf("A soma e: %d+%di", soma1, soma2); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "funcoes.c" int main() { float metros; printf("insira a medida em metros!\n"); scanf("%f",&metros); printf("%.2f metros equivale a:\n",metros); metros=convert(metros); printf("%.2f dm\n",metros); metros=convert(metros); printf("%.2f cm\n",metros); metros=convert(metros); printf("%.2f mm\n",metros); return 0; }
C
// pi.c #include <stdlib.h> #include <stdio.h> double f( double x ) { return 4.0 / ( 1 + x*x ); } int main( int argc, char *argv[] ) { int N, i; double deltaX, sum; if ( argc < 2 ) { printf( "Syntax %s N\n", argv[0] ); exit(1); } N = atoi( argv[1] ); sum = 0; deltaX = 1.0/N; for ( i = 0; i < N; i++ ) sum += f( i * deltaX ); printf( "%d iterations: Pi = %1.6f\n", N, sum*deltaX ); }
C
#include <stdio.h> #include "search.h" #include <stdlib.h> int check_uniq(FILE *fp , int roll_no){ //Accepting file pointer and roll no as parameters char namef[1000] , namel[1000] , date[20], category[30] ,BUFFER[1000]; int *roll , *fees; roll = (int *)malloc(sizeof(int)); fees = (int *)malloc(sizeof(int)); while(1){ search(namef,namel,roll,fees,date,category ,fp); //Searching a particular row of a database using search function declared in search.h if(feof(fp)) //When cursor reaches end of File break; if(*roll==roll_no) //If roll number is not unique return 0; fgets(BUFFER , 1000 , fp); //To get to next Line }return 1; } //display fucnctions void display_stud() { printf("\nnameF nameL Roll Fees DueDate\n"); } void display_staff() { printf("\nnameF nameL Staff ID Salary DueDate\n"); } void display() { printf("\nPLEASE AN CHOOSE AN ACTION FROM THE FOLLOWING LIST OF OPTIONS\n"); printf("|----------------WELCOME TO THIS SCHOOL BILLING SOFTWARE----------|\n"); printf("| |\n"); printf("| 1. ADD A RECORD |\n"); printf("| 2. DELETE A RECORD |\n"); printf("| 3. SEARCH A RECORD |\n"); printf("| 4. DOMAIN BASED SEARCHING(search for a range of records)|\n"); printf("| 5. EXIT THE SOFTWARE |\n"); printf("|_________________________________________________________________|\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(int argc, char* argv[]) { int fd = 0; fd = open("Hello.txt", O_WRONLY); if(fork() == 0) { write(fd, "Child", 5); } else { write(fd, "Parent", 6); } exit(0); }
C
#include<stdio.h> int main(){ int idade; float peso, altura, imc; printf("\nDigite sua idade\n"); scanf("%d", &idade); printf("\nDigite seu peso em quilos (separando com ponto)\n"); scanf("%f", &peso); printf("\nDigite sua altura em metros (separando com ponto)\n"); scanf("%f", &altura); imc = peso/(altura*altura); printf("\nCom %d anos voce tem um IMC de %.2f!\n\n", idade, imc); return 0; }
C
/* * Copyright (C) 2014 Soul Trace <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * */ #define _POSIX_SOURCE #define _POSIX_C_SOURCE 199309L /* getopt */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <string.h> #include <unistd.h> #define szbuf 32768 u_int32_t crc_tab[256]; u_int32_t chksum_crc32 (FILE *f) { register unsigned long crc; unsigned long i, j; char *buffer = malloc(szbuf); char *buf; crc = 0xFFFFFFFF; while (!feof(f)) { j = fread(buffer, 1, szbuf, f); buf = buffer; for (i = 0; i < j; i++) crc = ((crc >> 8) & 0x00FFFFFF) ^ crc_tab[(crc ^ *buf++) & 0xFF]; } free(buffer); return crc; } void chksum_crc32gentab () { unsigned long crc, poly; int i, j; poly = 0xEDB88320L; for (i = 0; i < 256; i++) { crc = i; for (j = 8; j > 0; j--) { if (crc & 1) crc = (crc >> 1) ^ poly; else crc >>= 1; } crc_tab[i] = crc; } } void usage(char *progname) { printf("Usage: %s [ -v Version ] [ -d Device_ID ] <input file>\n", progname); exit(1); } int main(int argc, char *argv[]) { struct signature { const char magic[4]; unsigned int device_id; char firmware_version[48]; unsigned int crc32; } sign = { { 'Z', 'N', 'B', 'G' }, 1, { "V.1.0.0(1.0.0)" }, 0 }; FILE *f; struct signature oldsign; char *filename; static const char *optString; int opt; if (argc < 1) usage(argv[0]); optString = "v:d:h"; opt = getopt( argc, argv, optString ); while( opt != -1 ) { switch( opt ) { case 'v': if (optarg == NULL) usage(argv[0]); strncpy(sign.firmware_version, optarg, sizeof(sign.firmware_version)-1); sign.firmware_version[sizeof(sign.firmware_version)-1]='\0'; /* Make sure that string is terminated correctly */ break; case 'd': sign.device_id = atoi(optarg); if (sign.device_id == 0) sign.device_id = (int)strtol(optarg, NULL, 16); break; case '?': case 'h': usage(argv[0]); break; default: break; } opt = getopt( argc, argv, optString ); } chksum_crc32gentab(); filename=argv[optind]; if (access(filename, W_OK) || access(filename, R_OK)) { printf("Not open input file %s\n", filename); exit(1); } f = fopen(argv[optind], "r+"); if (f != NULL) { fseek(f, sizeof(sign)*-1, SEEK_END); fread(&oldsign, sizeof(oldsign), 1, f); if (strncmp(oldsign.magic,"ZNBG", sizeof(oldsign.magic)) == 0 ) { printf("Image is already signed as:\nDevice ID: 0x%08x\nFirmware version: %s\nImage CRC32: 0x%x\n", oldsign.device_id, oldsign.firmware_version, oldsign.crc32); exit(0); } fseek(f, 0, SEEK_SET); sign.crc32 = chksum_crc32(f); fwrite(&sign, sizeof(sign), 1, f); fclose(f); printf("Image signed as:\nDevice ID: 0x%08x\nFirmware version: %s\nImage CRC32: 0x%x\n", sign.device_id, sign.firmware_version, sign.crc32); } return 0; }
C
##include <stdio.h> #include <stdlib.h> int main() { int number, result=0; char cymbol=65; printf("Enter number:"); scanf("%d", &number); while (!result) { result=number/12*10+number%12; if (number%12==10) printf("%d%c", number/12, cymbol); else if (number%12==11) printf("%d%c", number/12, cymbol+1); else printf("%d", result); } return 0; }
C
/* *定义一个函数,得到数组的最大值,要求函数的返回值一定是void * */ #include <stdio.h> void maxarr(int *p, int n, int *max) { int i; //*p--->*(p+0) --->p[0] *max = p[0]; for (i = 1; i < n; i++) { if (*(p+i) /*p[i]*/ > *max) *max = p[i]; } } int main(void) { int arr[10] = {1,5,2,9,4,10,17,1,2,3}; int m; maxarr(arr, 10, &m); printf("最大值是%d\n", m); return 0; }
C
#include <stdio.h> #include <string.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include "error.h" #include "graphics.h" #include "input.h" // Blit a button on the main screen surface int blit_button(struct s_context *cxt, const char *path, SDL_Rect pos, const char * text, const char *fpath) { int t = strlen(text); SDL_Colour c; SDL_Rect txtpos; SDL_Surface *tmp; SDL_Surface *b = IMG_Load(path); TTF_Font *f = TTF_OpenFont(fpath, 36); // 16x16 pixels by character if(b == NULL) { log_error("Could not create button surface", "blit_button", IMG_GetError(), 0); return -1; } // Set text to fully opaque green-ish white (0xB0FEB0) c.r = 0xB0; c.g = 0xFE; c.b = 0xB0; c.a = 0xFE; tmp = TTF_RenderText_Blended(f, text, c); if(tmp == NULL) { log_error("Could not put text on button surface", "blit_button", TTF_GetError(), 0); return GRFERR; } // The text must be less than 13 characters long // centralizes the string 'text' in the button txtpos.x = 105 - ((t * 16) / 2); txtpos.y = 30; SDL_BlitSurface(tmp, NULL, b, &txtpos); SDL_BlitSurface(b, NULL, cxt->screen, &pos); // Clean up the mess SDL_FreeSurface(tmp); SDL_FreeSurface(b); TTF_CloseFont(f); return 0; } int close_app(struct s_context *ctx) { SDL_FreeSurface(ctx->screen); SDL_DestroyWindow(ctx->win); SDL_DestroyRenderer(ctx->ren); IMG_Quit(); TTF_Quit(); SDL_Quit(); return 0; } int create_context(struct s_context *cxt, const char *title, const int sizex, const int sizey) { if(SDL_Init(SDL_INIT_EVERYTHING)) { log_error("Could not initialize SDL", "create_context", SDL_GetError(), 1); close_app(cxt); } if(IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG) { log_error("Could not initialize SDL_image", "create_context", IMG_GetError(), 1); close_app(cxt); } if(TTF_Init()) { log_error("Could not initialize SDL_ttf", "create_context", TTF_GetError(), 1); close_app(cxt); } cxt->win = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, sizex, sizey, SDL_WINDOW_SHOWN); cxt->ren = SDL_CreateRenderer(cxt->win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(cxt->win == NULL || cxt->ren == NULL) { log_error("Can't create window and/or renderer", "create_context", SDL_GetError(), 1); close_app(cxt); } // Set background as pale green (0x90EE90) cxt->screen = SDL_GetWindowSurface(cxt->win); SDL_FillRect(cxt->screen, NULL, SDL_MapRGB(cxt->screen->format, 0x90, 0xEE, 0x90)); return 0; } int show(struct s_context cxt) { SDL_Texture *tmp = SDL_CreateTextureFromSurface(cxt.ren, cxt.screen); SDL_RenderCopy(cxt.ren, tmp, NULL, NULL); SDL_RenderPresent(cxt.ren); SDL_DestroyTexture(tmp); return 0; } int blit_player(struct s_context *cxt, const int player, const int posx, const int posy) { SDL_Rect position; SDL_Surface *mark; position.x = posx; position.y = posy; /* FIXME = Performance can be improved by loading the image once and using it until the game is over, thus avoiding acessing the disk every time a player makes a move */ if(player == 1) // X mark = IMG_Load("res/x_100x100.png"); else if(player == -1) // O mark = IMG_Load("res/o_100x100.png"); else return INPERR; // the player parameter is invalid if(mark == NULL) { log_error("Coudn't load image file as surface", "blit_player", IMG_GetError(), 0); return GRFERR; // Coudn't load resource } SDL_BlitSurface(mark, NULL, cxt->screen, &position); return 0; } int blit_text(struct s_context * cxt, const int size, const char *text, const char *fpath, SDL_Rect pos) { SDL_Surface *tmp; SDL_Colour c; TTF_Font *f = TTF_OpenFont(fpath, size); // fully opaque pale green c.r = 0xB0; c.g = 0x00; c.b = 0xB0; c.a = 0xFF; // in case there's nothing to blit here if(strlen(text) == 0) return 0; tmp = TTF_RenderText_Blended(f, text, c); if(tmp == NULL) { log_error("Could not put text on temporary surface", "blit_text", TTF_GetError(), 0); return GRFERR; // Coudn't render } SDL_BlitSurface(tmp, NULL, cxt->screen, &pos); SDL_FreeSurface(tmp); TTF_CloseFont(f); return 0; } int clear_screen(struct s_context * cxt) { // Clean main surface cxt->screen = SDL_GetWindowSurface(cxt->win); SDL_FillRect(cxt->screen, NULL, SDL_MapRGB(cxt->screen->format, 0x90, 0xEE, 0x90)); return 0; } int put_cursor(struct s_context * cxt, const int player) { int posx, posy; SDL_Rect player_pos; // if player is o (-1), load o cursor, else loads x cursor SDL_Surface *player_surf = (player == -1) ? IMG_Load("res/cursor_o_16x16.png") : IMG_Load("res/cursor_x_16x16.png"); if(player_surf == NULL) { log_error("Coudn't load image file as surface", "blit_cursor", IMG_GetError(), 0); return GRFERR; } SDL_GetMouseState(&posx, &posy); if(posy < 110) // tests if cursor is out of the game space and is hidden { SDL_ShowCursor(1); // show cursor return 1; } else { SDL_ShowCursor(0); } player_pos.h = 16; player_pos.w = 16; player_pos.x = posx; player_pos.y = posy; SDL_BlitSurface(player_surf, NULL, cxt->screen, &player_pos); // clean up SDL_FreeSurface(player_surf); return 0; } int blit_element(struct s_context * cxt, const char * path, SDL_Rect pos) { SDL_Surface *element = IMG_Load(path); if(element == NULL) { log_error("Coudn't load image file as surface", "blit_element", IMG_GetError(), 0); return GRFERR; // Coudn't load resource } SDL_BlitSurface(element, NULL, cxt->screen, &pos); SDL_FreeSurface(element); return 0; } int show_error_window(const char * msg) { SDL_Event errev; struct s_context errormsgcxt; SDL_Rect ok_b; SDL_Rect txt; txt.x = 130 - ((strlen(msg) * 10) / 2); txt.y = 20; ok_b.h = 30; ok_b.w = 50; ok_b.x = 100; ok_b.y = 60; errormsgcxt.win = SDL_CreateWindow("-ERROR-", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 250, 100, SDL_WINDOW_SHOWN); errormsgcxt.ren = SDL_CreateRenderer(errormsgcxt.win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); clear_screen(&errormsgcxt); blit_text(&errormsgcxt, 24, msg, "res/f.ttf", txt); blit_element(&errormsgcxt, "res/OK_50x30.png", ok_b); show(errormsgcxt); while(1) { SDL_PollEvent(&errev); if(clicked(errev, ok_b)) { SDL_FreeSurface(errormsgcxt.screen); SDL_DestroyWindow(errormsgcxt.win); SDL_DestroyRenderer(errormsgcxt.ren); return 0; } } return 0; }
C
#include <stdio.h> int main(void) { int a,b,c; printf("enter the minutes"); scanf("%d",&a); b=a/60; c=a%60; printf("\n the time is %d hours and%d minutes",b,c); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> // Armazenar na matrix e imprimir valores. off_t fsize(const char *filename) { struct stat st; if (stat(filename, &st) == 0) return st.st_size; return -1; } int argOk(const char **argv) { if (argv[1] == 0) { printf("Insira o nome de um arquivo.\n"); exit(-1); } return 0; } int main(int argc, char const *argv[]) { argOk(argv); char *file_name; char file_char; int size; char all[1000]; FILE * fPointer; fPointer = fopen(file_name, "r"); strcpy(file_name, argv[1]); int file_size = fsize(file_name); while(file_char != EOF) { printf("size: %d\n", fgets(all, 100, fPointer)); file_char = fgetc(fPointer); } printf("%d", file_size); return 0; }
C
#include <stdio.h> int x; void leia () { printf("Digite um numero"); scanf ("%d",&x); } void imprime () { printf("o antecessor e: %d\n",x - 1); printf("o sucessor e:%d\n",x + 1); ; } int main() { leia(); imprime(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define FILE_NAME "queue.txt" #include <limits.h> // A structure to represent a queue typedef struct Queue { int front, rear, size; unsigned capacity; int* array; } Queue; // function to create a queue // of given capacity. // It initializes size of queue as 0 Queue* createQueue(unsigned capacity){ Queue* queue = (Queue*)malloc( sizeof(struct Queue)); queue->capacity = capacity; queue->front = queue->size = 0; // This is important, see the enqueue queue->rear = capacity - 1; queue->array = (int*)malloc( queue->capacity * sizeof(int)); return queue; } // Queue is full when size becomes // equal to the capacity int isFull(Queue* queue) { return (queue->size == queue->capacity); } // Queue is empty when size is 0 int isEmpty(Queue* queue) { return (queue->size == 0); } // Function to add an item to the queue. // It changes rear and size void enqueue(Queue* queue, int item) { if (isFull(queue)) return; queue->rear = (queue->rear + 1) % queue->capacity; queue->array[queue->rear] = item; queue->size = queue->size + 1; printf("%d enqueued to queue\n", item); } // Function to remove an item from queue. // It changes front and size int dequeue(Queue* queue) { if (isEmpty(queue)) return INT_MIN; int item = queue->array[queue->front]; queue->front = (queue->front + 1) % queue->capacity; queue->size = queue->size - 1; return item; } // Function to get front of queue int front(Queue* queue) { if (isEmpty(queue)) return INT_MIN; return queue->array[queue->front]; } // Function to get rear of queue int rear(Queue* queue) { if (isEmpty(queue)) return INT_MIN; return queue->array[queue->rear]; } Queue* command_file(Queue* queue){ FILE* fp; char cmd[1024]; int data = 0; fp = fopen(FILE_NAME, "r"); while(1) { fscanf(fp, "%s", cmd); if(!strcmp(cmd, "ENQUEUE")){ fscanf(fp, "%d", &data); enqueue(queue, data); } else if(!strcmp(cmd, "DEQUEUE")) dequeue(queue); else if(!strcmp(cmd, "FRONT")) printf("Front item is %d\n", front(queue)); else if(!strcmp(cmd, "REAR")) printf("Rear item is %d\n", rear(queue)); else if(!strcmp(cmd, "END")) break; } fclose(fp); } int main(){ Queue* queue = createQueue(100); command_file(queue); return 0; }
C
#include "physbot.h" #include "quadratic.h" #include "../physics.h" #include "../dr.h" #include "../cvxgen/solver.h" #include <math.h> // Angles of each wheel relative to the front of the bot. // TODO: these should actually be measured. const float rel_wheel_angles[4] = { 30, 120, -30, -120 }; void build_M_matrix(PhysBot pb, dr_data_t state, float M[3][4]) { int wheel_spin_direction; if (pb.rot.disp >= 0) { wheel_spin_direction = 1; } else { wheel_spin_direction = -1; } int i; for (i = 0; i < 4; i++) { float radians = rel_wheel_angles[i] * P_PI / 180.0f; float wheel_direction = state.angle + radians + (P_PI / 2.0f); float wheel_vector[2] = { cos(wheel_direction), sin(wheel_direction) }; float major_row = dot2D(pb.major_vec, wheel_vector); float minor_row = dot2D(pb.minor_vec, wheel_vector); M[0][i] = major_row; M[1][i] = minor_row; M[2][i] = wheel_spin_direction; } } void to_1d_matrix(float Q[4][4]) { int i; int j; int k = 0; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { params.Q[k] = Q[i][j]; k++; } } } void build_c_matrix(float a_req[3], float M[3][4], float c[4]) { int i; int j; for (i = 0; i < 4; i++) { c[i] = 0; } // loop each M col for (j = 0; j < 4; j++) { // loop each M row for (i = 0; i < 3; i++) { c[j] += (double) (a_req[i] * M[i][j]); } c[j] = 2 * c[j]; } } void transpose_qp(float M[3][4], float M_T[4][3]) { int i; int j; for (i = 0; i < 3; i++) { for (j = 0; j < 4; j++) { M_T[j][i] = M[i][j]; } } } void build_Q_matrix(float M[3][4], float M_T[4][3], float Q[4][4]) { int i; int j; int k; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { Q[i][j] = 0.0f; for (k = 0; k < 3; k++) { Q[i][j] += M_T[i][k] * M[k][j]; } } } } void put_c_matrix_in_params(float c[4]) { for (int i = 0; i < 4; i++) { params.c[i] = c[i]; } } /** * TODO: Figure out the units for the matrices so we make sure * that we get accelerations out of the optimization. */ void quad_optimize(PhysBot pb, dr_data_t state, float a_req[3]) { float M[3][4]; float M_T[4][3]; float Q[4][4]; float c[4]; build_M_matrix(pb, state, M); transpose_qp(M, M_T); build_c_matrix(a_req, M, c); put_c_matrix_in_params(c); build_Q_matrix(M, M_T, Q); set_defaults(); setup_indexing(); to_1d_matrix(Q); solve(); double x = *vars.x; // TODO: remove this print statement once we figure out what // parameters we need from the solver printf("%f\n", x); }
C
//To read a sorted array and search for an element using binary search #include <stdio.h> #include <conio.h> int main() { int a[30],n,i,t,low,mid,high,found=0; printf("Enter the number of elements:"); scanf("%d",&n); printf("\n Enter the elements of the array:"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\n Enter the element to search:"); scanf("%d",&t); low=0; high=n-1; while(high>=low) { mid=(low+high)/2; if(a[mid]==t) { found=1; break; } else if(t<a[mid]) { high=mid-1; } else { low=mid+1; } } if(found==0) { printf("not found"); } else { printf("\n Found at %d",mid); } }
C
#include "oh/computer/system.h" #include "oh/external/external.h" struct oh_computer_system_t { unsigned long order; oh_computer_logic_f logic; oh_computer_output_t *computations; }; static void compute_with_logic(oh_computer_system_t *system); static void free_computations(oh_computer_system_t *system); static void init_computations(oh_computer_system_t *system); void compute_with_logic(oh_computer_system_t *system) { assert(system); unsigned long each_computation; for (each_computation = 0; each_computation < system->order; each_computation++) { system->logic(each_computation, system->computations + each_computation); } } oh_computer_output_t *oh_computer_system_compute(oh_computer_system_t *system, unsigned long input) { return system->computations + input; } oh_computer_system_t *oh_computer_system_create(unsigned long order, oh_computer_logic_f logic) { oh_computer_system_t *system; system = malloc(sizeof *system); if (system) { system->order = order; system->logic = logic; system->computations = malloc(order * sizeof(oh_computer_output_t)); if (system->computations) { init_computations(system); compute_with_logic(system); } else { h_core_trace("malloc"); free(system); system = NULL; } } else { h_core_trace("malloc"); } return system; } oh_computer_system_t *oh_computer_system_create_from_file(char *filename) { h_core_trace_exit("TODO: implement"); return NULL; } void oh_computer_system_destroy(void *system_object) { assert(system_object); oh_computer_system_t *system; system = system_object; free_computations(system); free(system->computations); free(system); } char *oh_computer_system_get_as_string(void *system_object) { assert(system_object); oh_computer_system_t *system; unsigned long string_size; char *string; unsigned long each_computation; unsigned long each_bit; unsigned long string_position; oh_computer_output_t *output; h_core_bit_t bit; system = system_object; string_size = (OH_COMPUTER_OUTPUT_BITS + 1) * system->order; string = malloc(string_size + 1); if (string) { string_position = 0; for (each_computation = 0; each_computation < system->order; each_computation++) { for (each_bit = 0; each_bit < OH_COMPUTER_OUTPUT_BITS; each_bit++) { output = system->computations + each_computation; bit = *(output->bits + each_bit); if (bit) { *(string + string_position) = '1'; } else { *(string + string_position) = '0'; } string_position++; } *(string + string_position) = '\n'; string_position++; } *(string + string_position) = '\0'; } else { h_core_trace("malloc"); } return string; } void oh_computer_system_print(oh_computer_system_t *system) { assert(system); char *string; string = oh_computer_system_get_as_string(system); if (string) { printf("%s", string); free(string); } else { h_core_trace("oh_computer_system_get_as_string"); } } h_core_bool_t oh_computer_system_save_as_file(oh_computer_system_t *system, char *filename) { h_core_trace_exit("TODO: implement"); return h_core_bool_false; } void free_computations(oh_computer_system_t *system) { unsigned long each_computation; for (each_computation = 0; each_computation < system->order; each_computation++) { oh_computer_output_free(system->computations + each_computation); } } void init_computations(oh_computer_system_t *system) { unsigned long each_computation; for (each_computation = 0; each_computation < system->order; each_computation++) { oh_computer_output_init(system->computations + each_computation); } }
C
#include <stdio.h> #include <stdlib.h> int main() { float exorcismProcess=0.2; int flyNumber; float exorcismSpeed=5; float fatigueTime=5; float flyReturnSpeed=3; int exorcismTime=0; float flyResidue; printf("Vvedite chislo myh:"); scanf("%d", &flyNumber); while (flyNumber>0) { ++exorcismTime; flyResidue=flyNumber-exorcismSpeed+flyReturnSpeed; flyNumber=flyResidue; if (exorcismTime==5) { exorcismSpeed-=exorcismSpeed*exorcismProcess; } printf("%.0f\n", flyResidue); } printf("%d", exorcismTime); return 0; }
C
/*-- Copyright (c) 1996-1997 Microsoft Corporation Module Name: dacls.c Abstract: Extended version of cacls.exe Author: 14-Dec-1996 (macm) Environment: User mode only. Requires ANSI C extensions: slash-slash comments, long external names. Revision History: --*/ #include <windows.h> #include <caclscom.h> #include <dsysdbg.h> #include <stdio.h> #include <aclapi.h> #define CMD_PRESENT(index, list) ((list)[index].iIndex != -1) #define NO_INHERIT_ONLY // // Enumeration of command tags // typedef enum _CMD_TAGS { CmdTree = 0, CmdEdit, CmdContinue, CmdGrant, CmdRevoke, CmdReplace, CmdDeny, CmdICont, CmdIObj, #ifndef NO_INHERIT_ONLY CmdIOnly, #endif CmdIProp } CMD_TAGS, *PCMD_TAGS; VOID Usage ( IN PCACLS_STR_RIGHTS pStrRights, IN INT cStrRights, IN PCACLS_CMDLINE pCmdVals ) /*++ Routine Description: Displays the expected usage Arguments: Return Value: VOID --*/ { INT i; printf("Displays or modifies access control lists (ACLs) of files\n\n"); printf("DACLS filename [/T] [/E] [/C] [/G user:perm] [/R user [...]]\n"); printf(" [/P user:perm [...]] [/D user [...]]\n"); printf(" filename Displays ACLs.\n"); printf(" /%s Changes ACLs of specified files in\n", pCmdVals[CmdTree].pszSwitch); printf(" the current directory and all subdirectories.\n"); printf(" /%s Edit ACL instead of replacing it.\n", pCmdVals[CmdEdit].pszSwitch); printf(" /%s Continue on access denied errors.\n", pCmdVals[CmdContinue].pszSwitch); printf(" /%s user:perms Grant specified user access rights .\n", pCmdVals[CmdGrant].pszSwitch); printf(" /%s user Revoke specified user's access rights (only valid with /E).\n", pCmdVals[CmdRevoke].pszSwitch); printf(" /%s user:perms Replace specified user's access rights.\n", pCmdVals[CmdReplace].pszSwitch); printf(" /%s user:perms Deny specified user access.\n", pCmdVals[CmdDeny].pszSwitch); printf(" /%s Mark the ace as CONTAINER_INHERIT (folder or directory inherit)\n", pCmdVals[CmdICont].pszSwitch); printf(" /%s Mark the ace as OBJECT_INHERIT\n", pCmdVals[CmdIObj].pszSwitch); #ifndef NO_INHERIT_ONLY printf(" /%s Mark the ace as INHERIT_ONLY\n", pCmdVals[CmdIOnly].pszSwitch); #endif printf(" /%s Mark the ace as INHERIT_NO_PROPAGATE\n", pCmdVals[CmdIProp].pszSwitch); printf("The list of supported perms for the Grant and Replace operations are:\n"); for (i = 0; i < cStrRights; i++) { printf(" %c%c %s\n", pStrRights[i].szRightsTag[0], pStrRights[i].szRightsTag[1], pStrRights[i].pszDisplayTag); } printf("\nMultiple perms can be specified per user\n"); printf("Wildcards can be used to specify more that one file in a command.\n"); printf("You can specify more than one user in a command.\n\n"); printf("Example: DACLS c:\\temp /G user1:GRGW user2:SDRC\n"); } INT __cdecl main ( int argc, char *argv[]) /*++ Routine Description: The main the for this executable Arguments: argc - Count of arguments argv - List of arguments Return Value: VOID --*/ { DWORD dwErr = 0; CACLS_STR_RIGHTS pStrRights[] = { "NA", 0, "No Access", "GR", GENERIC_READ, "Read", "GC", GENERIC_WRITE, "Change (write)", "GF", GENERIC_ALL, "Full control", "SD", DELETE, "Delete", "RC", READ_CONTROL, "Read Control", "WP", WRITE_DAC, "Write DAC", "WO", WRITE_OWNER, "Write Owner", "RD", FILE_READ_DATA, "Read Data (on file) / List Directory (on Dir)", "WD", FILE_WRITE_DATA, "Write Data (on file) / Add File (on Dir)", "AD", FILE_APPEND_DATA, "Append Data (on file) / Add SubDir (on Dir)", "FE", FILE_EXECUTE, "Execute (on file) / Traverse (on Dir)", "DC", FILE_DELETE_CHILD, "Delete Child (on Dir only)", "RA", FILE_READ_ATTRIBUTES, "Read Attributes", "WA", FILE_WRITE_ATTRIBUTES, "Write Attributes", "RE", FILE_READ_EA, "Read Extended Attributes", "WE", FILE_WRITE_EA, "Write Extended Attributes" }; INT cStrRights = sizeof(pStrRights) / sizeof(CACLS_STR_RIGHTS); CACLS_CMDLINE pCmdVals[] = { "T", -1, FALSE, 0, // CmdTree "E", -1, FALSE, 0, // CmdEdit "C", -1, FALSE, 0, // CmdContinue "G", -1, TRUE, 0, // CmdGrant "R", -1, TRUE, 0, // CmdRevoke "P", -1, TRUE, 0, // CmdReplace "D", -1, TRUE, 0, // CmdDeny "F", -1, FALSE, 0, // CmdICont "O", -1, FALSE, 0, // CmdIObj #ifndef NO_INHERIT_ONLY "I", -1, FALSE, 0, // CmdIOnly #endif "N", -1, FALSE, 0, // CmdIProp }; INT cCmdVals = sizeof(pCmdVals) / sizeof(CACLS_CMDLINE); INT i; PSECURITY_DESCRIPTOR pInitialSD = NULL, pFinalSD; PACL pOldAcl = NULL, pNewAcl = NULL; DWORD fInherit = 0; BOOL fFreeAcl = FALSE; if (argc < 2) { Usage(pStrRights, cStrRights, pCmdVals); return(1); } else if (argc == 2 && (strcmp(argv[1], "-?") == 0 || strcmp(argv[1], "/?") == 0)) { Usage(pStrRights, cStrRights, pCmdVals); return(0); } // // Parse the command line // dwErr = ParseCmdline(argv, argc, 2, pCmdVals, cCmdVals); if (dwErr != ERROR_SUCCESS) { Usage(pStrRights, cStrRights, pCmdVals); return(1); } // // Set our inheritance flags // if (CMD_PRESENT(CmdICont, pCmdVals)) { fInherit |= CONTAINER_INHERIT_ACE; } if (CMD_PRESENT(CmdIObj, pCmdVals)) { fInherit |= OBJECT_INHERIT_ACE; } #ifndef NO_INHERIT_ONLY if (CMD_PRESENT(CmdIOnly, pCmdVals)) { fInherit |= INHERIT_ONLY_ACE; } #endif if (CMD_PRESENT(CmdIProp, pCmdVals)) { fInherit |= NO_PROPAGATE_INHERIT_ACE; } // // Ok, see if we need to read the existing security // if (CMD_PRESENT(CmdEdit, pCmdVals) || argc == 2) { dwErr = GetNamedSecurityInfoA(argv[1], SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pOldAcl, NULL, &pInitialSD); if (dwErr != ERROR_SUCCESS) { fprintf(stderr, "Failed to read the security off of %s: %lu\n", argv[1], dwErr); } } // // Either display the existing access or do the sets as requested // if (dwErr == ERROR_SUCCESS && argc == 2) { dwErr = DisplayAcl ( argv[1], pOldAcl, pStrRights, cStrRights ); } else { // // Ok, first we do the revokes // if (dwErr == ERROR_SUCCESS && CMD_PRESENT(CmdRevoke, pCmdVals)) { // // Make sure we've read it first... // if (CMD_PRESENT(CmdEdit, pCmdVals)) { dwErr = ProcessOperation( argv, &pCmdVals[CmdRevoke], REVOKE_ACCESS, pStrRights, cStrRights, fInherit, pOldAcl, &pNewAcl ); if (dwErr == ERROR_SUCCESS) { pOldAcl = pNewAcl; } } else { dwErr = ERROR_INVALID_PARAMETER; } } // // Then the grants // if (dwErr == ERROR_SUCCESS && CMD_PRESENT(CmdGrant, pCmdVals)) { // // First, see if we need to free the old acl on completion // if (pOldAcl == pNewAcl) { fFreeAcl = TRUE; } dwErr = ProcessOperation(argv, &pCmdVals[CmdGrant], GRANT_ACCESS, pStrRights, cStrRights, 0, pOldAcl, &pNewAcl); if (dwErr == ERROR_SUCCESS) { if (fFreeAcl == TRUE) { LocalFree(pOldAcl); } pOldAcl = pNewAcl; // // Now set it and optionally propagate it // dwErr = SetAndPropagateFileRights(argv[1], pNewAcl, DACL_SECURITY_INFORMATION, CMD_PRESENT(CmdTree, pCmdVals), CMD_PRESENT(CmdContinue, pCmdVals), TRUE, fInherit); } } // // Finally, the denieds // if (dwErr == ERROR_SUCCESS && CMD_PRESENT(CmdDeny, pCmdVals)) { // // First, see if we need to free the old acl on completion // if (pOldAcl == pNewAcl) { fFreeAcl = TRUE; } dwErr = ProcessOperation(argv, &pCmdVals[CmdDeny], DENY_ACCESS, pStrRights, cStrRights, 0, pOldAcl, &pNewAcl); if (dwErr == ERROR_SUCCESS) { if (fFreeAcl == TRUE) { LocalFree(pOldAcl); } pOldAcl = pNewAcl; // // Now set it and optionally propagate it // dwErr = SetAndPropagateFileRights(argv[1], pNewAcl, DACL_SECURITY_INFORMATION, CMD_PRESENT(CmdTree, pCmdVals), CMD_PRESENT(CmdContinue, pCmdVals), FALSE, fInherit); } } // // Finally, do the set if it hasn't already been done // if (dwErr == ERROR_SUCCESS && !CMD_PRESENT(CmdGrant, pCmdVals) && !CMD_PRESENT(CmdDeny, pCmdVals)) { dwErr = SetAndPropagateFileRights(argv[1], pNewAcl, DACL_SECURITY_INFORMATION, CMD_PRESENT(CmdTree, pCmdVals), CMD_PRESENT(CmdContinue, pCmdVals), FALSE, fInherit); } if (dwErr == ERROR_INVALID_PARAMETER) { Usage(pStrRights, cStrRights, pCmdVals); } LocalFree(pInitialSD); } LocalFree(pOldAcl); if(dwErr == ERROR_SUCCESS) { printf("The command completed successfully\n"); } else { printf("The command failed with an error %lu\n", dwErr); } return(dwErr == 0 ? 0 : 1); }
C
#ifndef STRUKTURY_H #define STRUKTURY_H #define MAX_BUFOR 1024 #define MAX_SKOK 2 #define DZIELNIK 4 #define dPlot_Plot8 DPlot_Plot8 #pragma comment(lib, "Ws2_32.lib") /*Struktura VOL zawierajca dane dotyczce objtoci zbiornika*/ struct VOL { float Czas[MAX_BUFOR]; double Wartosc[MAX_BUFOR]; } Objetosc; /*Struktura TEMP zawierajca dane dotyczce temperatury zbiornika*/ struct TEMP { int Czas[MAX_BUFOR]; double Wartosc[MAX_BUFOR]; } Temperatura; /** * Funkcja Pobieraj_DATA: Pobiera dane z serwera, na podstawie okreslonego zapytania *\param SOCKET ConnectSocket: SOCKETY utworzone w funkcji main *\param Zapytanie[10]: Tablica znakw bdca jednym z ustalonych zapyta. GET_VOL, lub GET_TEMP *\param Argument: Argument z funkcji main, wskazujcy miejsce w tablicy wartosc[MAX_BUFFER], pobierana z ptli for * \return Data: Zmienna typu Double bdca wartoci pobran z serwera, jest ona zapisywana do jednej ze struktur */ double Pobieraj_DATA(SOCKET ConnectSocket, char Zapytanie[10], int Argument); /** * Funkcja TworzPlik: Tworzy plik html bdcy wykresem dwch funkcji *\param VOL: Struktura zawierajca dane pobrane z serwera *\param TEMP: Struktura zawierajca dane pobrane z serwera *\param Argument: Argument z funkcji main, wskazujcy miejsce w tablicy wartosc[MAX_BUFFER], pobierana z ptli for *\param Czas_Pomiar: Czas pobierania danych z serwera okreslony przez uytkownika * \return Void */ void TworzPlik(struct VOL Objetosc, struct TEMP Temperatura, int Argument, int Czas_Pomiar); /** * Funkcja UsunSzumy_TEMP: Usuwa szumy z tablicy temperatury zbiornka *\param TEMP: Struktura zawierajca dane pobrane z serwera *\param Argument: Argument z funkcji main, wskazujcy miejsce w tablicy wartosc[MAX_BUFFER], pobierana z ptli for *\param Czas_Pomiar: Czas pobierania danych z serwera okreslony przez uytkownika * \return Wartosci_BezSzum: Tablica wartosci temperatury zbiornika nie zawierajca szumw */ double UsunSzumy_TEMP(struct TEMP Temperatura, int Czas_Pomiar, int Argument); /** * Funkcja UsunSzumy_VOL: Usuwa szumy z tablicy objtoci zbiornka *\param VOL: Struktura zawierajca dane pobrane z serwera *\param Argument: Argument z funkcji main, wskazujcy miejsce w tablicy wartosc[MAX_BUFFER], pobierana z ptli for *\param Czas_Pomiar: Czas pobierania danych z serwera okreslony przez uytkownika * \return Wartosci_BezSzum: Tablica wartosci objtoci zbiornika nie zawierajca szumw */ double UsunSzumy_VOL(struct VOL Objetosc, int Czas_Pomiar, int Argument); /** * Funkcja Tworz_DPLOT: Tworzy i uruchamia wykres danych, pobranych z serwera, w programie DPlot *\param VOL: Struktura zawierajca dane pobrane z serwera *\param Czas_Pomiar: Czas pobierania danych z serwera okreslony przez uytkownika * \return Void */ void Tworz_DPLOT(struct VOL Objetosc, int Czas_Pomiar); #endif
C
#include <stdio.h> int main() { int pulo, i,cano[101],n,score; scanf("%d %d", &pulo,&n); score = 0; for(i = 1; i<n+1; i++){ scanf("%d", &cano[i]); } for(i= 1; i<n; i++){ if( (cano[i] - cano[i+1] <= pulo) && (cano[i+1] - cano[i] <= pulo)) { score++; } } if(score == n-1){ printf("YOU WIN\n"); }else{ printf("GAME OVER\n"); } return 0; }
C
#include "Common.h" status_t getPath(path_t** path, node_t* file) { node_t* node = cur; if (file) node = file; while (node) { if (pushIntoPath(path, node) == FAIL) { printf("ERROR: unable to add node into path.\n"); return FAIL; } node = node->parent; } return SUCCESS; } status_t pushIntoPath(path_t** root, node_t* node) { path_t* newEl = (path_t*)malloc(sizeof(path_t)); if (!newEl) { printf("ERROR: memory allocation error.\n"); return FAIL; } newEl->node = node; if (!(*root)) newEl->next = NULL; else newEl->next = *root; *root = newEl; return SUCCESS; } status_t printPath(path_t* root) { if (!root) { printf("ERROR: path begin is not defined.\n"); return FAIL; } path_t* el = root; while (el) { printf("%s", el->node->name); if (el->node->type == 'F') printf("/"); else if (el->node->type == 'T') printf(".txt"); el = el->next; } printf("\n"); return SUCCESS; } void deletePath(path_t** root) { path_t* temp = *root; while (*root) { *root = (*root)->next; free(temp); temp = NULL; temp = *root; } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #define PORT "3490" //Port users will connect to #define BACKLOG 15 //How many pending connections queue will store void sigchldHandler(int s){ //save current errno int saved_errno = errno; while(waitpid(-1, NULL, WNOHANG) > 0); errno = saved_errno; } void *getInAddr(struct sockaddr *sa){ if (sa->sa_family == AF_INET) return &( ( (struct sockaddr_in*)sa)->sin_addr); else return &( ( (struct sockaddr_in6*)sa)->sin6_addr); } int main(){ int sockfd , new_fd , rv, yes =1; //Listen on sockfd, new connect on new_fd struct addrinfo hints , *servinfo , *p; struct sockaddr_storage their_addr; //Information of connector's socklen_t sin_size; struct sigaction sa; char s[INET6_ADDRSTRLEN]; memset(&hints , 0 , sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ( (rv = getaddrinfo(NULL , PORT , &hints , &servinfo) ) != 0){ printf("getaddrinfo: %s \n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } printf("Bound to addr: %u\n", ((struct sockaddr_in*)p->ai_addr)->sin_addr.s_addr); freeaddrinfo(servinfo); if (p == NULL ){ //Reached end of list and no connection available printf("server: failed to bind! \n"); exit(1); } if ( listen(sockfd, BACKLOG ) == -1) { perror("listen"); } sa.sa_handler = sigchldHandler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa , NULL) == -1){ perror("sigaction"); exit(1); } printf("server: waiting for connections... \n"); while(1){ //Main accept loop, where it waits for connections sin_size = sizeof(their_addr); new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if ( new_fd == -1){ perror("accept"); continue; } inet_ntop(their_addr.ss_family , getInAddr( (struct sockaddr *)&their_addr), s , sizeof(s)); printf("server: got connection from %s \n", s); if (!fork()){ //child proccess close(sockfd); //child does not need listener if (send(new_fd , "Hello Client!" , 13 , 0) == -1) //send msg size 13 perror("send"); close(new_fd); exit(0); } } return 0; }
C
//限速是通过使进程睡眠实现的,设置一个定时器计算当前的速度, //如果发现大于限定的速度,那么就通过: //睡眠时间 = (当前传输速度 / 最大传输速度-1) * 当前传输时间来计算。 void limit_rate(session_t *sess, int bytes_transfered, int is_upload) { sess->data_process = 1; // 睡眠时间 = (当前传输速度 / 最大传输速度 – 1) * 当前传输时间; long curr_sec = get_time_sec(); long curr_usec = get_time_usec(); double elapsed; elapsed = (double)(curr_sec - sess->bw_transfer_start_sec); elapsed += (double)(curr_usec - sess->bw_transfer_start_usec) / (double)1000000; if (elapsed <= (double)0) { elapsed = (double)0.01; } // 计算当前传输速度 unsigned int bw_rate = (unsigned int)((double)bytes_transfered / elapsed); double rate_ratio; if (is_upload) { if (bw_rate <= sess->bw_upload_rate_max) { // 不需要限速 sess->bw_transfer_start_sec = curr_sec; sess->bw_transfer_start_usec = curr_usec; return; } rate_ratio = bw_rate / sess->bw_upload_rate_max; } else { if (bw_rate <= sess->bw_download_rate_max) { // 不需要限速 sess->bw_transfer_start_sec = curr_sec; sess->bw_transfer_start_usec = curr_usec; return; } rate_ratio = bw_rate / sess->bw_download_rate_max; } // 睡眠时间 = (当前传输速度 / 最大传输速度 – 1) * 当前传输时间; double pause_time; pause_time = (rate_ratio - (double)1) * elapsed; nano_sleep(pause_time); sess->bw_transfer_start_sec = get_time_sec(); sess->bw_transfer_start_usec = get_time_usec(); }
C
#include "proc_signal.h" #include "errhandler.h" #include <stdlib.h> #include <signal.h> #if 1 handler_t* Signal(int signum, handler_t* handler) { struct sigaction action, old_action; action.sa_handler = handler; sigemptyset(&action.sa_mask); /* Block sigs of type being handled */ action.sa_flags = SA_RESTART; /* Restart syscalls, if possible */ if (sigaction(signum, &action, &old_action) < 0) { unix_error("Signal error"); } return (old_action.sa_handler); } #endif
C
#include <stdio.h> int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: ./recover 'name of a forensic image yo recover JPEGs'\n" ); return 1; } char *fi = argv[1]; FILE *inptr = fopen("card.raw", "r"); if (inptr == NULL) { fprintf(stderr, "Could not open %s.\n", fi); return 2; } //define outptr here to fopen later FILE *outptr = NULL; // filename: char array to store the resultant string; 002.jpg char JPEG[8]; // to keep track of number of JPEG files written int JPEGcount = 0; // store 512B blocks in an array, googled how to select data structure to hold buffer in JPEG unsigned char buffer[512]; // need to read 512 bytes at a time // fread(buffer, 1, 512, inptr) == 512 'cos once reach the end, !=512 and will jump out of loop while(fread(buffer, 1, 512, inptr) == 512) { // find beginning of JPEG if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) { sprintf(JPEG, "%03i.jpg", JPEGcount); //MUST NOT CREATE OUTPTR AGAIN 'COS WAS NULL EARLIER ALRD //open JPEG file to be written outptr = fopen(JPEG, "w"); // need to write 512 bytes at a time until a new JPEG is found fwrite(buffer, 1, 512, outptr); JPEGcount++; } else { if(outptr != NULL) { fwrite(buffer, 1, 512, outptr); } } } // close infile fclose(inptr); // success return 0; }
C
#pragma once /*! * \brief Use this to change the Default Settings for each component. Loaded when the Arduino starts, updated by user interaction on the website. * \details The Settings object is stored in EEPROM and kept between reboots. * \author GrowBoxGuy * \version 4.20 * \warning Only use these in the setup() function, or when a user initiated change is stored. EEPROM has a write limit of 100.000 cycles * \attention Never use the funtions defined here in loop() or a repeating cycle! EEPROM would wear out very fast * \attention Update the Version number when you make change to the structure in the SAVED TO EEPROM secton. This will overwrite the EEPROM settings with the sketch defaults. */ static const uint8_t Version = 4; ///< Increment this when you make a change in the SAVED TO EEPROM secton ///State machine - Defining possible states enum PumpStates {DISABLED, IDLE, PRIMING, RUNNING, BLOWOFF, MIXING}; //enum HempyState { DRY, WATERING}; //enum AeroState { SPRAYING }; ///THIS SECTION DOES NOT GET STORED IN EEPROM: ///Global constants static const uint8_t MaxTextLength = 32; ///Default char * buffer for storing a word + null terminator. Memory intense! static const uint8_t MaxShotTextLength = 64; ///Default char * buffer for storing mutiple words. Memory intense! static const int MaxLongTextLength = 256; ///Default char * buffer for storing a long text. Memory intense! static const uint8_t QueueDepth = 8; ///Limits the maximum number of active modules. Memory intense! static const uint8_t RollingAverageDepth = 10; ///Limits the maximum number of active modules. Memory intense! ///Global variables extern char LongMessage[MaxLongTextLength]; ///temp storage for assembling long messages (REST API, MQTT API) extern char ShortMessage[MaxShotTextLength]; ///temp storage for assembling short messages (Log entries, Error messages) extern char CurrentTime[MaxTextLength]; ///buffer for storing current time in text ///nRF24L01+ wireless receiver static const uint8_t WirelessCSNPin = 9; //< Pre-connected on RF-Nano static const uint8_t WirelessCEPin = 10; //< Pre-connected on RF-Nano static const uint8_t WirelessChannel[6] = {"Aero1"}; ///This needs to be unique and match with the Name of the HempyModule_Web object in the Main module static const uint8_t WirelessPayloadSize = 32; //Size of the wireless packages exchanged with the Main module. Max 32 bytes are supported on nRF24L01+ static const uint16_t WirelessMessageTimeout = 500; //Default 0.5sec - One package should be exchanged within this timeout (Including retries and delays) ///SAVED TO EEPROM - Before uploading the schetch increase the Version variable to override whatever is stored in the Arduino's EEPROM typedef struct { bool Debug = true; ///Logs debug messages to serial and web outputs bool Metric = true; ///Switch between Imperial/Metric units. If changed update the default temp and pressure values too. struct AeroModuleSettings { AeroModuleSettings(bool PressureTankPresent = false) : PressureTankPresent(PressureTankPresent) {} bool PressureTankPresent; }; struct AeroModuleSettings AeroModule1 = {.PressureTankPresent = true}; struct AeroponicsSettings { ///Common settings for both inheriting classes: Aeroponics_Tank and Aeroponics_NoTank AeroponicsSettings(bool SprayEnabled = true, int DayInterval = 0, int DayDuration = 0, int NightInterval = 0, int NightDuration = 0, float MaxPressure = 0.0) : SprayEnabled(SprayEnabled), DayInterval(DayInterval), DayDuration(DayDuration), NightInterval(NightInterval), NightDuration(NightDuration), MaxPressure(MaxPressure) {} bool SprayEnabled; ///Enable/disable spraying cycle int DayInterval; ///Spray every X minutes - When the lights are ON int DayDuration; ///Spray time in seconds - When the lights are ON int NightInterval; ///Spray every X minutes - When the lights are OFF int NightDuration; ///Spray time in seconds - When the lights are OFF float MaxPressure; ///Turn off pump above this pressure }; struct AeroponicsSettings AeroT1_Common = {.SprayEnabled= true, .DayInterval=15, .DayDuration = 10, .NightInterval=30, .NightDuration = 8, .MaxPressure = 7.0}; struct AeroponicsSettings AeroNT1_Common = {.SprayEnabled= true, .DayInterval=15, .DayDuration = 10, .NightInterval=30, .NightDuration = 8, .MaxPressure = 7.0}; struct AeroponicsSettings_TankSpecific { ///Settings for an Aeroponics setup WITH a pressure tank AeroponicsSettings_TankSpecific(float MinPressure = 0.0, uint8_t SpraySolenoidPin = 0, bool SpraySolenoidNegativeLogic=false) : MinPressure(MinPressure), SpraySolenoidPin(SpraySolenoidPin), SpraySolenoidNegativeLogic(SpraySolenoidNegativeLogic) {} float MinPressure; ///Turn on pump below this pressure uint8_t SpraySolenoidPin; bool SpraySolenoidNegativeLogic; }; struct AeroponicsSettings_TankSpecific AeroT1_Specific = {.MinPressure = 5.0, .SpraySolenoidPin = 5, .SpraySolenoidNegativeLogic=false}; struct PressureSensorSettings { PressureSensorSettings(uint8_t Pin = 0, float Offset = 0.0, float Ratio = 0.0) : Pin(Pin), Offset(Offset), Ratio(Ratio) {} uint8_t Pin; ///Pressure sensor Pin: Signal(yellow) float Offset; ///Pressure sensor calibration: voltage reading at 0 pressure float Ratio; ///Pressure sensor voltage to pressure ratio }; struct PressureSensorSettings Pres1 = {.Pin = A7, .Offset = 0.57, .Ratio = 2.7}; struct SoundSettings { SoundSettings(uint8_t Pin = 0) : Pin(Pin) {} uint8_t Pin; ///PC buzzer+ (red) bool Enabled = true; ///Enable PC speaker / Piezo buzzer }; struct SoundSettings Sound1 = {.Pin = 2}; ///Default settings for the Sound output struct WaterPumpSettings { WaterPumpSettings(uint8_t PumpPin = 0, bool PumpPinNegativeLogic = false, uint8_t BypassSolenoidPin = 0, bool BypassSolenoidNegativeLogic = false, bool PumpEnabled = false, int PumpTimeOut = 0, int PrimingTime = 0, int BlowOffTime = 0) : PumpPin(PumpPin), PumpPinNegativeLogic(PumpPinNegativeLogic), BypassSolenoidPin(BypassSolenoidPin), BypassSolenoidNegativeLogic(BypassSolenoidNegativeLogic), PumpEnabled(PumpEnabled), PumpTimeOut(PumpTimeOut), PrimingTime(PrimingTime), BlowOffTime(BlowOffTime) {} uint8_t PumpPin; ///< Pump relay pin bool PumpPinNegativeLogic; uint8_t BypassSolenoidPin; ///< Bypass solenoid relay pin bool BypassSolenoidNegativeLogic; bool PumpEnabled; ///< Enable/disable pump. false= Block running the pump int PumpTimeOut; ///< (Sec) Max pump run time int PrimingTime; ///< (Sec) For how long to keep the bypass solenoid on when starting the pump - Remove air bubbles from pump intake side int BlowOffTime; ///< (Sec) For how long to open the bypass solenoid on after turning the pump off - Release pressure from pump discharge side }; struct WaterPumpSettings AeroPump1 = {.PumpPin = 3, .PumpPinNegativeLogic= false, .BypassSolenoidPin = 4, .BypassSolenoidNegativeLogic = false, .PumpEnabled = true, .PumpTimeOut = 120, .PrimingTime = 10, .BlowOffTime = 3}; uint8_t CompatibilityVersion = Version; ///Should always be the last value stored. } Settings; /////////////////////////////////////////////////////////////// ///EEPROM related functions - Persistent storage between reboots ///Use cautiously, EEPROM has a write limit of 100.000 cycles - Only use these in the setup() function, or when a user initiated change is stored void saveSettings(Settings *ToSave); Settings *loadSettings(bool ResetEEPROM = false ); void restoreDefaults(Settings *ToOverwrite);
C
#include <stdio.h> float integral; float prev_error; void controller () { float set_point; float dt; float u; float error = set_point - y; integral += error * dt; float derivative = (error - prev_error) / dt; prev_error = error; u = Kp * error + Ki * integral + Kd * derivative; } int main () { integral = 0; prev_error = 0; printf("Halo Dino"); return 0; }
C
#include "holberton.h" #include "2-strlen.c" #include <stdlib.h> /** * str_concat - Entry point * @s1: String * @s2: String * * Description: Alocate memory adn concatenate 2 strings * Return: Pointer to resault */ char *str_concat(char *s1, char *s2) { int len1 = 0, len2 = 0, totlen = 0, i = 0, j = 0; char *dest; if (s1 != NULL) len1 = _strlen(s1); if (s2 != NULL) len2 = _strlen(s2); totlen = len1 + len2 + 1; dest = malloc(sizeof(char) * totlen); if (dest == NULL) return (NULL); for (i = 0 ; i < len1 ; i++) dest[i] = s1[i]; for (; i < totlen - 1; i++, j++) { dest[i] = s2[j]; } dest[i] = '\0'; return (dest); }
C
//SOMEWHY IT DOESN'T WORK FOR PLAINTEXT: world!$? ..BUT SEEMS TO WORK FOR EVEYTHING ELSE... #include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) { // validity checking if (argc == 2 ) { int local = 0; for (int i = 0, n = strlen(argv[1]); i < n; i++) { if (!(isalpha(argv[1][i]))) { local = 1; break; } } if (local == 0) { printf("Success\n%s\n", argv[1]); } else { printf("Usage: ./vigenere keyword\n"); return 1; } } else { printf("Usage: ./vigenere keyword\n"); return 1; } //changing keyword to an array of ints a = 0, b = 1, ... int key[strlen(argv[1])]; for (int i = 0, n = strlen(argv[1]); i < n; i++) { if (islower(argv[1][i])) { key[i] = (int) (argv[1][i] - 'a'); } else { key[i] = (int) (argv[1][i] - 'A'); } } string plain = get_string("plaintext: "); printf("\n"); int numbers[strlen(plain)]; for (int i = 0, n = strlen(plain); i < n; i++) { if (islower(plain[i])) //check if isupper or islower { numbers[i] = (int) (plain[i] - 'a'); // (int) transforms to ascii - 'a' ??? } //do something with the non-alpha charachters else if (isupper(plain[i])) { numbers[i] = (int) (plain[i] - 'A'); } else { numbers[i] = 30; //just something other } } int new_numbers[strlen(plain)]; for (int i = 0, n = strlen(plain), k = strlen(argv[1]), j = 0; i < n; i++) { if (isalpha(plain[i])) { new_numbers[i] = (numbers[i] + key[ j % k]) % 26; j++; } } //transform "back" everything char cipher[strlen(plain)]; for (int i = 0, n = strlen(plain); i < n; i++) { if (isalpha(plain[i])) { if (islower(plain[i])) //check if isupper or islower { cipher[i] = (char) (new_numbers[i] + 'a'); // (int) transforms to ascii - 'a' ??? } //do something with the non-alpha charachters else if (isupper(plain[i])) { cipher[i] = (char) (new_numbers[i] + 'A'); } else { eprintf("alpha not lower nor upper... idk what that means..\n"); } } else { cipher[i] = plain[i]; } } //output printf("ciphertext: %s\n", cipher); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* data_list.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lbenamer <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/17 18:49:14 by lbenamer #+# #+# */ /* Updated: 2017/04/17 18:49:16 by lbenamer ### ########.fr */ /* */ /* ************************************************************************** */ #include "lemin.h" t_lst *ft_init_lst(void) { t_lst *lst; if (!(lst = (t_lst*)malloc(sizeof(t_lst*)))) return (NULL); lst->line = NULL; lst->start = 0; lst->end = 0; lst->save = NULL; lst->next = NULL; return (lst); } t_lst *ft_new_lst(char *line, int start, int end) { t_lst *room; if (!(room = malloc(sizeof(t_lst)))) return (NULL); room->line = ft_strdup(line); room->start = start; room->end = end; room->next = NULL; return (room); } t_lst *ft_add_lst(t_lst *room, char *line, int start, int end) { t_lst *tmp; tmp = room; if (!room->line) { room = ft_new_lst(line, start, end); return (room); } else { while (tmp->next != NULL) tmp = tmp->next; tmp->next = ft_new_lst(line, start, end); } return (room); } t_lst *ft_new_fil(char *room, char *prev) { t_lst *fil; if (!(fil = (t_lst*)malloc(sizeof(t_lst)))) return (NULL); fil->line = room; fil->prev = prev; fil->next = NULL; return (fil); } t_lst *ft_add_fil(t_lst *fil, char *room, char *prev) { t_lst *tmp; tmp = fil; if (!fil->line) { fil = ft_new_fil(room, prev); return (fil); } else { while (tmp->next != NULL) tmp = tmp->next; tmp->next = ft_new_fil(room, prev); } return (fil); }
C
#include "common.h" #include "uart.h"//Don't use the UART! It disables my interrupts. #include "oc.h" #include "timer.h" #include "ui.h" #include <p24FJ128GB206.h> #include "pin.h" #include "keymap.h" #define MAX_OUTPUT 2^15 #define MOTOR_BASE_SPEED MAX_OUTPUT>>8 #define SERVO 8 #define KEYBOARD_CLOCK 12//green #define KEYBOARD_DATA 7//blue #define MOTOR 6 #define DISPLAY 9 //for TS53 servo, change if we change servos #define INTERVAL .02 #define MAXWIDTH .003 #define MINWIDTH .0006 //control constants #define START 'b' #define END 'c' #define FLIP_SERVO 'd' #define SLOW_MOTOR 'e' #define ACCEL_MOTOR 'f' //motor speeds #define SLOWER 0 #define FASTER 1 //keyboard reading variables volatile uint8_t data; volatile uint8_t new_command = 0; volatile uint8_t started, bits; volatile int bit_count = 0; volatile int keyup = 0;//was the last code a keyup code? int flip(int flipped){ if(flipped){ pin_write(&D[SERVO],MAX_OUTPUT); return 0; } else{ pin_write(&D[SERVO],0); return 1; } } uint16_t calc_speed(uint16_t speed, int m_dir){ if(m_dir && speed < MAX_OUTPUT){//go faster return speed << 1; } else if(!m_dir && speed > 0) {//go slower return speed >> 1; } else{ return speed; } } void main(void){ init_oc(); init_timer(); init_ui(); init_pin(); //init_uart(); //switch controller, shouldn't do anything char input = 'a'; pin_digitalOut(&D[DISPLAY]); pin_digitalOut(&D[SERVO]); pin_digitalOut(&D[MOTOR]); pin_clear(&D[MOTOR]); //keyboard pins pin_digitalIn(&D[KEYBOARD_CLOCK]);//clock input-blue pin_digitalIn(&D[KEYBOARD_DATA]);//data input-green //keyboard interrupt INTCON2bits.INT4EP = 1;//interrupt on negative edge INTCON1bits.NSTDIS = 1;//no nested interrupts IEC3bits.INT4IE = 1;//enable interrupt RPINR2bits.INT4R = 0x17;//set interrupt to RPin 23 IFS3bits.INT4IF = 0;//clear flag //servo values int flipped = 0; //servo pins oc_servo(&oc2,&D[SERVO], &timer2,INTERVAL,MINWIDTH,MAXWIDTH,0); //motor driving OC oc_pwm(&oc1, &D[MOTOR], &timer1, 500, 65536 >> 1); //motor variables uint16_t speed = 65536 >> 1; led_on(&led3); while(1){ //read the keyboard if(new_command){ input = keymap[data]; //grab character from array new_command = 0; //uart_putc(&uart1,input); } switch(input){ case START: //start the timer pin_set(&D[DISPLAY]); input = 'a'; case END: //stop the timer pin_clear(&D[DISPLAY]); pin_set(&D[DISPLAY]); input = 'a'; case FLIP_SERVO: flipped = flip(flipped); input = 'a'; case ACCEL_MOTOR: speed = calc_speed(speed, FASTER); pin_write(&D[MOTOR],speed); input = 'a'; case SLOW_MOTOR: speed = calc_speed(speed, SLOWER); pin_write(&D[MOTOR],speed); input = 'a'; } } } void __attribute__((interrupt, no_auto_psv)) _INT4Interrupt(void){//keyboard interrupt led_toggle(&led2); if(!started){ if(!pin_read(&D[KEYBOARD_DATA])){ started = 1; data = 0; new_command = 0; return; } } else if(bit_count<=8){ data |=(pin_read(&D[KEYBOARD_DATA])<<bit_count); bit_count++; return; } else{ bit_count = 0; started = 0; if(keyup){ keyup = 0; return; } if(data == 240){ keyup = 1; return; } new_command = 1; } IFS3bits.INT4IF = 0;//clear flag }
C
#include<stdio.h> #include<math.h> //#include<gsl_integration.h> #include<gsl/gsl_integration.h> double f(double x, void* params){ double func = (log(x)/sqrt(x)); return func; } double ing() { gsl_function F; F.function = &f; int limit = 999; gsl_integration_workspace* w = gsl_integration_workspace_alloc(limit); double a=0, b=1, acc=1e-6, eps=1e-6, result, error; gsl_integration_qags(&F, a, b, acc, eps, limit, w, &result, &error); gsl_integration_workspace_free(w); return result; } double f_erf(double x, void* params){ double f = 2/sqrt(M_PI)*exp(-pow(x,2)); return f; } double erf(double z){ gsl_function F; F.function =&f_erf; int limit = 999; gsl_integration_workspace* w = gsl_integration_workspace_alloc(limit); double a=0, acc=1e-6, eps=1e-6, result, error; gsl_integration_qags(&F, a, z, acc, eps, limit, w, &result, &error); gsl_integration_workspace_free(w); return result; } int main(){ printf("Exercise A: Integration the function gives %g and when I use an online calculator I get the same result\n",ing()); FILE* erf_plot= fopen("erf.data.txt","w"); for(double z=-5;z<=5;z+=0.1){ fprintf(erf_plot,"%10g %10g\n",z,erf(z)); } fclose(erf_plot); printf("\nI also made Exercise B.\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> void test() { printf("cur func : %s ; cur line : %d\n", __FUNCTION__, __LINE__); return; } void main() { printf("cur file : %s ; cur func : %s ; cur line : %d\n", __FILE__, __FUNCTION__, __LINE__); test(); return; } /* $ a.exe cur file : 1.c ; cur func : main ; cur line : 12 cur func : test ; cur line : 6 * */
C
/** ***************************************************** @brief USB, USB Communication library functions @file com.c @author Alexander Borg @version 1.0 @date 29-November-2019 @brief Source code for USB communication ***************************************************** */ #include <usb.h> /** @brief usb_send_data, sends an amount of data in blocking mode using UART over USB. @param char *, pointer to char array holding the data to send @return void, no return value */ void usb_send_data(char * data) { char * data_terminator = "\n\r"; char * buffer = strcat(data, data_terminator); HAL_UART_Transmit(&huart5, (uint8_t *)buffer, strlen(buffer), 100); } /** @brief usb_get_data, receives an amount of data in blocking mode using UART over USB @param void, no parameters @return char *, a pointer to a char array of length 6 with the data received. */ char * usb_get_data() { static char buffer[6]; HAL_UART_Receive(&huart5, (uint8_t *)buffer, 6, 10000); return buffer; }
C
/* * The expression that specifies the width of a bit-field shall be an integer * constant expression that has nonnegative value that shall not exceed the * number of bits in an object of the type that is specified if the colon and * expression are omitted. If the value is zero, the declaration shall have no * declarator. */ struct S1 { unsigned int a : 10.5; /* error */ }; int n; double d; struct S2 { unsigned int b : n; /* error */ unsigned int c : d; /* error */ }; struct S3 { unsigned int d : -5; /* error */ }; struct S4 { unsigned int e : 33; /* error */ }; struct S5 { unsigned int f : 0; /* error */ };
C
/*Caesar’s algorithm encrypts messages by "rotating" each letter by "k" positions. * If "p" is some plaintext, pi is the ith character in p, and k is a secret key (non-negative integer), then each letter, ci, in the ciphertext, c, is computed as ci=(pi+k)mod26 ci=(pi+k)mod26 wherein mod26 here means "remainder when dividing by 26." */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <cs50.h> int main (int argc,string argv[]) { if (argc!=2) { printf ("Usage: ./caesar positiveinteger \n"); return 1; } else if (argv[1] != NULL) { //make sure it's positive and bigger than 0 int k = atoi(argv[1]); if (k < 0){ printf ("Usage : integer has to be bigger than 0 " ); return 1 ; } //if k is greater than 26, alphabetical characters in your program’s input should remain alphabetical characters in your program’s output. else if (k > 26){ int x=k; k = x%26; } //once i have the k value i prompt the user for plaintext string s = get_string("plaintext: "); if (s == NULL) { return 1; } //now we need to apply the caesar logic in order to provide the ciphered text printf("ciphertext: "); for (int i=0,j=strlen(s); i<j;i++){ if (s[i] <=90){ int ascii=s[i]+k; if (ascii >90){ int sustrato=26-k; ascii = ascii-sustrato-k; s[i]=ascii; printf("%c", s[i]); } else { printf("%c", s[i]+k); } } if (s[i]>=97){ int ascii=s[i]+k; if (ascii>122){ int sustrato=26-k; ascii = ascii-sustrato-k; s[i]=ascii; printf("%c", s[i]); } else { printf("%c", s[i]+k); } } } printf ("\n"); } }
C
// POS50-C: Compliant Solution (Allocated Storage) void *childThread(void *val) { /* Correctly prints 1 */ int *res = (int *)val; printf("Result: %d\n", *res); free(res); return NULL; } void createThread(pthread *tid) { int result; /* Copy data into dynamic memory */ int *val = malloc(sizeof(int)); if (!val) { /* Handle error */ } *val = 1; if ((result = pthread_create(&id, NULL, childThread, val)) != 0) { /* Handle error */ } } int main(void) { pthread_t tid; int result; createThread(&tid); if ((result = pthread_join(tid, NULL)) != 0) { /* Handle error */ } return 0; }
C
#include "tinyfx.h" #include <stdio.h> #include <SDL2/SDL.h> #include <assert.h> #include <sys/signal.h> #include <stdlib.h> #define INTERNAL_RES 240 void *read_file(const char *filename) { FILE *f = fopen(filename, "r"); if (f) { fseek(f, 0L, SEEK_END); int bytes = ftell(f); rewind(f); char *buf = malloc(bytes+1); buf[bytes] = '\0'; fread(buf, 1, bytes, f); fclose(f); return buf; } printf("Unable to open file \"%s\"\n", filename); return NULL; } typedef struct state_t { uint16_t width; uint16_t height; uint16_t internal_width; uint16_t internal_height; SDL_Window *window; SDL_GLContext context; int dead; } state_t; int poll_events(state_t *state); void run(state_t *state) { tfx_reset(state->width, state->height); // tfx_dump_caps(); tfx_canvas fb = tfx_canvas_new(state->internal_width, state->internal_height, TFX_FORMAT_RGB565_D16); tfx_view v = tfx_view_new(); tfx_view_set_canvas(&v, &fb); tfx_view_set_clear_color(&v, 0xff00ffff); tfx_view_set_clear_depth(&v, 1.0); tfx_view back = tfx_view_new(); tfx_view_set_clear_color(&back, 0x555555ff); tfx_view_set_clear_depth(&back, 1.0); tfx_view_set_depth_test(&back, TFX_DEPTH_TEST_LT); char *vss = read_file("shader.vs.glsl"); char *fss = read_file("shader.fs.glsl"); if (!vss || !fss) { vss = read_file("test/shader.vs.glsl"); fss = read_file("test/shader.fs.glsl"); } assert(vss); assert(fss); const char *attribs[] = { "a_position", "a_color", NULL }; tfx_program prog = tfx_program_new(vss, fss, attribs); free(vss); free(fss); tfx_view *views[] = { &v, &back, NULL }; float verts[] = { 0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f }; tfx_vertex_format fmt = tfx_vertex_format_start(); tfx_vertex_format_add(&fmt, 3, false, TFX_TYPE_FLOAT); tfx_vertex_format_add(&fmt, 4, true, TFX_TYPE_FLOAT); tfx_vertex_format_end(&fmt); tfx_buffer vbo = tfx_buffer_new(verts, sizeof(verts), TFX_USAGE_STATIC, &fmt); tfx_uniform u = tfx_uniform_new("u_texture", TFX_UNIFORM_INT, 1); int uv[] = { 0 }; tfx_uniform_set_int(&u, uv); while (!state->dead) { state->dead = poll_events(state); // tfx_touch(&v); tfx_touch(&back); // tfx_blit(&v, &back, 0, 0, tfx_view_get_width(&back), tfx_view_get_height(&back)); tfx_set_vertices(&vbo, 3); tfx_set_state(0); tfx_submit(&back, prog, false); // process command buffer tfx_frame(views); SDL_GL_SwapWindow(state->window); } tfx_shutdown(); } int poll_events(state_t *state) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE ) { return 1; } switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { return 1; } default: break; } } return 0; } static state_t *g_state = NULL; void sigh(int signo) { if (signo == SIGINT) { g_state->dead = 1; puts(""); } // Make *SURE* that SDL gives input back to the OS. if (signo == SIGSEGV) { SDL_Quit(); } } #include <SDL2/SDL_opengl.h> typedef void (APIENTRY *DEBUGPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, void* userParam); typedef void (APIENTRY *DEBUGMSG)(DEBUGPROC callback, const void* userParam); DEBUGMSG glDebugMessageCallback = 0; static void debug_spew(GLenum s, GLenum t, GLuint id, GLenum sev, GLsizei len, const GLchar *msg, void *p) { printf("GL DEBUG: %s\n", msg); } int main(int argc, char **argv) { state_t state; memset(&state, 0, sizeof(state_t)); g_state = &state; SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); state.window = SDL_CreateWindow( "", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL ); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); // So that desktops behave consistently with RPi SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); state.context = SDL_GL_CreateContext(state.window); SDL_GL_GetDrawableSize( state.window, (int*)&state.width, (int*)&state.height ); SDL_GL_MakeCurrent(state.window, state.context); glDebugMessageCallback = (DEBUGMSG)SDL_GL_GetProcAddress("glDebugMessageCallback"); if (glDebugMessageCallback) { puts("GL debug enabled"); glDebugMessageCallback(&debug_spew, NULL); } float aspect = (float)state.width / state.height; state.internal_width = INTERNAL_RES*aspect; state.internal_height = INTERNAL_RES; printf("Display resolution: %dx%d\n", state.width, state.height); printf("Internal resolution: %dx%d\n", state.internal_width, state.internal_height); SDL_SetRelativeMouseMode(1); SDL_GL_SetSwapInterval(1); assert(signal(SIGINT, sigh) != SIG_ERR); run(&state); SDL_Quit(); return 0; }
C
/* * Copyright (c) 2014-2015 André Erdmann <[email protected]> * * Distributed under the terms of the MIT license. * (See LICENSE.MIT or http://opensource.org/licenses/MIT) */ #ifndef _COMMON_DYNSTR_H_ #define _COMMON_DYNSTR_H_ #include <stdlib.h> #include <sys/types.h> #ifndef DEFAULT_DYNSTR_SIZE enum { /** initial capacity of a dynstr_data object */ DEFAULT_DYNSTR_SIZE = 32 }; #endif /** * dynamically allocated data object type */ struct dynstr_data { /** pointer to the actual str */ char* data; /** number of currently used objects */ size_t current_size; /** current capacity of the the data object */ size_t max_size; }; /** * Initializes a dynamically allocated str data object. * * @param pdata pointer to a dynstr struct (should not be NULL) * @param initial_size initial capacity of the data structure (>= 0) * * @return 0 on success, else non-zero */ __attribute__((warn_unused_result)) int dynstr_data_init ( struct dynstr_data* const pdata, const size_t initial_size ); /** * Resizes a dynamically allocated str data object so that it has enough room * for at least min_size chars. No-op if there's already enough space * available. * * Frees the data if reallocation failed. * * @param pdata pointer to a dynstr struct (must not be NULL) * @param min_size requested size * * @return 0 on success, else non-zero */ __attribute__((warn_unused_result)) int dynstr_data_resize ( struct dynstr_data* const pdata, const size_t min_size ); /** * Resizes a dynamically allocated str data object so that it has enough room * for at least current_size + num_size chars. * No-op if there's already enough space available. * * Frees the data if reallocation failed. * * @param pdata pointer to a dynstr struct (must not be NULL) * @param num_items number of additional objects that should fit into * the dynstr struct (>0) * * @return 0 on success, else non-zero */ __attribute__((warn_unused_result)) int dynstr_data_grow ( struct dynstr_data* const pdata, const size_t num_items ); /** * Detaches the str from a dynamically allocated str data object (by setting * it to NULL) and resets the size counters. * Optionally stores the str in the given data_out pointer (if not NULL). * * @param pdata pointer to a dynstr struct (must not be NULL) * @param data_out pointer to a data pointer or NULL * *data_out should point to NULL */ void dynstr_data_unref ( struct dynstr_data* const pdata, char** const str_out ); /** * Destructs a dynamically allocated str object, freeing its memory. * * @param pdata pointer to a dynstr struct (must not be NULL) */ void dynstr_data_free ( struct dynstr_data* const pdata ); /** * Appends a str to a dynamically allocated str data object. * Optionally converts chars using the given function. * Chars for which the function returns NULL get filtered out. * * NOTE: may allocate considerably more space than required if convert_char() * filters out many..all chars. * * @param pdata pointer to a dynstr struct (must not be NULL) * @param str_len length of the input str * @param pstr input str * @param convert_char function pointer or NULL * * @return 0 on success, else non-zero */ int dynstr_data_append_str ( struct dynstr_data* const pdata, const size_t str_len, const char* const pstr, const char* (*convert_char) (size_t, const char*) ); /** * Same as dynstr_data_append_str(pdata, strlen(pstr), pstr, NULL). * (= just append that str.) */ int dynstr_data_append_str_simple ( struct dynstr_data* const pdata, const char* const pstr ); /** * Like dynstr_data_append_str_simple(), but appends a "join sequence" * (another string) before pstr if the dynstr is not empty. */ int dynstr_data_sjoin_append ( struct dynstr_data* const pdata, const char* const join_seq, const size_t join_seq_len, const char* const pstr ); /** * Like dynstr_data_append_str_simple(), * but appends a single char before pstr if the dynstr is not empty. */ int dynstr_data_cjoin_append ( struct dynstr_data* const pdata, const char join_chr, const char* const pstr ); /** * Appends a single char to a dynamically allocated str data object. * * @param pdata pointer to a dynstr struct (must not be NULL) * @param chr char to append * * @return 0 on success, else non-zero */ int dynstr_data_append_char ( struct dynstr_data* const pdata, const char chr ); /** * Removes whitespace characters and filters non-printable chars at the end * of the given dynstr object. * * @param pdata pointer to a dynstr struct (must not be NULL) * * @return 0 on success, else non-zero */ int dynstr_data_rstrip ( struct dynstr_data* const pdata ); /** * Returns the str stored in a struct dynstr_data*. * * Likely to be removed or replaced by a macro in future. */ char* dynstr_data_get ( struct dynstr_data* pdata ); /** * Sets the first char of a dynstr to '\0' and resets its length to 0. * This effectively "empties" the str (--insecure--). * * @param pdata * * @return always 0 */ int dynstr_data_truncate ( struct dynstr_data* pdata ); /** * Appends a null char '\0' to a dynstr. * Resizes the str if necessary. * * @param pdata * * @return 0 on success, else non-zero */ int dynstr_data_append_null ( struct dynstr_data* pdata ); #endif /* _COMMON_DYNSTR_H_ */
C
//编写一段程序,像下面那样读取一个整数并显示该整数加上12之后的结果。 #include <stdio.h> int main(void){ int a; printf("输入一个整数:"); scanf("%d", &a); printf("整数加上12的结果是%d\n", 12 + a); return 0; }
C
//#include <stdio.h> //#include <stdlib.h> // ///* //creator: //time:2015/9/12 //place:xust //*/ // //#define _TYPE int //typedef struct _node //{ // _TYPE data;// // struct _node *next; //}listlink,*pzlistlink; // ////ʼ //pzlistlink Initlistlink() //{ // pzlistlink head; // if(!(head=(pzlistlink)malloc(sizeof(pzlistlink)))) // return NULL ; // head->next=NULL; // return head; //} ////bool ////жǷǿ // //int IsEmptylistlink(pzlistlink head) //{ // if(head->next==NULL) // return 1; // return 0; //} // ////ҵiѽڵ //pzlistlink Get(pzlistlink head,int i) //{ // pzlistlink p; // int j; // if(IsEmptylistlink(head)) // return NULL; // if(i<1) // return NULL; // j=0; // p=head; // while(p->next!=NULL&&j<i) // { // p=p->next; // j++; // } // if(j==i) // return p; // else // return NULL;//ûҵiԪ // //} // ////ԪeԪ //pzlistlink Location_Postion_List(pzlistlink head,_TYPE value) //{ // pzlistlink p; // _TYPE data; // if(IsEmptylistlink(head)) // return NULL; // p=head; // while(p->data!=value&&p->next!=NULL) // { // p=p->next; // } // if(p->data==value) // return p;//ҵָԪ // else // return NULL;//ҲָԪ // //} // ////λ //int Location_Pos(pzlistlink head,_TYPE value) //{ // pzlistlink p; // int i=0; // p=head; // if(IsEmptylistlink(head)) // return -1; // while(p) // { // if(p->data!=value) // {p=p->next; // i++; // } // else // break; // } // if(p->data==value) // return i; // else // return 0; //} // //// ////ڵĵiλòԪe //int insert_list(pzlistlink head,int __j/*j1ʼ*/,_TYPE e) //{ // pzlistlink p,q; // int i; // p=head; // i=0; // while (p->next!=NULL&&i<__j-1)//ؼһ // { // p=p->next; // i++; // } // if(i!=__j-1)//˲λõķΧ // { // printf("λô"); // return 0; // } // if((q=(pzlistlink)malloc(sizeof(listlink)))==NULL) // exit(-1); // q->data=e; // q->next=p->next; // p->next=q; // return 1; //} // //int Del_list_Element(pzlistlink head,int i) //{ // pzlistlink p,q; // int j=0; // p=head; // while(p->next!=NULL&&j<i-1&&p->next->next!=NULL) // { // p=p->next; // j++; // } // if(j!=i-1) // { // printf("ɾλò"); // exit(-1); // } // q=p->next; // //*e=p->next->data; // p->next=q->next; // free(q); // return 1; // // //} // ////ij //int getlength(pzlistlink head) //{ // int i=0; // pzlistlink p; // p=head; // while(p->next!=NULL) // { // p=p->next; // i++; // } // return i; //} // //// //void destory(pzlistlink head) //{ // pzlistlink p,q; // p=head; // while(p!=NULL) // { // q=p; // p=p->next; // free(q); // q=NULL; // } //} //// //void printfallelement(pzlistlink head) //{ // pzlistlink p; // p=head; // while(p->next!=NULL) // { // p=p->next; // printf("%d ",p->data); // } //}
C
#include <stdio.h> #include <sys/resource.h> #include<unistd.h> int main() { int i=1; pid_t child; child=fork(); for(i=1;;i++) { child=fork(); printf("child=%d/n",i); if(child<0) break; } printf("Total forked:%d",i); return 0; }
C
/** * code for sudoku functionality * Authors: Antony 1, Spring 5/27/2020 * */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <time.h> #include "sudokustruct.h" #include "intpair.h" /* sudoku data structure */ typedef struct sudoku { int puzzle[9][9]; } sudoku_t; sudoku_t* new_sudoku(){ int grid[9][9]; sudoku_t *game = calloc(1, sizeof(grid)); if(game == NULL){ fprintf(stderr, "Error: cannot allocate space for sudoku. \n"); return NULL; } #ifdef GAUNTLET printf("Created new 9x9 sudoku\n"); #endif return game; } /* sudoku_validate helper functions */ int *check_row(sudoku_t *sudoku, int row); int *check_col(sudoku_t *sudoku, int col); int *check_box(sudoku_t *sudoku, int row, int col); int *find_options(int array[]); /* other helper functions */ bool check_full(sudoku_t *sudoku); bool check_empty(sudoku_t *sudoku); int *get_options(sudoku_t *sudoku, int row, int col); void copy_puzzle(sudoku_t *dest, sudoku_t *source); bool fill_puzzle(sudoku_t *sudoku, int row, int col); bool remove_squares(sudoku_t *sudoku, int remove); bool sudoku_validate(sudoku_t *sudoku, int row, int column); /* Takes in from stdin, loads into the sudoku data structure */ bool sudoku_load(sudoku_t *sudoku) { // loop through all the numbers in the board for(int row = 0; row < 9; row++){ for(int col = 0; col < 9; col++){ int num; if(fscanf(stdin, " %d", &num) != 1){ //checks stdin has 81 numbers fprintf(stderr, "Error: invalid sudoko board.\n"); return false; } //check validity if(num < 0 || num > 9){ fprintf(stderr, "Error: invalid sudoko entry.\n"); return false; } //add to data structure sudoku->puzzle[row][col] = num; } } #ifdef GAUNTLET printf("Successfully loaded sudoku\n"); #endif return true; } /* takes an empty sudoku and populates it randomly * clues is the number of filled squares at the end */ bool sudoku_build(sudoku_t *sudoku, int clues) { // make sure the supplied sudoku is empty if (! check_empty(sudoku)) { return false; } // seed the random number generator srand(time(NULL)); /* construct a solved/full grid * starts from the top left corner and moves left to right, then top to bottom */ fill_puzzle(sudoku, 0, 0); // remove spaces to turn the full grid into a puzzle remove_squares(sudoku, 81 - clues); #ifdef GAUNTLET printf("Successfully built sudoku\n"); #endif return true; } /* fills an empty sudoku puzzle randomly with a valid full grid * helper for sudoku_build */ bool fill_puzzle(sudoku_t *sudoku, int row, int col) { // if puzzle is full, return true (base case) if (check_full(sudoku)) { return true; } // find valid entries for the sqquare [row][col] int *options = get_options(sudoku, row, col); // determine the number of valid options int valid = 0; for (int i = 0; i < 9; i++) { if (options[i] == 1) { valid++; } } // if valid is 0, there are no valid options for this square and we need to backtrack! if (valid == 0) { free(options); return false; } /* turn the array from get_options into a form which can be randomly iterated over more easily * allocate an int array that can hold one entry per valid option for the spot */ int *formatted_options = calloc(valid, sizeof(valid)); /* add each valid number into the array * ex: if 2, 4, 7 were valid, resultant array is: { 2, 4, 7 } * j will end up equaling the last valid index into the array */ int j = 0; for (int i = 0; i < 9; i++) { if (options[i] == 1) { formatted_options[j] = i + 1; j++; } } free(options); // randomly select an int from formatted_options and insert it into the square int original_num = rand() % j; int num = original_num; sudoku->puzzle[row][col] = formatted_options[num]; /* grab the row and col to move to the next spot (moving left to right, then top to bottom) * (save them as new values instead of incrementing the current ones because the old values are * still needed in order to retry fill_puzzle with a different value in the current square) */ int next_row, next_col; if (col == 8) { next_col = 0; next_row = row + 1; } else { next_col = col + 1; next_row = row; } while (! fill_puzzle(sudoku, next_row, next_col)) { // move on to the next index in formatted_options (if we get to the end (j - 1), go back to the start) if (num == j - 1) { num = 0; } else { num++; } // replace the current value in the puzzle with the next one sudoku->puzzle[row][col] = formatted_options[num]; // if num gets back to original_num, we've tried every option and none of them worked ... return false if (num == original_num) { // clean up sudoku->puzzle[row][col] = 0; free(formatted_options); return false; } } // clean up free(formatted_options); return true; } /* turns a full grid into a valid puzzle with the specified number of squares removed * uses backtracking to find a puzzle with a unique solution * the boolean returned is leveraged for use in recursion, and the original call will * return true upon the successfu creation of a puzzle */ bool remove_squares(sudoku_t *sudoku, int remove) { // determine the number of squares left to empty int removed = 0; for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (sudoku->puzzle[row][col] == 0) { removed++; } } } // base cases if (sudoku_solve(sudoku, false) != 1) { // backtrack if sudoku doesn't have a unique solution return false; } else if (removed == remove) { // if we get here, we're finished return true; } // allocate an array with space for an intpair * for every filled square intpair_t **options = calloc(81 - removed, sizeof(intpair_t *)); // fill the array with an intpair containing the position of every nonzero/filled spot int filled = 0; for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (sudoku->puzzle[row][col] != 0) { options[filled] = new_intpair(row, col); filled++; } } } // take a random square from options, save its value, and remove it int original_index = rand() % filled; int index = original_index; // note the starting index so that later we can tell if we have tried every square int row = intpair_getRow(options[index]); int col = intpair_getCol(options[index]); int value = sudoku->puzzle[row][col]; sudoku->puzzle[row][col] = 0; // recursive case ... if what we inserted invalidates the puzzle, try different options until we have a unique solution again while (sudoku_solve(sudoku, false) != 1 || ! remove_squares(sudoku, remove)) { // restore the old value (removing it caused an issue!) sudoku->puzzle[row][col] = value; // grab the next nonzero square from options if (index == filled - 1) { // wrap back to the start of the array index = 0; } else { index++; } // check if we have already tried and failed to find a unique solution for every spot (backtrack if we have) if (index == original_index) { for (int i = 0; i < filled; i++) { intpair_delete(options[i]); } free(options); return false; } // if we still have spots to try, take the next row and col from options and try that spot row = intpair_getRow(options[index]); col = intpair_getCol(options[index]); // save the value there value = sudoku->puzzle[row][col]; // empty the square/set the position to zero sudoku->puzzle[row][col] = 0; } // clean up and return true for (int i = 0; i < filled; i++) { intpair_delete(options[i]); } free(options); return true; } bool sudoku_solve_forwards(sudoku_t *sudoku) { //check to see if the grid needs solving if(check_full(sudoku)){ return true; } //go through the entire board for(int row = 0; row < 9; row++){ for(int col = 0; col < 9; col++){ //check if sudoko square is empty if(sudoku->puzzle[row][col] == 0){ //loop through all possible values // find valid entries for the spot [row][col] int *options = get_options(sudoku, row, col); // determine the number of valid options int valid = 0; for (int i = 0; i < 9; i++) { if (options[i] == 1) { valid++; } } // if valid is 0, there are no valid options for this square and we need to backtrack! if (valid == 0) { free(options); return false; } int *formatted_options = calloc(valid, sizeof(int)); // add each valid number into the array int j = 0; for (int i = 0; i < 9; i++) { if (options[i] == 1) { formatted_options[j] = i + 1; j++; } } free(options); //now try to solve sudoku for(int val = 0; val < valid; val++){ //try placing a value sudoku->puzzle[row][col] = formatted_options[val]; //clean up arrays if(sudoku_validate(sudoku, row, col)){ //valid place //recursive call if(sudoku_solve_forwards(sudoku)){ free(formatted_options); return true; } } } if(formatted_options != NULL){ free(formatted_options); } sudoku->puzzle[row][col] = 0; //means couldn't find a number to place return false; } } } return false; } bool sudoku_solve_backwards(sudoku_t *sudoku) { //check to see if the grid needs solving if(check_full(sudoku)){ return true; } //go through the entire board for(int row = 0; row < 9; row++){ for(int col = 0; col < 9; col++){ //check if sudoko square is empty if(sudoku->puzzle[row][col] == 0){ // find valid entries for the spot [row][col] int *options = get_options(sudoku, row, col); // determine the number of valid options int valid = 0; for (int i = 0; i < 9; i++) { if (options[i] == 1) { valid++; } } // if valid is 0, there are no valid options for this square and we need to backtrack! if (valid == 0) { free(options); return false; } int *formatted_options = calloc(valid, sizeof(int)); // add each valid number into the array int j = 0; for (int i = 0; i < 9; i++) { if (options[i] == 1) { formatted_options[j] = i + 1; j++; } } free(options); //now try to solve sudoku for(int val = valid-1; val >= 0; val--){ //try placing a values sudoku->puzzle[row][col] = formatted_options[val]; if(sudoku_validate(sudoku, row, col)){ //valid place //recursive call if(sudoku_solve_backwards(sudoku)){ free(formatted_options); return true; } } } if(formatted_options != NULL){ free(formatted_options); } sudoku->puzzle[row][col] = 0; //means couldn't find a number to place return false; } } } return false; } /* solve overall */ int sudoku_solve(sudoku_t* sudoku, bool print){ sudoku_t* one = new_sudoku(); sudoku_t* two = new_sudoku(); copy_puzzle(one, sudoku); copy_puzzle(two, sudoku); //solve both puzzle copies forward and backwards if(!sudoku_solve_forwards(one) || !sudoku_solve_backwards(two)){ //unable to solve board sudoku_delete(one); sudoku_delete(two); return 0; } //print the answer if(print){ sudoku_print(two); } #ifdef GAUNTLET sudoku_print(one); printf("-----\n"); sudoku_print(two); #endif //go through the entire board to compare outputs for(int row = 0; row < 9; row++){ for(int col = 0; col < 9; col++){ if(one->puzzle[row][col] != two->puzzle[row][col]){ //means more than one board solution sudoku_delete(one); sudoku_delete(two); return 2; } } } sudoku_delete(one); sudoku_delete(two); return 1; //default one board solution } /* helper for sudoko_solve */ bool check_full(sudoku_t *sudoku){ for(int row = 0; row < 9; row++){ for(int col = 0; col < 9; col++){ if(sudoku->puzzle[row][col] == 0){ return false; } } } return true; } /* helper for sudoku_load */ bool check_empty(sudoku_t *sudoku) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (sudoku->puzzle[row][col] != 0) { return false; } } } return true; } bool sudoku_print(sudoku_t *sudoku) { if(sudoku == NULL) { return false; } // Print the the puzzle for (int r = 0; r < 9; r++) { for (int c = 0; c < 9; c++) { fprintf(stdout, "%d ", sudoku->puzzle[r][c]); } fprintf(stdout, "\n"); } return true; } bool sudoku_delete(sudoku_t *sudoku) { if(sudoku != NULL) { free(sudoku); return true; } return false; } /* sudoku_validate method */ // checks that there are no collisions for the row, column, and square around the current point bool sudoku_validate(sudoku_t *sudoku, int row, int column){ // check sudoku exists if (sudoku == NULL){ // throw error and return false fprintf(stderr, "error: must pass valid sudoku board\n"); return false; } // call check_row, col, and square int *rowoptions = check_row(sudoku, row); int *coloptions = check_col(sudoku, column); int *squareoptions = check_box(sudoku, row, column); if (rowoptions == NULL || coloptions == NULL || squareoptions == NULL){ // clean up if (rowoptions != NULL) { free(rowoptions); } if (coloptions != NULL) { free(coloptions); } if (squareoptions != NULL) { free(squareoptions); } // return false if any of them failed return false; } // clean up free(rowoptions); free(coloptions); free(squareoptions); // return true return true; } /* get_options method * returns an array of ints indicating which numbers are valid entries for a specified square * array returned by get_options is dynamically allocated and needs to be freed by the user * 1 means that a number is valid, 0 means that it is not * example array if 1, 3, 6, 8 and 9 are valid options and 2, 4, 5, and 7 are not: * { 1, 0, 1, 0, 0, 1, 0, 1, 1, } */ int *get_options(sudoku_t *sudoku, int row, int col){ // check that the board is not null if (sudoku == NULL){ // throw an error and return NULL fprintf(stderr, "error: must pass valid sudoku board\n"); return NULL; } // call check row, col, and square int *rowoptions = check_row(sudoku, row); int *coloptions = check_col(sudoku, col); int *squareoptions = check_box(sudoku, row, col); // initialize an array for options int *options = malloc(sizeof(int) * 9); // loop through indices, check if each element is found in all options arrays for (int i = 0; i < 9; i++){ if (rowoptions[i] == 1 && coloptions[i] == 1 && squareoptions[i] == 1){ // add this element to the overarching options array options[i] = 1; } else { options[i] = 0; } } // cleanup free(rowoptions); free(coloptions); free(squareoptions); /* NOTE: THE INDICES IN THE RETURNED OPTIONS ARRAY CORRESPOND TO AVAILABLE * NUMBERS BUT ARE OFFSET BY 1 (SO INDEX 0 CORRESPONDS TO 1, ETC) */ return options; } /* check_row helper method */ int *check_row(sudoku_t *sudoko, int row){ // create array for checking row int rowcount[9] = { 0 }; // loop through the row and check that each integer only occurs once (except for 0) for (int colnum = 0; colnum < 9; colnum++){ // get the int at this spot int num = sudoko->puzzle[row][colnum]; //printf("checking row: %d col: %d, num is %d\n", row, colnum, num); // don't check if the num is 0 if (num != 0){ // check the count in the rowcount array if (rowcount[num - 1] != 0){ // return NULL if we've already seen this num return NULL; } // otherwise, increment the count rowcount[num - 1] += 1; } } // get the options for what int can go in this square int *options = find_options(rowcount); // return the options array if no collisions found return options; } /* check_col helper method */ int *check_col(sudoku_t *sudoko, int col){ // create array for checking col int colcount[9] = { 0 }; // loop through the row and check that each integer only occurs once (except for 0) for (int rownum = 0; rownum < 9; rownum++){ // get the int at this spot int num = sudoko->puzzle[rownum][col]; //printf("checking row: %d col: %d, num is %d\n", rownum, col, num); // don't check if the num is 0 if (num != 0){ // check the count in the colcount array if (colcount[num - 1] != 0){ // return NULL if we've seen this num return NULL; } // otherwise, increment the count colcount[num - 1] += 1; } } // get the options for what int can go in this square int *options = find_options(colcount); // return the options array if no collisions found return options; } /* check_box helper method */ int *check_box(sudoku_t *sudoku, int row, int col){ // variables for the row and column bottom left corner int rowcorner; int colcorner; // array for checking ints in the square int squarecount[9] = { 0 }; // get the row number for the bottom left corner of the square if (row < 3){ rowcorner = 0; } else if (row < 6){ rowcorner = 3; } else{ rowcorner = 6; } // get the column number for the square's bottom left corner if (col < 3){ colcorner = 0; } else if (col < 6){ colcorner = 3; } else{ colcorner = 6; } // loop through the square for (int x = rowcorner; x < rowcorner + 3; x++){ for (int y = colcorner; y < colcorner + 3; y++){ // get the number at the current square int num = sudoku->puzzle[x][y]; //printf("checking row: %d col: %d, num is %d\n", x, y, num); // don't check if the num is 0 if (num != 0){ // check the count in the colcount array if (squarecount[num - 1] != 0){ // return NULL return NULL; } // otherwise, increment the count squarecount[num - 1] += 1; } } } // get the options for what int can go in this square int *options = find_options(squarecount); // return the options array if no collisions found return options; } /* find_options helper method */ // find the numbers that can go in a particular spot, given the count array int *find_options(int array[]){ // initialize an array with all zeros int *options = malloc(sizeof(int) * 9); // loop through the passed array for (int i = 0; i < 9; i++){ // if any of the indices store 0, add this index to the options array if (array[i] == 0){ options[i] = 1; } else { options[i] = 0; } } return options; } // copies the puzzle from source into the puzzle in dest void copy_puzzle(sudoku_t *dest, sudoku_t *source) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { dest->puzzle[row][col] = source->puzzle[row][col]; } } } // Testing code. Run it through the mega gauntlet #ifdef GAUNTLET int main() { //future test code here printf("Testing the sudoku_solve()....\n"); sudoku_t* puzzle = new_sudoku(); sudoku_load(puzzle); int res = sudoku_solve(puzzle, true); if(res == 0){ fprintf(stdout, "No solutions. \n"); } else if (res == 1){ fprintf(stdout, "One solution. \n"); } else{ fprintf(stdout, "Two or more solutions. \n"); } return 0; } #endif #ifdef TESTCREATE int main() { sudoku_t *sudoku = new_sudoku(); printf("Test random creation"); sudoku_build(sudoku); sudoku_print(sudoku); return 0; } #endif
C
#include "servidor.h" int main() { int id, status; id = msgget( IPC_KEY, IPC_CREAT | IPC_EXCL | 0666 ); exit_on_error(id, "Erro no msgget."); printf("Estou a usar a fila de mensagens id=%d\n", id); mensagem m; while(1) { status = msgrcv(id, &m, sizeof(m.conteudo), MSG_TYP, 0); exit_on_error(status, "erro ao receber"); printf("Recebi de %s a msg: %s\n", m.conteudo.nome, m.conteudo.texto); m.tipo = m.conteudo.pid; sprintf(m.conteudo.texto, "Sr(a) %s recebi a sua msg", m.conteudo.nome); status = msgsnd(id, &m, sizeof(m.conteudo), 0); exit_on_error(status, "erro ao enviar"); } }
C
#include <stdio.h> int main (void){ int x, y; while(scanf("%d %d", &x, &y) != EOF){ if(x>=y){ printf("%d\n", x-y); } if(x<y){ printf("%d\n", y-x); } } return 0; }
C
#include <stdio.h> int main(){ printf("a=%d ; b=%d ; c=%d ; d=%d ; e=%d ; f=%d ; g=%d ; h=%d\n", 1, 2, 3, 4, 5, 6, 7, 8) ; return 0; };
C
#include<stdio.h> int a[100][100]; int min(int a,int b){ if(a>b) return b; return a; } void warshall(int a[][100],int n) { int i,j,k; for(k=1;k<=n;k++){ for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ a[i][j]=min(a[i][j],a[i][k]+a[k][j]); } } } printf("shortest paths are \n"); for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ printf("%d ",a[i][j]); } printf("\n"); } } int main() { int n,i,j; printf("enter no of vertices"); scanf("%d",&n); // *a=(int*)malloc((n+1)*sizeof(int)); printf("enter array elements"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&a[i][j]); warshall(a,n); /* for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ printf("%d ",a[i][j]); } printf("\n"); }*/ return 0; }
C
#define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <stddef.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> #include "queue.h" #include "/home/fas/hpcprog/ahs3/cpsc424/utils/timing/timing.h" #define DEBUG 0 #define INF -1 typedef struct s_adj_node{ int vertex; int weight; struct s_adj_node* next; } adj_node; /*Moore's Algorithm*/ int N; // number of vertices int* sources; // source node int num_sources; omp_lock_t dist_lock, queue_lock; adj_node** adj_listhead; int count[8]; void process(int vi, int* dist, queue* pq, bool* isInQueue){ adj_node* vj_p = adj_listhead[vi]; // Loop over edges out of vi while(vj_p){ int vj = vj_p -> vertex; int newdist_vj; bool needToUpdate; // Do this if new distance is smaller { newdist_vj = dist[vi] + vj_p->weight;// new distance throught vi needToUpdate = (newdist_vj < dist[vj]) || (dist[vj] == INF); } { if(needToUpdate){ omp_set_lock(&queue_lock); dist[vj] = newdist_vj; if(isInQueue[vj] == false){ q_enqueue(vj, pq); isInQueue[vj] = true; } omp_unset_lock(&queue_lock); } vj_p = vj_p -> next; } } } int moore(int source){ // distance between source vertex and current vertex int* dist; bool* isInQueue; queue q; // Initialize dist =(int *) malloc((N+1) * sizeof(int)); isInQueue =(bool *) malloc((N+1) * sizeof(bool)); for(int i = 1; i <= N; i++) dist[i] = INF; for(int i = 1; i <= N; i++) isInQueue[i] = false; // queue is empty q_init(&q); dist[source] = 0; q_enqueue(source, &q); // Loop over entries in queue while(true){ #pragma omp parallel shared(dist, adj_listhead, q, dist_lock, queue_lock) #pragma omp single while(!q_isEmpty(&q)){ int vi; omp_set_lock(&queue_lock); vi = q_dequeue(&q); isInQueue[vi] = false; omp_unset_lock(&queue_lock); #pragma omp task { count[omp_get_thread_num()]++; process(vi, dist, &q, isInQueue); } } // All done // implicit barrier // all tasks should be finished below this line if(q_isEmpty(&q)) break; } if(DEBUG){ printf("source = %d, ", source); printf("%d %d %d", dist[1], dist[N-1], dist[N]); printf("\n"); } free(dist); free(isInQueue); } void adj_list_add(int vertex, int weight, adj_node** adj_head){ adj_node* node = (adj_node*)malloc(sizeof(adj_node)); node -> vertex = vertex; node -> weight = weight; node -> next = NULL; while(*adj_head != NULL){ adj_head = &((*adj_head) -> next); } *adj_head = node; } void print_adj_list(adj_node** adj_head, int n){ for(int i = 1; i <= n; i++){ printf("%d: ", i); adj_node * node = adj_head[i]; while(node != NULL){ printf("%d -> ", node->vertex); node = node -> next; } printf("NULL\n"); } } void readGraph(char* filename){ FILE* fp; int num_nodes, num_edges; int start, end, weight; char tmp[10]; char* line; size_t len = 100; fp = fopen(filename, "r"); if(fp == NULL){ printf("can not open graph file %s\n", filename); return ; } line = (char*)malloc(sizeof(char) * len); while(getline(&line, &len, fp) != -1){ if(line[0] == 'c') continue; // comment line if(line[0] == 'p'){ // program line sscanf(line, "%s %s %d %d", tmp, tmp, &num_nodes, &num_edges); N = num_nodes; // initialization adj_listhead = (adj_node**)malloc(sizeof(adj_node**) * (N + 1)); for(int i = 1; i <= N; i++) adj_listhead[i] = NULL; }else if(line[0] == 'a'){ // data line sscanf(line, "%s %d %d %d", tmp, &start, &end, &weight); adj_list_add(end, weight, &adj_listhead[start]); } } fclose(fp); free(line); } bool readSource(char* filename){ FILE* fp; char tmp[10]; char* line; size_t len = 100; int source; int idx; fp = fopen(filename, "r"); if(fp == NULL){ printf("can not open source file %s\n", filename); return false; } line = (char*)malloc(sizeof(char) * len); while(getline(&line, &len, fp) != -1){ if(line[0] == 'c') continue; else if(line[0] == 'p'){ sscanf(line, "%s %s %s %s %d", tmp, tmp, tmp, tmp, &num_sources); sources = (int*)malloc(sizeof(int) * num_sources); idx = 0; }else if(line[0] == 's'){ sscanf(line, "%s %d", tmp, &source); sources[idx++] = source; } } fclose(fp); free(line); } int main(int argc, char **argv ) { /* This is the shortest path project for CPSC424/524. Author: Bo Song, Yale University Date: 4/25/2016 Credits: This program is based on the description provided by Andrew Sherman */ double wct0, wct1, total_time, cput; char* sourceFile, * graphFile; for(int i = 0; i < 8; i++) count[i] = 0; #pragma omp parallel printf("num of threads = %d\n", omp_get_num_threads()); if(argc != 3){ printf("serial <graphfile> <sourcefile>\n"); return -1; } graphFile = argv[1]; sourceFile = argv[2]; timing(&wct0, &cput); printf("reading graph...\n"); readGraph(graphFile); printf("reading source...\n"); readSource(sourceFile); // print_adj_list(adj_listhead, N); omp_init_lock(&dist_lock); omp_init_lock(&queue_lock); for(int i = 0; i < num_sources; i++){ // if(DEBUG) // printf("Computing source %d\n", sources[i]); moore(sources[i]); } for(int i = 1; i <=N; i++){ adj_node* node = adj_listhead[i]; while(node){ adj_node* next = node->next; free(node); node = next; } } free(sources); timing(&wct1, &cput); //get the end time total_time = wct1 - wct0; printf("Message printed by master: Total elapsed time is %f seconds.\n",total_time); printf("Thread load balance: "); for(int i = 0; i < 8; i++){ printf("%d ", count[i]); } printf("\n"); }
C
/// ===================================================================================== /// /// Filename: ejson.h /// /// Description: a easier way to handle json, you can also using it as a simple dic /// /// 1. we using list and dict to handle items in list and obj /// 2. we recorded the item which you accessed last time in list, we'll search /// from the recorded item in next time /// /// Version: 1.1 /// Created: 12/18/2016 08:51:34 PM /// Revision: none /// Compiler: gcc /// /// Author: Haitao Yang, [email protected] /// Company: /// /// ===================================================================================== #ifndef __EJSON_H__ #define __EJSON_H__ #include "etype.h" #include "eobj.h" #include "estr.h" #ifdef __cplusplus extern "C" { #endif /** ----------------------------------------------------- * * ejson basic * */ eobj ejson_new(etypeo type, eval v); // create a ejson obj eobj ejson_parseS (constr json); // parse str to ejson obj eobj ejson_parseSEx(constr json, constr* err, eopts opts); // parse str to ejson obj eobj ejson_parseF (constr path); // parse file to ejson obj eobj ejson_parseFEx(constr path, constr* err, eopts opts); // parse file to ejson obj uint ejson_checkS (constr json); // check if json format is correct in str, returns the checked obj's cnt uint ejson_checkSEx(constr json, constr* err, eopts opts); // check if json format is correct in str, returns the checked obj's cnt uint ejson_checkF (constr path); // check if json format is correct in file, returns the checked obj's cnt uint ejson_checkFEx(constr path, constr* err, eopts opts); // check if json format is correct in filr, returns the checked obj's cnt int ejson_clear (eobj r); // clear a ejson obj, only effect on EOBJ and EARR int ejson_clearEx(eobj r, eobj_rls_ex_cb rls, eval prvt); // clear a ejson obj, only effect on EOBJ and EARR int ejson_free (eobj o); // release a ejson obj, including all children int ejson_freeEx(eobj o, eobj_rls_ex_cb rls, eval prvt); // release a ejson obj, including all children etypeo ejson_type (eobj o); uint ejson_size (eobj o); // Returns the size of ESTR or ERAW or number of items in EOBJ or EARR, else return 0 bool ejson_isEmpty(eobj o); // Returns false if ejson contains items, otherwise return true void ejson_show(ejson r); constr ejson_errp(); constr ejson_err (); /** ----------------------------------------------------- * * ejson add * * @note * 1. if root obj to add to is a ARR obj, the key from * param of obj/src will never check, use the exist key in * obj or src. * * 2. if root obj to add to is a OBJ obj, must have a * key from param or obj/src, if key is set in param, the * key in obj/src will always be replaced by it * * 3. see 'ejson val's note to get the meaning of 'k', * 'i', 'p' APIs. * */ eobj ejson_addJ(eobj r, constr key, constr json); // parse a json to obj and add it to root eobj ejson_addT(eobj r, constr key, etypeo type); // add an obj to root, the obj can be defined as EFLASE, ETURE, ENULL, EARR, EOBJ eobj ejson_addI(eobj r, constr key, i64 val ); // add an NUM obj to root eobj ejson_addF(eobj r, constr key, f64 val ); // add an NUM obj to root eobj ejson_addS(eobj r, constr key, constr str ); // add a STR obj to root eobj ejson_addP(eobj r, constr key, conptr ptr ); // add a PTR obj to root eobj ejson_addR(eobj r, constr key, uint len ); // add a RAW obj to root, alloc a new space(len) for data eobj ejson_addO(eobj r, constr key, eobj o ); // add an exist obj to obj eobj ejson_rAddJ(eobj r, constr rawk, constr key, constr json); // add an json obj to specific obj in root via rawk eobj ejson_rAddT(eobj r, constr rawk, constr key, etypeo type); // add an type obj to specific obj in root via rawk, only support EFLASE, ETURE, ENULL, EARR, EOBJ eobj ejson_rAddI(eobj r, constr rawk, constr key, i64 val ); // add an NUM obj to specific obj in root via rawk eobj ejson_rAddF(eobj r, constr rawk, constr key, f64 val ); // add an NUM obj to specific obj in root via rawk eobj ejson_rAddS(eobj r, constr rawk, constr key, constr str ); // add a STR obj to specific obj in root via rawk eobj ejson_rAddP(eobj r, constr rawk, constr key, conptr ptr ); // add a PTR obj to specific obj in root via rawk eobj ejson_rAddR(eobj r, constr rawk, constr key, uint len ); // add a RAW obj to specific obj in root via rawk, alloc a new space(len) for data eobj ejson_rAddO(eobj r, constr rawk, constr key, eobj o ); // add an exist obj to specific obj in root via rawk eobj ejson_iAddJ(eobj r, u32 idx , constr key, constr json); // add an json obj to specific obj in root via idx eobj ejson_iAddT(eobj r, u32 idx , constr key, etypeo type); // add an type obj to specific obj in root via idx, only support EFLASE, ETURE, ENULL, EARR, EOBJ eobj ejson_iAddI(eobj r, u32 idx , constr key, i64 val ); // add an NUM obj to specific obj in root via idx eobj ejson_iAddF(eobj r, u32 idx , constr key, f64 val ); // add an NUM obj to specific obj in root via idx eobj ejson_iAddS(eobj r, u32 idx , constr key, constr str ); // add a STR obj to specific obj in root via idx eobj ejson_iAddP(eobj r, u32 idx , constr key, conptr ptr ); // add a PTR obj to specific obj in root via idx eobj ejson_iAddR(eobj r, u32 idx , constr key, uint len ); // add a RAW obj to specific obj in root via idx, alloc a new space(len) for data eobj ejson_iAddO(eobj r, u32 idx , constr key, eobj o ); // add an exist obj to specific obj in root via idx eobj ejson_pAddJ(eobj r, constr path, constr key, constr json); // add an json obj to specific obj in root via path eobj ejson_pAddT(eobj r, constr path, constr key, etypeo type); // add an type obj to specific obj in root via path, only support EFLASE, ETURE, ENULL, EARR, EOBJ eobj ejson_pAddI(eobj r, constr path, constr key, i64 val ); // add an NUM obj to specific obj in root via path eobj ejson_pAddF(eobj r, constr path, constr key, f64 val ); // add an NUM obj to specific obj in root via path eobj ejson_pAddS(eobj r, constr path, constr key, constr str ); // add a STR obj to specific obj in root via path eobj ejson_pAddP(eobj r, constr path, constr key, conptr ptr ); // add a PTR obj to specific obj in root via path eobj ejson_pAddR(eobj r, constr path, constr key, uint len ); // add a RAW obj to specific obj in root via path, alloc a new space(len) for data eobj ejson_pAddO(eobj r, constr path, constr key, eobj o ); // add an exist obj to specific obj in root via path /** ----------------------------------------------------- * * ejson val * * get obj or val from a ejson obj * * @note * * 1. we have three race of APIs: * * RACE MEAN KEY_TYPE SUPPORT * --------------------------------- * r raw key constr EOBJ/EARR * i idx uint EARR * p path constr EOBJ/EARR * * * for r race APIs, we consider rawk as a whole key and * can not be splited * * for p race APIs, we consider path as a continues key * chan like "fruits[0].name", then we will found the target * like this: 'fruits' -> '0' -> 'name'. * * { * "fruits[0].name" : "tomato", * -------- * ^---------------------------- k found this * * "fruits": [ {"name":"apple"}, {"name":"pear"} ] * ------- * ^--------------------------- p found this * } * * 3. for p race APIs, you can split a key with '.' or '[]', * they are simply the same: * * fruits[0].name : fruits -> 0 -> name * fruits.0[name] : fruits -> 0 -> name * fruits.0.[name] : fruits -> 0 -> "" -> name * * 4. for p race APIs, the key in '[]' can not be split again * * fruits[0.name] : fruits -> 0.name * * @return * ejson_kisTrue: * Returns true if the val in eobj is likely true: * 1. the type of obj is ETRUE * 2. the val of i64 or f64 is not 0 * 3. the ptr val is not 0 * 4. the str val is not empty * 5. the len of raw is not 0 */ //! rawkey eobj ejson_r (eobj r, constr rawk); // Returns the eobj with the specific rawk i64 ejson_rValI (eobj r, constr rawk); // Returns the value i64 of eobj if exist and type matchs ENUM, else return 0 f64 ejson_rValF (eobj r, constr rawk); // Returns the value f64 of eobj if exist and type matchs ENUM, else return 0 constr ejson_rValS (eobj r, constr rawk); // Returns the cstr of eobj if exist and type matchs EPTR, else return 0 cptr ejson_rValP (eobj r, constr rawk); // Returns the ptr of eobj if exist and type matchs ESTR, else return 0 cptr ejson_rValR (eobj r, constr rawk); // Returns the ptr of raw in eobj if exist and type matchs ERAW, else return 0 etypeo ejson_rType (eobj r, constr rawk); // Returns eobj's type if exist, else return EOBJ_UNKNOWN constr ejson_rTypeS (eobj r, constr rawk); // Returns eobj's type in string type uint ejson_rLen (eobj r, constr rawk); // Returns eobj's len if found and type matchs ESTR, ERAW, EOBJ, EARR else return 0 bool ejson_rIsTrue(eobj r, constr rawk); // Returns true if the val in eobj is likely true //! idx eobj ejson_i (eobj r, uint idx); // Returns the eobj in the specific idx i64 ejson_iValI (eobj r, uint idx); // Returns the value i64 of eobj if exist and type matchs ENUM, else return 0 f64 ejson_iValF (eobj r, uint idx); // Returns the value f64 of eobj if exist and type matchs ENUM, else return 0 constr ejson_iValS (eobj r, uint idx); // Returns the cstr of eobj if exist and type matchs EPTR, else return 0 cptr ejson_iValP (eobj r, uint idx); // Returns the ptr of eobj if exist and type matchs ESTR, else return 0 cptr ejson_iValR (eobj r, uint idx); // Returns the ptr of raw in eobj if exist and type matchs ERAW, else return 0 etypeo ejson_iType (eobj r, uint idx); // Returns eobj's type if exist, else return EOBJ_UNKNOWN constr ejson_iTypeS (eobj r, uint idx); // Returns eobj's type in string type uint ejson_iLen (eobj r, uint idx); // Returns eobj's len if found and type matchs ESTR, ERAW, EOBJ, EARR else return 0 bool ejson_iIsTrue(eobj r, uint idx); // Returns true if the val in eobj is likely true //! path eobj ejson_p (eobj r, constr path); // Returns the eobj with the specific path i64 ejson_pValI (eobj r, constr path); // Returns the value i64 of eobj if exist and type matchs ENUM, else return 0 f64 ejson_pValF (eobj r, constr path); // Returns the value f64 of eobj if exist and type matchs ENUM, else return 0 constr ejson_pValS (eobj r, constr path); // Returns the cstr of eobj if exist and type matchs EPTR, else return 0 cptr ejson_pValP (eobj r, constr path); // Returns the ptr of eobj if exist and type matchs ESTR, else return 0 cptr ejson_pValR (eobj r, constr path); // Returns the ptr of raw in eobj if exist and type matchs ERAW, else return 0 etypeo ejson_pType (eobj r, constr path); // Returns eobj's type if exist, else return EOBJ_UNKNOWN constr ejson_pTypeS (eobj r, constr path); // Returns eobj's type in string type uint ejson_pLen (eobj r, constr path); // Returns eobj's len if exist and type matchs ESTR, ERAW, EOBJ, EARR else return 0 bool ejson_pIsTrue(eobj r, constr path); // Returns true if the val in eobj is likely true /** ----------------------------------------------------- * * ejson format * * @param * opts - can be EO_COMPACT or EO_PRETTY * * @note * if passed in 'out' is 0, create and returned a new * buf, else write to it; * */ estr ejson_toS (eobj o, estr* out, eopts opts); estr ejson_kToS(eobj o, constr rawk, estr* out, eopts opts); estr ejson_iToS(eobj o, u32 idx , estr* out, eopts opts); estr ejson_pToS(eobj o, constr path, estr* out, eopts opts); /** ----------------------------------------------------- * * ejson take and free * */ eobj ejson_takeH(eobj r); // for EOBJ, EARR eobj ejson_takeT(eobj r); // for EOBJ, EARR eobj ejson_takeO(eobj r, eobj o); // for EOBJ, EARR eobj ejson_takeR(eobj r, constr rawk); // for EOBJ, EARR eobj ejson_takeI(eobj r, int idx); // for EARR eobj ejson_takeP(eobj r, constr path); // for EOBJ, EARR int ejson_freeH(eobj r); // for EOBJ, EARR int ejson_freeT(eobj r); // for EOBJ, EARR int ejson_freeO(eobj r, eobj obj); // for EOBJ, EARR int ejson_freeR(eobj r, constr rawk); // for EOBJ, EARR int ejson_freeI(eobj r, int idx); // for EARR int ejson_freeP(eobj r, constr path); // for EOBJ, EARR int ejson_freeHEx(eobj r, eobj_rls_ex_cb rls, eval prvt); int ejson_freeTEx(eobj r, eobj_rls_ex_cb rls, eval prvt); int ejson_freeOEx(eobj r, eobj obj, eobj_rls_ex_cb rls, eval prvt); int ejson_freeREx(eobj r, constr rawk, eobj_rls_ex_cb rls, eval prvt); int ejson_freeIEx(eobj r, int idx, eobj_rls_ex_cb rls, eval prvt); int ejson_freePEx(eobj r, constr pkey, eobj_rls_ex_cb rls, eval prvt); /** ----------------------------------------------------- * * ejson comparing * * @return * 1: obj > val * 0: obj == val * -1: obj < val * -2: obj is NULL * -3: type not match * -4: val of cstr is null */ #define ejson_cmpI eobj_cmpI #define ejson_cmpF eobj_cmpF #define ejson_cmpS eobj_cmpS int ejson_rCmpI(eobj r, constr rawk, i64 val); int ejson_rCmpF(eobj r, constr rawk, f64 val); int ejson_rCmpS(eobj r, constr rawk, constr str); int ejson_iCmpI(eobj r, u32 idx , i64 val); int ejson_iCmpF(eobj r, u32 idx , f64 val); int ejson_iCmpS(eobj r, u32 idx , constr str); int ejson_pCmpI(eobj r, constr path, i64 val); int ejson_pCmpF(eobj r, constr path, f64 val); int ejson_pCmpS(eobj r, constr path, constr str); /** ----------------------------------------------------- * * ejson iterationg * * @note * for perfomance, we do not check type of o in * ejson_next() and ejson_prev() * */ eobj ejson_first(eobj r); eobj ejson_last (eobj r); eobj ejson_next (eobj o); eobj ejson_prev (eobj o); eobj ejson_rFirst(eobj r, constr rawk); eobj ejson_rLast (eobj r, constr rawk); eobj ejson_pFirst(eobj r, constr path); eobj ejson_pLast (eobj r, constr path); #define ejson_foreach( r, itr) for(itr = ejson_first (r ); (itr); itr = ejson_next(itr)) #define ejson_kForeach(r, rawk, itr) for(itr = ejson_rFirst(r, rawk); (itr); itr = ejson_next(itr)) #define ejson_pForeach(r, path, itr) for(itr = ejson_pFirst(r, path); (itr); itr = ejson_next(itr)) #define ejson_foreach_s( r, itr) for(eobj _INNER_ = ejson_first (r ), itr; (itr = _INNER_, _INNER_ = ejson_next(_INNER_), itr); ) #define ejson_kForeach_s(r, rawk, itr) for(eobj _INNER_ = ejson_rFirst(r, rawk), itr; (itr = _INNER_, _INNER_ = ejson_next(_INNER_), itr); ) #define ejson_pForeach_s(r, path, itr) for(eobj _INNER_ = ejson_pFirst(r, path), itr; (itr = _INNER_, _INNER_ = ejson_next(_INNER_), itr); ) /** ----------------------------------------------------- * * ejson set * * @note * 1. if target not exsit, create automatically if the last * found obj is a EOBJ obj * 2. the found obj will be reset always, any children of it * will be delete automatically, be careful by using it, * it may cause memleak when have EPTR or ERAW obj associated * with the delete obj * 3. we do not create any not exsit obj for EARR obj * */ eobj ejson_rSetT(eobj r, constr rawk, etypeo t); eobj ejson_rSetI(eobj r, constr rawk, i64 val); eobj ejson_rSetF(eobj r, constr rawk, f64 val); eobj ejson_rSetS(eobj r, constr rawk, constr str); eobj ejson_rSetP(eobj r, constr rawk, constr ptr); eobj ejson_rSetR(eobj r, constr rawk, uint len); eobj ejson_iSetT(eobj r, u32 idx , etypeo t); eobj ejson_iSetI(eobj r, u32 idx , i64 val); eobj ejson_iSetF(eobj r, u32 idx , f64 val); eobj ejson_iSetS(eobj r, u32 idx , constr str); eobj ejson_iSetP(eobj r, u32 idx , constr ptr); eobj ejson_iSetR(eobj r, u32 idx , uint len); eobj ejson_pSetT(eobj r, constr path, etypeo t); eobj ejson_pSetI(eobj r, constr path, i64 val); eobj ejson_pSetF(eobj r, constr path, f64 val); eobj ejson_pSetS(eobj r, constr path, constr str); eobj ejson_pSetP(eobj r, constr path, constr ptr); eobj ejson_pSetR(eobj r, constr path, uint len); /// ----------------------------------------------------- //! @brief ejson substitute string /// /// @return the modified obj if setted /// eobj ejson_rReplaceS(eobj root, constr rawk, constr from, constr to); eobj ejson_pReplaceS(eobj root, constr path, constr from, constr to); /// ----------------------------------------------------- /// @brief ejson counter /// /// @note: /// 1. if NUM obj not exsit in EOBJ, will create automatically /// 2. only support NUM obj if target obj exist /// 3. return LLONG_MIN if failed /// i64 ejson_pp (eobj o); // increase 1 i64 ejson_mm (eobj o); // decrease 1 i64 ejson_incr(eobj o, i64 v); // increase v i64 ejson_decr(eobj o, i64 v); // decrease v i64 ejson_rPP (eobj r, constr rawk); i64 ejson_rMM (eobj r, constr rawk); i64 ejson_rIncr(eobj r, constr rawk, i64 v); i64 ejson_rDecr(eobj r, constr rawk, i64 v); i64 ejson_iPP (eobj r, u32 idx ); i64 ejson_iMM (eobj r, u32 idx ); i64 ejson_iIncr(eobj r, u32 idx , i64 v); i64 ejson_iDecr(eobj r, u32 idx , i64 v); i64 ejson_pPP (eobj r, constr path); i64 ejson_pMM (eobj r, constr path); i64 ejson_pIncr(eobj r, constr path, i64 v); i64 ejson_pDecr(eobj r, constr path, i64 v); /** ----------------------------------------------- * @brief * ejson sort operation * * @note: * it only effect on EOBJ and EARR obj of ejson * */ //! supplied default sort cb int __KEYS_ACS(eobj a, eobj b); // Ascending via key string in all obj, dictionary sequence int __KEYS_DES(eobj a, eobj b); // Descending via key string in all obj, dictionary sequence int __VALI_ACS(eobj a, eobj b); // Ascending via int value in NUM obj int __VALI_DES(eobj a, eobj b); // Descending via int value in NUM obj eobj ejson_sort (eobj r, eobj_cmp_cb cmp); eobj ejson_kSort(eobj r, constr rawk, eobj_cmp_cb cmp); eobj ejson_pSort(eobj r, constr path, eobj_cmp_cb cmp); /// -- ejson version constr ejson_version(); #ifdef __cplusplus } #endif #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "ListyString.h" // Name: Ahmed Mansour // NID: ah505081 // This function reads an file and performs actions on a string. int processInputFile(char *filename) { ListyString *listy = malloc(sizeof(ListyString)); char *str = malloc(sizeof(char) * 1024); char commandChar; char keyChar; char *strToken; FILE *inputFile = fopen(filename, "r"); if (inputFile == NULL) return 1; fgets(str, 1024, inputFile); listy = createListyString(str); while (fgets(str, 1024, inputFile) != NULL) { commandChar = strtok(str, " ")[0]; if (commandChar == '@') { keyChar = strtok(NULL, " ")[0]; strToken = strtok(NULL, " "); replaceChar(listy, keyChar, strToken); } else if (commandChar == '+') { strToken = strtok(NULL, " "); listyCat(listy, strToken); } else if (commandChar == '-') { keyChar = strtok(NULL, " ")[0]; replaceChar(listy, keyChar, ""); } else if (commandChar == '~') { reverseListyString(listy); } else if (commandChar == '?') { printf("%d\n", listyLength(listy)); } else if (commandChar == '!') { printListyString(listy); } } return 0; } // This function creates a ListyString object. ListyString *createListyString(char *str) { int stringLength = 0; ListyString *listy = malloc(sizeof(ListyString)); ListyNode *node = malloc(sizeof(ListyNode)); if (str == NULL || str == " ") { listy->head = NULL; listy->length = 0; return listy; } listy->head = node; stringLength = strlen(str) - 1; for (int i = 0; i < stringLength; i++) { node->data = str[i]; node->next = malloc(sizeof(ListyNode)); node = node->next; listy->length++; } return listy; } // This function frees all memory related to the passed ListyString. ListyString *destroyListyString(ListyString *listy) { if (listy != NULL) { if (listy->head != NULL) { free(listy->head); } free(listy); } return NULL; } // This function copies the data from one ListyString to the other entierly seperate ListyString. ListyString *cloneListyString(ListyString *listy) { ListyNode *node = malloc(sizeof(ListyNode)); ListyNode *temp = malloc(sizeof(ListyNode)); ListyString *newListy = malloc(sizeof(ListyString)); if (listy == NULL) return NULL; if (listy->head == NULL) { newListy->head = NULL; } newListy->length = listy->length; temp = listy->head; newListy->head = node; for (int i = 0; i < listy->length; i++) { node->data = temp->data; node->next = calloc(1, sizeof(ListyNode)); node = node->next; temp = temp->next; } return newListy; } // This function takes a given character and replaces all instances of that key in the ListyString with a given string. void replaceChar(ListyString *listy, char key, char *str) { ListyString *newListy = malloc(sizeof(ListyString)); ListyNode *temp = malloc(sizeof(ListyNode)); ListyNode *newTemp = malloc(sizeof(ListyNode)); int stringLength; int listyLength; if (listy == NULL || listy->head == NULL) return; temp = listy->head; newListy->head = newTemp; if (str == NULL) str = ""; stringLength = strlen(str) - 1; temp = listy->head; newListy->head = newTemp; listyLength = listy->length; if (stringLength != 0) { while (temp->next != NULL) { for (int i = 0; i < listyLength; i++) { if (temp->data == key) { for (int j = 0; j < stringLength; j++) { newTemp->data = str[j]; newTemp->next = malloc(sizeof(ListyNode)); newTemp = newTemp->next; newListy->length++; } } else { newTemp->data = temp->data; newTemp->next = malloc(sizeof(ListyNode)); newTemp = newTemp->next; newListy->length++; } temp = temp->next; } } } else { while (temp != NULL) { if (temp->data != key) { newTemp->data = temp->data; if (temp->next != NULL) { newTemp->next = malloc(sizeof(ListyNode)); newTemp = newTemp->next; newListy->length++; } } temp = temp->next; } } listy->head = newListy->head; listy->length = newListy->length; listy = newListy; } // This function reverses the positions of all the data in the ListyString void reverseListyString(ListyString *listy) { ListyString *newListy = malloc(sizeof(ListyString)); ListyNode *temp = malloc(sizeof(ListyNode)); ListyNode *newTemp = malloc(sizeof(ListyNode)); if (listy == NULL || listy->head == NULL) return; newListy->length = listy->length; newListy->head = newTemp; for (int i = 0; i < newListy->length; i++) { temp = listy->head; while (temp->next->next != NULL && temp->next->data != '\n') temp = temp->next; newTemp->data = temp->data; newTemp->next = malloc(sizeof(ListyNode)); newTemp = newTemp->next; temp->next = NULL; } listy->head = newListy->head; listy = newListy; } // This function appends the ListyString with the given string ListyString *listyCat(ListyString *listy, char *str) { ListyNode *node = malloc(sizeof(ListyNode)); ListyString *newListy = malloc(sizeof(ListyString)); int strLength; if (listy == NULL && str == NULL) return NULL; strLength = strlen(str); if (listy == NULL && strLength > 0) createListyString(str); else if (listy == NULL && str == "") { newListy->head = NULL; newListy->length = 0; return newListy; } else if (str != NULL || str != "") { node = listy->head; while (node->next != NULL) node = node->next; for (int i = 0; i < strLength; i++) { node->data = str[i]; node->next = malloc(sizeof(ListyNode)); node = node->next; } listy->length += strLength - 1; } return listy; } // This function compares two strings and checks for any difference int listyCmp(ListyString *listy1, ListyString *listy2) { int differenceFound = 0; ListyNode *node1 = malloc(sizeof(ListyNode)); ListyNode *node2 = malloc(sizeof(ListyNode)); if ((listy1 == NULL && listy2 != NULL) || (listy1 != NULL && listy2 == NULL)) return 1; else if (listy1 == NULL && listy2 == NULL) return 0; else if (listy1->length == 0 && listy2->length == 0) return 0; node1 = listy1->head; node2 = listy2->head; while ((node1 != NULL || node2 != NULL) || differenceFound == 1) { if (node1->data != node2->data) { differenceFound = 1; } node1 = node1->next; node2 = node2->next; } if (differenceFound == 1) return 1; else return 0; } // This function returns the length of the ListyString int listyLength(ListyString *listy) { if (listy == NULL) return -1; else if (listy != NULL && listy->head == NULL) return 0; else return listy->length; } // This function prints out all the data held within the ListyString void printListyString(ListyString *listy) { ListyNode *temp; char *str = malloc(sizeof(char) * 1024); if (listy == NULL || listy->length == 0) { printf("(empty string)"); } temp = listy->head; for (int i = 0; i < listy->length; i++) { if (temp->data != '\n') printf("%c", temp->data); temp = temp->next; } printf("\n"); } double difficultyRating(void) { return 4.5; } double hoursSpent(void) { return 20.0; } int main(int argc, char **argv) { processInputFile(argv[1]); return 0; }
C
#ifndef CLIENT_H #define CLIENT_H /* Macros compativeis com o ADT tree */ #define Item2 Client #define Key2 long int #define key2(A) A->ref #define less2(A, B) key2(A) < key2(B) #define deleteItem2 free #define NULLitem2 NULL /** * Estrutura client - Representa um cliente de referencia/chave ref. Emitiu * nche cheques num valor total de vche e benificiou de nchb cheques num valor * de vchb (inicialmente, sao campos todos a zero, exepto a referencia) */ typedef struct client { long int ref, nche, vche, nchb, vchb; } *Client; /* Construtor */ Client newCLIENT(long int ref); /* Cria um novo cliente com a referencia ref */ /* Getters/Acessores */ long int CLIENTref(Client); /* Referencia do cliente */ long int CLIENTnche(Client); /* Numero de cheques emitidos */ long int CLIENTnchb(Client); /* Numero de cheques benificiados */ long int CLIENTvche(Client); /* Valor total dos cheques emitidos */ long int CLIENTvchb(Client); /* Valor total dos cheques benificiados*/ /* Setters/Mutadores */ void CLIENTaddChe(Client); /* Incrementa o numero de cheques emitidos */ void CLIENTremoveChe(Client); /* Decrementa o numero de cheques emitidos */ void CLIENTaddChb(Client); /* Incrementa o numero de cheques benificiados */ void CLIENTremoveChb(Client); /* Decrementa o numero de cheques benificiados */ void CLIENTupdateVChe(Client, int); /* Soma ao valor total de emitidos */ void CLIENTupdateVChb(Client, int); /* Soma ao valor total de benificiados */ /* Testes */ int CLIENTexists(Client); /* Verifica se o cliente "existe" (nao nulo) */ /* Representacao */ void CLIENTinfo(Client); /* Imprime a informacao do cliente */ void CLIENTinfoOrdered(Client); /* Representacao alternativa da informacao */ #endif /* CLIENT_H */
C
#include <stdio.h> /* 6. Faça um algoritmo que leia um caractere e informe se o mesmo é uma vogal ou não */ main () { char letra; printf("\ninforme um caracter: "); scanf(" %c",&letra); switch(letra) { case 'a': case 'e': case 'i': case 'o': case 'u': printf("\nSIM"); break; default: printf("\nNAO"); break; } }
C
#include <xinu.h> // Returns the CPU Gross Time of a Proccess syscall getuptime() { // Disabe Interrupts intmask mask = disable(); // Get Current Process struct procent *prptr = &proctab[currpid]; // No Proc if(prptr->prstate == PR_FREE) { restore(mask); return SYSERR; } // Return Usage Time uint32 time = prptr->pgrosscpu + currproctime; restore(mask); return time; }
C
#include <stdarg.h> #include <stdio.h> #include "callinfo.h" int mlog(int pc, const char *fmt, ...) { static unsigned int id = 1; va_list ap; int res; res = fprintf(stderr, "[%04u] ", id++); if (pc) { char buf[16]; unsigned long long ofs; if (get_callinfo(&buf[0], sizeof(buf), &ofs) != -1) { res += fprintf(stderr, "%12s:%-3llx: ", buf, ofs); } else { res += fprintf(stderr, "%5c%10p : ", ' ', NULL); } } va_start(ap, fmt); res += vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); return res; }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include "../headers/config_reader.h" int init_str(char** str, int dim){ *str = malloc(sizeof(char)*dim); if(*str == NULL){ perror("config_reader: init_str"); return 0; } for(int i = 0; i < dim; i++){ (*str)[i] = 0; } return 1; } void free_str(char** str){ free(*str); } int init_strptr(char*** strptr, int dim1, int dim2) { *strptr = malloc(sizeof(char*)*dim1); if(*strptr == NULL){ perror("config_reader: init_strptr"); return 0; } for(int i = 0; i < dim1; i++){ (*strptr)[i] = malloc(sizeof(char)*dim2); if((*strptr)[i] == NULL){ perror("config_reader: init_strptr"); return 0; } for(int j = 0; j < dim2; j++){ (*strptr)[i][j] = 0; } } return 1; } void free_strptr(char*** strptr, int dim1){ for(int i = 0; i < dim1; i++){ free((*strptr)[i]); } free((*strptr)); } int init_strptrptr(char**** strptrptr, int dim1, int dim2, int dim3){ *strptrptr = malloc(sizeof(char**)*dim1); if(*strptrptr == NULL){ perror("config_reader: init_strptrptr"); return 0; } for(int i = 0; i < dim1; i++){ (*strptrptr)[i] = malloc(sizeof(char*)*dim2); if((*strptrptr)[i] == NULL){ perror("config_reader: init_strptrptr"); return 0; } for(int j = 0; j < dim2; j++){ (*strptrptr)[i][j] = malloc(sizeof(char)*dim3); if((*strptrptr)[i][j] == NULL){ perror("config_reader: init_strptrptr"); return 0; } for(int k = 0; k < dim3; k++){ (*strptrptr)[i][j][k] = 0; } } } return 1; } void free_strptrptr(char**** strptrptr, int dim1, int dim2){ for(int i = 0; i < dim1; i++){ for(int j = 0; j < dim2; j++){ free((*strptrptr)[i][j]); } free((*strptrptr)[i]); } free((*strptrptr)); } void insert_string_array(char** originalp, char** newp, int index){ char** original = originalp; char** new = newp; char** copy; init_strptr(&copy, MAX_SIZE, MAX_SIZE); int original_index = index; int copy_index = 0; for(; strcmp(original[index], ""); index++){ strcpy(copy[copy_index], original[index]); copy_index++; } index = original_index; for(int i = 0; strcmp(new[i], ""); i++){ strcpy(original[index], new[i]); index++; } for(int i = 0; i < copy_index; i++){ strcpy(original[index], copy[i]); index++; } free_strptr(&copy, MAX_SIZE); } int is_field(char* str, char begin, char end) { int last = 0; if(str == NULL){return 0;} if(str[0] != begin) { return 0; } for(; str[last] != 0; last++){} if(last == 1) { return 0; } if(str[last-1] != end) { return 0; } return 1; } int file_reader(char* filename, char* buffer) { int ret; FILE* fp = fopen(filename, "r"); if(fp == NULL){ printf("config_reader: file_reader: error getting file: %s\n", filename); perror("config_reader: file_reader"); return 0; } char c = 0; int i = 0; c = fgetc((FILE*)fp); // repeat until c is EOF while(c != EOF ) { buffer[i] = c; i++; c = fgetc((FILE*)fp); } buffer[i] = 0; fclose(fp); return 1; } int config_reader(char* filename, config* cfg) { char* buffer; if(!init_str(&buffer, 1000)) {return 0;} if(!file_reader(filename, buffer)) {return 0;} if(!init_strptr(&cfg->words, MAX_SIZE, MAX_SIZE)) {return 0;} if(!init_str(&cfg->filename, MAX_SIZE) && cfg->verbose) { printf("config_reader: config_reader: failed to save filename, continueing anyway\n"); } else { strcpy(cfg->filename, filename); } int word_counter = 0; int current_word = 0; char* eol_str; init_str(&eol_str, 2); eol_str[0] = cfg->eol; int i = 0; for(i = 0; buffer[i] != 0; i++) { if(buffer[i] == ' ') { /* add array for next word */ if(strcmp(cfg->words[current_word], "")) { word_counter = 0; current_word++; } } else if( buffer[i] == cfg->eol){ /* add eol as word */ if(strcmp(cfg->words[current_word], "")) { word_counter = 0; current_word++; } strcpy(cfg->words[current_word], eol_str); /* add array for next word */ word_counter = 0; current_word++; } else { cfg->words[current_word][word_counter] = buffer[i]; word_counter++; } } word_counter = 0; current_word++; free_str(&buffer); free_str(&eol_str); return 1; } int get_field(config cfg, char* field_name, char** field) { char* full_field_name; if(!init_str(&full_field_name, 50)) {return 0;} char* field_char; if(!init_str(&field_char, 2)) {return 0;} field_char[0] = cfg.begin_field; strcat(full_field_name, field_char); strcat(full_field_name, field_name); field_char[0] = cfg.end_field; strcat(full_field_name, field_char); int i = 0; int found = 0; for(i = 0; strcmp(cfg.words[i], ""); i++) { if(strcmp(cfg.words[i], full_field_name) == 0) { i+=2; /* two to go down a line */ found = 1; break; } } if(found == 0) { printf("config_reader: get_field: failed to find field %s\n", full_field_name); return 0; } int index = 0; for(; strcmp(cfg.words[i], "") && !is_field(cfg.words[i], cfg.begin_field, cfg.end_field); i++) { strcpy(field[index], cfg.words[i]); index++; } free_str(&full_field_name); return 1; } int get_attr(config cfg, char** field, char* attr, char*** val) { char* new_line; if(!init_str(&new_line, 2)) {return 0;} new_line[0] = cfg.eol; int current_val = 0; int current_val_number = 0; int found = 0; int after_nl = 0; for(int i = 0; strcmp(field[i], ""); i++) { if(strcmp(field[i], new_line) == 0) { after_nl = 1; } if(strcmp(field[i], attr) == 0 && after_nl) { found = 1; i+=1; int curr_i = i; for(; strcmp(field[i], "") && strcmp(field[i], new_line); i++) { strcpy(val[current_val_number][current_val], field[i]); current_val++; } i = curr_i; current_val = 0; current_val_number++; } if(strcmp(field[i], new_line)) { after_nl = 0; } } free_str(&new_line); if(found == 0 && cfg.verbose) {printf("config_reader: get_attr: failed to find %s\n", attr);} return found; } int get_first_attr(config cfg, char** field, char* attr, char** val) { char* new_line; if(!init_str(&new_line, 2)) {return 0;} new_line[0] = cfg.eol; int current_val = 0; int found = 0; int after_nl = 0; for(int i = 0; strcmp(field[i], ""); i++) { if(strcmp(field[i], new_line) == 0) { after_nl = 1; } if(strcmp(field[i], attr) == 0 && after_nl) { found = 1; i+=1; int curr_i = i; for(; strcmp(field[i], "") && strcmp(field[i], new_line); i++) { strcpy(val[current_val], field[i]); current_val++; } break; } if(strcmp(field[i], new_line)) { after_nl = 0; } } free_str(&new_line); if(found == 0 && cfg.verbose) {printf("config_reader: get_attr: failed to find %s\n", attr);} return found; } int get_last_attr(config cfg, char** field, char* attr, char** val) { char* new_line; if(!init_str(&new_line, 2)) {return 0;} new_line[0] = cfg.eol; int current_val = 0; int found = 0; int after_nl = 0; for(int i = 0; strcmp(field[i], ""); i++) { if(strcmp(field[i], new_line) == 0) { after_nl = 1; } if(strcmp(field[i], attr) == 0 && after_nl) { found = 1; i+=1; int curr_i = i; for(int j = 0; strcmp(val[j], ""); j++){ strcpy(val[j], ""); } for(; strcmp(field[i], "") && strcmp(field[i], new_line); i++) { strcpy(val[current_val], field[i]); current_val++; } i = curr_i; current_val = 0; } if(strcmp(field[i], new_line)) { after_nl = 0; } } free_str(&new_line); if(found == 0 && cfg.verbose) {printf("config_reader: get_attr: failed to find %s\n", attr);} return found; } int dir_get_attr(config cfg, char* fieldname, char* attr, char*** val) { char** field; if(!init_strptr(&field, MAX_SIZE, MAX_SIZE)) {return 0;} if(!get_field(cfg, fieldname, field)) {return 0;} if(!get_attr(cfg, field, attr, val)) {return 0;} free_strptr(&field, MAX_SIZE); return 1; } int dir_get_first_attr(config cfg, char* fieldname, char* attr, char** val) { char** field; if(!init_strptr(&field, MAX_SIZE, MAX_SIZE)) {return 0;} if(!get_field(cfg, fieldname, field)) {return 0;} if(!get_first_attr(cfg, field, attr, val)) {return 0;} free_strptr(&field, MAX_SIZE); return 1; } int dir_get_last_attr(config cfg, char* fieldname, char* attr, char** val) { char** field; if(!init_strptr(&field, MAX_SIZE, MAX_SIZE)) {return 0;} if(!get_field(cfg, fieldname, field)) {return 0;} if(!get_last_attr(cfg, field, attr, val)) {return 0;} free_strptr(&field, MAX_SIZE); return 1; } void set_cfg_field(config* cfg, char begin, char end) { cfg->begin_field = begin; cfg->end_field = end; }; void set_cfg_eol(config* cfg, char eol) { cfg->eol= eol; }; void auto_cfg_setup(config* cfg) { set_cfg_field(cfg, '[', ']'); set_cfg_eol(cfg, '\n'); cfg->verbose = 0; } void cfg_setup(config* cfg, char eol, char begin, char end, char verbosity) { set_cfg_field(cfg, begin, end); set_cfg_eol(cfg, eol); cfg->verbose = verbosity; } int save_config(config* cfg, char* filename){ FILE* fp = fopen(filename, "w"); char* eol_str; if(!init_str(&eol_str, 2)) {return 0;} eol_str[0] = cfg->eol; char* copy_word = malloc(MAX_SIZE*sizeof(char)); for(int i = 0; strcmp(cfg->words[i], ""); i++){ if(strcmp(cfg->words[i], eol_str) != 0) { strcat(strcpy(copy_word, cfg->words[i]), " "); } else { strcpy(copy_word, cfg->words[i]); } if(fputs(copy_word, fp) == EOF){ printf("config_reader: save_config: failed to save to file %s", filename); return 0; } } free_str(&eol_str); fclose(fp); return 1; } int set_field_attr(config* cfg, char* field_name, char* attr, char** new_val) { char* full_field_name = ""; if(!init_str(&full_field_name, 50)) {return 0;} char* field_char; if(!init_str(&field_char, 2)) {return 0;} field_char[0] = cfg->begin_field; strcat(full_field_name, field_char); strcat(full_field_name, field_name); field_char[0] = cfg->end_field; strcat(full_field_name, field_char); int i = 0; int found = 0; for(i = 0; strcmp(cfg->words[i], ""); i++) { if(strcmp(cfg->words[i], full_field_name) == 0) { i+=2; /* two to go down a line */ found = 1; break; } } if(found == 0) { printf("config_reader: set_field_attr: failed to find %s\n", full_field_name); return 0; } int findex = i; /* field index */ char* new_line; if(!init_str(&new_line, 2)) {return 0;} new_line[0] = cfg->eol; new_line[1] = 0; int current_val = 0; int current_val_number = 0; found = 0; int after_nl = 0; for(i = 0; strcmp(cfg->words[i+findex], "") && !is_field(cfg->words[i+findex], cfg->begin_field, cfg->end_field); i++) { if(strcmp(cfg->words[i+findex], new_line) == 0) { after_nl = 1; } if(strcmp(cfg->words[i+findex], attr) == 0) { found = 1; i+=1; int curr_i = i; int curr_new_val = 0; int copying = 1; for(; strcmp(cfg->words[i+findex], "") != 0 && strcmp(cfg->words[i+findex], new_line) != 0 && !is_field(cfg->words[i+findex], cfg->begin_field, cfg->end_field); i++) { if(copying){ strcpy(cfg->words[i+findex], new_val[curr_new_val]); } else{ strcpy(cfg->words[i+findex], " "); } curr_new_val++; if(strcmp(new_val[curr_new_val], "") == 0){ copying = 0; } } if(strcmp(new_val[curr_new_val], "")){ /* we need to insert words! */ insert_string_array(cfg->words, new_val+curr_new_val, findex+i); } current_val = 0; current_val_number++; } if(strcmp(cfg->words[i+findex], new_line)) { after_nl = 0; } } if(found == 0) { printf("config_reader: set_field_attr: failed to find %s in field %s\n", attr, full_field_name); return 0; } free_str(&full_field_name); free_str(&new_line); return 1; } int close_config(config* cfg, int save){ if(save){ if(!save_config(cfg, cfg->filename)) {return 0;} } free_strptr(&cfg->words, MAX_SIZE); free_str(&cfg->filename); free(cfg); return 1; } int set_field(config* cfg, char* field_name, char** new_field){ char* full_field_name = ""; if(!init_str(&full_field_name, 50)) {return 0;} char* field_char; if(!init_str(&field_char, 2)) {return 0;} field_char[0] = cfg->begin_field; strcat(full_field_name, field_char); strcat(full_field_name, field_name); field_char[0] = cfg->end_field; strcat(full_field_name, field_char); int i = 0; int found = 0; for(i = 0; strcmp(cfg->words[i], ""); i++) { if(strcmp(cfg->words[i], full_field_name) == 0) { i+=2; /* two to go down a line */ found = 1; break; } } if(found == 0) { printf("config_reader: set_field_attr: failed to find %s\n", full_field_name); return 0; } int findex = i; /* field index */ char* new_line; init_str(&new_line, 2); new_line[0] = cfg->eol; new_line[1] = 0; found = 0; for(i = 0; strcmp(cfg->words[i+findex], "") && !is_field(cfg->words[i+findex], cfg->begin_field, cfg->end_field) && strcmp(new_field[i], ""); i++){ cfg->words[i+findex] = new_field[i]; } if(strcmp(new_field[i], "")) { insert_string_array(cfg->words, new_field+i, i+findex); } free_str(&full_field_name); free_str(&new_line); return 1; } /* TEST CODE int main(){ config cfg; cfg_setup(&cfg, '\n', '[', ']'); printf("%d\n", config_reader("..\\example.cfg", &cfg)); char** field; init_strptr(&field, MAX_SIZE, MAX_SIZE); char*** val; init_strptrptr(&val, 20, 10, 50); char** fval; init_strptr(&fval, 10, 50); char** lval; init_strptr(&lval, 10, 50); get_field(cfg, "FIELD1", field); printf("FIELD1: \n"); for(int i = 0; strcmp(field[i], ""); i++) { printf("%s ", field[i]); } printf("attr MIN: \n"); dir_get_last_attr(cfg, "FIELD1", "TEST", lval); for(int i = 0; strcmp(lval[i], ""); i++) { printf("%d: %s ", i, lval[i]); } field[0] = "test"; field[1] = "\n"; field[2] = "for"; field[3] = "\n"; field[4] = "field"; field[5] = "change"; printf("FIELD1: \n"); for(int i = 0; strcmp(field[i], ""); i++) { printf("%s ", field[i]); } set_field(&cfg, "FIELD2", field); printf("\n\nPRINTING WORDS\n\n"); for(int i = 0; strcmp(cfg.words[i], ""); i++) { printf("%s ", cfg.words[i]); } save_config(&cfg, "new.cfg"); close_config(&cfg, 0); return 0; } */
C
#include "lists.h" /** * is_palindrome - check if a singly linked list is a palindrome * @head: list to check * Return: 0 if not a palindrome 1 if it is */ int is_palindrome(listint_t **head) { listint_t *aux; int i, j[10000]; if (head == NULL) return (0); if (*head == NULL) return (1); aux = *head; for (i = 0; aux; i++, aux = aux->next) j[i] = aux->n; aux = *head; while (i > 0) { if (aux->n != j[i - 1]) return (0); aux = aux->next; i--; } return (1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "films.h" #include "utils.h" int main(int argc, char *argv[]) { if (argc != 3 && argc != 4) return ARG_ERR; if (strcmp(argv[2], "title") && strcmp(argv[2], "name") && strcmp(argv[2], "year")) return ARG_ERR; if (argc == 4 && strlen(argv[3]) > N) return ARG_ERR; if (argc == 4 && !strcmp(argv[2], "year") && (is_year(argv[3]) == ARG_ERR || atoi(argv[3]) <= 0)) return ARG_ERR; Field key; if (!strcmp(argv[2], "title")) key = TITLE; else if (!strcmp(argv[2], "name")) key = NAME; else if (!strcmp(argv[2], "year")) key = YEAR; FILE *in = NULL; in = fopen(argv[1], "r"); if (!in) { return READ_FILE_ERR; } fseek(in, 0, SEEK_END); if (!ftell(in)) { fclose(in); return EMPTY; } fseek(in, 0, SEEK_SET); size_t file_len = 0; if (size_file(in, &file_len)) { fclose(in); return READ_FILE_ERR; } cinema **list = create_cinema_list(file_len); if (!list) { fclose(in); return ALLOCATION_ERR; } if (fill(in, list, file_len, key)) { free_list(list, file_len); fclose(in); return READ_FILE_ERR; } if (argc == 3) { print(list, file_len); } else { int rc = bin_search(list, key, argv[3], file_len); if (rc == -1) { printf("Not found\n"); } else { int ind = rc; printf("%s\n%s\n%ld\n", list[ind]->title, list[ind]->name, list[ind]->year); } } free_list(list, file_len); fclose(in); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <string.h> int main(void){ FILE * fp; char nomEquip[100],nomEquipFitxer[100]; int trobat = 0; fp = fopen("lliga2007.txt","r"); if (fp == NULL){ printf("No s'ha pogut obrir el fitxer\n"); }else { printf("Diguem el nom del equip del que vols saber els gols.\n"); gets(nomEquip); while(!feof(fp)){ fscanf(fp,"%s",nomEquipFitxer); if(strcmp(nomEquip,nomEquipFitxer) == 0){ fscanf(fp,"%s",nomEquipFitxer); printf("Aquest equip a marcat %s gols\n",nomEquipFitxer); trobat = 1; }else if (feof(fp) && trobat == 0){ printf("Aquest equip no es troba dins el fitxer\n"); } } fclose(fp); } return 0; }
C
//Q8. WAP to find Factorial of a number [use for loop]. #include<stdio.h> void main() { int n,i; long fact; fact=1; printf("Enter a number : "); scanf("%d",&n); for(i=1;i<=n;i++) { fact*=i; } printf("\n Factorial = %d",fact); }
C
#include <stdio.h> #include <stdlib.h> #define MAX_LENGTH 256 // compte le nombre de ligne du fichier int countLines(FILE * filePointer){ int count = 0; char * stringBuffer = (char *) malloc( MAX_LENGTH ); while(!feof(filePointer)){ fgets(stringBuffer, MAX_LENGTH, filePointer); count++; } free(stringBuffer); rewind(filePointer); return count; } // vérification du fichier : chaque état a son délimiteur sur chaque ligne int checkStates(FILE * filePointer){ char delim = ';'; char * stringBuffer = (char *) malloc(MAX_LENGTH); int cpt = 0; // passage des 3 premières lignes (headers) for(int i = 0; i < 3; i++){ fgets(stringBuffer, MAX_LENGTH, filePointer); } int j; for(int i = 0; i < 5; i++){ fgets(stringBuffer, MAX_LENGTH, filePointer); j = 0; while(stringBuffer[j] != '\0'){ if(stringBuffer[j] == delim){ cpt++; } j++; } } free(stringBuffer); rewind(filePointer); if(cpt == 20){ return 0; } else { return 1; } } // renvoi 1 ou 0 selon la validité du fichier int checkFile(FILE * filePointer){ int lineCount = countLines(filePointer); int stateCheck = checkStates(filePointer); if(lineCount == 8 && stateCheck == 0){ return 0; } else { return 1; } }
C
/* ** my_power_rec.c for in /home/marque_p/rendu/Piscine_C_J05 ** ** Made by Kamil Marque ** Login <[email protected]> ** ** Started on Mon Oct 5 10:40:41 2015 Kamil Marque ** Last update Mon Oct 5 10:42:19 2015 Kamil Marque */ int my_power_rec(int nb, int power) { int res; res = nb; if (power == 0) return (1); else if (power < 0) return (0); else if (power == 1) return (nb); else res = res * my_power_rec(nb, power - 1); return (res); }
C
#include "filetools.h" int load_file_to_memory(const char *filename, char **buffer) { int size = 0; FILE *f = fopen(filename, "rb"); if (f == NULL) { *buffer = NULL; // -1 means file opening failed return -1; } // figure out the file size fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); // allocate buffer, add one more byte for zero termination *buffer = (char *)malloc(size + 1); if (size != fread(*buffer, sizeof(char), size, f)) { // free the memory in case of an error free(*buffer); // -2 means file reading failed return -2; } // close the file fclose(f); // zero terminate (*buffer)[size] = 0; return size; }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> #include <math.h> #include "headfile.h" void num_find(struct student *head) { int num; char m; int j,flag=0; cyan printf("Ŀѧѧţ"); white scanf("%d",&num); fflush(stdin); struct student *headp,*prem,*findnotehead,findnote;//ҵĽڵ findnotehead=(struct student *)calloc(1,sizeof(struct student));//ڵͷڴoutput headp=head; prem=head; head=head->next; while(head) { if(head->num==num) { cyan printf("ѾҵĿ꣺"); flag=1; yellow printf("%d\n",num); white findnote=*head; findnote.next=NULL; findnotehead->next=&findnote; output1(findnotehead); cyan printf("Ƿ޸ģy/n"); white scanf("%c",&m); fflush(stdin); if(m=='y') { char x; cyan printf("޸:r\nɾ:d\n룺"); white scanf("%c",&x); fflush(stdin); if(x=='r') { yellow printf("¼Ϣ"); white cyan printf("ѧţ"); white scanf("%d",&head->num); cyan printf("뿨ţ"); white scanf("%d",&head->id); cyan printf(""); white scanf("%s",head->name); //getchar(); cyan printf("Դأ"); white scanf("%s",head->birplace); cyan printf("꼶"); white scanf("%d",&head->grade); cyan printf("רҵ"); white scanf("%s",head->major); cyan printf("һͨ״̬"); white scanf("%d",&head->status); while(head->status!=0&&head->status!=1)//Ƿ { getchar(); red printf("Ƿ룡\n"); fflush(stdin); white cyan printf("һͨ״̬"); white scanf("%d",&head->status); } save1(headp,3); } else if(x=='d') { prem->next=head->next; save1(headp,3); } else { red printf("Ƿ룡"); white } } else if(m=='n') { cyan printf("صȡѧϢ˵\n"); system("pause"); white } else { red printf("Ƿ룡"); white } break; } else { prem=head; head=head->next; } } if(flag==0) { red printf("ûвҵĿѧ\n"); white system("pause"); } Inmenu1(); } void name_find(struct student *head) { char name[100]; char m; int j,flag=0; cyan printf("Ŀѧ"); white scanf("%s",name); fflush(stdin); struct student *headp,*prem,*findnotehead,findnote;//ҵĽڵ findnotehead=(struct student *)calloc(1,sizeof(struct student));//ڵͷڴoutput headp=head; prem=head; head=(struct student*)head->next; while(head) { if(strcmp(head->name,name)==0) { cyan printf("ѾҵĿ꣺"); flag=1; yellow printf("%s\n",name); white findnote=*head; findnote.next=NULL; findnotehead->next=&findnote; output1(findnotehead); cyan printf("Ƿ޸Ļɾy/n"); white scanf("%c",&m); fflush(stdin); if(m=='y') { char x; cyan printf("޸:r\nɾ:d\n룺"); white scanf("%c",&x); fflush(stdin); if(x=='r') { // yellow printf("¼Ϣ"); white cyan printf("ѧţ"); white scanf("%d",&head->num); cyan printf("뿨ţ"); white scanf("%d",&head->id); cyan printf(""); white scanf("%s",head->name); //getchar(); cyan printf("Դأ"); white scanf("%s",head->birplace); cyan printf("꼶"); white scanf("%d",&head->grade); cyan printf("רҵ"); white scanf("%s",head->major); cyan printf("һͨ״̬"); white scanf("%d",&head->status); while(head->status!=0&&head->status!=1)//Ƿ { getchar(); red printf("Ƿ룡\n"); fflush(stdin); white cyan printf("һͨ״̬"); white scanf("%d",&head->status); } save1(headp,3); }// else if(x=='d') { prem->next=head->next; save1(headp,3); } else { red printf("Ƿ룡"); white } } else if(m=='n') { cyan printf("صȡѧϢ˵\n"); system("pause"); white } else { red printf("Ƿ룡"); white } break; } else { prem=head; head=head->next; } } if(flag==0) { red printf("ûвҵĿѧ\n"); white system("pause"); } Inmenu1(); } void id_find(struct student *head) { int num; char m; int j,flag=0; cyan printf("ĿѧĿţ"); white scanf("%d",&num); fflush(stdin); struct student *headp,*prem,*findnotehead,findnote;//ҵĽڵ findnotehead=(struct student *)calloc(1,sizeof(struct student));//ڵͷڴoutput headp=head; prem=head; head=head->next; while(head) { if(head->id==num) { cyan printf("ѾҵĿ꣺"); flag=1; yellow printf("%d\n",num); white findnote=*head; findnote.next=NULL; findnotehead->next=&findnote; output1(findnotehead); cyan printf("Ƿ޸ģy/n"); white scanf("%c",&m); fflush(stdin); if(m=='y') { char x; cyan printf("޸:r\nɾ:d\n룺"); white scanf("%c",&x); fflush(stdin); if(x=='r') { yellow printf("¼Ϣ"); white cyan printf("ѧţ"); white scanf("%d",&head->num); cyan printf("뿨ţ"); white scanf("%d",&head->id); cyan printf(""); white scanf("%s",head->name); //getchar(); cyan printf("Դأ"); white scanf("%s",head->birplace); cyan printf("꼶"); white scanf("%d",&head->grade); cyan printf("רҵ"); white scanf("%s",head->major); cyan printf("һͨ״̬"); white scanf("%d",&head->status); while(head->status!=0&&head->status!=1)//Ƿ { getchar(); red printf("Ƿ룡\n"); fflush(stdin); white cyan printf("һͨ״̬"); white scanf("%d",&head->status); } save1(headp,3); } else if(x=='d') { prem->next=head->next; save1(headp,3); } else { red printf("Ƿ룡"); white } } else if(m=='n') { cyan printf("صȡѧϢ˵\n"); system("pause"); white } else { red printf("Ƿ룡"); white } break; } else { prem=head; head=head->next; } } if(flag==0) { red printf("ûвҵĿѧ\n"); white system("pause"); } Inmenu1(); } void id_find2(struct use *head) { int num; char m; int j,flag=0; cyan printf("ĿѧĿţ"); white scanf("%d",&num); fflush(stdin); struct use *headp,*prem,*findnotehead,findnote;//ҵĽڵ findnotehead=(struct use *)calloc(1,sizeof(struct use));//ڵͷڴoutput headp=head; prem=head; head=head->next; while(head) { if(head->id==num) { cyan printf("ѾҵĿ꣺"); flag=1; yellow printf("%d\n",num); white findnote=*head; findnote.next=NULL; findnotehead->next=&findnote; output1(findnotehead); cyan printf("Ƿ޸ģy/n"); white scanf("%c",&m); fflush(stdin); if(m=='y') { char x; cyan printf("޸:r\nɾ:d\n룺"); white scanf("%c",&x); fflush(stdin); if(x=='r') { yellow printf("¼Ϣ"); white cyan printf("뿨ţ"); white scanf("%d",&head->id); cyan printf("鼮"); white scanf("%s",head->book); //getchar(); cyan printf("ʳ"); white scanf("%s",head->food); save2(headp,3); } else if(x=='d') { prem->next=head->next; save1(headp,3); } else { red printf("Ƿ룡"); white } } else if(m=='n') { cyan printf("صȡһͨϢ˵\n"); system("pause"); white } else { red printf("Ƿ룡"); white } break; } else { prem=head; head=head->next; } } if(flag==0) { red printf("ûвҵĿ꿨ţ\n"); white system("pause"); } Inmenu2(); }
C
/* Take input from the user and ask user to choose 0 for triangular star pattern and 1 for reversed triangular star pattern Then print the pattern accordingly * ** *** **** -> Triangular star pattern ***** **** *** ** * -> Reversed triangular star pattern */ #include <stdio.h> void starpattern(int rows); void squar(int rows, int type); void rect(int rows, int type); void reversstarpatern(int rows); int main() { int rows, type; // Code for printing a Reactangle with * // printf("enter the value of lenght \n"); // scanf("%d", &rows); // printf("enter the value of bredth \n"); // scanf("%d", &type); // rect(rows, type); // Code for printing Squar with * // printf("enter the value of lenght \n"); // scanf("%d", &rows); // printf("enter the value of bredth \n"); // scanf("%d", &type); // squar(rows, type); printf("Type 0 for triangular star pattern and 1 for reversed triangular star pattern\n"); scanf("%d", &type); switch (type) { case 0: printf("You have selected Triangual star patren.\n Enter the value for your star patrens\n"); scanf("%d", &rows); starpattern(rows); break; case 1: printf("You have selected Revese Triangual star patren.\n Enter the value for your star patrens\n"); scanf("%d", &rows); reversstarpatern(rows); break; default: printf("You have entered the wrong choice\n"); break; } return 0; } void starpattern(int rows) { // This function will print star patren for (int i = 0; i < rows; i++) { for (int j = 0; j <= i; j++) { printf("*"); } printf("\n"); } } void reversstarpatern(int rows) { // This function will print revers srar patren for (int i = 0; i < rows; i++) { for (int j = 0; j <= rows - i - 1; j++) { printf("*"); } printf("\n"); } } void rect(int rows, int type) { // This function will print reactangle for (int i = 0; i < type; i++) { printf("\t"); for (int j = 0; j <= rows * type; j++) { printf("*"); } printf("\n"); } } void squar(int rows, int type) { // This function will print squar for (int i = 0; i < type; i++) { printf("\t"); for (int j = 0; j <= rows * 2; j++) { printf("*"); } printf("\n"); } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int index_of(char** names, int tam, char name[]){ for(int i = 0; i < tam; i++){ if(strcmp(names[i], name) == 0) return i; } return -1; } int main(){ int n, idC, in, pres, i, j, *saldo; char **names, cara[13]; scanf("%d", &n); while(n!=0){ names = (char**) malloc(sizeof(char)*n); for(i = 0; i < n; i++) names[i] = (char*) malloc(sizeof(char)*13); saldo = (int*) malloc(sizeof(int)*n); for(i = 0; i < n; i++){ scanf("%s", names[i]); saldo[i] = 0; } for(i = 0; i < n; i++){ scanf("%s", cara); idC = index_of(names, n, cara); scanf("%d", &in); scanf("%d", &pres); if(pres!=0 && idC >= 0) saldo[idC] -= (in/pres)*pres; for(j = 0; j < pres; j++){ scanf("%s", cara); idC = index_of(names, n, cara); if(idC >= 0) saldo[idC] += in/pres; } } for(i=0; i < n; i++) printf("%s %d\n", names[i], saldo[i]); printf("\n"); free(names); free(saldo); scanf("%d", &n); } return 0; }
C
//====================================================================== // f06.c / JAS // Tree of child processes with some zombies // In another terminal, execute command 'ps u' //---------------------------------------------------------------------- #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { int i, pid; for (i=1;i<=3;i++) { pid=fork(); if (pid > 0) { printf("I'm the parent (PID=%d)\n\n",getpid()); sleep(5); } else { printf("I'm the son (PID=%d). My parent is %d\n\n",getpid(),getppid()); break; // NOTE THIS } } printf ("PID=%d exiting ...\n",getpid()); return 0; }
C
/* Copyright (C) 2016 RDA Technologies Limited and/or its affiliates("RDA"). * All rights reserved. * * This software is supplied "AS IS" without any warranties. * RDA assumes no responsibility or liability for the use of the software, * conveys no license or title under any patent, copyright, or mask work * right to the product. RDA reserves the right to make changes in the * software without notification. RDA also make no representation or * warranty that such application will be suitable for the specified use * without further testing or modification. */ #include <sul.h> #include <string.h> // //GSMBCD码,如果转化奇数个数字的话,将会在对应高位补F //支持'*''#''p' //13811189836 --> 0x31 0x18 0x11 0x98 0x38 0xF6 // UINT16 SUL_AsciiToGsmBcd( INT8 *pNumber, // input UINT8 nNumberLen, UINT8 *pBCD // output should >= nNumberLen/2+1 ) { UINT8 Tmp; UINT32 i; UINT32 nBcdSize = 0; UINT8 *pTmp = pBCD; if(pNumber == (CONST INT8 *)NULL || pBCD == (UINT8 *)NULL) return FALSE; SUL_MemSet8(pBCD, 0, nNumberLen >> 1); for(i = 0; i < nNumberLen; i++) { switch(*pNumber) { case '*': Tmp = (INT8)0x0A; break; case '#': Tmp = (INT8)0x0B; break; case 'p': Tmp = (INT8)0x0C; break; //-------------------------------------------- //Modify by lixp 20070626 begin //-------------------------------------------- case 'w': Tmp = (INT8)0x0D; break; case '+': Tmp = (INT8)0x0E; break; //-------------------------------------------- //Modify by lixp 20070626 end //-------------------------------------------- default: Tmp = (INT8)(*pNumber - '0'); break; } if(i % 2) { *pTmp++ |= (Tmp << 4) & 0xF0; } else { *pTmp = (INT8)(Tmp & 0x0F); } pNumber++; } nBcdSize = nNumberLen >> 1; if(i % 2) { *pTmp |= 0xF0; nBcdSize += 1; } return nBcdSize; } // // 该函数会去掉最后的F,同时将A转化为‘*’将B转化为‘#’将C转化为‘p’ // --> 13811189836 // UINT16 SUL_GsmBcdToAscii ( UINT8 *pBcd, // input UINT8 nBcdLen, UINT8 *pNumber // output ) { UINT8 i; UINT8 *pTmp = pNumber; UINT16 nSize = nBcdLen * 2; for(i = 0; i < nBcdLen; i++) { if((pBcd[i] & 0x0F) == 0x0A) { *pTmp = '*'; } else if((pBcd[i] & 0x0F) == 0x0B) { *pTmp = '#'; } else if((pBcd[i] & 0x0F) == 0x0C) { *pTmp = 'p'; } // -------------------------------------------- // Modify by lixp 20070626 begin // -------------------------------------------- else if ((pBcd[i] & 0x0F) == 0x0D) { *pTmp = 'w'; } else if ((pBcd[i] & 0x0F) == 0x0E) { *pTmp = '+'; } // -------------------------------------------- // Modify by lixp 20070626 end // -------------------------------------------- else { *pTmp = (pBcd[i] & 0x0F) + 0x30; } pTmp ++; if((pBcd[i]) >> 4 == 0x0A) { *pTmp = '*'; } else if((pBcd[i]) >> 4 == 0x0B) { *pTmp = '#'; } else if((pBcd[i]) >> 4 == 0x0C) { *pTmp = 'p'; } // -------------------------------------------- // Modify by lixp 20070626 begin // -------------------------------------------- else if((pBcd[i]) >> 4 == 0x0D) { *pTmp = 'w'; } else if((pBcd[i]) >> 4 == 0x0E) { *pTmp = '+'; } // -------------------------------------------- // Modify by lixp 20070626 end // -------------------------------------------- else { *pTmp = (pBcd[i] >> 4) + 0x30; } pTmp++; } pTmp--; if(*pTmp == 0x3f) { *pTmp = 0x00; nSize -= 1; } return nSize; } UINT16 SUL_AsciiToGsmBcdEx( INT8 *pNumber, // input UINT8 nNumberLen, UINT8 *pBCD // output should >= nNumberLen/2+1 ) { UINT8 Tmp; UINT32 i; UINT32 nBcdSize = 0; UINT8 *pTmp = pBCD; if(pNumber == (CONST INT8 *)NULL || pBCD == (UINT8 *)NULL) return FALSE; SUL_MemSet8(pBCD, 0, nNumberLen >> 1); for(i = 0; i < nNumberLen; i++) { switch(*pNumber) { case 0x41: case 0x61: Tmp = (INT8)0x0A; break; case 0x42: case 0x62: Tmp = (INT8)0x0B; break; case 0x43: case 0x63: Tmp = (INT8)0x0C; break; //-------------------------------------------- //Modify by lixp 20070626 begin //-------------------------------------------- case 0x44: case 0x64: Tmp = (INT8)0x0D; break; case 0x45: case 0x65: Tmp = (INT8)0x0E; break; case 0x46: case 0x66: Tmp = (INT8)0x0F; break; //-------------------------------------------- //Modify by lixp 20070626 end //-------------------------------------------- default: Tmp = (INT8)(*pNumber - '0'); break; } if(i % 2) { *pTmp++ |= (Tmp << 4) & 0xF0; } else { *pTmp = (INT8)(Tmp & 0x0F); } pNumber++; } nBcdSize = nNumberLen >> 1; if(i % 2) { *pTmp |= 0xF0; nBcdSize += 1; } return nBcdSize; } UINT16 SUL_GsmBcdToAsciiEx ( UINT8 *pBcd, // input UINT8 nBcdLen, UINT8 *pNumber // output ) { UINT8 i; UINT8 *pTmp = pNumber; UINT16 nSize = nBcdLen * 2; for(i = 0; i < nBcdLen; i++) { if((pBcd[i] & 0x0F) == 0x0A) { *pTmp = 0x41; } else if((pBcd[i] & 0x0F) == 0x0B) { *pTmp = 0x42; } else if((pBcd[i] & 0x0F) == 0x0C) { *pTmp = 0x43; } // -------------------------------------------- // Modify by lixp 20070626 begin // -------------------------------------------- else if ((pBcd[i] & 0x0F) == 0x0D) { *pTmp = 0x44; } else if ((pBcd[i] & 0x0F) == 0x0E) { *pTmp = 0x45; } // -------------------------------------------- // Modify by lixp 20070626 end // -------------------------------------------- else if ((pBcd[i] & 0x0F) == 0x0F) { *pTmp = 0x46; } else { *pTmp = (pBcd[i] & 0x0F) + 0x30; } pTmp ++; if((pBcd[i]) >> 4 == 0x0A) { //*pTmp = 0x61; *pTmp = 0x41; } else if((pBcd[i]) >> 4 == 0x0B) { //*pTmp =0x62; *pTmp = 0x42; } else if((pBcd[i]) >> 4 == 0x0C) { //*pTmp =0x63; *pTmp = 0x43; } // -------------------------------------------- // Modify by lixp 20070626 begin // -------------------------------------------- else if((pBcd[i]) >> 4 == 0x0D) { //*pTmp =0x64; *pTmp = 0x44; } else if((pBcd[i]) >> 4 == 0x0E) { //*pTmp =0x65; *pTmp = 0x45; } else if((pBcd[i]) >> 4 == 0x0F) { //*pTmp =0x66; *pTmp = 0x46; } // -------------------------------------------- // Modify by lixp 20070626 end // -------------------------------------------- else { *pTmp = (pBcd[i] >> 4) + 0x30; } pTmp++; } pTmp--; if(*pTmp == 0x3f) { *pTmp = 0x00; nSize -= 1; } return nSize; } UINT16 SUL_gsmbcd2ascii ( UINT8 *pBcd, // input UINT8 nBcdLen, UINT8 *pNumber // output ) { UINT8 i; UINT8 *pOutput = pNumber; UINT8 nTable[]= {'*','#','p','w','+'}; for(i = 0; i < nBcdLen; i++) { UINT8 low4bits = pBcd[i] & 0x0F; UINT8 high4bits = pBcd[i] >> 4; if(low4bits < 0x0A) //0 - 0x09 { *pOutput++ = low4bits + '0'; } else if(low4bits < 0x0F) //0x0A - 0x0E { *pOutput++ = nTable[low4bits - 0x0A]; } if(high4bits < 0x0A) //0 - 0x09 { *pOutput++ = high4bits + '0'; } else if(high4bits < 0x0F) //0x0A - 0x0E { *pOutput++ = nTable[high4bits - 0x0A]; } } return pOutput - pNumber; } /* UINT8 *pBcd, Input data UINT16 nBcdLen, Number of input data in byte UINT8 *pNumber, Output buffer, Its size should be twice nBcdLen at least. */ UINT16 SUL_gsmbcd2asciiEx( UINT8 *pBcd, UINT16 nBcdLen, UINT8 *pNumber ) { UINT16 i; UINT8 *pTmp = pNumber; for(i = 0; i < nBcdLen; i++) { UINT8 high4bits = pBcd[i] >> 4; UINT8 low4bits = pBcd[i] & 0x0F; if(low4bits < 0x0A) *pTmp++ = low4bits + '0'; // 0 - 0x09 else if(low4bits < 0x0F) // 0x0A - 0x0F *pTmp++ = low4bits - 0x0A + 'A'; if(high4bits < 0x0A) *pTmp++ = high4bits + '0'; // 0 - 9 else if(high4bits < 0x0F) // 0x0A - 0x0F *pTmp++ = high4bits - 0x0A + 'A'; } return pTmp - pNumber; } UINT8 SUL_hex2ascii(UINT8* pInput, UINT16 nInputLen, UINT8* pOutput) { UINT16 i; UINT8* pBuffer = pOutput; for(i = 0; i < nInputLen; i++) { UINT8 high4bits = pInput[i] >> 4; UINT8 low4bits = pInput[i] & 0x0F; if(high4bits < 0x0A) *pOutput++ = high4bits + '0'; // 0 - 9 else // 0x0A - 0x0F *pOutput++ = high4bits - 0x0A + 'A'; if(low4bits < 0x0A) *pOutput++ = low4bits + '0'; // 0 - 0x09 else // 0x0A - 0x0F *pOutput++ = low4bits - 0x0A + 'A'; } return pOutput -pBuffer; } UINT8 SUL_ascii2hex(UINT8* pInput, UINT8* pOutput) { UINT16 i = 0; UINT16 length = strlen(pInput); UINT16 j = length; UINT8 nData; UINT8* pBuffer = pOutput; UINT8* pIn = pInput; if((length & 0x01) == 0x01) { nData = pIn[0]; if((nData >= '0') && (nData <= '9')) *pBuffer = nData - '0'; else if((nData >= 'a') && (nData <= 'f')) *pBuffer = nData - 'a' + 10; else if((nData >= 'A') && (nData <= 'F')) *pBuffer = nData - 'A' + 10; else return 0; length--; pBuffer++; pIn++; } for(i = 0; i < length; i++) { if((i & 0x01 ) == 0x01) // even is high 4 bits, it should be shift 4 bits for left. *pBuffer = (*pBuffer) << 4; else *pBuffer = 0; nData = pIn[i]; if((nData >= '0') && (nData <= '9')) *pBuffer |= nData - '0'; else if((nData >= 'a') && (nData <= 'f')) *pBuffer |= nData - 'a' + 10; else if((nData >= 'A') && (nData <= 'F')) *pBuffer |= nData - 'A' + 10; else return 0; if((i & 0x01 ) == 0x01) pBuffer++; } if((j & 0x01 ) == 0x01) length++; return (length + 1) >> 1; }
C
#include <stdio.h> int main() { float sb, sl, inss; printf("digite o valor do SB "); scanf("%f", &sb); if(sb <= 420) { inss = ( sb * 8 ) / 100; sl = sb - inss; printf("Valor do inss = %f , valor do salario liquido = %f", inss, sl); } if((sb > 420) && (sb < 1350)) { inss = ( sb * 9 ) / 100; sl = sb - inss; printf("Valor do inss = %f , valor do salario liquido = %f", inss, sl); } if(sb > 1350) { inss = ( sb * 10 ) / 100; sl = sb - inss; printf("Valor do inss = %f , valor do salario liquido = %f", inss, sl); } return 0; }
C
///////////////////////////////////////////////////////////////////////////////////////////////////// // Accept character from user and display its ASCII value in decimal, // octal and hexadecimal format. // Input : A // Output : Decimal 65 // Octal 0101 // Hexadecimal 0X41 // Author : Annaso Chavan ///////////////////////////////////////////////////////////////////////////////////////////////////// #include<stdio.h> #include<stdlib.h> void Display(char ch) { printf("Decimal %d\n",ch); printf("Octal %o\n",ch); printf("Hexadecimal %X",ch); } int main() { char cValue = '\0'; printf("Enter the character :"); scanf("%c",&cValue); Display(cValue); return 0; }
C
#include "bubble.h" // Takes an array and the array size as inputs and sorts it in a Bubble Sort // method void Bubble_sort(int *arr, int size) { printf("Bubble Sort\n"); int moves = 0; int compares = 0; int j = 0; for (int i = 0; i <= size - 1; i++) { j = size - 1; while (j > i) { compares += 1; if (arr[j] < arr[j - 1]) { moves += 3; int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } j -= 1; } } printf("%d elements, %d moves, %d compares\n", size, moves, compares); return; } // Psuedo Code Aquired From Lab Document
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* dirs_handling.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shasnaou <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/08 18:44:02 by shasnaou #+# #+# */ /* Updated: 2019/06/15 15:07:01 by shasnaou ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" int read_dir(t_ptr *ptr, t_list **i, char *name, char *d_name) { *i = NULL; ptr->data.dir = opendir(name); if (!ptr->one_arg) { ft_putstr(name); ft_putstr(":\n"); } ptr->one_arg = 0; if (!(ptr->data.dir)) { print_errors(d_name); return (-1); } while ((ptr->data.d = readdir(ptr->data.dir))) { if (!ptr->flags[a] && *(ptr->data.d->d_name) == '.') continue ; addinfo(i, ptr, name, ptr->data.d->d_name); } closedir(ptr->data.dir); return (0); } void free_info_and_ldirs(t_ptr *ptr, t_list **ldirs, t_list **i) { t_list *cp_ldirs; if (*i) free_handler(ptr, &(*i)); while (*ldirs) { cp_ldirs = *ldirs; *ldirs = (*ldirs)->next; free(cp_ldirs); } } void sort_and_print(t_ptr *ptr, t_list **info, t_list **ldirs) { ascii_sort(info); ascii_sort(ldirs); sort(ptr, &(*info)); sort(ptr, &(*ldirs)); print_info(ptr, &(*info)); } int dirs_handling(t_ptr *ptr, char *name, char *d_name) { char *path; t_list *info; t_list *ldirs; t_info *dir; t_list *dtmp; path = NULL; read_dir(ptr, &info, name, d_name); ldirs = get_list_dirs(&info); sort_and_print(ptr, &info, &ldirs); dtmp = ldirs; while (dtmp) { dir = (t_info *)dtmp->content; if (ft_strcmp(dir->d_name, "..") && ft_strcmp(dir->d_name, ".")) { path = ft_strjoinc(name, '/', dir->d_name); ft_putchar_fd('\n', 1); dirs_handling(ptr, path, dir->d_name); free(path); } dtmp = dtmp->next; } free_info_and_ldirs(ptr, &ldirs, &info); return (0); }
C
#include<stdio.h> void main() { int a=0,b=0; while(a<10) { if(a==5) { a=a+1; continue; }else{ printf("%d",a); b=b+1; a=a+1; } } }