language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>
#include "propietarios.h"
int prop_menu ()
{
int opc;
printf("::::::::::::::::::: MENU DE OPERACIONES :::::::::::::::::::");
printf("\n\n");
printf(" 1- AGREGAR PROPIETARIO\n");
printf(" 2- MODIFICAR NUMERO DE TARJETA\n");
printf(" 3- DAR DE BAJA PROPIETARIO\n");
printf(" 4- LISTAR PROPIETARIO/S\n");
printf(" 5- INGRESO DE VEHICULO\n");
printf(" 6- LISTA DE VEHICULOS EN EL ESTACIONAMIENTO\n");
printf(" 7- EGRESO DE VEHICULO\n");
printf(" 8- RECAUDACION TOTAL DEL ESTACIONAMIENTO\n");
printf(" 9- RECAUDACION TOTAL POR MARCA\n");
printf("10- LISTA DE PROPIETARIO CON SU/S VEHICULO/S\n");
printf("11- LISTA DE PROPIETARIO/S QUE POSEEN VEHICULO MARCA AUDI\n");
printf("12- LISTA DE VEHICULOS EN EL ESTACIONAMIENTO ORDENADOS POR PATENTE\n");
printf("\n13- ORDENADO POR MARCA\n");
printf("14- LISTA DE AUTOS EGRESADOS\n");
printf("15- TICKET DEL VEHICULO EGRESADO CON MAYOY IMPORTE\n");
printf("\n20- SALIR\n");
printf("\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n");
opc=getValidInt("\n Elija una operacion: ", "\n\n ERROR. Operacion invalida ", 1, 20);
return opc;
}
/********************************************************************************************/
int prop_inicializar (ePropietario* pPropietario ,int cantidad)
{
int i, retorna=-1;
if(pPropietario!=NULL && cantidad>0)
{
for(i=0;i<cantidad;i++)
{
pPropietario[i].isEmpty==FREE; //FREE=0 que esta vacio
}
retorna=0;
}
return retorna;
}
/********************************************************************************************/
void prop_hardCode (ePropietario* pPropietario)
{
int idAux[5]={100,101,102,103,104};
char apellidoAux[][51]={"Rueda","Gonsalez","Fernandez","Hernandez","Rodriguez"};
char nombreAux[][51]={"Matias","Maria","Pablo","Agustina","Aldana"};
char direccionAux [][100]={"Localidad 111","Localidad 222","Localidad 333","Localidad 444","Localidad 555"};
int tarjetaAux[5]={10001,20002,30003,40004,50005};
int i;
for(i=0;i<5;i++)
{
pPropietario[i].idPropietario=idAux[i];
strcpy(pPropietario[i].apellido, apellidoAux[i]);
strcpy(pPropietario[i].nombre, nombreAux[i]);
strcpy(pPropietario[i].direccion, direccionAux[i]);
pPropietario[i].numTarjeta=tarjetaAux[i];
pPropietario[i].isEmpty=FULL;
}
}
/********************************************************************************************/
/** \brief funcion que genera un ID, iniciando en 103 para dar desde el 104 en adelante
* \param void
* \return int Retorna el id generado
*/
int prop_creatId ()
{
static int contar=104;
contar++;
return contar;
}
/********************************************************************************************/
int prop_buscarEspacioLibre (ePropietario* pPropietario, int cantidad)
{
int i, space=-1; //devuelve -1 en caso de no encontrar espacio libre
for(i=0;i<cantidad;i++)
{
if(pPropietario[i].isEmpty==FREE)
{
space=i;
break;
}
}
return space;
}
/********************************************************************************************/
int prop_buscarPorID (ePropietario* pPropietario, int cantidad, int id)
{
int i, indice=-1;
if(pPropietario!=NULL)
{
for(i=0;i<cantidad;i++)
{
if( pPropietario[i].idPropietario==id && pPropietario[i].isEmpty==FULL)
{
indice=i;
break;
}
}
}
return indice;
}
/********************************************************************************************/
void prop_darDeAlta (ePropietario* pPropietario, int cantidad)
{
int lugar, i;
int aux_id, aux_tarjeta;
char aux_name[51], aux_lastName[51], aux_direccion[100];
lugar=prop_buscarEspacioLibre(pPropietario,cantidad);
if(lugar == -1)
{
printf("\n :::::::::::::::::::::::::::::::::::::::::::::::::\n");
printf(" :: Memoria llena, imposible seguir operando. ::\n");
printf(" :::::::::::::::::::::::::::::::::::::::::::::::::\n\n\n");
}
else
{
getValidString("\n APELLIDO: ","\n\n ERROR, apellido invalido\n",aux_lastName);
for(i=0;i<strlen(aux_lastName);i++)
{
if(i==0)
{
aux_lastName[i]=toupper(aux_lastName[i]);
}
}
getValidString("\n NOMBRE: ","\n\n ERROR, nombre invalido\n",aux_name);
for(i=0;i<strlen(aux_name);i++)
{
if(i==0)
{
aux_name[i]=toupper(aux_name[i]);
}
}
printf("\n DIRECCION: ");
setbuf(stdin,NULL);
scanf("%[^\n]", aux_direccion);
while(esAlfaNumerico(aux_direccion)==0)
{
printf("\n\n ERROR, direccion invalidad\n DIRECCION: ");
setbuf(stdin,NULL);
scanf("%[^\n]", aux_direccion);
}
for(i=0;i<strlen(aux_direccion);i++)
{
if(i==0)
{
aux_direccion[i]=toupper(aux_direccion[i]);
}
}
aux_tarjeta=getValidInt("\n TARJETA DE CREDITO (5 NUMEROS) : ","ERROR, numero invalido \n\n",00000,99999);
aux_id=prop_creatId();
printf("\n\n Id generado: %d",aux_id);
prop_setDatos(pPropietario, lugar, aux_id, aux_lastName,aux_name,aux_direccion,aux_tarjeta);
printf("\n\n Alta exitosa!!!!!\n\n");
}
}
/********************************************************************************************/
void prop_setDatos (ePropietario* pPropietario, int lugar, int id, char apellido[], char nombre[], char direccion[], int tarjeta )
{
pPropietario[lugar].idPropietario=id;
strcpy(pPropietario[lugar].apellido, apellido);
strcpy(pPropietario[lugar].nombre, nombre);
strcpy(pPropietario[lugar].direccion, direccion);
pPropietario[lugar].numTarjeta=tarjeta;
pPropietario[lugar].isEmpty=FULL;
}
/********************************************************************************************/
/********************************************************************************************/
int prop_print (ePropietario* pPropietario, int cantidad)
{
int retorna=-1, i;
for(i=0;i<cantidad;i++)
{
if(pPropietario!=NULL && cantidad>0)
{
printf("\n ID \t APELLIDO \t NOMBRE \t DIRECCION \t TARJETA DE CREDITO");
for(i=0;i<cantidad;i++)
{
if(pPropietario[i].isEmpty==FULL)
{
printf("\n %d \t %5s \t %5s \t %5s \t %10d ",pPropietario[i].idPropietario,pPropietario[i].apellido,pPropietario[i].nombre,pPropietario[i].direccion,pPropietario[i].numTarjeta);
retorna=0;
}
}
}
}
return retorna;
}
void prop_ordenar_apelidoNombre (ePropietario* pPropietario, int cantidad)
{
ePropietario auxiliar;
int i,j, noOrdenado=-1;
if(pPropietario!=NULL && cantidad>0)
{
while(noOrdenado==-1)
{
noOrdenado=0;
for(i=0;i<cantidad-1;i++)
{
for(j=i+1;j<cantidad;j++)
{
if(strcmp(pPropietario[j].apellido, pPropietario[i].apellido)<0)
{
auxiliar=pPropietario[i];
pPropietario[i]=pPropietario[j];
pPropietario[j]=auxiliar;
noOrdenado=-1;
}
else if(strcmp(pPropietario[j].apellido, pPropietario[i].apellido)==0 && strcmp(pPropietario[j].nombre, pPropietario[i].nombre)<0)
{
auxiliar=pPropietario[i];
pPropietario[i]=pPropietario[j];
pPropietario[j]=auxiliar;
noOrdenado=-1;
}
}
}
}
}
}
int prop_print_ordenCrecienteNombreApellido (ePropietario* pPropietario, int cantidad)
{
int retorna=-1, i;
prop_ordenar_apelidoNombre(pPropietario,cantidad);
for(i=0;i<cantidad;i++)
{
if(pPropietario!=NULL && cantidad>0)
{
printf("\n ID \t APELLIDO \t NOMBRE \t DIRECCION \t TARJETA DE CREDITO");
for(i=0;i<cantidad;i++)
{
if(pPropietario[i].isEmpty==FULL)
{
printf("\n %d \t %5s \t %5s \t %5s \t %10d ",pPropietario[i].idPropietario,pPropietario[i].apellido,pPropietario[i].nombre,pPropietario[i].direccion,pPropietario[i].numTarjeta);
retorna=0;
}
}
}
}
return retorna;
}
/********************************************************************************************/
void prop_actualizar (ePropietario* pPropietario, int cantidad)
{
int i, aux_id, lugar;
int aux_tarjeta;
//char aux_lastName[51], aux_name[51], aux_direccion[100];
int stop=-1;
char confirmar;
aux_id=getValidInt("\n ID del propietario a actulizar: ","\n ERROR, id invalido\n\n ", 100,120);
lugar=prop_buscarPorID(pPropietario,cantidad,aux_id);
if(pPropietario!=NULL)
{
if(lugar>=0)
{
system("cls");
printf("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n");
printf("\ Propietario a renovar: \nID: %d \n APELLIDO: %s \n NOMBRE: %s \n DIRECCION: %s \n NUMERO TARJETA: %d \n",pPropietario[lugar].idPropietario,pPropietario[lugar].apellido,pPropietario[lugar].nombre,pPropietario[lugar].direccion,pPropietario[lugar].numTarjeta);
printf("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n");
confirmar=getChar("\n Desea actualizar? (s/n): ");
do{
if(confirmar=='s')
{
aux_tarjeta=getValidInt("\n\n NUEVO NUMERO DE TARJETA : ","ERROR, numero invalido \n\n",00000,99999);
pPropietario[lugar].numTarjeta=aux_tarjeta;
stop=1;
}
else if(confirmar=='n')
{
printf("\n\n Actualizacion cancelada\n\n");
stop=1;
}
else
{
printf("\n Respuesta invalida\n");
stop=-1;
}
}while(stop!=1);
}
else
{
printf("\n :::::::::::::::::::::::::::::::::::::::::::::::::\n");
printf(" :: Id: %d no existe en el sistema. ::\n",aux_id);
printf(" :::::::::::::::::::::::::::::::::::::::::::::::::\n\n\n");
}
}
}
|
C
|
/*
* Multistage graph algorithm implementation in C
* by Shaik Sameer, jan 28 2021
*/
#include <stdio.h>
void solve(int N, int graph[][N+1], int stages)
{
int cost[N+1]; // cost array to store the optimal cost of every vertex to the sink
int d[N+1]; // destination array to store the optimal destination of every vertex
int source = 1;
int sink = N;
cost[sink] = 0; // cost to reach from sink to sink = 0
d[sink] = sink; // destination of sink is sink itself.
// first stage contains only one source vertex
// last stage contains only one sink vertex
// go from previous stage of sink to first stage and figure out optimal costs and destinations
for (int i = N-1; i >= 1; i--)
{
// Now figure out minimum cost edge to this stage (i) to i+1 th stage
int min = 32767;
// since it is a directed graph and there are no backward edges
// so move forward only
for (int j = i+1; j <= N; j++)
// if edge exists from i to j and edge cost + optimal cost of next stage vertex connected to it < min
// then update the min, cost, d.
if (graph[i][j] != 0 && graph[i][j] + cost[j] < min)
{
min = graph[i][j] + cost[j];
d[i] = j;
}
cost[i] = min;
}
printf("Minimum cost is %d\n", cost[source]);
printf("The path is: ");
int path[stages+1];
path[source] = 1;
path[stages] = sink;
for (int i = 2; i < stages; i++)
path[i] = d[path[i-1]];
for (int i = 1; i <= stages; i++)
printf("%d->", path[i]);
}
int main(int argc, char const *argv[])
{
int N;
printf("Enter the number of nodes: ");
scanf("%d", &N);
int stages;
printf("Enter the number of stages: ");
scanf("%d", &stages);
int graph[N+1][N+1];
printf("Enter the adjacency matrix\n");
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
scanf("%d", &graph[i][j]);
solve(N, graph, stages);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void enqueue();
void display();
void dequeue();
void isEmpty();
void isFull();
int a[10],i=0,e,n,t,front=-1,rear=-1;
main()
{
printf(" 17BCE0042\n");
char option='T';
while(option=='T')
{
printf("\n");
printf("Enter command (17BCE0042)\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. isEmpty\n");
printf("5. isFull\n");
printf("6. Peek\n");
printf("7. Exit\n\n");
scanf("%d",&n);
switch(n)
{
case 1:
enqueue();
display();
break;
case 2:
dequeue();
display();
break;
case 3:
display();
break;
case 4:
isEmpty();
break;
case 5:
isFull();
display();
break;
case 6:
printf("\nPeek is %d\n",a[rear]);
break;
case 7:
printf(" Thankyou!!\n");
exit(0);
}
}
}
void dequeue()
{
if (rear==-1)
{
printf("Sorry\nQueue is Empty\n");
return;
}
for(i=front;i<rear;i++)
{
a[i]=a[i+1];
}
printf("Done\n");
rear--;
}
void enqueue()
{
if (rear==4)
{
printf("Sorry\nQueue is already full\n");
return;
}
if(front==-1)
{
front++;
}
printf("Enter number\n");
scanf("%d",&e);
a[rear+1]=e;
rear++;
}
void display()
{
printf("\n");
for (i=0;i<=rear;i++)
{
printf("%d\n",a[i]);
}
}
void isEmpty()
{
if (rear==-1)
{
printf("Yes, it is empty");
}
else
{
printf("No it is not empty");
}
}
void isFull()
{
if (rear==4)
{
printf("Queue is FULL!!");
}
else{
printf("No it is not full");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "timers_lib.h"
// node of a list (bucket)
struct node_t{
int value;
int hash_code;
struct node_t * next;
};
int MAX_LOCKS=64;
struct HashSet{
//int length;
struct node_t ** table;
int capacity;
int setSize;
__int128 atomic_locks;
int locks_length;
__int128 owner;
};
int NULL_VALUE = 5139239;
__int128 get_count(__int128 a){
__int128 b = a >>64;
return b;
}
__int128 get_pointer(__int128 a){
__int128 b = a << 64;
b= b >>64;
return b;
}
__int128 set_count(__int128 a, __int128 count){
__int128 count_temp = count << 64;
__int128 b = get_pointer(a);
b = b | count_temp;
return b;
}
__int128 set_pointer(__int128 a, __int128 ptr){
__int128 b = 0;
__int128 c = get_count(a);
b = set_count(b,c);
ptr = get_pointer(ptr);
b= b | ptr;
return b;
}
__int128 set_both(__int128 a, __int128 ptr, __int128 count){
a=set_pointer(a,ptr);
a=set_count(a,count);
return a;
}
void lock_set (int * locks, int hash_code){
int indx=hash_code;
//int indx=hash_code % H->locks_length;
while (1){
if (!locks[indx]){
if(!__sync_lock_test_and_set(&(locks[indx]),1)) break;
}
}
}
void unlock_set(int *,int);
// operations call acquire to lock
void acquire(struct HashSet *H,int hash_code){
__int128 me = (__int128) omp_get_thread_num();
__int128 who,cpy_owner,mark;
while (1){
cpy_owner=H->owner;
who=get_pointer(cpy_owner);
mark=get_count(cpy_owner);
while((mark==(__int128)1)&&(who!=me)){
cpy_owner=H->owner;
who=get_pointer(cpy_owner);
mark=get_count(cpy_owner);
}
//int old_locks_length=H->locks_length;
//int * old_locks=H->locks;
__int128 cpy_locks=H->atomic_locks;
__int128 old_locks=get_pointer(cpy_locks);
int old_locks_length =(int)get_count(cpy_locks);
lock_set(old_locks,hash_code % old_locks_length);
cpy_owner=H->owner;
who=get_pointer(cpy_owner);
mark=get_count(cpy_owner);
if(((!mark) || (who==me))&&(H->atomic_locks==cpy_locks)){
return;
}
else{
unlock_set(old_locks,hash_code % old_locks_length);
}
}
}
void unlock_set(int * locks, int hash_code){
int indx=hash_code;
//int indx=hash_code % H->locks_length;
locks[indx] = 0;
}
void release(struct HashSet * H,int hash_code){
unlock_set((int *)get_pointer(H->atomic_locks),hash_code % ((int)get_count(H->atomic_locks)));
}
//search value in bucket;
int list_search(struct node_t * Head,int val){
struct node_t * curr;
curr=Head;
while(curr){
if(curr->value==val) return 1;
curr=curr->next;
}
return 0;
}
//add value in bucket;
//NOTE: duplicate values are allowed...
void list_add(struct HashSet * H, int key,int val,int hash_code){
struct node_t * curr;
struct node_t * next;
struct node_t * node=(struct node_t *)malloc(sizeof(struct node_t));
/*node->value=val;
node->next=NULL;
curr=H->table[key];
if(curr==NULL){
H->table[key]=node;
return ;
}
while(curr->next){
curr=curr->next;
next=curr->next;
}
curr->next=node;
*/
node->value=val;
node->hash_code=hash_code;
if(H->table[key]==NULL) node->next=NULL;
else node->next=H->table[key];
H->table[key]=node;
}
// delete from bucket. The fist value equal to val will be deleted
int list_delete(struct HashSet *H,int key,int val){
struct node_t * curr;
struct node_t * next;
struct node_t * prev;
curr=H->table[key];
prev=curr;
if((curr!=NULL)&&(curr->value==val)) {
H->table[key]=curr->next;
free(curr);
return 1;
}
while(curr){
if( curr->value==val){
prev->next=curr->next;
free(curr);
return 1;
}
prev=curr;
curr=curr->next;
}
return 0;
}
void initialize(struct HashSet * H, int capacity){
int i;
H->setSize=0;
H->capacity=capacity;
H->table = (struct node_t **)malloc(sizeof(struct node_t *)*capacity);
for(i=0;i<capacity;i++){
H->table[i]=NULL;
}
int new_locks_length=capacity;
int * new_locks=(int *)malloc(sizeof(int) * capacity);
for(i=0;i<capacity;i++) new_locks[i]=0;
H->atomic_locks = set_both(H->atomic_locks,(__int128)new_locks,(__int128)new_locks_length);
printf("length count %lld \n",get_count(H->atomic_locks));
H->owner = set_both(H->owner,(__int128)NULL_VALUE,0);
}
int policy(struct HashSet *H){
return ((H->setSize/H->capacity) >4);
}
void resize(struct HashSet *);
int contains(struct HashSet *H,int hash_code, int val){
int bucket_index = hash_code % H->capacity;
int res=list_search(H->table[bucket_index],val);
acquire(H,hash_code);
bucket_index = hash_code % H->capacity;
res=list_search(H->table[bucket_index],val);
release(H,hash_code);
return res;
}
//reentrant ==1 means we must not lock( we are calling from resize so we have already locked the data structure)
void add(struct HashSet *H,int hash_code, int val, int reentrant){
if(!reentrant) acquire(H,hash_code);
int bucket_index = hash_code % H->capacity;
list_add(H,bucket_index,val,hash_code);
//H->setSize++;
__sync_fetch_and_add(&(H->setSize),1);
if(!reentrant) release(H,hash_code);
if(!reentrant) {if (policy(H)) resize(H);}
}
int delete(struct HashSet *H,int hash_code, int val){
acquire(H,hash_code);
int bucket_index = hash_code % H->capacity;
int res=list_delete(H,bucket_index,val);
//H->setSize--;
__sync_fetch_and_sub(&(H->setSize),1);
release(H,hash_code);
return res;
}
void quiesce(struct HashSet *H){
int i;
int *locks=(int *)get_pointer(H->atomic_locks);
int locks_length=(int*) get_count(H->atomic_locks);
for(i=0;i<locks_length;i++){
while(locks[i]==1); //TODO: is it a race?
}
}
void resize(struct HashSet *H){
int i;
__int128 mark,me;
struct node_t * curr;
int old_capacity = H->capacity;
int new_capacity = old_capacity * 2;
me = (__int128)omp_get_thread_num();
__int128 expected_value = set_both(expected_value,(__int128)NULL_VALUE,0);
__int128 new_owner=set_both(new_owner,me,(__int128)1);
if(__sync_bool_compare_and_swap(&(H->owner),expected_value,new_owner)){
//for(i=0;i<H->locks_length;i++) lock_set(H,i);
if(old_capacity!=H->capacity) {
//for(i=0;i<H->locks_length;i++) //unlock_set(H,i);
H->owner=set_both(H->owner,(__int128)NULL_VALUE,0);
return; //somebody beat us to it
}
quiesce(H);
//H->locks_length = new_capacity; //in this implementetion
//locks_length == capacity
//edit!!
int new_locks_length;
if(new_capacity<=64) new_locks_length=new_capacity;
else new_locks_length=64;
struct node_t ** old_table = H->table;
H->setSize=0;
H->table = (struct node_t **)malloc(sizeof(struct node_t *)*new_capacity);
for(i=0;i<new_capacity;i++){
H->table[i]=NULL;
}
//re hash everything from the old table to the new one
for(i=0;i<old_capacity;i++){
curr=old_table[i];
while(curr){
int val = curr->value;
int hash_code = curr->hash_code;
//int bucket_index= hash_code % new_capacity;
add(H,hash_code,val,1);
curr=curr->next;
}
}
//free(old_table);
//all locks should be free now (quiesce ensures that)
//so we might as well delete the old ones and make new ones
int * old_locks = (int *)get_pointer(H->atomic_locks);
//for(i=0;i<old_capacity;i++) if( H->locks[i]!=0) printf("HEY!\n");
int * new_locks = (int *)malloc(sizeof(int) * new_locks_length);//edit!
for(i=0;i<new_locks_length;i++) new_locks[i]=0;//edit
__int128 temp_atomic_locks=set_both(temp_atomic_locks,(__int128)new_locks,(__int128)new_locks_length);
H->atomic_locks=temp_atomic_locks;
H->capacity = new_capacity;
expected_value = new_owner;
new_owner = set_both(new_owner,(__int128)NULL_VALUE,0);
if(!__sync_bool_compare_and_swap(&(H->owner),expected_value,new_owner))
printf("This should not have happened\n");
//free(old_locks);
}
}
/* Arrange the N elements of ARRAY in random order.
Only effective if N is much smaller than RAND_MAX;
if this may not be the case, use a better random
number generator. */
void shuffle(int *array, size_t n)
{
if (n > 1)
{
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
void print_set(struct HashSet * H){
int i;
for(i=0;i<H->capacity;i++){
struct node_t * curr=H->table[i];
while(curr){
printf("(%d) ",curr->value);
curr=curr->next;
}
printf("--\n");
}
}
void main(int argc,char * argv[]){
int num_threads=atoi(argv[1]);
int inp_1=atoi(argv[2]);
int inp_2=atoi(argv[3]);
int inp_3=atoi(argv[4]);
struct HashSet * H=(struct HashSet *) malloc(sizeof(struct HashSet));
initialize(H,16);
srand(time(NULL));
int c,k,i,j;
int op_count=1000000;
int finds=inp_1;
int deletes=inp_2;
int inserts=inp_3;
timer_tt * timer;
//int MAX_COUNT=100000;//NOTE!!!! we assume that count=10*MAX_SIZE
int value_table[op_count];
int op_table[op_count];
for(i=0;i<op_count;i++) value_table[i]=rand()%100000;
for(i=0;i<finds;i++) op_table[i]=1;
for(i=0;i<deletes;i++) op_table[finds+i]=2;
for(i=0;i<inserts;i++) op_table[finds+deletes+i]=3;
shuffle(op_table,op_count);
int segm=op_count/num_threads;
int indx,res;
double total_time=0;
#pragma omp parallel for num_threads(num_threads) shared(H,value_table,op_table) private(c,j,timer,res,k,indx) reduction(+:total_time)
for(i=0;i<num_threads;i++){
c=50;
timer = timer_init(timer);
timer_start(timer);
for(j=0;j<(1000000/num_threads);j++){
for(k=0;k<c;k++);
indx=(omp_get_thread_num()*segm+j)%op_count;
if(op_table[indx]==1) res=contains(H,value_table[indx],value_table[indx]);
else if(op_table[indx]==2) res=delete(H,value_table[indx],value_table[indx]);
else add(H,value_table[indx],value_table[indx],0);
}
timer_stop(timer);
total_time = timer_report_sec(timer);
printf("%thread %d timer %lf\n",omp_get_thread_num(),timer_report_sec(timer));
}
double avg_total_time=total_time/(double)num_threads;
printf("avg total time %lf\n",avg_total_time);
printf("%d \n",H->setSize);
printf("%d \n",H->capacity);
return;
}
|
C
|
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv) {
int fd1 = open("out.txt", O_RDWR);
char str[] = "xyz";
char c;
write(fd1, str, 1);
read(fd1, &c, 1);
write(fd1, &c, 1);
return 0;
}
|
C
|
#include "os.h"
#include "reg.h"
#include "string.h"
#include "buffer.h"
void *stdin;
void putchar(char c)
{
while (!(*(USART2_SR) & USART_FLAG_TXE));
*(USART2_DR) = (c & 0xFF);
}
void puts(const char *str)
{
while (*str) {
while (!(*(USART2_SR) & USART_FLAG_TXE));
*(USART2_DR) = (*str & 0xFF);
str++;
}
}
void putsln(const char *str)
{
while (*str) {
while (!(*(USART2_SR) & USART_FLAG_TXE));
*(USART2_DR) = (*str & 0xFF);
str++;
}
putchar('\r');
putchar('\n');
}
void putd(int value)
{
char tmp[12];
itostr(value, tmp);
puts(tmp);
}
unsigned getline(char *strPtr)
{
unsigned i = 0;
while (1) {
if (buf_get_back(strPtr, stdin) == 1) {
if (*strPtr == '\n' || *strPtr == '\r') {
if (*strPtr == '\r' && *buf_seek_back(stdin) == '\n')
buf_get_back(strPtr, stdin);
*strPtr = '\0';
break;
}
++strPtr;
++i;
}
}
return i;
}
|
C
|
/*************************************************************************
> File Name: readdir.c
> Author: jianghechao
> Mail: 591378033@qq.com
> Created Time: Wed 23 Apr 2014 11:39:37 PM CST
************************************************************************/
#include<stdio.h>
#include<dirent.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
DIR *dir = NULL;
struct dirent *pdirent = NULL;
dir = opendir(argv[1]);
if(dir==NULL)
perror(argv[1]);
while((pdirent=readdir(dir))!=NULL)
printf("%s\n",pdirent->d_name);
closedir(dir);
return 0;
}
|
C
|
#include <stdio.h>
//niz sa ispita
int main() {
int i, niz[100],n,br=1;
printf("Unesite niz: ");
for(i=0;i<100;i++) {
scanf("%d", &niz[i]);
if(niz[i]==-1) break;
}
n=i;
for(i=1;i<n;i++) {
if(niz[i]>niz[i-1]) br++;
}
printf("Ima %d opadajucih podnizova", br);
return 0;
}
|
C
|
/**
* @chinese
* @file stringchar.c
* @author 胡俊远
* @date Thu Oct 13 10:00:00 2011
*
* @brief 字符串和char处理模块
* @endchinese
*
* @english
* @file stringchar.c
* @author Hu Junyuan
* @date Thu Oct 13 10:00:00 2011
*
* @brief string and char handling module
* @endenglish
*/
#include <sys/times.h>
#include <sys/time.h>
#include <unistd.h>
#ifndef _ARM_A23
#include <execinfo.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include "config.h"
#include "debug.h"
struct timeval oldtime;
int PLATFORM_TYPE = 0; // 硬件平台类型, 0-A20, 1-RK3288,2-M186,3-A83 gorui,4-3352 psam
char *PLATFORM_TYPE_NAME[PLATFORM_TYPE_MAX+1]={
"A20",
"XHRK3288",
"3QM186",
"GRA83",
"Unknown"
};
/**
* @chinese
* 截取字符串末尾的"\r\n"
*
* @param buf 要处理的字符串
*
* @return 无
* @endchinese
*
* @english
* remove "\r\n" from end of string
*
* @param buf string to handle
*
* @return none
* @endenglish
*
*/
void cut_rn(char *buf)
{
if(buf==NULL) return;
while(*buf)
{
if(*buf=='\n'||*buf=='\r')
{
*buf=0;
return;
}
else
{
buf++;
}
}
}
/**
* @chinese
* 根据分隔符sep,将src中的第index列字符传给dest
* 如分隔符为",",src为"aaa,bb,ccccc,,d,",则第0列为aaa,第1列为bb,第3列为空
* 注意:分隔符长度为1
*
* @param src 源字符串
* @param sep 分隔符
* @param index 第几列
* @param dest 保存目标地址
* @param dest_len 目标地址长度
*
* @return 第index列字符串长度
* @endchinese
*
* @english
* get the index string from src according to sep
*
* @param src src
* @param sep sep
* @param index index
* @param dest dest
* @param dest_len dest lenth
*
* @return len of dest
* @endenglish
*
*/
int string_get_item_with_sep(char *src, char *sep, int index, char *dest, int dest_len)
{
int len_tmp=0,len=0,retlen=0;
int i=0;
if(src == NULL ||dest== NULL || strlen(src) == 0||sep == NULL)
{
return ERROR;
}
for(i=0;i<=index;i++)
{
len_tmp=strcspn(src+len, sep);
if(len>=strlen(src))
{
break;
}
if(i==index)
{
memset(dest,0,dest_len);
retlen=dest_len>len_tmp?len_tmp:dest_len;
memcpy(dest,src+len,retlen);
}
len=len+len_tmp+1;
}
return retlen;
}
/**
* @chinese
* 字节数据转换为可打印字符串
* 如:{0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01} --> "C8329BFD0E01"
*
* @param pSrc 源数据指针
* @param pDst 目标字符串指针
* @param nSrcLength 源数据长度
*
* @return 目标字符串长度
* @endchinese
*
* @english
* change byte data string to printable string.
* for example:{0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01} --> "C8329BFD0E01"
*
* @param pSrc pointer which point to source string
* @param pDst pointer which point to resulting string.
* @param nSrcLength the length of source data
*
* @return length of the resulting string
* @endenglish
*
*/
int hex2string(unsigned char* pSrc, char* pDst, int nSrcLength)
{
const char tab[]="0123456789ABCDEF";//0x0-0xf的字符查找表
int i=0;
for(i=0;i<nSrcLength;i++)
{
*pDst++ = tab[*pSrc >> 4]; //输出高4位
*pDst++ = tab[*pSrc & 0x0f];// 输出低4位
pSrc++;
}
*pDst = '\0';
return (nSrcLength * 2);
}
/**
* @chinese
* 可打印字符串转换为字节数据
* 如:"C8329BFD0E01" --> {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01}
*
* @param pSrc 源数据指针
* @param pDst 目标字符串指针
* @param nSrcLength 源数据长度
*
* @return 目标字符串长度
* @endchinese
*
* @english
* change byte printable string to data string
* for example:"C8329BFD0E01" --> {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01}
*
* @param pSrc pointer which point to source string
* @param pDst pointer which point to resulting string.
* @param nSrcLength the length of source data
*
* @return length of the resulting string
* @endenglish
*
*/
int string2hex(char* pSrc, char* pDst, int nSrcLength)
{
int i=0;
for (i=0;i<nSrcLength;i+=2)
{
//输出高4位
if((*pSrc>='0')&&(*pSrc<='9'))
{
*pDst=(*pSrc-'0')<<4;
}
else
{
*pDst=(*pSrc-'A'+10)<<4;
}
pSrc++;
// 输出低4位
if((*pSrc>='0')&&(*pSrc<='9'))
{
*pDst|=*pSrc-'0';
}
else
{
*pDst|=(*pSrc-'A'+10);
}
pSrc++;
pDst++;
}
return (nSrcLength/2);
}
/**
* @chinese
* 打印字符的十六进制
*
* @param data 字符
* @param len 字符长度
*
* @return none
* @endchinese
*
* @english
*
* @param data data
* @param len len of data
*
* @return none
*
* @endenglish
*
*/
void print_hex(char * data, int len)
{
int i=0;
if(len<=0)
return;
plog("\r\n---------------------\r\n");
for(i=0;i<len;i++)
{
plog("%02X ",data[i]);
}
plog("\r\n---------------------\r\n");
}
void printf_none(char *format, ...)
{
return;
}
long GetTickCount( )
{
long tck;
struct tms tmp;
tck = sysconf( _SC_CLK_TCK );
// return times( NULL ) * ( 1000 / tck );
return times( &tmp ) * ( 1000 / tck ); //modify by aduo 2014.9.11
}
//函数功能 1到4字节的HEX数值数据转换为无符号整型
//参数: in:输入首址
// size: 输入的字符数,若超过4,则取4
// flag: 输入的主机字节序,0:小端模式 其它:大端模式 (输出固定为小端模式)
//返回值 转换结果
unsigned int HexToUInt(void *in, unsigned int size, int flag)
{
unsigned int ret = 0;
unsigned char * str = (unsigned char *)&ret;
unsigned char * indata = (unsigned char *)in;
if (size > 4)
{
size = 4;
}
if (flag)
{
switch (size)
{
case 4:
*(str + 0) = *(indata + 3);
*(str + 1) = *(indata + 2);
*(str + 2) = *(indata + 1);
*(str + 3) = *(indata + 0);
break;
case 3:
*(str + 0) = *(indata + 2);
*(str + 1) = *(indata + 1);
*(str + 2) = *(indata + 0);
break;
case 2:
*(str + 0) = *(indata + 1);
*(str + 1) = *(indata + 0);
break;
case 1:
*(str + 0) = *(indata + 0);
break;
default:
break;
}
}
else
{
switch (size)
{
case 4:
*(str + 3) = *(indata + 3);
case 3:
*(str + 2) = *(indata + 2);
case 2:
*(str + 1) = *(indata + 1);
case 1:
*(str + 0) = *(indata + 0);
break;
default:
break;
}
}
return ret;
}
//函数功能:将小端模式的无符号整数转换为任何字节序的HEX格式
//参数: in:输入无符号整数,小端模式(逆序)
// out:输出首址
// size:输入的字节数,1、2、3、4
// flag:输出主机字节序,0:小端模式 其它:大端模式 (输入固定为小端模式)
//返回值 0:转换成功,-1:输出位数不足
int UIntToHex(unsigned int in, void * out, unsigned int size, int flag)
{
int ret = 0;
unsigned char * str = (unsigned char *)out;
unsigned char * indata = (unsigned char *)∈
if (size > 4)
{
size = 4;
}
if (flag)
{
switch (size)
{
case 4:
*(str + 3) = *(indata + 0);
*(str + 2) = *(indata + 1);
*(str + 1) = *(indata + 2);
*(str + 0) = *(indata + 3);
break;
case 3:
*(str + 2) = *(indata + 0);
*(str + 1) = *(indata + 1);
*(str + 0) = *(indata + 2);
break;
case 2:
*(str + 1) = *(indata + 0);
*(str + 0) = *(indata + 1);
break;
case 1:
*(str + 0) = *(indata + 0);
break;
default:
break;
}
}
else
{
switch (size)
{
case 4:
*(str + 3) = *(indata + 3);
case 3:
*(str + 2) = *(indata + 2);
case 2:
*(str + 1) = *(indata + 1);
case 1:
*(str + 0) = *(indata + 0);
break;
default:
break;
}
}
switch (size)
{
case 1:
if (in > 0x000000FF)
{
ret = -1;
}
break;
case 2:
if (in > 0x0000FFFF)
{
ret = -1;
}
break;
case 3:
if (in > 0x00FFFFFF)
{
ret = -1;
}
break;
default:
break;
}
return ret;
}
/**
* @chinese
* 获得sdk编译版本
*
* @param data sdk编译版本(值如下:_DM365/_ARM_2410);
*
* @return 成功返回TRUE,失败返回FALSE
* @endchinese
*
* @english
* get sdk compilation version
* @param data sdk compilation version(value:(_DM365/_ARM_2410);
*
* @return success return TRUE,false return FALSE
*
* @endenglish
*
*/
int get_sdk_version(char *data)
{
if(data== NULL)
{
return FALSE;
}
memset(data,0,sizeof(data));
#ifdef _DM365
strcpy(data,"_DM365");
#endif
#ifdef _ARM_2410
strcpy(data,"_ARM_2410");
#endif
#ifdef _AM335X
strcpy(data,"_AM335X");
#endif
#ifdef _ARM_A23
if(PLATFORM_TYPE>=PLATFORM_TYPE_MAX)
PLATFORM_TYPE=PLATFORM_TYPE_MAX;
sprintf(data,"_%s_android",PLATFORM_TYPE_NAME[PLATFORM_TYPE]);
#endif
return TRUE;
}
//获取库版本号
int get_library_version(char *data)
{
if(data==NULL)
{
return FALSE;
}
#ifdef DEVICE_REGISTER
char *reg="REG ";
#else
char *reg="";
#endif
//memset(data,0,sizeof(data));
#ifdef _DM365
strcpy(data,"_DM365");
#endif
#ifdef _ARM_2410
strcpy(data,"_ARM_2410");
#endif
#ifdef _ARM_2416
sprintf(data,"180315 3.0.0.4 %s %s",reg,__TIME__);
#endif
#ifdef _AM335X
//
sprintf(data,"7.3.0.5 %s180301 %s",reg,__TIME__);
#endif
#ifdef _A20_UBUNTU
sprintf(data,"1.3.0.5 %s180301 %s",reg,__TIME__);
#endif
#ifdef _ARM_A23
if(PLATFORM_TYPE>=PLATFORM_TYPE_MAX)
PLATFORM_TYPE=PLATFORM_TYPE_MAX;
sprintf(data,"1.3.0.5 %s180410 %s %s",reg,PLATFORM_TYPE_NAME[PLATFORM_TYPE],__TIME__);
// PLATFORM_TYPE = 0; // 硬件平台类型, 0-A20, 1-RK3288,2-M186,3-A83 gorui
#endif
printf("%s %s\n",__func__,data);
return TRUE;
}
// just for synel 20170804
char *get_a20sdk_version()
{
static char *ver = "9.01.00.00.20171130";
return ver;
}
/***************************************************************************************************************
FunctionName:StrToBCD
FunctionDescription:change string to BCD code
return value:if success return true,otherwise false
***************************************************************************************************************/
int StrToBCD(const char *Src,char *Des,int iDesLen)
{
char chTemp = 0;
int iSrcLen = 0,i=0;
if (NULL == Src)
{
return -1;
}
if (NULL == Des)
{
return -1;
}
if (0 == iDesLen)
{
return -1;
}
iSrcLen = strlen(Src);
if (iSrcLen > iDesLen * 2)
{
return -1;
}
chTemp = 0;
for (i = 0; i < iSrcLen; i++)
{
if (i % 2 == 0)
{
chTemp = (Src[i] << 4) & 0xF0;
}
else
{
chTemp = (chTemp & 0xF0) | (Src[i] & 0x0F);
Des[i / 2] = chTemp;
}
}
if (i % 2 != 0)
{
Des[i / 2] = chTemp;
}
return 1;
}
//与这个对应的BCD码转换为字符串的函数
int BCDToStr(const char *Src, char *Des)
{
int iSrcLen = 0,i=0;
char chTemp ,chDes;
if (NULL == Src)
{
return -1;
}
if (NULL == Src)
{
return -1;
}
iSrcLen = strlen(Src);
chTemp = 0;
chDes = 0;
for ( i = 0; i < iSrcLen; i++)
{
chTemp = Src[i];
chDes = chTemp >> 4;
Des[i * 2] = chDes + '0';
chDes = (chTemp & 0x0F) + '0';
Des[i * 2 + 1] = chDes;
}
return 1;
}
//函数功能:将10进制文本格式的字符串(0结束)转换为BCD码,不足部分补0xff,空格符作为分隔符被忽略。
// 若缓冲区长度不足,则返回错误。
// 两个有效16进制文本字符转换为1个16进制数值字符,只允许最后字符为单个字符,否则视为格式错误。
// 单个有效10进制文本字符转换为高4位,低4为补"F"。
//参数: in: 输入文本串地址
// out: 结果输出串地址
// outMaxLen: 输出缓冲区大小
//结果: 0: 正确, -1: 错误
// 输入指针为NULL、输出指针为NULL、非法输入值(出现非16进制字符)等,返回 -1
//示例: 输入文本串" 1234 567" ,输出为{0x12, 0x34, 0x56, 0x7F}
int thex2bcd(const char *in, unsigned char *out, int outLen)
{
int len = 0;
int a = 0;
int b = 0;
int overFlag = 0; //结束标志
if (in == NULL || out == NULL)
{
//AfxMessageBox("y111111111111111111");
return -1;
}
if (!outLen)
{
//AfxMessageBox("y22222222222222");
return 0;
}
while (*in)
{
switch(*in)
{
case ' ':
if (1 == a) //已读入单个10进制文本字符
{
b <<= 4;
b += 0x0f; //单个字符后面补"F"
*out++ = b; //写入结果缓冲区
len++;
a = 0;
b = 0;
overFlag = 1; //结束标志
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (overFlag)
{
return -1; //非法格式
}
if (outLen == len)
{
//AfxMessageBox("y3333333333333333333333");
return -1; //超过缓冲区
}
b = (b << 4) + (*in - '0'); //转换后移入临时变量b
if (1 == a) //读入2个10进制文本字符,转换结果写缓冲区
{
*out++ = b;
len++;
a = 0;
b = 0;
}
else
{
a++;
}
break;
default:
//AfxMessageBox("y44444444444444444444");
return -1;
break;
}
in++;
}
if (outLen > len && 1 == a)
{
b <<= 4;
b += 0x0f; //单个字符后面补"F"
*out++ = b;
len++;
}
for (; len < outLen; len++)
{
*out++ = 0xff; //填充
}
// //AfxMessageBox("y5555555555555555555555");
return len;
}
//函数说明:BCD码(允许尾部为"F")转换为THEX格式,1个字节转换为2个字节
//参数: in: 输入压缩BCD字符串首地址
// out: 结果输出THex数值格式字符串首地址
// Len: 需转换的压缩BCD字符串长度,以字节计
//结果: >0:输出字符的个数, 0:完成, -1: 错误
// 输入指针为NULL、输出指针为NULL、len < 0 、非BCD等,返回 -1
int bcd2thex(const unsigned char *in, char *out, int len)
{
int i;
int overFlag = 0; //结束标志
unsigned char tmpchar;
int outlen = 0;
if (in == NULL || out == NULL || len < 0)
{
return -1;
}
if (!len)
{
return 0;
}
for (i= 0; i < len; i++)
{
tmpchar = in[i] >> 4; //处理高位
if (tmpchar > 9)
{
if (tmpchar == 0x0f)
{
overFlag = 1; //结束标志
}
else
{
return -1; //非法
}
}
else
{
if (overFlag)
{
return -1; //结束标志后有数字
}
*out++ = tmpchar + '0';
outlen++;
}
tmpchar = in[i] & 0x0f; //处理低位
if (tmpchar > 9)
{
if (tmpchar == 0x0f)
{
overFlag = 1; //结束标志
}
else
{
return -1; //非法
}
}
else
{
if (overFlag)
{
return -1; //结束标志后有数字
}
*out++ = tmpchar + '0';
outlen++;
}
}
return outlen;
}
#if 1 // lfg 20160128 add
//函数功能:将16进制数值型字符串转换为16进制文本格式的字符串。
// 一个16进制格式字符转换为两个16进制文本格式字符。
//参数: in: 输入Hex格式(即16进制)字符串首地址
// out: 结果输出16进制格式文本串首地址
// Len: 需转换的Hex格式字符串长度,以字节计
// fillchar:不为0时为填充的字符,为0不填充。
//结果: 返回输出16进制格式文本字符串的长度,以字节计(输出的16进制文本字符串自动在后面补0)
// 输入指针为NULL、输出指针为NULL、len < 0 等,返回 -1
//示例: fillchar = " ", 输入文本串{0x12, 0x03, 0x5A, 0x0B, 0x45, 0x68},输出为"12 03 5A 0B 45 68"
int HexToTHex(const unsigned char *in, char *out, int len, char fillchar)
{
char table1[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int i = 0;
if (in == NULL || out == NULL || len < 0)
{
return -1;
}
if (!len)
{
return 0;
}
for (i= 0; i < len; i++)
{
*out++ = table1[in[i] >> 4];
*out++ = table1[in[i] & 0x0F];
if (fillchar)
{
*out++ = fillchar;
}
}
if ((len) && (fillchar))
{
out--;
}
*out = 0;
return fillchar ? (len * 3 - 1) : (len * 2);
}
int UIntToBcd(unsigned int in, unsigned char *out, unsigned int size)
{
unsigned int i = 0;
if ((size > 5) || (size == 0))
{
return -1; //参数错误
}
unsigned char hexbuff[5];
for (i = 0; i < size; i++)
{
hexbuff[4-i] = in % 100;
in = in / 100;
}
if (in)
{
return -1; //超限
}
return HexToBcd(hexbuff+(5-size), out, size);
}
//函数功能:将16进制文本格式的字符串(0结束)转换为16进制数值型字符串(不自动补0),空格符作为分隔符被忽略。
// 两个有效16进制文本字符转换为1个16进制数值字符,当出现单个字符(结尾字符或后面为空格)时,单个有
// 效16进制文本字符转换为1个16进制数值字符的高4位(低4位为0)。
//参数: in: 输入文本串地址
// out: 结果输出串地址
// outMaxLen: 输出缓冲区大小
//结果: 返回输出字符串的长度,以字节计
// 输入指针为NULL、输出指针为NULL、非法输入值(出现非16进制字符)等,返回 -1
//示例: 输入文本串" 123 5a b 4568" ,输出为{0x12, 0x03, 0x5A, 0x0B, 0x45, 0x68}
int THexToHex(const char *in, unsigned char *out, int outMaxLen)
{
int len = 0;
int a = 0;
int b = 0;
if (in == NULL || out == NULL)
{
return -1;
}
if (!outMaxLen)
{
return 0;
}
memset(out, 0, outMaxLen); //20130108
while (*in)
{
switch(*in)
{
case ' ':
if (1 == a) //已读入单个16进制文本字符
{
b <<= 4;
*out++ = b; //写入结果缓冲区
len++;
a = 0;
b = 0;
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
b = (b << 4) + (*in - '0'); //转换后移入临时变量b
if (1 == a) //读入2个16进制文本字符,转换结果写缓冲区
{
*out++ = b;
len++;
a = 0;
b = 0;
}
else
{
a++;
}
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
b = (b << 4) + (*in - 'A' + 0x0A);
if (1 == a)
{
*out++ = b;
len++;
a = 0;
b = 0;
}
else
{
a++;
}
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
b = (b << 4) + (*in - 'a' + 0x0A);
if (1 == a)
{
*out++ = b;
len++;
a = 0;
b = 0;
}
else
{
a++;
}
break;
default:
return -1;
break;
}
if (outMaxLen == len)
{
break;
}
in++;
}
if (outMaxLen > len && 1 == a)
{
b <<= 4;
*out++ = b;
len++;
}
return len;
}
//函数说明:16进制数值格式字符串(字符数组)转换为压缩BCD码格式字符串(字符数组)
//参数: in: 输入Hex数值格式字符串首地址
// out: 结果输出压缩BCD格式字符串首地址
// Len: 需转换长度,以字节计
//结果: 返回输出压缩BCD串的长度,以字节计
// 输入指针为NULL、输出指针为NULL、len < 0 等,返回 -1
//示例: 输入文本串{0x12, 0x03, 0x55, 0x08, 0x45, 0x62},输出为{0x18, 0x03, 0x85, 0x08, 0x69, 0x98}
int HexToBcd(const unsigned char *in, unsigned char *out, int len)
{
int i;
if (in == NULL || out == NULL || len < 0)
{
return -1;
}
if (!len)
{
return 0;
}
for (i= 0; i < len; i++)
{
if (in[i] > 99)
{
return -1;
}
*out++ = ((in[i]/10) << 4) + in[i]%10;
}
return len;
}
//函数说明:压缩BCD码格式的字符串转换为HEX数值格式的字符串,1个字节转换为1个字节
//参数: in: 输入压缩BCD字符串首地址
// out: 结果输出Hex数值格式字符串首地址
// Len: 需转换的压缩BCD字符串长度,以字节计
//结果: 返回输出Hex数值格式字符串的长度,以字节计
// 输入指针为NULL、输出指针为NULL、len < 0 、非BCD等,返回 -1
//示例: 输入文本串{0x18, 0x03, 0x85, 0x08, 0x69, 0x98},输出为{0x12, 0x03, 0x55, 0x08, 0x45, 0x62}
int BcdToHex(const unsigned char *in, unsigned char *out, int len)
{
int i;
if (in == NULL || out == NULL || len < 0)
{
return -1;
}
if (!len)
{
return 0;
}
for (i= 0; i < len; i++)
{
if (((in[i]&0x0f) > 9) || ((in[i] >> 4) > 9))
{
return -1;
}
*out++ = (in[i] >> 4) * 10 + (in[i] & 0x0f);
}
return len;
}
int BcdToUInt(unsigned char *in, unsigned int *out, unsigned int size)
{
int i = 0;
if ((size > 5) || (size == 0))
{
return -1; //参数错误
}
unsigned char hexbuff[5];
memset(hexbuff, 0 ,5);
int ret;
ret = BcdToHex(in, hexbuff+(5-size), size);
if (ret < 0)
{
return ret;
}
*out = 0;
for (i = 0; i < 5; i++)
{
*out = (*out * 100 + hexbuff[i]);
}
return 0;
}
//函数功能:将位串转换为无符号整型
//参数: in: 输入首址
// ByteOffset:开始位所在字节相对输入首址的偏移量,以字节计
// BitOffset:开始位相对所在字节开始位的偏移量,以位计
// BitLen:位串的位数
//返回值: 转换结果
unsigned int BitToUInt(void *in, unsigned int ByteOffset, unsigned int BitOffset, unsigned int BitLen)
{
unsigned int ret = 0;
unsigned char * str;
unsigned char tmp;
unsigned char table1[] = {0x00, 0x01, 0x03, 0x07 ,0x0F, 0x1F, 0x3F, 0x7F, 0xFF};
if (NULL == in) //无输入,返回0
{
return 0;
}
BitLen = BitLen > 32 ? 32 : BitLen;
BitOffset = BitOffset > 7 ? 0 : BitOffset;
str = (unsigned char *)in + ByteOffset;
if ((8 - BitOffset) > BitLen) //所有位在一个字节内,且未右对齐
{
tmp = *str >> (8 - BitOffset - BitLen); //右对齐
ret = tmp & (table1[BitLen]); //取出结果
BitLen = 0;
}
else
{
tmp = *str; //位所在首字符值
ret = tmp & (table1[8 - BitOffset]); //取出首字符中的位
BitLen -= (8 - BitOffset); //未处理的位
}
BitOffset = 0; //剩余字节位的偏移量置初值0
str++; //指向下一个字节
while (BitLen >0)
{
if (8 > BitLen) //不足1字节
{
tmp = *str >> (8 - BitLen); //取出剩余结果
ret = (ret << BitLen) + tmp; //得到结果值
BitLen = 0;
}
else
{
tmp = *str;
ret = (ret << 8) + tmp; //当前字节内容加到结果
BitLen -= 8;
}
str++;
}
return ret;
}
//函数功能:将无符号整数转换为位串填充到指定位置
//参数: in: 输入无符号整数
// out: 需要填充位串的首地址
// ByteOffset:开始位所在字节相对输入首址的偏移量,以字节计
// BitOffset:开始位相对所在字节开始位的偏移量,以位计
// BitLen:位串的位数
//返回值: 0:成功,-1:失败
int UIntToBit(unsigned int in, void *out, unsigned int ByteOffset, unsigned int BitOffset, unsigned int BitLen)
{
unsigned char * str;
unsigned char tmp;
if ((NULL == out)||(BitLen > 32)||(BitOffset > 7)||(in >= ((unsigned int)1 << BitLen)))
{
return -1;
}
str = (unsigned char *)out + ByteOffset;
if ((8 - BitOffset) > BitLen)
{
tmp = in << (8 - BitOffset - BitLen); //移位到BitOffset
*str = (((0xFF >> BitOffset) ^ (0xFF << (8 - BitOffset - BitLen))) & *str) | tmp; //填充
BitLen = 0;
}
else
{
tmp = in >> (BitLen - (8 - BitOffset)); //取出最左端所在字节需填充的内容
*str = (~(0xFF >> BitOffset) & *str) | tmp; //填充
BitLen -= (8 - BitOffset);
}
BitOffset = 0;
str++;
while (BitLen >0)
{
if (8 > BitLen)
{
tmp = in << (8 - BitLen);
*str = ((0xFF >> BitLen) & *str) | tmp;
BitLen = 0;
}
else
{
*str = in >> (BitLen - 8); //自动丢弃高字节内容
BitLen -= 8;
}
str++;
}
return 0;
}
//函数功能:判断是否闰年
//参数: year:年份
//返回值: 1:闰年, 0:普通年
int isLeapYear(unsigned int year)
{
if ((year%400 == 0) || ((year%100 != 0) && (year%4 == 0)))
{
return 1;
}
else
{
return 0;
}
}
//函数功能:将以若干秒为单位的数值转换为时间
//参数: in:从参考年的开始累积的单位秒数
// RefYear:参考年,从该年的1月1日0时0分0秒开始计算
// UnitSec:单位,即每单位的秒数
//返回值:
//
//
int UIntToTimeStr(unsigned int in, char *out, unsigned int RefYear, unsigned int UnitSec, char *format)
{
unsigned int table1[2][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}};
unsigned int table2[2] = {365, 366};
char * formatStr = format;
struct TTime time1 = {RefYear, 1 , 1, 0, 0, 0};
unsigned int days , secs;
int LeapFlag = 0;
if ((RefYear > 3000) || (UnitSec > 3600) || ((in/UnitSec) > 0xFFFFFFFF))
{
return -1;
}
days = in * UnitSec / (24 * 3600);
secs = in * UnitSec % (24 * 3600);
while (1)
{
LeapFlag = isLeapYear(time1.year);
if (days < table2[LeapFlag])
{
while (1)
{
if (days < table1[LeapFlag][time1.month])
{
time1.day += days;
break;
}
else
{
days -= table1[LeapFlag][time1.month];
time1.month++;
}
}
break;
}
else
{
time1.year++;
days -= table2[LeapFlag];
}
}
time1.hour = secs / 3600;
time1.minute = (secs % 3600) / 60;
time1.second = secs % 60;
if (formatStr && out)
{
while (*formatStr)
{
switch (*formatStr)
{
case 'Y':
case 'y':
if ((*(formatStr + 1) == 'Y') || (*(formatStr + 1) == 'y'))
{
if ((*(formatStr + 2) == 'Y') || (*(formatStr + 2) == 'y'))
{
if ((*(formatStr + 3) == 'Y') || (*(formatStr + 3) == 'y'))
{
if ((*(formatStr + 4) == 'Y') || (*(formatStr + 4) == 'y'))
{
return -1;//非法(5位年)
}
else
{
sprintf(out, "%04d", time1.year % 10000);//4位年
out += 4;
formatStr += 4;
}
}
else
{
return -1;//非法(3位年)
}
}
else
{
sprintf(out, "%02d", time1.year % 100); //2位年
out += 2;
formatStr += 2;
}
}
else
{
return -1;//非法(1位年)
}
break;
case 'M':
if (*(formatStr + 1) == 'M')
{
if (*(formatStr + 2) == 'M')
{
return -1;//非法(3位月)
}
else
{
sprintf(out, "%02d", time1.month); //2位月
out += 2;
formatStr += 2;
}
}
else
{
return -1;//非法(1位月)
}
break;
case 'D':
case 'd':
if ((*(formatStr + 1) == 'D') || (*(formatStr + 1) == 'd'))
{
if ((*(formatStr + 2) == 'D') || (*(formatStr + 2) == 'd'))
{
return -1;//非法(3位天)
}
else
{
sprintf(out, "%02d", time1.day); //2位天
out += 2;
formatStr += 2;
}
}
else
{
return -1;//非法(1位天)
}
break;
case 'H':
case 'h':
if ((*(formatStr + 1) == 'H') || (*(formatStr + 1) == 'h'))
{
if ((*(formatStr + 2) == 'H') || (*(formatStr + 2) == 'h'))
{
return -1;//非法(3位小时)
}
else
{
sprintf(out, "%02d", time1.hour); //2位小时
out += 2;
formatStr += 2;
}
}
else
{
return -1;//非法(1位小时)
}
break;
case 'm':
if (*(formatStr + 1) == 'm')
{
if (*(formatStr + 2) == 'm')
{
//非法(3位分钟)
}
else
{
sprintf(out, "%02d", time1.minute); //2位分钟
out += 2;
formatStr += 2;
}
}
else
{
return -1;//非法(1位分钟)
}
break;
case 'S':
case 's':
if ((*(formatStr + 1) == 'S') || (*(formatStr + 1) == 's'))
{
if ((*(formatStr + 2) == 'S') || (*(formatStr + 2) == 's'))
{
return -1;//非法(3位秒)
}
else
{
sprintf(out, "%02d", time1.second);//2位秒
out += 2;
formatStr += 2;
}
}
else
{
return -1;//非法(1位秒)
}
break;
default:
sprintf(out, "%c", *formatStr++);
out++;
break;
}
}
}
return 0;
}
//函数功能: 判断字符串是否为指定长度的数字ASCII码组成
int isdec(char *str, int len)
{
int i = 0;
for (i = 0; i < len; i++)
{
if ((str[i] < '0') || (str[i] > '9'))
{
return 0;
}
}
return 1;
}
//函数功能: 将数字ASCII码组成的字符串转换为无符号整型,最大长度为len,遇到非法字符结束
unsigned int atoUInt(char *str, int len)
{
unsigned int ret = 0;
int i = 0;
for (i = 0; i < len; i++)
{
if ((str[i] < '0') || (str[i] > '9'))
{
return ret;
}
ret = ret * 10 + (str[i] - '0');
}
return ret;
}
//函数功能:将10进制文本格式的字符串(0结束)转换为BCD码,不足部分补0xff,空格符作为分隔符被忽略。
// 若缓冲区长度不足,则返回错误。
// 两个有效16进制文本字符转换为1个16进制数值字符,只允许最后字符为单个字符,否则视为格式错误。
// 单个有效10进制文本字符转换为高4位,低4为补"F"。
//参数: in: 输入文本串地址
// out: 结果输出串地址
// outMaxLen: 输出缓冲区大小
//结果: 0: 正确, -1: 错误
// 输入指针为NULL、输出指针为NULL、非法输入值(出现非16进制字符)等,返回 -1
//示例: 输入文本串" 1234 567" ,输出为{0x12, 0x34, 0x56, 0x7F}
int THexToBcd(const char *in, unsigned char *out, int outLen)
{
int len = 0;
int a = 0;
int b = 0;
int overFlag = 0; //结束标志
if (in == NULL || out == NULL)
{
//AfxMessageBox("y111111111111111111");
return -1;
}
if (!outLen)
{
//AfxMessageBox("y22222222222222");
return 0;
}
while (*in)
{
switch(*in)
{
case ' ':
if (1 == a) //已读入单个10进制文本字符
{
b <<= 4;
b += 0x0f; //单个字符后面补"F"
*out++ = b; //写入结果缓冲区
len++;
a = 0;
b = 0;
overFlag = 1; //结束标志
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (overFlag)
{
return -1; //非法格式
}
if (outLen == len)
{
//AfxMessageBox("y3333333333333333333333");
return -1; //超过缓冲区
}
b = (b << 4) + (*in - '0'); //转换后移入临时变量b
if (1 == a) //读入2个10进制文本字符,转换结果写缓冲区
{
*out++ = b;
len++;
a = 0;
b = 0;
}
else
{
a++;
}
break;
default:
//AfxMessageBox("y44444444444444444444");
return -1;
break;
}
in++;
}
if (outLen > len && 1 == a)
{
b <<= 4;
b += 0x0f; //单个字符后面补"F"
*out++ = b;
len++;
}
for (; len < outLen; len++)
{
*out++ = 0xff; //填充
}
// //AfxMessageBox("y5555555555555555555555");
return len;
}
//函数说明:BCD码(允许尾部为"F")转换为THEX格式,1个字节转换为2个字节
//参数: in: 输入压缩BCD字符串首地址
// out: 结果输出THex数值格式字符串首地址
// Len: 需转换的压缩BCD字符串长度,以字节计
//结果: >0:输出字符的个数, 0:完成, -1: 错误
// 输入指针为NULL、输出指针为NULL、len < 0 、非BCD等,返回 -1
int BcdToTHex(const unsigned char *in, char *out, int len)
{
int i;
int overFlag = 0; //结束标志
unsigned char tmpchar;
int outlen = 0;
if (in == NULL || out == NULL || len < 0)
{
return -1;
}
if (!len)
{
return 0;
}
for (i= 0; i < len; i++)
{
tmpchar = in[i] >> 4; //处理高位
if (tmpchar > 9)
{
if (tmpchar == 0x0f)
{
overFlag = 1; //结束标志
}
else
{
return -1; //非法
}
}
else
{
if (overFlag)
{
return -1; //结束标志后有数字
}
*out++ = tmpchar + '0';
outlen++;
}
tmpchar = in[i] & 0x0f; //处理低位
if (tmpchar > 9)
{
if (tmpchar == 0x0f)
{
overFlag = 1; //结束标志
}
else
{
return -1; //非法
}
}
else
{
if (overFlag)
{
return -1; //结束标志后有数字
}
*out++ = tmpchar + '0';
outlen++;
}
}
return outlen;
}
int getYear(unsigned int in, unsigned int RefYear, unsigned int UnitSec)
{
unsigned int table1[2][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}};
unsigned int table2[2] = {365, 366};
struct TTime time1 = {RefYear, 1 , 1, 0, 0, 0};
unsigned int days , secs;
int LeapFlag = 0;
if ((RefYear > 3000) || (UnitSec > 3600) || ((in/UnitSec) > 0xFFFFFFFF))
{
return -1;
}
days = in * UnitSec / (24 * 3600);
secs = in * UnitSec % (24 * 3600);
while (1)
{
LeapFlag = isLeapYear(time1.year);
if (days < table2[LeapFlag])
{
while (1)
{
if (days < table1[LeapFlag][time1.month])
{
time1.day += days;
break;
}
else
{
days -= table1[LeapFlag][time1.month];
time1.month++;
}
}
break;
}
else
{
time1.year++;
days -= table2[LeapFlag];
}
}
time1.hour = secs / 3600;
time1.minute = (secs % 3600) / 60;
time1.second = secs % 60;
return time1.year - RefYear;
}
int getMonth(unsigned int in, unsigned int RefYear, unsigned int UnitSec)
{
unsigned int table1[2][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}};
unsigned int table2[2] = {365, 366};
struct TTime time1 = {RefYear, 1 , 1, 0, 0, 0};
unsigned int days , secs;
int LeapFlag = 0;
if ((RefYear > 3000) || (UnitSec > 3600) || ((in/UnitSec) > 0xFFFFFFFF))
{
return -1;
}
days = in * UnitSec / (24 * 3600);
secs = in * UnitSec % (24 * 3600);
while (1)
{
LeapFlag = isLeapYear(time1.year);
if (days < table2[LeapFlag])
{
while (1)
{
if (days < table1[LeapFlag][time1.month])
{
time1.day += days;
break;
}
else
{
days -= table1[LeapFlag][time1.month];
time1.month++;
}
}
break;
}
else
{
time1.year++;
days -= table2[LeapFlag];
}
}
time1.hour = secs / 3600;
time1.minute = (secs % 3600) / 60;
time1.second = secs % 60;
return time1.month;
}
int getDay(unsigned int in, unsigned int RefYear, unsigned int UnitSec)
{
unsigned int table1[2][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}};
unsigned int table2[2] = {365, 366};
struct TTime time1 = {RefYear, 1 , 1, 0, 0, 0};
unsigned int days , secs;
int LeapFlag = 0;
if ((RefYear > 3000) || (UnitSec > 3600) || ((in/UnitSec) > 0xFFFFFFFF))
{
return -1;
}
days = in * UnitSec / (24 * 3600);
secs = in * UnitSec % (24 * 3600);
while (1)
{
LeapFlag = isLeapYear(time1.year);
if (days < table2[LeapFlag])
{
while (1)
{
if (days < table1[LeapFlag][time1.month])
{
time1.day += days;
break;
}
else
{
days -= table1[LeapFlag][time1.month];
time1.month++;
}
}
break;
}
else
{
time1.year++;
days -= table2[LeapFlag];
}
}
time1.hour = secs / 3600;
time1.minute = (secs % 3600) / 60;
time1.second = secs % 60;
return time1.day;
}
//函数功能 1到4字节的HEX数值数据转换为有符号整型
//参数: in:输入首址
// size: 输入的字符数,若超过4,则取4
// flag: 输入的主机字节序,0:小端模式 其它:大端模式 (输出固定为小端模式)
//返回值 转换结果
int HexToInt(void *in, unsigned int size, int flag)
{
unsigned char indata[4];
memset(indata, 0, 4);
if (size > 4)
{
size = 4;
}
else if (size == 0)
{
return 0;
}
if (flag) //大端
{
if (*(char *)in & 0x80)
{
memset(indata, 0xff, 4);
}
memcpy(indata+(4-size), in, size);
// indata[0] |= (indata[4-size]&(unsigned char)0x80);
// indata[4-size] &= (unsigned char)0x7F;
}
else
{
if (*((char *)in + size - 1) & 0x80)
{
memset(indata, 0xff, 4);
}
memcpy(indata, in, size);
// indata[3] |= (indata[size-1]&(unsigned char)0x80);
// indata[size-1] &= (unsigned char)0x7F;
}
return HexToUInt(indata, 4, flag);
}
//函数功能:将小端模式的有符号整数转换为任何字节序的HEX格式
//参数: in:输入有符号整数,小端模式(逆序)
// out:输出首址
// size:输入的字节数,1、2、3、4
// flag:输出主机字节序,0:小端模式 其它:大端模式 (输入固定为小端模式)
//返回值 0:转换成功,-1:输出位数不足
int IntToHex(int in, void *out, unsigned int size, int flag)
{
int ret = 0;
//unsigned char * str = (unsigned char *)out;
unsigned char indata[4];
if (size > 4)
{
size = 4;
}
else if (size == 0)
{
return 0;
}
ret = UIntToHex(in, indata, 4, flag);
if (ret)
{
return ret;
}
if (flag) //大端
{
memcpy(out, indata+(4-size), size);
*((unsigned char *)out) |= (indata[0]&(unsigned char)0x80);
}
else
{
memcpy(out, indata, size);
*((unsigned char *)out+size-1) |= (indata[3]&(unsigned char)0x80);
}
switch (size)
{
case 1:
if ((in > 0x7F) || (in < (0 - 0x80)))
{
ret = -1;
}
break;
case 2:
if ((in > 0x7FFF) || (in < (0 - 0x8000)))
{
ret = -1;
}
break;
case 3:
if ((in > 0x7FFFFF) || (in < (0 - 0x800000)))
{
ret = -1;
}
break;
default:
break;
}
return ret;
}
int TimeToUInt(struct TTime *in, unsigned int *out, unsigned int RefYear, unsigned int UnitSec)
{
unsigned int table1[2][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}};
unsigned int table2[2] = {365, 366};
unsigned int days , secs;
int LeapFlag = 0;
if ((RefYear > 3000) || (UnitSec > 3600))
{
return -1;
}
if ((in->year < RefYear) || (in->year > 9999))
{
return -1; //非法年
}
if ((in->month > 12) || (in->month < 1))
{
return -1; //非法月
}
LeapFlag = isLeapYear(in->year);
if (in->day > table1[LeapFlag][in->month])
{
return -1; // 非法日
}
// in->hour = 23;
// in->minute = 59;
// in->second = 59;
days = 0;
secs = 0;
unsigned int i;
for (i = RefYear; i < in->year; i++)
{
LeapFlag = isLeapYear(i);
days += table2[LeapFlag];
if (days > (0xffffffff / (24 * 3600) * UnitSec))
{
return -1; //超限
}
}
LeapFlag = isLeapYear(in->year);
for (i = 1; i < in->month; i++)
{
days += table1[LeapFlag][i];
if (days > (0xffffffff / (24 * 3600) * UnitSec))
{
return -1; //超限
}
}
days += (in->day - 1);
if (days > (0xffffffff / (24 * 3600) * UnitSec))
{
return -1; //超限
}
*out = days * ((24 * 3600) / UnitSec);
secs += (in->hour * 3600);
secs += (in->minute * 60);
secs += in->second;
*out += secs / UnitSec;
return 0;
}
// 字符串分隔 20130716
// 该函数不会改变原字符串内容
// In--待分隔字符串
// Out--目标字符数组, 二维数组,第二维固定长度64
// oSize -- 目标字符数组大小
// Sep--分隔符如"," ":" ...
// 返回实际解析的字段个数
#if 0
int LeeDivideStr(char *In, char Out[][64], unsigned int oSize, char Sep)
{
int i = 0, j = 0, k = 0;
if (In == NULL || oSize > 512)
{
return -1;
}
memset(Out, 0, 64 * oSize);
for( i = 0, j = 0; i < oSize; i++, j++ )
{
k = 0;
while( In[j] && In[j] != Sep && k < 63)
{
Out[i][k] = In[j];
j++;
k++;
}
if (k == 63)
{
while(In[j] && In[j] != Sep)
j++;
}
Out[i][k] = '\0'; // must do before if (!buf[j])
if( !In[j] ) // must judge
{
break;
}
}
return i+1;
}
#endif
char inputNumber(char* prompt, int defValue)
{
char vKey, vRet;
char vStr[16] = {0}, *vStr2;
// PRINTF("\n%s, def=%d\n", prompt, defValue);
while(1)
{
vKey = getchar();
if ((vKey >= '0' && vKey <= '9')
||(vKey >= 'A' && vKey <= 'Z')
|| (vKey >= 'a' && vKey <= 'z'))
{
vRet = vKey;
printf("vret = %c\n", vRet);
break;
}
// else if ( vKey == '\n' )
// {
// if (vCnt == 0)
// vRet = defValue;
// goto RET;
// }
}
while(1)
{
vKey = getchar();
if ( vKey == 0x0A ) // '\n'
break;
}
RET:
return vRet;
}
// AB 01 03 33 01 33 03 6D A5 --> AB0103330133036DA5
int cutSpaceChar(const char* pSrc, unsigned char* pDst)
{
char *p = (char *)pSrc;
while(*p)
{
if (*p != ' ') // cut space
{
*pDst++ = *p;
}
p++;
}
return 0;
}
// 可打印字符串转换为字节数据
// 如:"C8329BFD0E01" --> {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01}
// 输入: pSrc - 源字符串指针
// nSrcLength - 源字符串长度
// 输出: pDst - 目标数据指针
// 返回: 目标数据长度
int stringToBytes(const char* pSrc, unsigned char* pDst, int nSrcLength)
{
int i=0;
for ( i = 0; i < nSrcLength; i += 2)
{
if (!isxdigit(*pSrc) || !isxdigit(*(pSrc + 1)))
{
return -1;
break;
}
// 输出高4位
if ((*pSrc >= '0') && (*pSrc <= '9'))
{
*pDst = (*pSrc - '0') << 4;
}
else if ((*pSrc >= 'A') && (*pSrc <= 'F'))
{
*pDst = (*pSrc - 'A' + 10) << 4;
}
else
{
*pDst = (*pSrc - 'a' + 10) << 4;
}
pSrc++;
// 输出低4位
if ((*pSrc>='0') && (*pSrc<='9'))
{
*pDst |= *pSrc - '0';
}
else if ((*pSrc >= 'A') && (*pSrc <= 'F'))
{
*pDst |= *pSrc - 'A' + 10;
}
else
{
*pDst |= *pSrc - 'a' + 10;
}
pSrc++;
pDst++;
}
return (nSrcLength / 2);
}
// 创建多级目录
int create_multi_dir(const char *path)
{
int i, len;
len = strlen(path);
char dir_path[len+1];
dir_path[len] = '\0';
strncpy(dir_path, path, len);
for (i=0; i<len; i++)
{
if (dir_path[i] == '/' && i > 0)
{
dir_path[i]='\0';
if (access(dir_path, F_OK) < 0)
{
if (mkdir(dir_path, 0755) < 0)
{
printf("mkdir=%s:msg=%s\n", dir_path, strerror(errno));
return -1;
}
}
dir_path[i]='/';
}
}
return 0;
}
void readini2( FILE *file, char *group, char *member, char *values )
{
char buf[256], tmpbuf1[256], tmpbuf2[256], *p1;
int len = 0, flag = 0;
memset( buf, 0, 256 );
rewind( file ); //pointer to file header
while( fgets( buf, 256, file ) )
{
p1 = buf;
cut_rn( buf );
if( strcmp( buf, group ) == 0 )
{
flag = 1;
continue;
} // find the group position and set it
if( flag )
{
if( *p1 == '[' )
{
values = NULL;
break;
}
if( strlen( buf ) == 0 ) // 20130718 lee 允许空行
{
continue;
}
len = strcspn( buf, "=" ); //cut up members of group and value with '='
memset( tmpbuf1, 0, sizeof( tmpbuf1 ) );
memset( tmpbuf2, 0, sizeof( tmpbuf2 ) );
strncpy( tmpbuf1, buf, len );
p1 += len;
p1++;
if( strcmp( tmpbuf1, member ) == 0 )
{
strcpy( values, p1 );
break;
} //read values of members
}
memset( buf, 0, sizeof( buf ) );
}
cut_rn( values );
}
#endif
/********************************************************************
* Function: my_strstr()
* Description: 在一个字符串中查找一个子串;
* Calls: 无;
* Called By: 无
* Input: ps: 源; pd:子串
* Output: 无;
* Return : 0:源字符串中没有子串; 1:源字符串中有子串;
* Author: ChenZhiFa
* Others: 无;
* date of completion:
*********************************************************************/
char * my_strstr(char * ps,char *pd)
{
char *pt = pd;
int c = 0;
while(*ps != '\0')
{
if(*ps == *pd)
{
while(*ps == *pd && *pd!='\0')
{
ps++;
pd++;
c++;
}
}
else
{
ps++;
}
if(*pd == '\0')
{
//sum++;
return (ps - c);
}
c = 0;
pd = pt;
}
return 0;
}
///********************************************************************
//* Function: memcpy()
//* Description: 复制一个内存区域到另一个区域;
//* Calls: 无;
//* Called By: 无
//* Input: src: 源;
// count: 复制字节数.
//* Output: dest: 复制目的地;
//* Return : dest;
//* Author: ChenZhiFa
//* Others: 无;
//* date of completion:
//*********************************************************************/
//void * memcpy(void * dest,const void *src,size_t count)
//{
// char *tmp = (char *) dest, *s = (char *) src;
// while (count--)
// *tmp++ = *s++;
// return dest;
//}
/********************************************************************
* Function: str_replace()
* Description: 在一个字符串中查找一个子串,并且把所有符合的子串用
另一个替换字符串替换。
* Calls: memcpy();
* Called By: 无
* Input: p_source:要查找的母字符串; p_seach要查找的子字符串;
p_repstr:替换的字符串;
* Output: p_result:存放结果;
* Return : 返回替换成功的子串数量;
* Author: ChenZhiFa
* Others: p_result要足够大的空间存放结果,所以输入参数都要以\0结束;
* date of completion:
*********************************************************************/
int str_replace(char *p_result,char* p_source,char* p_seach,char *p_repstr)
{
int c = 0;
int repstr_leng = 0;
int searchstr_leng = 0;
char *p1;
char *presult = p_result;
char *psource = p_source;
char *prep = p_repstr;
char *pseach = p_seach;
int nLen = 0;
repstr_leng = strlen(prep);
searchstr_leng = strlen(pseach);
do{
p1 = my_strstr(psource,p_seach);
if (p1 == 0)
{
strcpy(presult,psource);
return c;
}
c++; //匹配子串计数加1;
printf("结果:%s\r\n",p_result);
printf("源字符:%s\r\n",p_source);
// 拷贝上一个替换点和下一个替换点中间的字符串
nLen = p1 - psource;
memcpy(presult, psource, nLen);
// 拷贝需要替换的字符串
memcpy(presult + nLen,p_repstr,repstr_leng);
psource = p1 + searchstr_leng;
presult = presult + nLen + repstr_leng;
}while(p1);
return c;
}
|
C
|
/* POJ 1200
* 特别简单的一道Hash
* 认真看题即可
*/
#include <stdio.h>
#include <string.h>
char str[16000001];
char hash[16000000];
int main()
{
int x[26],total;
int n,nc,i,j,key,pow,result;
memset(hash,0,sizeof(hash));
memset(x,-1,sizeof(x));
scanf("%d%d",&n,&nc);
scanf("%s",str);
result=0;
total=0;
for(i=n-1;str[i]!=0;i++)
{
key=0;
pow=1;
for(j=i;j>i-n;j--)
{
if(x[str[j]-'a']==-1)x[str[j]-'a']=total++;
key+=(x[str[j]-'a'])*pow;
pow*=nc;
}
if(!hash[key])
{
hash[key]=1;
result++;
}
}
printf("%d\n",result);
return 0;
}
|
C
|
/*
习题3-5 三角形判断 (15 分)
给定平面上任意三个点的坐标(x1,y1),(x2,y2),(x3,y3)检验它们能否构成三角形。
输入格式:
输入在一行中顺序给出六个[?100,100]范围内的数字,即三个点的坐标x
x1,y1,x2,y2,x3,y3
输出格式:
若这3个点不能构成三角形,则在一行中输出“Impossible”;若可以,则在一行中输出该三角形的周长和面积,格式为“L = 周长, A = 面积”,输出到小数点后2位。
输入样例1:
4 5 6 9 7 8
输出样例1:
L = 10.13, A = 3.00
输入样例2:
4 6 8 12 12 18
输出样例2:
Impossible
*/
#include<stdio.h>
#include<math.h>
double getLenth(double x, double y);
int main() {
double x1, y1, x2, y2, x3, y3;
scanf("%lf", &x1);
scanf("%lf", &y1);
scanf("%lf", &x2);
scanf("%lf", &y2);
scanf("%lf", &x3);
scanf("%lf", &y3);
if ((x1 == x2 && x2 == x3) || (y1 == y2 && y2 == y3)) {
printf("Impossible");
} else if ((x1 - x2) * (y3 - y2) == (y1 - y2) * (x3 - x2)) {
printf("Impossible");
} else {
//使用海伦公式
double l1 = getLenth(x1 - x2, y1 - y2);
double l2 = getLenth(x1 - x3, y1 - y3);
double l3 = getLenth(x3 - x2, y3 - y2);
double L = l1 + l2 + l3;
double p = L / 2;
double A = sqrt(p * (p - l1) * (p - l2) * (p - l3));
printf("L = %.2lf, A = %.2lf", L, A);
}
return 0;
}
double getLenth(double x, double y) {
return sqrt(pow(x, 2) + pow(y, 2));
}
|
C
|
#include "holberton.h"
/**
* append_text_to_file - function that appends text to a file
* @filename: file name
* @text_content: text content
* Return: 1 on success, -1 otherwise
*/
int append_text_to_file(const char *filename, char *text_content)
{
int fd, x, i;
if (filename == NULL)
return (-1);
if (text_content == NULL)
text_content = "";
for (i = 0; text_content[i] != 0; i++)
;
fd = open(filename, O_RDWR | O_APPEND);
if (fd == -1)
return (-1);
x = write(fd, text_content, i);
if (x == -1)
return (-1);
close(fd);
return (1);
}
|
C
|
#include <stdio.h>
#define __USE_XOPEN_EXTENDED
#include <string.h>
#include <faup/hash/hash.h>
#include <faup/hash/htable.h>
struct _foobar_t {
char *name;
int blah;
};
typedef struct _foobar_t foobar_t;
static size_t rehash(const void *e, void *unused)
{
return hash_string(((foobar_t *)e)->name);
}
static bool streq(const void *e, void *string)
{
return strcmp(((foobar_t *)e)->name, string) == 0;
}
int main(int argc, char **argv)
{
struct htable ht;
foobar_t *foo;
foobar_t *ret;
htable_init(&ht, rehash, NULL);
foo = malloc(sizeof(foobar_t));
foo->name = strdup("fumier");
foo->blah = 123;
htable_add(&ht, hash_string(foo->name), foo);
ret = (foobar_t *)htable_get(&ht, hash_string("gugus"), streq, "gugus");
if (ret) {
printf("Found\n");
} else {
printf("Not found\n");
}
free(foo->name);
free(foo);
return 0;
}
|
C
|
#include <unistd.h>
void ft_putchar(char c);
int main(void)
{
char c;
c = 'c';
ft_putchar(c);
}
void ft_putchar(char c)
{
write(1, &c, 1);
}
|
C
|
/*
Alunos:
Igor Ferreira Murras / DRE: 118156052
Jonathan Suhett Barbêdo / DRE: 120021182
Versão GCC: 10.2.0
*/
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_RESET "\x1b[0m"
#include<stdio.h>
#include<stdint.h>
/*Número é par ou não:
A variável x negada deixa o bit menos significativo igual a 0, caso x seja ímpar,
e igual a 1, caso x seja par. Ao fazer (~x & 1) passamos o ~x por uma máscara que zera
todos os bits, exceto o menos significativo. E assim, obtemos 1 caso x seja par e 0 caso xseja ímpar
*/
int32_t ehPar(int32_t x) {
return ~x & 1;
}
/*Módulo 8:
7 é uma máscara que só deixa todos os bits de x igual a 0, menos os três bits menos significativos,
que são exatamente os bits que representam a congruência de x, módulo 8
*/
int32_t mod8(int32_t x){
return (x & 7);
}
/* Negativo:
Aqui aplicamos a lógica de que na representação de complemento a 2 o número com seus bits invertidos significa o seu valor negativo menos um,
então precisamos acrescentar 1 para obter exatamente o negativo do número em questão.
*/
int32_t negativo(int32_t x){
return (~x)+1;
}
/* BITWISEAND:
Nesse caso a solução é obtida por meio da equivalencia constatada pelo Teorema de Demorgan, sabemos que este diz que ~(A&B) = ~A | ~B,
então pela mesma lógica podemos obter que (A & B) = ~( ~A | ~B )
*/
int32_t bitwiseAnd(int32_t x, int32_t y){
return ~((~x) | (~y));
}
/*Igualdade:
Nessa função utilizamos o fato do XOR de um número consigo mesmo resultar 0, então combinando isso com '!',
é obtido 1 quando os números são iguais e 0 caso sejam diferentes, visto que !n para n diferente de 0 é igual a 0
*/
int32_t ehIgual(int32_t x, int32_t y){
return !(x ^ y);
}
/*Limpa Bit em N:
A primeira operação realizada nesse caso é o deslocamento do valor 1 para o bit N desejado, e logo após é realizada a inversão dos bits desse valor
obtendo 0 no bit em posição N e todos os outros com 1. Dessa forma quando realizamos um AND entre qualquer número e o esse valor obtido com apenas
o bit N igual a 0 o resultado é o valor x com o bit N zerado.
*/
int32_t limpaBitN(int32_t x, int8_t n){
return x & ~(1<<n) ;
}
/*Bit em p:
Aqui é realizada a mesma lógica do que foi usado para resolver a função 'ehPar', com um AND do ultimo bit com o valor 1, porém antes é feito um deslocamento
para que o bit de comparação desejado seja movido até a posição mais à direita.
*/
int32_t bitEmP(int32_t x, uint8_t p){
return (x>>p) & 1; // mesma logica do numero par só que deslocado
}
/*Byte em p:
Deslocar p 3 unidades para a esquerda resulta em múltiplos de 8 (2^3), podendo assumir os valores 0x0, 0x8, 0x10 e 0x18,
dependendo do valor de p. Isso faz com que x seja deslocado para direita uma quantidade de vezes suficientes para que o byte
pdesejado seja o LSB. Então o número é passado pela máscara 255, que faz com que apenas o byte menos significativo seja
mantido, e os outros ficam iguais a 0.
*/
int32_t byteEmP(int32_t x, uint8_t p){
return (x >> (p << 3) ) & 255 ; // mesma logica do bit em p só que deslocando a cada 2^3 intervalos (para andar 8 bits/2byte)
}
/* Seta byte em p:
Primeiro, utilizando a lógica do item anterior, o byte 0xFF é deslocado para a esquerda de forma a ficar na posição desejada.
Seus bits são invertidos para que quando for feita a operação & com x, o byte desejado seja transformado em 0x00 e o resto
do número continue igual.
Depois o byte y é deslocado para a posição que foi zerada anteriormente, e com a operação | y é inserido no x sem alterar
o restante do número.
*/
int32_t setaByteEmP(int32_t x, int32_t y, uint8_t p){
return ( ~( 255 << ( p<<3 ) ) & x ) | (y << ( p<<3 ) ) ;
// primeiro zeramos o byte na posicao do byte p (por meio da inversao de 1111 1111 [= 255] deslocado para a posição do byte
// e depois fizemos AND do inverso de 255 com X que é o valor com byte a ser alterado, obtendo assim a posicao toda 0000 0000)
// depois disso fazemos o OR do resultado anterior com Y (byte a ser inserido) deslocado para a posicao requisitada
// obtendo a insercao de Y no lugar do byte desejado
}
/*Mínimo:
A lógica utilizada nessa solução é retornar y caso y<x ou retornar x caso x<y. Para isso foi utilizado o termo -(x < y), que possui dois casos:
0 caso y<x, também resultando 0 para a operação ((x ^ y) & 0) , de forma que a operação restante seria y ^ 0, que tem o próprio y como resultado
-1(0xFFFFFFFF) caso x<y, obtendo a operação ((x ^ y) & -1) que equivale à própria operação (x ^ y), já que -1 é um valor neutro da operação &,
dessa forma, junto da operação exterior é obtido y^(x^y), o que equivale a x, visto que y^y anula-se.
Assim o resultado esperado é obtido.
*/
int32_t minimo(int32_t x, int32_t y){
return y ^ ((x ^ y) & -(x < y)); //
}
/*Negação lógica:
Exploramos o fato de que quando deslocamos um número positivo para a direita, o byte da esqueda se torna 0, e quando o número
é negativo, o byte da esquerda se torna 1.
E (~x + 1) é utilizado para diferenciar os números positivos do 0, tendo em vista que o 0 com os bits invertidos é -1, e
após somar 1 volta a ser 0. Esse é o único caso em que o resultado de (~x + 1) em que um número não negativo tem o bit mais à
esqueda igual a 0.
caso x > 0 :
( (~x + 1) >> 31) obtemos 0xFFFFFFFF
( (x >> 31) | ((~x + 1) >> 31) ) obtido (0x00000000 | 0xFFFFFFFF) que retorna 0xFFFFFFFF
( (x >> 31) | ((~x + 1) >> 31) ) + 1 como 0xFFFFFFFF é igual a -1, obtemos a operação -1 + 1 = 0
caso x = 0 :
( (~x + 1) >> 31) obtemos 0xFFFFFFFF
( (x >> 31) | ((~x + 1) >> 31) ) obtido (0x00000000 | 0x00000000) que retorna 0x00000000
( (x >> 31) | ((~x + 1) >> 31) ) + 1 ultimo bit a direita 1, valor decimal 1
caso x < 0 :
( (~x + 1) >> 31) obtemos 0x00000000
( (x >> 31) | ((~x + 1) >> 31) ) obtido (0xFFFFFFFF | 0x00000000) que retorna 0xFFFFFFFF
( (x >> 31) | ((~x + 1) >> 31) ) + 1 como 0xFFFFFFFF é igual a -1, obtemos a operação -1 + 1 = 0
*/
int32_t negacaoLogica(int32_t x){
return ( (x >> 31) | ((~x + 1) >> 31) ) + 1;
}
void teste(int32_t saida, int32_t esperado) {
static uint8_t test_number = 0;
test_number++;
if(saida == esperado)
printf(ANSI_COLOR_GREEN "PASSOU! Saída: %-10d\t Esperado: %-10d\n" ANSI_COLOR_RESET,
saida, esperado);
else
printf(ANSI_COLOR_RED "%d: FALHOU! Saída: %-10d\t Esperado: %-10d\n" ANSI_COLOR_RESET,
test_number, saida, esperado);
}
int main() {
puts(ANSI_COLOR_BLUE "Primeiro lab - bits" ANSI_COLOR_RESET);
puts("");
puts("Teste: ehPar");
teste(ehPar(2), 1);
teste(ehPar(1), 0);
teste(ehPar(3), 0);
teste(ehPar(13), 0);
teste(ehPar(100), 1);
teste(ehPar(125), 0);
teste(ehPar(1024), 1);
teste(ehPar(2019), 0);
teste(ehPar(2020), 1);
teste(ehPar(-1), 0);
teste(ehPar(-27), 0);
teste(ehPar(-1073741825), 0);
teste(ehPar(1073741824), 1);
teste(ehPar(2147483647), 0);
teste(ehPar(-2147483648), 1);
teste(ehPar(0), 1);
puts("");
puts("Teste: mod8");
teste(mod8(0), 0);
teste(mod8(4), 4);
teste(mod8(7), 7);
teste(mod8(8), 0);
teste(mod8(-1), 7);
teste(mod8(-8), 0);
teste(mod8(2147483647), 7);
teste(mod8(-2147483648), 0);
puts("");
puts("Teste: negativo");
teste(negativo(0), 0);
teste(negativo(1), -1);
teste(negativo(-1), 1);
teste(negativo(2147483647), -2147483647);
teste(negativo(-2147483647), 2147483647);
teste(negativo(-2147483648), 2147483648);
puts("");
puts("Teste: bitwiseAnd");
teste(bitwiseAnd(1, 3), 1);
teste(bitwiseAnd(-1, 0), 0);
teste(bitwiseAnd(-1, 0x7FFFFFFF), 0x7FFFFFFF);
teste(bitwiseAnd(0b0100, 0b1100), 0b0100);
puts("");
puts("Teste: ehIgual");
teste(ehIgual(1,1), 1);
teste(ehIgual(1,0), 0);
teste(ehIgual(0,1), 0);
teste(ehIgual(-1,1), 0);
teste(ehIgual(-1,-1), 1);
teste(ehIgual(2147483647,-1), 0);
teste(ehIgual(2147483647,-2147483647), 0);
teste(ehIgual(2147483647,-2147483648), 0);
teste(ehIgual(2147483647,-2147483648), 0);
puts("");
puts("Teste: limpaBitN");
teste(limpaBitN(1,0), 0);
teste(limpaBitN(0b1111,1), 0b1101);
teste(limpaBitN(15,3), 7);
teste(limpaBitN(-1,31), 2147483647);
teste(limpaBitN(-1,0), -2);
teste(limpaBitN(2147483647, 30), 1073741823);
puts("");
puts("Teste: bitEmP");
teste(bitEmP(1, 0), 1); // b01 => retorna 1
teste(bitEmP(1, 1), 0); // b01 => retorna 0
teste(bitEmP(2, 0), 0); // b10 => retorna 0
teste(bitEmP(2, 1), 1); // b10 => retorna 1
teste(bitEmP(9, 2), 0); // b1001 => retorna 0
teste(bitEmP(-4194305, 22), 0);
teste(bitEmP(9, 3), 1);
teste(bitEmP(16, 3), 0);
teste(bitEmP(0x1 << 5, 4), 0);
teste(bitEmP(0x1 << 31, 31), 1);
teste(bitEmP(-1073741825, 30), 0);
teste(bitEmP(-1073741825, 31), 1);
puts("");
puts("Teste: byteEmP");
teste(byteEmP(0x766B, 1), 0x76);
teste(byteEmP(0x766B, 0), 0x6B);
teste(byteEmP(0x8420, 0), 0x20);
teste(byteEmP(0x12345678, 3), 0x12); // retorna 0x12
teste(byteEmP(0x12345678, 2), 0x34); // retorna 0x34
teste(byteEmP(0x12345678, 1), 0x56); // retorna 0x56
teste(byteEmP(0x12345678, 0), 0x78); // retorna 0x78
teste(byteEmP(0x321, 1), 0x03); // retorna 0x03
teste(byteEmP(0x321, 0), 0x21); // retorna 0x21
puts("");
puts("Teste: setaByteEmP");
teste(setaByteEmP(0x00, 0xFF, 0), 0x000000FF);
teste(setaByteEmP(0x00, 0xFF, 1), 0x0000FF00);
teste(setaByteEmP(0x00, 0xFF, 2), 0x00FF0000);
teste(setaByteEmP(0x00, 0xFF, 3), 0xFF000000);
teste(setaByteEmP(0x01234567, 0x33, 2), 0x01334567);
teste(setaByteEmP(0xdeadbeef, 0x00, 0), 0xdeadbe00);
teste(setaByteEmP(0xdeadbeef, 0x00, 1), 0xdead00ef);
puts("");
puts("Teste: minimo");
teste(minimo(0,1), 0);
teste(minimo(0,10), 0);
teste(minimo(1, 128), 1);
teste(minimo(-1, 0), -1);
teste(minimo(-1, -2), -2);
teste(minimo(2147483647, 2147483646), 2147483646);
teste(minimo(-2147483648, -2147483647), -2147483648);
teste(minimo(-2147483648, -1), -2147483648);
puts("");
puts("Teste: negacaoLogica");
teste(negacaoLogica(0), 1);
teste(negacaoLogica(1), 0);
teste(negacaoLogica(-1), 0);
teste(negacaoLogica(64), 0);
teste(negacaoLogica(-64), 0);
teste(negacaoLogica(2147483647), 0);
teste(negacaoLogica(-2147483648), 0);
puts("");
}
|
C
|
#ifndef types_h
#define types_h
#include <allegro5/allegro5.h>
#include <string.h>
#include <math.h>
#include "utils.h"
/** Tipo delle funzioni che si occupano di copiare un valore */
typedef void * (* duplicate_function)(void *);
/** Tipo delle funzioni che si occupano di deallocare un valore */
typedef void (* delete_function)(void *);
/** Tipo delle funzioni che si occupano di confrontare due valori (0 = uguali) */
typedef int (* compare_function)(void *, void *);
/** Tipo delle funzioni che si occupano di calcolare la dimensione, in bytes, di un valore */
typedef size_t (* size_function)(void *);
/**
* Funzioni per gestire un tipo di dato
*/
struct type_functions {
/** Puntatore alla funzione di copia */
duplicate_function duplicate;
/** Puntatore alla funzione di deallocazione */
delete_function delete;
/** Puntatore alla funzione di confronto */
compare_function compare;
/** Puntatore alla funzione di calcolo della dimensione */
size_function size;
};
/**
* Tipo di dato booleano
*/
#ifndef __bool_true_false_are_defined
#ifndef bool
#ifdef _Bool
#define bool _Bool
#else
#define bool int
#endif
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif // bool
#endif // __bool_true_false_are_defined
/**
* Macro per la dichiarazione delle funzioni necessario per gestire un tipo di dato.
* Tutti i parametri sono opzionali ad eccezione di type_name.
*
* @param type_name Nome del tipo di dato
* @param delf Funzione di deallocazione
* @param szf Funzione per il calcolo della dimensione
* @param dupf Funzione di copia
* @param compf Funzione di confronto
*/
#define TYPE_FUNCTIONS_DEFINE(...) OVERLOAD(TYPE_FUNCTIONS_DEFINE_, __VA_ARGS__)
#define TYPE_FUNCTIONS_DEFINE_1(type_name) struct type_functions type_name ## _ ## functions = {NULL, NULL, NULL, NULL}
#define TYPE_FUNCTIONS_DEFINE_2(type_name, delf) struct type_functions type_name ## _ ## functions = {NULL, (delete_function)delf, NULL, NULL}
#define TYPE_FUNCTIONS_DEFINE_3(type_name, delf, szf) struct type_functions type_name ## _ ## functions = {NULL, (delete_function)delf, NULL, (size_function)szf}
#define TYPE_FUNCTIONS_DEFINE_4(type_name, delf, szf, dupf) struct type_functions type_name ## _ ## functions = {(duplicate_function)dupf, (delete_function)delf, NULL, (size_function)szf}
#define TYPE_FUNCTIONS_DEFINE_5(type_name, delf, szf, dupf, compf) struct type_functions type_name ## _ ## functions = {(duplicate_function)dupf, (delete_function)delf, (compare_function)compf, (size_function)szf}
#define TYPE_FUNCTIONS_DECLARE(ty) extern struct type_functions ty ## _ ## functions
// Dimensione minima da allocare quando si crea una stringa
#define STRING_DEFAULT_BUFFER_SIZE 32
// Funzioni per gestire tipo di dato
TYPE_FUNCTIONS_DECLARE(string);
TYPE_FUNCTIONS_DECLARE(long);
TYPE_FUNCTIONS_DECLARE(float);
TYPE_FUNCTIONS_DECLARE(no);
#define long_value(addr) (addr ? *((long *)addr) : 0)
#define bool_value(addr) (!!long_value(addr))
#define float_value(addr) (addr ? *((float *)addr) : 0.f)
#define long_value_nocheck(addr) (*((long *)addr))
#define bool_value_nocheck(addr) (!!long_value_nocheck(addr))
#define float_value_nocheck(addr) (*((float *)addr))
#endif // types_h
|
C
|
#include "md.h"
#define FILE_PATH_MAX 256
const char *testMdFileName = "test.md";
char fp[FILE_PATH_MAX] = {0};
md_t *md = NULL;
int get_test_md_path(){
int ret = 0;
char *currFilePath = __FILE__;
size_t currFilePathSize = strlen(currFilePath);
int i = currFilePathSize - 1;
size_t dirPathSize = 0;
for(; i >= 0; i--){
if('/' == currFilePath[i]){
dirPathSize = i;
break;
}
}
memset(fp,0,FILE_PATH_MAX);
R(dirPathSize >= FILE_PATH_MAX - 1);
snprintf(fp,dirPathSize + 2,"%s/",currFilePath);
snprintf(fp + dirPathSize + 1, FILE_PATH_MAX - dirPathSize - 1, "%s",testMdFileName);
return ret;
}
int main(int argc,char *argv[]){
int ret = 0;
if(argc > 1){
testMdFileName = argv[1];
}
RL(get_test_md_path(),"get_test_md_path() failed!\n");
printf("test.md file path : %s\n",fp);
RL(md_init(&md),"md_init() failed!\n");
md_result_t *result = NULL;
RL(md_result_init(&result),"md_result_init() failed!\n");
RL(md_parse_file(md,result,fp),"md_parse_file() failed!\n");
RL(md_result_print(result),"md_result_print() failed!\n");
RL(md_result_free(&result),"md_result_free() failed!\n");
RL(md_free(&md),"md_free() failed!");
mem_show();
return ret;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* Create main funciton */
int main()
{
char CharacterName[] = "John";
int CharacterAge = 35;
/* %s used for characters */
printf("There once was a man named %s\n", CharacterName);
printf("he was %d years old\n", CharacterAge);
/* %d used for integers */
printf("He liked being named %s\n", CharacterName);
printf("He did not like being %d years old\n", CharacterAge);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int a,b,c;
int tmp;
scanf("%d%d%d", &a,&b,&c);
if( a > b ){ // Worst Case: swapping a with b
tmp = a;
a = b;
b = tmp;
}
if( b > c ){// Worst Case: swapping b(old a) with c
tmp = b;
b = c;
c = tmp;
if(a > b){// Worst Case: swapping old C(now b) with a. c finished moving to First Position after A
tmp = a;
a = b;
b = tmp;
}
}//Best Case Scenario Jumps If blocks to print values automatically
printf("%d %d %d\n", a,b,c);
return 0;
}
|
C
|
#include <stdio.h>
/* This is a comment. */
int main(int argc, char *argv[])
{
int distance = 100;
// \n is important because otherwise the line will end with a % sign
printf("You are %d miles away.\n", distance);
printf("HELLO HOW ARE YOU\n");
return 0; // The program still works if you delete this line.
}
|
C
|
/* radare - LGPL - Copyright 2007-2015 - pancake */
// TODO: RRef - reference counting
#include <stdio.h>
#define _R_LIST_C_
#include "r_util.h"
inline RListIter *r_list_iter_new () {
return malloc (sizeof (RListIter));
}
void r_list_iter_free (RListIter *list) {
/* do nothing? */
}
RListIter *r_list_iter_get_next(RListIter *list) {
return list ? list->n : NULL;
}
void *r_list_iter_get_data(RListIter *list) {
if (list == NULL) return NULL;
return list->data;
}
RListIter *r_list_iterator (const RList *list) {
return list? list->head: NULL;
}
RListIter *r_list_push (RList *list, void *item) {
return r_list_append (list, item);
}
RListIter *r_list_get_next (RListIter *list) {
return list ? list->n : NULL;
}
R_API void* r_list_first(const RList *list) {
if (list && list->head) {
return list->head->data;
}
return NULL;
}
R_API void r_list_init(RList *list) {
list->head = NULL;
list->tail = NULL;
list->free = NULL;
}
R_API int r_list_length(const RList *list) {
int count = 0;
RListIter *iter = r_list_iterator (list);
while (iter) {
count ++;
iter = iter->n;
}
return count;
}
/* remove all elements of a list */
R_API void r_list_purge (RList *list) {
if (list) {
RListIter *it = list->head;
while (it) {
RListIter *next = it->n;
r_list_delete (list, it);
it = next;
}
list->head = list->tail = NULL;
}
}
/* free the list */
R_API void r_list_free (RList *list) {
if (list) {
r_list_purge (list);
free (list);
}
}
R_API bool r_list_delete_data (RList *list, void *ptr) {
void *p;
RListIter *iter;
r_list_foreach (list, iter, p) {
if (ptr == p) {
r_list_delete (list, iter);
return true;
}
}
return false;
}
R_API void r_list_delete (RList *list, RListIter *iter) {
if (list && iter){
r_list_split_iter (list, iter);
if (list->free && iter->data)
list->free (iter->data);
iter->data = NULL;
free (iter);
}
}
R_API void r_list_split (RList *list, void *ptr) {
if (list) {
RListIter *iter = r_list_iterator (list);
while (iter) {
void *item = iter->data;
if (ptr == item) {
r_list_split_iter (list, iter);
free (iter);
break;
}
iter = iter->n;
}
}
}
R_API void r_list_split_iter (RList *list, RListIter *iter) {
if (list->head == iter) list->head = iter->n;
if (list->tail == iter) list->tail = iter->p;
if (iter->p) iter->p->n = iter->n;
if (iter->n) iter->n->p = iter->p;
}
//Warning: free functions must be compatible
#define r_list_empty(x) (x == NULL || (x->head == NULL && x->tail == NULL))
R_API int r_list_join (RList *list1, RList *list2) {
if (!list1 || !list2)
return 0;
if (r_list_empty (list2))
return 0;
if (r_list_empty (list1)) {
list1->head = list2->head;
list1->tail = list2->tail;
} else if (list1->tail == NULL) {
list1->tail = list2->head;
} else if (list2->head != NULL) {
list1->tail->n = list2->head;
list2->head->p = list1->tail;
}
list2->head = list2->tail = NULL;
/* the caller must free list2 */
return 1;
}
R_API RList *r_list_new() {
RList *list = R_NEW0(RList);
if (!list) return NULL;
r_list_init (list);
return list;
}
R_API RList *r_list_newf(RListFree f) {
RList *l = r_list_new ();
if (l) l->free = f;
return l;
}
R_API RListIter *r_list_item_new (void *data) {
RListIter *new = R_NEW (RListIter);
if (!new) return NULL;
new->data = data;
return new;
}
R_API RListIter *r_list_append(RList *list, void *data) {
RListIter *new = NULL;
if (list && data) {
new = R_NEW (RListIter);
if (new == NULL) return new;
if (list->tail)
list->tail->n = new;
new->data = data;
new->p = list->tail;
new->n = NULL;
list->tail = new;
if (list->head == NULL)
list->head = new;
}
return new;
}
R_API RListIter *r_list_prepend(RList *list, void *data) {
RListIter *new = R_NEW (RListIter);
if (!new) return NULL;
if (list){
if (list->head)
list->head->p = new;
new->data = data;
new->n = list->head;
new->p = NULL;
list->head = new;
if (list->tail == NULL)
list->tail = new;
return new;
}
free (new);
return NULL;
}
R_API RListIter *r_list_insert(RList *list, int n, void *data) {
RListIter *it, *new;
int i;
if (list) {
if (!list->head || n == 0)
return r_list_prepend (list, data);
for (it = list->head, i = 0; it && it->data; it = it->n, i++) {
if (i == n) {
new = R_NEW (RListIter);
if (!new) return NULL;
new->data = data;
new->n = it;
new->p = it->p;
if (it->p)
it->p->n = new;
it->p = new;
return new;
}
}
}
return r_list_append (list, data);
}
R_API void *r_list_pop(RList *list) {
void *data = NULL;
RListIter *iter;
if (list) {
if (list->tail) {
iter = list->tail;
if (list->head == list->tail) {
list->head = list->tail = NULL;
} else {
list->tail = iter->p;
list->tail->n = NULL;
}
data = iter->data;
free (iter);
}
return data;
}
return NULL;
}
R_API void *r_list_pop_head(RList *list) {
void *data = NULL;
RListIter *iter;
if (list) {
if (list->head) {
iter = list->head;
if (list->head == list->tail) {
list->head = list->tail = NULL;
} else {
list->head = iter->n;
list->head->p = NULL;
}
data = iter->data;
free (iter);
}
return data;
}
return NULL;
}
R_API int r_list_del_n(RList *list, int n) {
RListIter *it;
int i;
if (!list)
return R_FALSE;
for (it = list->head, i = 0; it && it->data; it = it->n, i++)
if (i == n) {
if (it->p == NULL && it->n == NULL) {
list->head = list->tail = NULL;
} else if (it->p == NULL) {
it->n->p = NULL;
list->head = it->n;
} else if (it->n == NULL) {
it->p->n = NULL;
list->tail = it->p;
} else {
it->p->n = it->n;
it->n->p = it->p;
}
free (it);
return R_TRUE;
}
return R_FALSE;
}
R_API void *r_list_get_top(const RList *list) {
if (list && list->tail)
return list->tail->data;
return NULL;
}
R_API void *r_list_get_bottom(const RList *list) {
if (list && list->head)
return list->head->data;
return NULL;
}
R_API void r_list_reverse(RList *list) {
RListIter *it, *tmp;
if (list) {
for (it = list->head; it && it->data; it = it->p) {
tmp = it->p;
it->p = it->n;
it->n = tmp;
}
tmp = list->head;
list->head = list->tail;
list->tail = tmp;
}
}
R_API RList *r_list_clone (RList *list) {
RList *l = NULL;
RListIter *iter;
void *data;
if (list) {
l = r_list_new ();
l->free = NULL;
r_list_foreach (list, iter, data)
r_list_append (l, data);
}
return l;
}
R_API void r_list_sort(RList *list, RListComparator cmp) {
RListIter *it;
RListIter *it2;
if (list) {
for (it = list->head; it && it->data; it = it->n) {
for (it2 = it->n; it2 && it2->data; it2 = it2->n) {
if (cmp (it->data, it2->data)>0) {
void *t = it->data;
it->data = it2->data;
it2->data = t;
}
}
}
}
}
R_API RListIter *r_list_add_sorted(RList *list, void *data, RListComparator cmp) {
RListIter *it, *new = NULL;
if (list && data && cmp) {
for (it = list->head; it && it->data && cmp (data, it->data)>0; it = it->n) ;
if (it) {
new = R_NEW (RListIter);
new->n = it;
new->p = it->p;
new->data = data;
new->n->p = new;
if (new->p == NULL)
list->head = new;
else new->p->n = new;
} else {
r_list_append (list, data);
}
return new;
}
return NULL;
}
R_API int r_list_set_n(RList *list, int n, void *p) {
RListIter *it;
int i;
if (list)
for (it = list->head, i = 0; it && it->data; it = it->n, i++) {
if (i == n) {
it->data = p;
return R_TRUE;
}
}
return R_FALSE;
}
R_API void *r_list_get_n(const RList *list, int n) {
RListIter *it;
int i;
if (list)
for (it = list->head, i = 0; it && it->data; it = it->n, i++)
if (i == n)
return it->data;
return NULL;
}
R_API void *r_list_get_by_int(const RList *list, int off, int n) {
ut8 *p;
RListIter *iter;
r_list_foreach (list, iter, p) {
if (!memcmp (&n, p+off, sizeof (int)))
return p;
}
return NULL;
}
R_API void *r_list_get_by_int64(const RList *list, int off, ut64 n) {
ut8 *p;
RListIter *iter;
r_list_foreach (list, iter, p) {
if (!memcmp (&n, p+off, sizeof (ut64)))
return p;
}
return NULL;
}
R_API void *r_list_get_by_string(const RList *list, int off, const char *str) {
char *p;
RListIter *iter;
r_list_foreach (list, iter, p) {
const char *ptr = p+off;
if (!strcmp (str, ptr))
return p;
}
return NULL;
}
R_API RListIter *r_list_contains (const RList *list, const void *p) {
void *q;
RListIter *iter;
r_list_foreach (list, iter, q) {
if (p == q)
return iter;
}
return NULL;
}
R_API RListIter *r_list_find (const RList *list, const void *p, RListComparator cmp) {
void *q;
RListIter *iter;
r_list_foreach (list, iter, q) {
if (cmp (p, q) == 0)
return iter;
}
return NULL;
}
#if TEST
// TODO: move into t/list.c
int main () {
RListIter *iter, *it;
RList *l = r_list_new ();
r_list_append (l, "foo");
r_list_append (l, "bar");
r_list_append (l, "cow");
r_list_prepend (l, "HEAD");
r_list_prepend (l, "HEAD 00");
it = r_list_append (l, "LAST");
{
char *str;
r_list_foreach(l, iter, str) {
printf("-- %s\n", str);
}
printf("--**--\n");
r_list_foreach_prev(l, iter, str) {
printf("-- %s\n", str);
}
}
iter = r_list_iterator (l);
while (r_list_iter_next (iter)) {
const char *str = r_list_iter_get (iter);
printf ("-> %s\n", str);
}
eprintf ("--sort--\n");
r_list_sort (l, (RListComparator)strcmp);
iter = r_list_iterator (l);
while (r_list_iter_next (iter)) {
const char *str = r_list_iter_get (iter);
printf ("-> %s\n", str);
}
r_list_delete (l, it);
char *foo = (char*) r_list_get_n (l, 2);
printf (" - n=2 => %s\n", foo);
iter = r_list_iterator (l);
while (r_list_iter_next (iter)) {
RListIter *cur = iter;
char *str = r_list_iter_get (iter);
if (!strcmp (str, "bar"))
r_list_delete (l, cur);
}
iter = r_list_iterator (l);
while (r_list_iter_next (iter)) {
char *str = r_list_iter_get (iter);
//XXX r_list_delete (l, iter);
printf (" - %s\n", str);
}
r_list_free (l);
/* ------------- */
l = r_list_new ();
l->free = free;
r_list_append (l, strdup ("one"));
r_list_append (l, strdup ("two"));
r_list_append (l, strdup ("tri"));
it = r_list_append (l, strdup ("LAST"));
r_list_delete (l, it);
{
RListIter* i = r_list_iterator (l);
for (; i; i = i->n) {
char *str = i->data;
printf (" * %s\n", str);
}
}
r_list_free (l);
l = r_list_new ();
l->free = free;
r_list_append (l, strdup ("one"));
r_list_append (l, strdup ("two"));
r_list_append (l, strdup ("tri"));
{
char *str;
r_list_foreach (l, it, str)
printf (" - %s\n", str);
RList *list;
list = r_list_clone (l);
r_list_foreach (list, it, str)
printf (" - %s\n", str);
r_list_reverse (l);
r_list_foreach (l, it, str)
printf (" * %s\n", str);
}
r_list_free (l);
//r_list_free (l);
return 0;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "holberton.h"
/**
* create_array - create char array and init it with a specific char
* @size: the size of the memory to print
* @c: char to init values to
*
* Return: pointer to array
*/
char *create_array(unsigned int size, char c)
{
char *ptr = NULL;
unsigned int i;
if (size > 0)
{
ptr = (char *)malloc(size * sizeof(char));
if (ptr == NULL)
return (NULL);
for (i = 0; i < size; i++)
ptr[i] = c;
}
return (ptr);
}
|
C
|
/**
* usual head files
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sqlite.h>
/*********************************************************
************** Function Declaration ***************
*********************************************************/
static int cb(void *arg, int cnt, char **value, char **name)
{
int i = 0;
for (i = 0; i < cnt; i++) {
printf("name: %s, value: %s\n", name[i], value[i]);
}
return 0;
}
/*********************************************************
****************** Main Function ******************
*********************************************************/
int main(int agrc, char *agrv[])
{
int rt = 0; /* return value of function main */
sqlite_t *sql = sqlite_create();
sql->open(sql, "test.db");
//sql->exec(sql, "create table tb(id INTEGER PRIMARY KEY, data TEXT)");
//sql->exec(sql, "insert into tb values (1, \"init sqlite3\")");
sql->get_data(sql, "select * from tb;", cb);
sql->destroy(sql);
return rt;
}
|
C
|
// ADS 2020 - LINGUAGEM DE PROGRAMAO
// CAPTULO 07 - EXERCCIO 05
/* Solicitar um nome e mostrar a primeira, ultima, a quarta, da primeiro
terceira, da primeira ultima. Mostrar a posio de cada letra no vetor.*/
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
#include<locale.h>
#include<string.h>
main(){
setlocale(LC_ALL,"");
system("cls");
printf("\nCAPTULO 07 - EXERCCIO 03 - Solicitar um nome e mostrar a \nprimeira, ltima, a quarta, da primeiro terceira, da primeira \nltima. Mostrar a posio de cada letra no vetor.");
printf("\n\n");
char nome[100];
int n, tam;
printf("Digite o nome com no mximo 100 caracteres: ");
gets(nome);
tam=strlen(nome);
printf("\n\nA primeira letra %c.", nome[0]);
sleep(2000);
printf("\n\nA ltima letra %c.", nome[(tam-1)]);
sleep(2000);
printf("\n\nA quarta letra %c.", nome[3]);
printf("\n");
sleep(2000);
for(n=0;n<=2;n++){
printf("\nNa posio %2d temos a letra %c.", n+1, nome[n]);
sleep(1000);
}
printf("\n");
sleep(2000);
for(n=0;n<tam;n++){
printf("\nNa posio %2d temos a letra %c.", n+1, nome[n]);
sleep(1000);
}
sleep(2000);
printf("\n\nPrograma Finalizado.");
sleep(3000);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int value;
struct Node *leftChild,*rightChild;
};
struct Node* root = NULL;
struct Node* temp = NULL;
int leafcount =0;
int height=0,max=0,internalNode = 0,level=0,currentlevel=0;
void insert(struct Node* rootnode, struct Node* newnode)
{
if(rootnode->value>newnode->value)
{
if(rootnode->leftChild==NULL)
{
rootnode->leftChild = newnode;
}
else
{
rootnode = rootnode->leftChild;
insert(rootnode,newnode);
}
}
else if(rootnode->value!=newnode->value)
{
if(rootnode->rightChild==NULL)
{
rootnode->rightChild=newnode;
}
else
{
rootnode = rootnode->rightChild;
insert(rootnode,newnode);
}
}
}
void inorder(struct Node* rootnode)
{
if(rootnode!=NULL)
{
inorder(rootnode->leftChild);
printf("%d ",rootnode->value);
inorder(rootnode->rightChild);
}
}
void leafNodeCount(struct Node* rootnode)
{
if(rootnode!=NULL)
{
if(rootnode->leftChild==NULL && rootnode->rightChild == NULL)
{
leafcount++;
}
leafNodeCount(rootnode->leftChild);
leafNodeCount(rootnode->rightChild);
}
}
void heightOfTree(struct Node* rootnode)
{
if(rootnode!=NULL)
{
if(height>max)
{
max=height;
}
height+=1;
heightOfTree(rootnode->leftChild);
heightOfTree(rootnode->rightChild);
height-=1;
}
}
void FindLevelOfElement(struct Node* rootnode,int value){
if(rootnode!=NULL){
if(rootnode->value==value){
level = currentlevel+1;
return;
} else{
currentlevel +=1;
FindLevelOfElement(rootnode->leftChild,value);
FindLevelOfElement(rootnode->rightChild,value);
currentlevel -=1;
}
}
}
void FindInternalNodes(struct Node* rootnode){
if(rootnode!=NULL){
if(rootnode->leftChild!=NULL || rootnode->rightChild!=NULL){
internalNode++;
}
FindInternalNodes(rootnode->leftChild);
FindInternalNodes(rootnode->rightChild);
}
}
int main()
{
int n,cnt,findingValue;
scanf("%d",&n);
root=(struct Node*)malloc(sizeof *root);
root->leftChild = root->rightChild = NULL;
scanf("%d",&root->value);
for(cnt=1; cnt<n; cnt++)
{
temp=(struct Node*)malloc(sizeof *temp);
scanf("%d",&temp->value);
temp->leftChild = temp->rightChild = NULL;
insert(root,temp);
}
printf("Enter the value to find the level : ");
scanf("%d",&findingValue);
printf("\n The traversal of the tree : ");
inorder(root);
FindInternalNodes(root);
leafNodeCount(root);
heightOfTree(root);
FindLevelOfElement(root,findingValue);
printf("\n LeafNode Count : %d",leafcount);
printf("\n Height : %d", max);
printf("\n Internal Nodes : %d",internalNode);
printf("\n Level of the %d element is level %d",findingValue,level);
printf("\n Depth of the tree is %d",max+1);
}
|
C
|
/*Programa que permita o mantemento dun arquivo de libros (altas, baixas, modificacins e consultas)
Os datos de cada libro estan grabados nun arquivo
binario (libros.dat)no que os datos de cada rexistro
estn nunha estructura cos seguintes campos:
cdigo de libro 5 caracteres
Ttulo 30 caracteres
Autor 30 caracteres
Editorial 20 caracteres
Precio real precision simple
unidades enteiro corto
altas: pedir codigo, comprobar que non existe, introducir datos si non existe. baixas: pedir codigo, comprobar
que existe e eliminar se existe (duas maneiras de eliminar: eliminacion fisica: copiar ficheiro con todos os
datos menos o que queremos eliminar e eliminar o ficheiro orixinal; ou por marca: poemos un caracter nulo, na
primeira posicion do vector). modificacions: pedir codigo, si existe, modificar. consultas: comprobar si existe
codigo, si existe, ver os datos do libro.
*/
//librerias
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
//estructura
struct libros{
char codigo_libro[5];
char titulo[30];
char autor[30];
char editorial[20];
float precio;
short int unidades;
};
//fseek
//fsetpos
//fgetpos
//remove
//rename
//rewind
//declaracion de funcions
void altas();
void baixas();
void modificacions();
void consultas();
/////////////////////////////////////////////////////////////////MAIN///////////////////////////////////////////
int main(){
//declaracion de variable
int a;
do{//MENU
printf("\nElixe unha destas opcions\n");
printf("0-Sair\n");
printf("1-Altas\n");
printf("2-Baixas\n");
printf("3-Modificacions\n");
printf("4-Consultas\n");
//introducir eleccion
scanf("%d",&a);
switch(a){
case 1:
altas();
break;
case 2:
baixas();
break;
case 3:
modificacions();
break;
case 4:
consultas();
break;
}
}while(a!=0);//si se elixe 0 (sair) sae do programa
system("pause");
}
////////////////////////////////////ALTAS///////////////////////////////////////////////////////////////////////
void altas(){
FILE *fich;
//declaracion de variables
char cod[5];
struct libros introducir={0};
int i;
int band=0;;
printf("\nIntroduce o codigo do libro que queres introducir:\n");
scanf("%s",&cod);
///////abrese o ficheiro para comprobar se o codigo (e polo tanto o libro tamen) xa existe//////////////////////
fich=fopen("libros.dat","ab+");
rewind(fich);
if(!fich){
printf("\nO archivo non existe. Creando archivo. Introduce os datos do libro:\n");
band=2;
}
if(band!=2){
for(i=0;!feof(fich);i++){
fread(&introducir, sizeof(struct libros), 1,fich);
if(!feof(fich)){
if(strcmp(cod,introducir.codigo_libro)==0){
printf("\nO libro xa existe. Non se pode introducir\n");
band=1;
break;
}
}
}
}
//si o libro ainda non existe, entra no ficheiro para introducir os datos dese libro
if(band!=1){
strcpy(introducir.codigo_libro,cod);
printf("\nIntroducir titulo, autor, editorial, precio e unidades\n");
printf("Titulo:\n");
fflush(stdin);
gets(introducir.titulo);
printf("Autor:\n");
fflush(stdin);
gets(introducir.autor);
printf("Editorial:\n");
fflush(stdin);
gets(introducir.editorial);
printf("Precio:\n");
fflush(stdin);
scanf("%f",&introducir.precio);
printf("Unidades:\n");
fflush(stdin);
scanf("%hd",&introducir.unidades);
fwrite(&introducir, sizeof(struct libros), 1, fich);
printf("\n%s %s - %s ",introducir.codigo_libro,introducir.titulo,introducir.autor);
printf("- %s - %.2f - %hd\n",introducir.editorial,introducir.precio,introducir.unidades);
}
if(fclose(fich)){
printf("\nERRO! O ficheiro non puido ser cerrado\n");
system("pause");
return;
}
band=0;
}
////////////////////////////////////BAIXAS/////////////////////////////////////////////////////////////////////
void baixas(){
FILE *fich;
fich=fopen("libros.dat","rb+");
struct libros quitar;
char cod[5], borrar[]={0};
int band=0;
int i;
//comproba si o libro existe
printf("\nIntroduce o codigo do libro que queres consultar:\n");
scanf("%s",&cod);
rewind(fich);
for(i=0;!feof(fich);i++){
fread(&quitar, sizeof(struct libros), 1,fich);
if(!feof(fich)){
if(strcmp(cod,quitar.codigo_libro)==0){
band=1;
break;
}
}
}
if(band==0){
printf("\nO libro non existe\n");
}
//eliminar o libro
if(band==1){
fseek(fich,-sizeof(quitar),SEEK_CUR);
strcpy(quitar.codigo_libro, borrar);
fwrite(&quitar, sizeof(quitar.codigo_libro), 1, fich);
printf("Libro borrado\n");
}
if(fclose(fich)){
printf("ERRO! O ficheiro non puido ser cerrado\n");
system("pause");
return;
}
}
////////////////////////////////////MODIFICACIONS////////////////////////////////////////////////////////////////
void modificacions(){
FILE *fich;
struct libros modificar;
int i;
int band=0;
fpos_t posicion;
char cod[5];
fich=fopen("libros.dat","rb+");
//comproba si o libro existe
printf("\nIntroduce o codigo do libro que queres consultar:\n");
scanf("%s",&cod);
rewind(fich);
for(i=0;!feof(fich);i++){
fread(&modificar, sizeof(struct libros), 1,fich);
if(!feof(fich)){
if(strcmp(cod,modificar.codigo_libro)==0){
band=1;
break;
}
}
}
if(band==0){
printf("\nO libro non existe\n");
}
//modificar os datos do libro
if(band==1){
fseek(fich,-sizeof(modificar),SEEK_CUR);
printf("\nIntroducir titulo, autor, editorial, precio e unidades\n");
printf("Titulo:\n");
fflush(stdin);
gets(modificar.titulo);
printf("Autor:\n");
fflush(stdin);
gets(modificar.autor);
printf("Editorial:\n");
fflush(stdin);
gets(modificar.editorial);
printf("Precio:\n");
fflush(stdin);
scanf("%f",&modificar.precio);
printf("Unidades:\n");
fflush(stdin);
scanf("%hd",&modificar.unidades);
fseek(fich,-sizeof(modificar),SEEK_CUR);
fwrite(&modificar, sizeof(struct libros), 1, fich);
}
if(fclose(fich)){
printf("ERRO! O ficheiro non puido ser cerrado\n");
system("pause");
return;
}
}
/////////////////////////////////////CONSULTAS/////////////////////////////////////////////////////////////////
void consultas(){
FILE *fich;
fich=fopen("libros.dat","rb");
char cod[5];
int i;
int band=0;
if(!fich){
printf("ERRO! o ficheiro non se puido abrir\n");
system("pause");
return;
}
struct libros consultar={0};
printf("\nIntroduce o codigo do libro que queres consultar:\n");
scanf("%s",&cod);
for(i=0;!feof(fich);i++){
fread(&consultar, sizeof(struct libros), 1,fich);
if(!feof(fich)){
if(strcmp(cod,consultar.codigo_libro)==0){
printf("\n%s %s - %s ",consultar.codigo_libro,consultar.titulo,consultar.autor);
printf("- %s - %.2f - %hd\n",consultar.editorial,consultar.precio,consultar.unidades);
band=1;
break;
}
}
}
if(band!=1){
printf("O libro non existe, ou introduciches un codigo erroneo. Comproba si o codigo \202 correcto\n");
}
band=0;
if(fclose(fich)){
printf("ERRO! O ficheiro non puido ser cerrado\n");
system("pause");
return;
}
}
|
C
|
/*
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void print_my_port_num(int sock);
int main(){
int sock0;
struct sockaddr_in client;
socklen_t len;
int sock;
struct addrinfo hints, *res;
int err;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_STREAM;
err = getaddrinfo(NULL, "12345", &hints, &res);
if (err != 0) {
printf("getaddrinfo : %s\n", gai_strerror(err));
return 1;
}
/*
ソケットの作成
*/
sock0 = socket(res->ai_family, res->ai_socktype, 0);
if (sock0 < 0) {
perror("socket");
return 1;
}
if (bind(sock0, res->ai_addr, res->ai_addrlen) != 0) {
perror("bind");
return 1;
}
/*
addrinfo構造体を解放
*/
freeaddrinfo(res);
/*
TCPクライアントから接続要求を待つ
*/
if (listen(sock0, 5) != 0) {
perror("listen");
return 1;
}
print_my_port_num(sock0);
/*
TCPクライアントからの接続要求を受け付ける
*/
len = sizeof(client);
sock = accept(sock0, (struct sockaddr *)&client, &len);
/*
5文字送信
*/
char write_str[] = "HOGE\n";
int write_str_len = strlen(write_str);
write(sock, write_str, write_str_len);
/*
TCPセッションの終了
*/
close(sock);
/*
listenするsocketの終了
*/
close(sock0);
return 0;
}
/*
ポート番号とbindされたアドレスを表示する関数
*/
void print_my_port_num(int sock){
char buf[48];
struct sockaddr_in s;
socklen_t sz;
sz = sizeof(s);
/*
ソケットの「名前」を取得
*/
if (getsockname(sock, (struct sockaddr *)&s, &sz) != 0) {
perror("getsockname");
return;
}
/*
bindされているIPアドレスを文字列へ変換
*/
inet_ntop(AF_INET, &s.sin_addr, buf, sizeof(buf));
/*
結果を表示
*/
printf("%s : %d\n", buf, ntohs(s.sin_port));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct process //Structure of a process
{
int pt; //Process Number
int at; //Arrival Time
int bt; //Burst Time
int wt; //Waiting Time
int tt; //Turn Around Time
int rt; //Remaining Time
int ct; //Completion Time
int completed; //Completed or not
int prior; //Priority of process
}pro;
int n; //Number of processes
int q[100]; //Queue
int front=-1,rear=-1; //Front and rear of queue
void enqueue(int i) //Function to enqueue process in queue
{
//if(rear==100)
//printf("overflow");
rear++;
q[rear]=i;
if(front==-1)
front=0;
}
int dequeue() //Function to dequeue process from queue
{
//if(front==-1)
//printf("underflow");
int temp=q[front];
if(front==rear)
{front=-1;rear=-1;}
else
front++;
return temp;
}
int isInQueue(int i) //Function to check if process is in queue
{
int k;
for(k=front;k<=rear;k++)
{
if(q[k]==i)
return 1;
}
return 0;
}
void sortByArrival(struct process *p) //Sorting by arrival time
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
int main()
{
int i,j,time=0;
int sum_bt=0; //Total burst time
int tq,count; //Time Quantun
struct process *p;
float avgwt=0; //Average Waiting Time
float atat = 0; //Average TurnAround Time
scanf("%d%d",&n,&tq); //Enter total Number of processes
count=n;
p = malloc(n*sizeof(pro));
for(i=0;i<n;i++) //Enter the details of project
{
scanf("%d%d%d%d",&p[i].pt,&p[i].at,&p[i].bt,&p[i].prior);
p[i].rt=p[i].bt; //Remaining Time of process
p[i].completed=0;
sum_bt+=p[i].bt;
}
sortByArrival(p);
enqueue(0);
for(time=p[0].at; count>0;)
{
// printf("count value %d front value %d\n",count,front);
if(count>0 && front==-1)
{
time++;
sum_bt++;
for(j=0;j<n;j++)
{
if(p[j].at<=time && p[j].completed!=1 && isInQueue(j)!=1)
{
enqueue(j);
}
}
}
else
{
i=dequeue();
if(p[i].rt<=tq)
{
time+=p[i].rt;
p[i].rt=0;
p[i].completed=1;
count--;
time+=p[i].rt;
p[i].wt=time-p[i].at-p[i].bt;
p[i].tt=time-p[i].at;
p[i].ct = time;
for(j=0;j<n;j++)
{
if(p[j].at<=time && p[j].completed!=1&& isInQueue(j)!=1)
{
enqueue(j);
}
}
}
else
{
time+=tq;
p[i].rt-=tq;
for(j=0;j<n;j++)
{
if(p[j].at<=time && p[j].completed!=1&&i!=j&& isInQueue(j)!=1)
{
enqueue(j);
}
}
enqueue(i);
}
}
}
for(i=0;i<n;i++)
{
atat+=p[i].tt;
avgwt+=p[i].wt;
printf("%d %d %d %d\n",p[i].pt,p[i].ct,p[i].tt,p[i].wt); //Process name,Completion Time,TurnAround Time,Waiting Time
}
printf("Average TT: %f\n",atat/n); //Average Turn Around Time
printf("Average WT: %f\n",avgwt/n); //Average Waiting time
return 0;
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>// bool,
struct Tree
{
struct Tree *Right;
struct Tree *Left;
double Data;
};
void init(struct Tree **t)// ,
{
*t = (struct Tree *)malloc(sizeof(struct Tree));
(*t)->Right = NULL;
(*t)->Left = NULL;
(*t)->Data = 2147483648;// 1 ,
}
void clean(struct Tree *t)
{
if (t != NULL)//
{
if (t->Right != NULL)
clean(t->Right);
if (t->Left != NULL)
clean(t->Left);
free(t);
}
}
struct Tree* find(struct Tree *t, int value)
{
if (t->Data==value)
return t;
else
{
if (value < t->Data)
{
if (t->Left != NULL)
return(find(t->Left, value));
else
return NULL;
}
else
{
if (t->Right != NULL)
return(find(t->Right, value));
else
return NULL;
}
}
}
int find_with_output(struct Tree *t, int value)
{
if (t->Data == value)
{
printf("_ ");//
if (t->Left != NULL)
printf("%d ", (int)t->Left->Data);
else
printf("_ ");
if (t->Right != NULL)
printf("%d", (int)t->Right->Data);
else
printf("_");
}
else
{
if (value < t->Data)
{
if (t->Left != NULL)
{
if (t->Left->Data == value)
{
printf("%d ", (int)t->Data);
if ((t->Left->Left) != NULL)
printf("%d ", (int)t->Left->Left->Data);
else
printf("_ ");
if ((t->Left->Right) != NULL)
printf("%d", (int)t->Left->Right->Data);
else
printf("_");
}
else
return(find_with_output(t->Left, value));
}
else
return 1;
}
else
{
if (t->Right != NULL)
{
if (t->Right->Data == value)
{
printf("%d ", (int)t->Data);
if ((t->Right->Left) != NULL)
printf("%d ", (int)t->Right->Left->Data);
else
printf("_ ");
if ((t->Right->Right) != NULL)
printf("%d", (int)t->Right->Right->Data);
else
printf("_");
}
else
return(find_with_output(t->Right, value));
}
else
return 1;
}
}
return 0;
}
int insert(struct Tree *t, int value)
{
if (t->Data == 2147483648)// --
{
t->Data = value;
return 0;
}
if (t->Data == value)//
return 1;
if (value > (t->Data))//
{
if ((t->Right)!=NULL)// ,
return(insert(t->Right, value));
else// ,
{
t->Right=(struct Tree *)malloc(sizeof(struct Tree));
t->Right->Right = NULL;
t->Right->Left = NULL;
t->Right->Data = value;
return 0;
}
}
else//
{
if ((t->Left) != NULL)
return(insert(t->Left, value));
else
{
t->Left = (struct Tree *)malloc(sizeof(struct Tree));
t->Left->Right = NULL;
t->Left->Left = NULL;
t->Left->Data = value;
return 0;
}
}
}
int deep(struct Tree *t)
{
int r=0, l=0;
if ((t->Right) != NULL)
r=deep(t->Right);
if ((t->Left) != NULL)
l = deep(t->Left);
if (r > l)// ,
return (r+1);
return (l+1);
}
int remove_node(struct Tree **t, int value)
{
if ((*t)->Data == value)//
{// , ,
if ((*t)->Right != NULL)// -
{
struct Tree *Temp = (*t)->Right, *Temp2;// .
if (Temp->Left != NULL)//
{
while (Temp->Left->Left != NULL)//
Temp = Temp->Left;
(*t)->Data = Temp->Left->Data;//, , ,
Temp2=Temp->Left;//
Temp->Left=Temp2->Right;//
free(Temp2);//
}
else// ,
{
struct Tree *Temp;
(*t)->Data = (*t)->Right->Data;//
Temp = (*t)->Right;//,
(*t)->Right = (*t)->Right->Right;//
free(Temp);
}
}
else// ,
{
struct Tree *Temp;
Temp = (*t);
(*t) = (*t)->Left;// --
free(Temp);//
Temp = NULL;
}
return 0;
}
else//
{
if (value < ((*t)->Data))
{
if ((*t)->Left != NULL)
return(remove_node(&((*t)->Left), value));
else
return 1;
}
else
{
if (((*t)->Right) != NULL)
return(remove_node(&((*t)->Right), value));
else
return 1;
}
}
}
int remove_min(struct Tree *t)
{
struct Tree *Temp = t, *Temp2;// .
if (Temp->Left != NULL)//
{
while (Temp->Left->Left != NULL)//
Temp = Temp->Left;
Temp2 = Temp->Left;//
Temp->Left = Temp2->Right;//
free(Temp2);//
}
else// ,
{
Temp = t->Right;
free(t);
t = Temp;
}
return 0;
}
int rotate_right(struct Tree **t)//
{
if (*t == NULL)
return 1;
struct Tree *A, *B, *C=(*t)->Right, *x=(*t)->Left, *y=(*t), *Temp = (struct Tree *)malloc(sizeof(struct Tree));
if (x != NULL)
{
A = x->Left;
B = x->Right;
}
else
return 1;//
Temp->Right = y;// NULL,
Temp->Left = A;
Temp->Right->Right = C;
Temp->Right->Left = B;
Temp->Data = x->Data;
free(x);
(*t) = Temp;
return 0;
}
int rotate_left(struct Tree **t)//
{
if (*t == NULL)
return 1;
struct Tree *A = (*t)->Left, *B, *C, *x = (*t), *y = (*t)->Right, *Temp=(struct Tree *)malloc(sizeof(struct Tree));
if (y != NULL)
{
B = y->Left;
C = y->Right;
}
else
return 1;//
Temp->Right = C;
Temp->Left = x;
Temp->Left->Right = B;
Temp->Left->Left = A;
Temp->Data = y->Data;
free(y);
(*t) = Temp;
return 0;
}
int print_tree(struct Tree *t)// ?
{
if (t == NULL)
{
printf("-\n");
return 1;
}
struct Tree *Temp=t;
int Rang=0, i, j, k, sk;//k-- , i-- , j--
int *comb;
Rang = deep(t);
comb = (int*)malloc(sizeof(int));//
for (i = 0; i < Rang; i++)//
{
if (i != 0)
{
comb = (int*)realloc(comb, i* sizeof(int));//
for (j = 0; j < i; j++)
comb[j] = 0;//
}
//
j = 1;
sk = i;
while (sk != 0)
{
j = j * 2;
sk--;
}
//
while (j != 0)
{
k = 0;
Temp = t;
for (k = 0; k < i; k++)//
{
if (comb[k] == 0)
{
if ((Temp->Left) != NULL)
Temp = Temp->Left;
else
{
k = -1;//
break;
}
}
else
{
if ((Temp->Right) != NULL)
Temp = Temp->Right;
else
{
k = -1;//
break;
}
}
}
if (i != 0)
{
sk=i-1;
comb[sk]++;//
while (1)
{
if (comb[sk] == 2)
{
comb[sk] = 0;
sk--;
if (sk < 0)
break;// ,
else
comb[sk]++;
}
else
break;// , ,
}
}
if (k==-1)//
printf("_");
else
printf("%d", (int)Temp->Data);
j--;
if (j != 0)
printf(" ");
}
printf("\n");
}
return 1;
}
int all(struct Tree *t)
{
if (t == NULL)
return 0;
int r, l;
l = all(t->Left);
r = all(t->Right);
return (l + r+1);
}
int main()
{
struct Tree *t;
int i;
double a;
init(&t);//1 ,
for (i = 0; i < 4; i++)
{
scanf("%lf", &a);
insert(t, a);
}
print_tree(t);//2 ,
printf("\n");
for (i = 0; i < 3; i++)//3
{
scanf("%lf", &a);
insert(t, a);
}
print_tree(t);//4 ,
printf("\n");
for (i = 0; i < 2; i++)
{
scanf("%lf", &a);//5 6
a = find_with_output(t, a);
if (a == 1)
printf("-");
printf("\n\n");
}
scanf("%lf", &a);// 7
remove_node(&t, a);
print_tree(t);//8
printf("\n");
while (1)//9
{
a=rotate_left(&t);
if (a == 1)
break;
}
print_tree(t);//10
printf("\n");
while (1)//11
{
a = rotate_right(&t);
if (a == 1)
break;
}
print_tree(t);//12
printf("\n");
printf("%d\n\n", all(t));//13
clean(t);//14
t = NULL;
print_tree(t);//15
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,i,j,k;
printf("Enter no. of rows:- ");
scanf("%d", &n);
printf("\nPattern is :- \n");
for(i=1;i<=n;i++) //for rows
{
for(j=1; j<=(n-i);j++) //for space
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char ss[20],su[5];
char *s,*sub;
int l=0;
printf("enter the value of string\n");
gets(ss);
//scanf("%s",ss);
printf("enter the value of substring character\n");
gets(su);
//scanf("%s",su);
s=ss;
sub=su;
l=strlen(s);
if(l==strspn(s,sub))
printf("both strings are anagram to each other");
else
printf("strings are not anagram..");
getch();
}
|
C
|
#include "hash_tables.h"
/**
* hash_table_set - function that adds an element to the hash table.
* @ht: is the hash table to add or update the key/value
* @key: is the key. key can not be an empty string.
* @value: is the value associated with the key. value must be duplicated.
* value can be an empty string
* Return: 1 if it succeeded, 0 otherwise
*/
int hash_table_set(hash_table_t *ht, const char *key, const char *value)
{
char *new_value = NULL;
unsigned long int index = 0;
hash_node_t *node = NULL, *colision = NULL;
/*validations to table*/
if (!ht || !ht->array || ht->size == 0)
return (0);
/*validations to key an value*/
if (!key || (strcmp(key, "") == 0) || !value)
return (0);
/*search the index*/
index = key_index((const unsigned char *)key, ht->size);
/*compare key if colision*/
colision = ht->array[index];
while (colision)
{
if (strcmp(colision->key, key) == 0)
{
new_value = strdup(value);
if (!new_value)
return (0);
free(colision->value);
colision->value = new_value;
return (1);
}
colision = colision->next;
}
/*not found key then insert node*/
node = insert_node(ht, key, value, index);
if (!node)
return (0);
return (1);
}
/**
* insert_node - insert node at the start
* @ht: is the hash table to add or update the key/value
* @key: is the key. key can not be an empty string.
* @value: is the value associated with the key. value must be duplicated.
* value can be an empty string
* @index: index of array to insert node
* Return: 1 if it succeeded, 0 otherwise
*/
hash_node_t *insert_node(hash_table_t *ht, const char *key, const char *value,
unsigned long int index)
{
hash_node_t *node = NULL;
node = malloc(sizeof(hash_node_t));
if (!node)
return (NULL);
/*inicialize the node*/
node->next = NULL;
node->key = strdup(key);
if (!node->key)
{
free(node);
return (NULL);
}
node->value = strdup(value);
if (!node->value)
{
free(node->key);
free(node);
return (NULL);
}
/*insert the node*/
if (ht->array[index] == NULL)
ht->array[index] = node;
else
{
node->next = ht->array[index];
ht->array[index] = node;
}
return (node);
}
|
C
|
/*
* type.h
* Date : 11-14-2014
* Author : HouBiao,WangHanCheng
*/
#ifndef TYPE_H_
#define TYPE_H_
typedef double FLOAT; //
// ṹ
typedef struct
{
FLOAT real; // ʵ
FLOAT imag; // 鲿
}complex;
// ٽλ
typedef struct
{
FLOAT phsE; // E֧·λ
FLOAT phsP; // P֧·λ
FLOAT phsL; // L֧·λ
}EPLPhs;
// NCO
typedef struct
{
FLOAT fo; // Ƶ
FLOAT fcw; // Ƶʿ
FLOAT phs; // λ
}NCO;
// NCO
typedef struct
{
FLOAT fo; // Ƶ
FLOAT fcw; // Ƶʿ
EPLPhs phs; // ٽλ
}TrkNCO;
// ˲ϵ
typedef struct
{
FLOAT dll_a; // DLL˲ϵA
FLOAT dll_b; // DLL˲ϵB
FLOAT dll_reg; // DLL˲Ĵ
FLOAT dll_gain; // DLL˲
FLOAT fll_a; // FLL˲ϵA
FLOAT fll_b; // FLL˲ϵB
FLOAT pll_a; // PLL˲ϵA
FLOAT pll_b; // PLL˲ϵB
FLOAT pll_c; // PLL˲ϵC
FLOAT pll_reg0; // PLL˲Ĵ0
FLOAT pll_reg1; // PLL˲Ĵ1
FLOAT pll_gain; // PLL˲
FLOAT fll_gain; // FLL˲
}LPF;
#endif
|
C
|
#include <stdio.h>
int num = 5;
int static num2 = 0;
void incrPtint(void);
void incrPrint(void) {
int num = 1;
num++;
printf("incrPrint(): num --> %d \n", num); //Լ .
}
int main(void) {
num = 10;
printf("num: %d \n", num);
incrPrint();
incrPrint();
incrPrint();
printf("num: %d \n", num);
return 0;
}
|
C
|
#include "camera.h"
#include "ray.h"
#include "hit.h"
#include "material.h"
#include "vectors.h"
OrthographicCamera::OrthographicCamera(Vec3f cp,Vec3f dir, Vec3f u, float size)
{
center_point = cp;
direction = dir;
direction.Normalize();
Vec3f temp = u;
up = u-temp*u.Dot3(direction);
Vec3f::Cross3(horizontal,direction,up);
image_size = size;
}
Ray OrthographicCamera::generateRay(Vec2f point)
{
return Ray(center_point+(point[0]-0.5)*horizontal*image_size+(point[1]-0.5)*up*image_size,direction);
}
float OrthographicCamera::getTMin() const
{
return FLT_MIN;
}
PerspectiveCamera::PerspectiveCamera(Vec3f &c, Vec3f &dir, Vec3f &u, float a)
{
center_point = c;
direction = dir;
direction.Normalize();
Vec3f temp = u;
up = u-temp*u.Dot3(direction);
Vec3f::Cross3(horizontal,direction,up);
angle = a;
virtual_location = 10;
image_size = 2*virtual_location*tan(angle/2);
}
Ray PerspectiveCamera::generateRay(Vec2f point)
{
Vec3f dir = (direction*virtual_location+(point[0]-0.5)*horizontal*image_size+(point[1]-0.5)*up*image_size);
dir.Normalize();
return Ray(center_point,dir);
}
float PerspectiveCamera::getTMin() const
{
return 0;
}
|
C
|
#include "bar.h"
Bar newBar(Point center, Texture texture, int id){
Bar b;
b.id = id;
b.center = center;
b.width = WINDOW_WIDTH/10;
b.height = 12;
b.speed = 0;
b.texture = texture;
return b;
}
void barDraw(Bar *bar){
float w = bar->width/2;
float h = bar->height/2;
float x = bar->center.x;
float y = bar->center.y;
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, bar->texture.memory);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(x-w, y+h);
glTexCoord2f(1, 0); glVertex2f(x+w, y+h);
glTexCoord2f(1, 1); glVertex2f(x+w, y-h);
glTexCoord2f(0, 1); glVertex2f(x-w, y-h);
glEnd();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
void barRun(Bar *bar){
bar->center.x += bar->speed;
if(bar->center.x - bar->width/2 < -WINDOW_WIDTH/2){
bar->center.x = -WINDOW_WIDTH/2 + bar->width/2;
}
if(bar->center.x + bar->width/2 > WINDOW_WIDTH/2){
bar->center.x = WINDOW_WIDTH/2 - bar->width/2;
}
}
void changeBarSpeed(Bar *bar, int control, int type){
switch(type){
case SPEED_UP:
switch(control){
case CONTROL_LEFT:
bar->speed -= 10;
break;
case CONTROL_RIGHT:
bar->speed += 10;
break;
case CONTROL_START:
break;
default:
break;
}
break;
case SPEED_STOP:
bar->speed = 0;
break;
default:
break;
}
}
void changeBarSize(Bar *bar, int type){
switch(type){
case BAR_BIGGER:
bar->width *= 2;
break;
case BAR_SMALLER:
bar->width *= 0.5;
break;
default:
break;
}
}
void changeBarDistance(Bar *bar, int type){
int dir = (bar->id%2 == 0) ? 1 : -1;
switch(type){
case BAR_CLOSER:
bar->center.y += 100 * dir;
break;
case BAR_FURTHER:
bar->center.y -= 100 * dir;
break;
}
}
void barRender(Bar *bar){
barRun(bar);
barDraw(bar);
}
|
C
|
#include "header.h"
int main(){
int n, i, j;
printf("masukkan jumlah angka: ");
scanf("%d", &n);
char str[n][100];
for(i=0; i<n; i++){
scanf(" %s", &str[i]);
}
int hitungan = 0;
for(i=0; i<jumVo(n, str); i++){
hitungan++;
for(j=0; j<n; j++){
if(j==0){
printf("%d", hitungan);
}
printf("%s ", str[j]);
}
printf("\n");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: acolin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/23 16:22:04 by acolin #+# #+# */
/* Updated: 2021/09/28 22:36:16 by acolin ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <libgen.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putstr(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
ft_putchar(str[i]);
i++;
}
}
int ft_puterror(char *name, char *namefile, char *error)
{
ft_putstr(name);
ft_putchar(':');
ft_putchar(' ');
ft_putstr(namefile);
ft_putchar(':');
ft_putchar(' ');
ft_putstr(error);
return (0);
}
int ft_read(int file_d, char *buffer, char *exec, char *filename)
{
int reader;
reader = read(file_d, buffer, 1);
if (reader < 0)
{
ft_puterror(exec, filename, strerror(errno));
return (0);
}
while (reader != 0)
{
ft_putchar(buffer[0]);
reader = read(file_d, buffer, 1);
}
return (1);
}
int main(int argc, char *argv[])
{
int file_d;
char buffer[1];
char buffer_ult[30000];
int i;
file_d = 0;
i = 1;
if (argc == 1)
{
while(1)
{
read(0, buffer_ult, 30000);
ft_putstr(buffer_ult);
}
}
else
{
while (i < argc)
{
file_d = open(argv[i], O_RDONLY);
if (file_d < 0)
{
ft_puterror(basename(argv[0]), argv[i], strerror(errno));
ft_putchar('\n');
}
else
{
ft_read(file_d, buffer, basename(argv[0]), argv[i]);
close(file_d);
ft_putchar('\n');
}
i++;
}
}
}
|
C
|
/*
* Slist.c
*
* Created on: Sep 18, 2014
* Author: nvthanh
*/
#include <stdio.h>
#include <stdbool.h>
#include "Slist.h"
slist * slist_append(slist * list, void * data)
{
slist * walk=list;
slist * add_item= (slist*)malloc(sizeof(slist));
if(!add_item)
{
perror("Out of memory !!!\n");
return list;
}
add_item->data = data;
add_item->next=NULL;
do{
if(walk){
if(walk->next == NULL){
walk->next=add_item;
break;
}
}else{
return add_item;
}
walk=walk->next;
}while(walk);
return list;
}
slist * slist_remove_by_data(slist * list, void * data)
{
return slist_remove_by_data_x(list,data,NULL);
}
slist * slist_remove_by_data_x(slist * list, void * data, void (* release_data) (void * data))
{
if(!list) return NULL;
slist * walk=list, *tmp=list, *out_list=list;
while(walk){
if(walk->data == data){
if(tmp==walk){ //first item
// printf("Found ========= \n");
if(release_data){
release_data(walk->data);
}
out_list = walk->next;
tmp=walk;
walk=walk->next;
free(tmp);
tmp=walk;
continue;
}else{ //not first item
if(release_data){
release_data(walk->data);
}
tmp->next = walk->next;
free(walk);
walk=tmp->next;
continue;
}
}else{
tmp=walk;
walk=walk->next;
}
}
return out_list;
}
slist * slist_remove_by_index(slist * list, int index)
{
//index begin by 0
return slist_remove_by_index_x(list,index, NULL);
}
slist * slist_remove_by_index_x(slist * list, int index, void (* release_data) (void * data))
{
if(!list) return NULL;
//index begin by 0
slist * walk=list,*tmp=list, *out_list = list;
int i=0;
while(i<index){
if(walk && walk->next){
tmp=walk;
walk=walk->next;
}else{
return out_list;
}
i++;
}
if(index == 0 ) { //first
out_list = walk->next;
if(release_data) {
release_data(walk->data);
}
free(walk);
}else if(i==index ){ //normal and not first
tmp->next = walk->next;
if(release_data) {
release_data(walk->data);
}
free(walk);
}
return out_list;
}
slist * slist_delete_all(slist * list)
{
return slist_delete_all_x(list,NULL);
}
slist * slist_delete_all_x(slist * list, void (*release_data)(void *data))
{
if(!list) return NULL;
//index begin by 0
slist * walk=list;
while(walk){
list=walk;
walk=walk->next;
if(release_data) release_data(list->data);
free(list);
}
return NULL;
}
slist * slist_concat(slist * list, slist * added_list)
{
if(!list && !added_list ) return NULL;
slist * walk=list;
while(walk){
if(! walk->next) break;
walk=walk->next;
}
if(walk){
walk->next=added_list;
}else{
return added_list;
}
return list;
}
slist * slist_insert(slist * list,void * data,void * data_cond, bool (*condition)(void * data1,void * data2))
{
if(!list || !condition) return list;
slist * walk=list;
while(walk){
if(condition(walk->data,data_cond)==true){
slist * inst= (slist*)malloc(sizeof(slist));
if(!inst){
perror("Out of memory !!!\n");
return list;
}
inst->data=data;
inst->next=walk->next;
walk->next=inst;
return list;
}
walk=walk->next;
}
return list;
}
slist * slist_sort(slist * list, bool (*compare_func)(void * data1, void * data2) )
{
if(!list || !compare_func) return list;
slist *walk=list, * tmp=list;
void * tmp_data;
while(tmp){
walk=tmp->next;
while(walk){
if(compare_func(tmp->data,walk->data) == true){
tmp_data = tmp->data;
tmp->data = walk->data;
walk->data=tmp_data;
}
walk=walk->next;
}
tmp=tmp->next;
}
return list;
}
slist * slist_find(slist * list, void * data, bool (*compare_func)(void * data1, void * data2))
{
if(!list || !compare_func) return list;
slist *walk=list;
while(walk){
if(compare_func(data,walk->data) != false) return walk;
walk=walk->next;
}
return NULL;
}
size_t slist_size(slist * list)
{
if(!list) return 0;
slist *walk=list;
size_t sz=0;
while(walk)
{
sz++;
walk=walk->next;
}
return sz;
}
inline void slist_trace(slist *list, void * data, void (* trace_func)(int index, void * data,void * itemData))
{
slist_work(list,data,trace_func);
}
void slist_work(slist *list, void * data,void (* work_func)(int index,void * data,void * itemData))
{
if(!work_func || !list) return;
volatile int i=0;
while(list){
work_func(i++,data,list->data);
list=list->next;
}
}
//ninhld add
slist* slist_prepend(slist *list, void* data)
{
slist *new_list;
new_list = (slist*) malloc (sizeof (slist));
new_list->data = data;
new_list->next = list;
return new_list;
}
slist* slist_nth(slist *list, int n)
{
while (n-- > 0 && list)
list = list->next;
return list;
}
void * slist_nth_data(slist *list, int n)
{
while (n-- > 0 && list)
list = list->next;
return list ? list->data : NULL;
}
int slist_index(slist *list, void *data)
{
int i;
i = 0;
while (list)
{
if (list->data == data)
return i;
i++;
list = list->next;
}
return -1;
}
slist* slist_last(slist *list)
{
if (list)
{
while (list->next)
list = list->next;
}
return list;
}
slist* slist_insert_index (slist *list, void *data, int position)
{
slist *prev_list = NULL;
slist *tmp_list = NULL;
slist *new_list = NULL;
if (position < 0)
return slist_append (list, data);
else if (position == 0)
return slist_prepend (list, data);
new_list = (slist *)malloc(sizeof(slist));
if(!new_list)
{
perror("Out of memory !!!\n");
return list;
}
new_list->data = data;
if (!list)
{
new_list->next = NULL;
return new_list;
}
//prev_list = NULL;
tmp_list = list;
while ((position-- > 0) && tmp_list)
{
prev_list = tmp_list;
tmp_list = tmp_list->next;
}
if (prev_list)
{
new_list->next = prev_list->next;
prev_list->next = new_list;
}
else
{
new_list->next = list;
list = new_list;
}
return list;
}
|
C
|
#include <stdio.h>
int main(void){
long l;
long double d;
int i,k,n;
scanf("%d",&n);
for (k=1;k<=n;k++){
d=1;
l=1;
for (i=1;i<=k;i++){
d*=i;
l*=i;
}
printf("long :%d!=%ld\n",k,l);
printf("double:%d!=%Lf\n\n",k,d);
}
return 0;
}
|
C
|
#include<stdio.h>
int main(void)
{
int a, b, v;
char s;
printf("Number 1: ");
scanf("%d", &a);
printf("Number 2: ");
scanf("%d", &b);
s = '+';
v = a+b;
printf("\n%d%c%d = %d\n", a, s, b, v);
s = '-';
v = a-b;
printf("\n%d%c%d = %d\n", a, s, b, v);
s = '*';
v = a*b;
printf("\n%d%c%d = %d\n", a, s, b, v);
s = '/';
v = a/b;
printf("\n%d%c%d = %d\n", a, s, b, v);
return 0;
}
|
C
|
#include <stdio.h>
#define func(...) myfunc((struct mystru){__VA_ARGS__})
struct mystru { const char* name;int number; };
void myfunc(struct mystru ms){
printf("%s:%d\n",ms.name?:"untitled",ms.number);
}
int main(int argc,char **argv){
func("three",3);
func(.number=100);
func(.name="zero");
return 0;
}
|
C
|
#define NDEBUG
#include<iostream>
#include<cstdlib>
#include"./Containers.H"
#include"bits/ExplSumTreeTable.H"
#include"bits/WeightSumTable.H"
#include<cassert>
#include<ctime>
#define NUM_PASSES 1
#define DEF_LOG_HASH_SIZE 24 /* 16M */
using namespace std;
struct MyPolicy:public SetContainerPolicy<size_t> {
static const size_t MagicEmptyKey=UINT_MAX;
};
struct MyParams:public DefaultContainerParams {
typedef void StatusPolicy;
//typedef SmallHashController<80, 30, Pow2DivHashController<> > HashController;
};
int main(int argc, char* argv[]) {
unsigned hashSize;
unsigned numRands;
unsigned mask;
if (argc < 2) {
hashSize=1 << DEF_LOG_HASH_SIZE;
std::cerr << "Using default hash size:" << hashSize << "\n";
} else {
hashSize= 1 << atoi(argv[1]);
std::cerr << "Size read:" << hashSize << "\n";
}
numRands=2*hashSize;
mask=numRands-1;
cerr << "In main\n";
size_t * randvals=new size_t[numRands];
size_t * randweights=new size_t[numRands];
cerr << "Entering constructor!\n";
//Set<size_t, LinearHash, ValueTable, MyPolicy, MyParams> hash;
//Set<size_t> hash;
Map<size_t, size_t, LinearHash, ExplSumTreeTable, MyPolicy, MyParams> hash;
//AutoMap<size_t, bool, LinearHash, ValueTable, MyPolicy, MyParams> hash;
//AutoMap<size_t, int, LinearHash, ValueTable, MyPolicy, MyParams> hash;
cerr << "Construction done! Filling with rands:\n";
/* First fill...*/
{
Set<size_t> tempHash;
for (size_t i=0; i < numRands; ++i) {
assert(tempHash.size()==i);
do {
randvals[i]=rand();
} while (tempHash.put(randvals[i])); /* We do not accept duplicates. */
randweights[i]=rand();
}
assert(tempHash.size()==numRands);
assert(tempHash.isLegal());
std::cerr << "Hope we destroy...";
}
std::cerr << "...before this. Init fill...";
for (size_t i=0; i < hashSize; i++) {
assert(hash.size()==i);
hash[randvals[i]]=randweights[i];
}
assert(hash.size()==hashSize);
assert(hash.isLegal());
/* Status: no duplicates to be encountered in the standard loop.
* Hash filled with the vals in the head of the randvals[]. */
cerr << "...done. Begin holdttest\n";
clock_t cpustart=clock();
for (unsigned i=0; i<numRands*NUM_PASSES; ++i) {
assert(hash.contains(randvals[i & mask]));
assert(hash[randvals[i & mask]]==randweights[i & mask]);
assert(hash[randvals[i & mask]]==randweights[i & mask]);
//std::cerr << "#";
hash.remove(randvals[i & mask]);
//std::cerr << "!";
hash[randvals[(i+hashSize) & mask]]=randweights[(i+hashSize) & mask];
assert(hash.size()==hashSize);
/* Check the legality once per pass. */
assert(((i & mask) != 0)
|| (hash.isLegal()));
}
std::cerr << "\nHolds per sec:"
<< ((((float) (numRands))*NUM_PASSES*CLOCKS_PER_SEC)
/(clock()-cpustart))
<< "\n";
assert(hash.isLegal());
std::cerr << hash.elemSize() << "\n";
}
|
C
|
#include <stdio.h>
int main()
{
float length;
printf("Enter length in cm --> ");
scanf("%f", &length);
if (1)
{printf("\nLength in feet is %f feet", length/30.48);
printf("\nLength in inches is %f inches\n", length/12);}
}
|
C
|
/*
* arboles.C: Script de ROOT para mostrar el uso de árboles.
*
* Ejemplo para el curso introductorio de ROOT.
* Laboratorio Avanzado
*
* Héctor Pérez, mayo 2020.
*
*/
#include <iostream>
#include <string>
#include <vector>
#include "TTree.h"
#include "TFile.h"
#include "TCanvas.h"
#include "TH1D.h"
#include "TRandom3.h"
/* Función para crear, llenar y guardar un árbol en un archivo */
void WriteTree(const char* NombreDelArchivo)
{
/* Primero se crean dos variables tipo Double_t que serán
* guardadas como ramas en el árbol*/
Double_t Var_a;
Double_t Var_b;
/* Se abre un archivo donde se guardará el árbol */
TFile *aFile = new TFile(NombreDelArchivo,"recreate");
/* Se crea una instancia de un árbol*/
TTree *aTree = new TTree("Arb1","Arbol de ejemplo");
/* Se crean las ramas de árbol. El primer argumento es
* el nombre de la rama. Luego la dirección de memoria
* de la variable/estructura/objeto que se almacenará
* en la rama. Por último las hojas y el tipo de dato
* que almacenan en formato <nombre_de_hoja>/<tipo>.
* Cada hoja se separa por : */
aTree->Branch("Var_a_Branch",&Var_a,"Var_a/D");
aTree->Branch("Var_b_Branch",&Var_b,"Var_b/D");
/* Se llena el árbol con 1000 entradas aleatorias */
for(Int_t i = 0; i<1000; i++)
{
Var_a = gRandom->Gaus();
Var_b = gRandom->Gaus();
aTree->Fill();
}
/* Se escribe el árbol en el archivo */
aTree->Write();
/* Se cierra el archivo */
aFile->Close();
}
/* Esta función lee un árbol de un archivo y un histograma
* para cada rama del árbol */
void ReadTree(const char * NombreDelArchivo)
{
/* Primero se abre el archivo para lectura */
TFile *oFile = new TFile(NombreDelArchivo);
if(!oFile)
{
std::cout<<"No fue posible abrir el archivo "<< NombreDelArchivo << std::endl;
return;
}
/* Se crea un puntero de árbol para cargar los datos
* del archivo */
TTree *oTree;
/* Se busca el árbol en el archivo. Nótese que se debe
* saber el nombre del árbol que se desea cargar. */
oTree = (TTree*)oFile->Get("Arb1");
/* Para cargar los datos del árbol, se debe conocer la
* estructura con que este fue creado, ya que se deben
* extraer los datos de la misma forma. Se crean un
* par de variables Double_t donde se colocarán los datos .*/
Double_t Var_A;
Double_t Var_B;
/* Se asocian las direcciones de estas variables con las
* ramas. */
oTree->SetBranchAddress("Var_a_Branch",&Var_A);
oTree->SetBranchAddress("Var_b_Branch",&Var_B);
/* Se obtiene el número de entradas */
Long_t Entradas = (Long_t)oTree->GetEntries();
/* Se crean las instancias de los histogramas */
TH1D *Hist_A = new TH1D("Ha","Datos rama Var_a",100,0,0);
TH1D *Hist_B = new TH1D("Hb","Datos rama Var_b",100,0,0);
/* Se obtienen los datos */
for(Long_t i = 0; i<Entradas; i++)
{
oTree->GetEntry(i);
Hist_A->Fill(Var_A);
Hist_B->Fill(Var_B);
}
/* Se crea un canvas para mostrar las gráficas de la función y del
* histograma aleatorio. */
TCanvas *oCanvas = new TCanvas("C1","Ejemplos de ROOT",800,400);
/* Se crean 2 pads */
oCanvas->Divide(2);
/* Primer TPad */
oCanvas->cd(1);
Hist_A->Draw();
/* Segundo TPad */
oCanvas->cd(2);
Hist_B->Draw();
}
|
C
|
#include <stdio.h>
int main(void){
int n; // N Է ϴ
int i,j; // ݺ
int result=0; // Ҽ
int cnt = 0; //
scanf("%d", &n); // Է
for(i=2; i<n; i++){
cnt = 0; //
for(j=1; j<=i; j++){ // i j++
if ( i % j == 0){ // Ҽ (cnt) Ѱ
cnt ++;
}
}
if (cnt == 2){ // 2
result += 1; // ϳ Ų.
}
}
printf("%d", result); //
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mff.h>
int main(int argc,char **argv)
{
FILE *def,*tag;
char *temp = malloc(512);
smud_file *myfile;
char *buffer = malloc(1024);
char *work = malloc(16384);
short vnum;
int i;
if(argc<2)
{
printf(" Usage: %s <filename>\n",argv[0]);
exit(0);
}
sprintf(temp,"%s.def",argv[1]);
def = fopen(temp,"r");
if(!def)
{
printf("Cannot open source file %s.\n",temp);
exit(0);
}
sprintf(temp,"%s.tag",argv[1]);
tag = fopen(temp,"r");
if(!tag)
{
printf("Cannot open tag file %s.\n",temp);
exit(0);
}
myfile=new_file();
i=0;
while(fgets(buffer,1024,def))
{
*(buffer+strlen(buffer)-1)=0;
if(*buffer=='%')
{
if(i==0)
{
*(work+strlen(work)-1)=0;
*(work+strlen(work)-1)=0;
vnum=atoi(work);
} else {
if(fgets(temp,512,tag))
{
*(temp+strlen(temp)-1)=0;
*(work+strlen(work)-1)=0;
*(work+strlen(work)-1)=0;
add_entry(myfile,vnum,temp,work);
} else {
rewind(tag);
*(work+strlen(work)-1)=0;
*(work+strlen(work)-1)=0;
vnum=atoi(work);
i=0;
}
}
bzero(work,16384);
i++;
} else {
work=strcat(work,buffer);
work=strcat(work,"\\n");
}
}
sprintf(temp,"%s.mff",argv[1]);
write_file(myfile,temp);
fclose(def);
fclose(tag);
free(temp);
return 0;
}
|
C
|
#ifndef FECHA_H_INCLUDED
#define FECHA_H_INCLUDED
typedef struct
{
int dia;
int mes;
int anio;
} eFecha;
#endif // FECHA_H_INCLUDED
int obtenerFecha(int* diaAux, int * mesAux, int* anioAux);
/** \brief recibe las referencias a memoria de dia mes y ao y le pide al usuario valores validos para las mismas
*
* \param puntero a dia
* \param puntero a mes
* \param puntero a ao
* \return 1 si pudo obtener la fecha, -1 si no
*
*/
|
C
|
#ifndef DEVICES_DISK_H
#define DEVICES_DISK_H
#include <inttypes.h>
#include <stdint.h>
/* Size of a disk sector in bytes. */
#define DISK_SECTOR_SIZE 512
/* Index of a disk sector within a disk.
Good enough for disks up to 2 TB. */
typedef uint32_t disk_sector_t;
/* Format specifier for printf(), e.g.:
printf ("sector=%"PRDSNu"\n", sector); */
#define PRDSNu PRIu32
void disk_init (void);
void disk_print_stats (void);
struct disk *disk_get (int chan_no, int dev_no);
disk_sector_t disk_size (struct disk *);
void disk_read (struct disk *, disk_sector_t, void *);
void disk_write (struct disk *, disk_sector_t, const void *);
#endif /* devices/disk.h */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "points.h"
#include "triangle.h"
int main()
{
printf("Hello world!\n");
Point *p1=createPoint(0,0);
Point *p2=createPoint(8,0);
Point *p3=createPoint(0,6);
Triangle *tr=createTriangleByPoints(p1,p2,p3);
printTriangle(tr);
printf("sguare of triangle %f\n",SquareOfTriangle(tr));
printf("perimetr of triangle %f\n",PerimetrOfTriangle(tr));
deletePoint(p1);
deletePoint(p1);
deletePoint(p1);
deleteTriangle(tr);
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a[20];
int k,mid,i,first,last,n,f=0;
printf("Enter the no of elements -" );
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
printf("->");
scanf("%d",&a[i]);
}
printf("Array is ");
for(i=0;i<n;i++)
{
printf("%d,",a[i]);
}
printf("\nEnter the element to be searched - ");
scanf("%d",&k);
first=0;
last=n-1;
mid=(first+last)/2;
while(first<=last)
{
if(a[mid]<k)
{
first=mid+1;
mid=(first+last)/2;
}
else if(a[mid]>k)
{
last=mid-1;
mid=(first+last)/2;
}
else
{
f=1;
printf("Item found at position %d\n",mid+1);
break;
}
}
if(f==0)
{
printf("Item not found\n");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct point {
int x;
int y;
};
int main()
{
struct point first = {100, 100};
struct point second = first;
struct point third = {.x=20, .y=30};
second.y = 200;
printf("(%d, %d)\n",first.x, first.y);
printf("(%d, %d)\n",second.x, second.y);
printf("(%d, %d)\n",third.x, third.y);
return 0;
}
|
C
|
#include "Header.h"
//////////////////////////////////////////////////////////////
//
// Name: DigitsSum
// Description: Accept N numbers from user and
// display summation of digits of each number
// in it
//
// Input: N: 6
// 8225 665 3 76 953 858
// Output: 17 17 3 13 17 21
//
// Author: Vivek Shrihari Doke
// Date: 19 August 2020
//
/////////////////////////////////////////////////////////////
void DigitsSum(int *iptr, int iLength) {
int i=0;
int iNo = 0, iDigit = 0, iSum = 0;
for(i=0; i<iLength; i++) {
iNo = *(iptr+i);
while(iNo != 0) {
iDigit = iNo % 10;
iSum = iSum + iDigit;
iNo = iNo / 10;
}
printf("%d ",iSum);
iSum = 0;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int counter=0;
int thread_count=4;
pthread_mutex_t barrier_mutex;
void* threadFn(void* rank){
long my_rank = (long) rank;
srand(my_rank);
pthread_mutex_lock(&barrier_mutex);
counter++;
pthread_mutex_unlock(&barrier_mutex);
printf("thread %ld is waiting\n", my_rank);
while (counter < thread_count);
printf("thread %ld finish\n", my_rank);
return NULL;
}
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
thread_count = strtol(argv[1], NULL, 10);
thread_handles = malloc (thread_count * sizeof(pthread_t));
for (thread=0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], NULL, threadFn, (void*) thread);
}
for (thread=0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], NULL);
}
return 0;
}
|
C
|
/*
* function for uart comms
*/
#include "mcu_defs.h"
#include <avr/io.h>
// Set up MCU
#define F_CPU CLOCK
#include <util/setbaud.h>
#include <util/delay.h>
#include "uart.h"
void uart_init(void)
{
UBRR0H = UBRRH_VALUE; // Set baud values correctly
UBRR0L = UBRRL_VALUE;
UCSR0B = (1 << RXEN0 ) | (1 << TXEN0); // Enable transmit & receive
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // 8 bit, no parity, one stop bit
}
int uart_putchar(char c, FILE *stream)
{
if (c == '\n')
uart_putchar('\r', stream); // Handle newline
loop_until_bit_is_set(UCSR0A, UDRE0); // Wait for transmit buffer to be empty
UDR0 = c;
return 0;
}
int uart_putrawchar(char c)
{
if (c == '\n')
uart_putrawchar('\r'); // Handle newline
loop_until_bit_is_set(UCSR0A, UDRE0); // Wait for transmit buffer to be empty
UDR0 = c;
return 0;
}
int uart_getchar(FILE *stream)
{
char c;
loop_until_bit_is_set(UCSR0A, RXC0); // Wait until byte received
c = UDR0;
uart_putchar(c, stream); //echo byte back so we can see what we typed
return c;
}
int uart_getrawchar(void)
{
char c;
loop_until_bit_is_set(UCSR0A, RXC0); // Wait until byte received
c = UDR0;
uart_putrawchar(c); //echo byte back so we can see what we typed
return c;
}
void raw_printf(char *string)
{
int i = 0;
while (string[i] != '\0') // C strings are null terminated
{
uart_putrawchar(string[i]);
i++;
}
}
char *raw_scanf(void)
{
return "";
}
|
C
|
#include "hack.h"
int read_from_file_stream(
FILE *stream, unsigned char *data, size_t buf_capacity, size_t *dlen)
{
if (dlen) {
*dlen = 0;
}
if (!stream || !data || !dlen) {
return -1; // some argument is invalid
}
for (;;) {
int thisbyte = getc(stream);
if (thisbyte != EOF) {
if (*dlen < buf_capacity) {
data[*dlen] = (unsigned char) thisbyte;
*dlen += 1;
} else {
return -2; // the buffer is too small
}
} else {
if (feof(stream)) {
return 0;
} else if (ferror(stream)) {
return -3; // the file stream has errors occurred
} else {
return -4; // the file stream has unknown errors occurred
}
}
}
}
int write_to_file_stream(FILE *stream, const unsigned char *data, size_t dlen)
{
size_t fwrite_status;
if (!stream || (dlen > 0 && !data)) {
return -1; // some argument is invalid
}
if (dlen > 0) {
fwrite_status = fwrite(data, 1, dlen, stream);
if (fwrite_status != dlen) {
if (ferror(stream)) {
return -2; // the file stream has errors occurred
} else {
return -3; // the file stream has unknown errors occurred
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
/*
param msg(const, str: pointer)
*/
static void die(const char* msg){
/*
perror()
エラー番号に対応するエラーメッセージを標準エラー出力。
msgを標準エラー出力
*/
perror(msg);
/*
exit()
プログラムの終了
EXIT_FAILURE : 失敗終了状態
*/
exit(EXIT_FAILURE);
}
static void set_nonblocking(int sock){
/*
fcntl()
ファイルディスクリプタの操作を行う
fcntl(int fd, int cmd, long arg)
fd: オープンされたファイルディスクリプタ
cmd: F_GETFL(ファイル状態フラグを読み出す。)
arg: ファイル状態フラグに arg で指定された値を設定
*/
int flag = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flag | O_NONBLOCK);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int cards[5];
char suits[5];
char lastSuit = '\0';
int suitchange = 0;
int i,j;
int jokers = 0;
int neighbors[2];
int bounds[2];
int ind;
int breaker_a = -1;
int breaker_b = -1;
int in_a_row = 0;
int row_value = -1;
int isRoyalFlush = 0;
int isFlush = 0;
int straights[13];
int tmp;
int isStraight = 0;
int straightRank = 0;
if(argc < 7)
{
fprintf(stderr,"USAGE:%s n1 n2 n3 n4 n5 ind\n",argv[0]);
exit(-1);
}
for(i = 0; i < 13 ; i++)
{
straights[i] = 0;
}
for(i = 0,jokers = 0 ; i < 5 ; i++)
{
cards[i] = atoi(argv[(i+1)]);
suits[i] = '\0';
if(cards[i] == -1)
{
jokers++;
continue;
}
for(j = 0 ; j < strlen(argv[(i+1)]); j++)
{
if(isalpha(argv[(i+1)][j]))
{
suits[i] = argv[(i+1)][j];
break;
}
}
if(cards[i] >= 0 && cards[i] < 13)
{
straights[cards[i]] = 1;
}
}
neighbors[0] = 0;
neighbors[1] = 0;
ind = atoi(argv[6]);
if(ind < 0 )
ind = 0;
if(ind > 4)
ind = 4;
bounds[0] = ind;
bounds[1] = ind;
/*our card it not a joker*/
for(i = ind - 1; i > -1; i--)
{
if(cards[i] == cards[ind] || cards[i] == -1)
{
neighbors[0]++;
bounds[0] = i;
continue;
}
breaker_a = cards[i];
break;
}
for(i = ind + 1; i < 5; i++)
{
if(cards[i] == cards[ind] || cards[i] == -1)
{
neighbors[1]++;
bounds[1] = i;
continue;
}
breaker_b = cards[i];
break;
}
in_a_row = 1 + neighbors[0] + neighbors[1];
row_value = cards[ind];
if(cards[ind] == -1)
{
/*the card we flipped on is a joker*/
if((breaker_a > -1) && (breaker_a < breaker_b))
{
bounds[0]--;
row_value = breaker_a;
in_a_row++;
}
else if((breaker_b > -1) && (breaker_b < breaker_a))
{
row_value = breaker_b;
bounds[1]++;
in_a_row++;
}
else if((breaker_a > -1) && (breaker_a == breaker_b))
{
bounds[0]--;
bounds[1]++;
in_a_row += 2;
row_value = breaker_a;
}
else
{
/*we have 5 jokers - make it a Royal Flush*/
in_a_row = 0;
isStraight = 1;
isFlush = 1;
isRoyalFlush = 1;
straightRank = 0;
}
}
for(i = 0; !isStraight && i < 9 ; i++)
{
straightRank = i;
for(j = i,tmp = jokers ; j < (i + 5) ; j++)
{
if(straights[j])
{
continue;
}
tmp--;
if(tmp < 0)
{
break;
}
}
if(j == (i + 5))
{
bounds[0] = i;
bounds[1] = j - 1;
isStraight = 1;
}
}
if(!isStraight)
{
straightRank = -1;
}
if(in_a_row >= 3)
{
printf("Have a touple %d [%d .. %d]\n",row_value,bounds[0],bounds[1]);
suitchange = 0;
lastSuit = '\0';
for(i = bounds[0] ; i <= bounds[1] ; i++)
{
if(suits[i] == '\0')
{
continue;
}
if(lastSuit == '\0')
{
lastSuit = suits[i];
continue;
}
if(lastSuit != suits[i])
{
suitchange = 1;
}
}
if(!suitchange)
{
isFlush = 1;
}
}
if(isStraight)
{
printf("This hand is a Straight [%d .. %d]\n",bounds[0],bounds[1]);
for(i = 0 ; i < 5 ; i++)
{
if(suits[i] == '\0')
{
continue;
}
if(lastSuit == '\0')
{
lastSuit = suits[i];
continue;
}
if(lastSuit != suits[i])
{
suitchange = 1;
}
}
if(!suitchange)
{
isFlush = 1;
if( straightRank == 0)
{
isRoyalFlush = 1;
}
}
}
if(isFlush)
{
printf("This hand has a flush element\n");
}
if(isRoyalFlush)
{
printf("This hand is a Royal Flush\n");
}
}
|
C
|
/*
* Author: lngost
* See https://github.com/lngost/algorithm-practice
*/
#include <stdlib.h>
#include <math.h>
#ifndef _ORDER_DEFINED_
#define _ORDER_DEFINED_
typedef const int ORDER;
#define ORDER_ND 1 // non-descending
#define ORDER_NA 2 // non-ascending
#endif
static void merge(int a[], int p, int q, int r, ORDER order) {
int n1 = q - p + 1;
int n2 = r - q;
int *lArray = malloc(n1 * sizeof(int));
int *rArray = malloc(n2 * sizeof(int));
for(int i=0; i<n1; i++) {
lArray[i] = a[p+i];
}
for(int j=0; j<n2; j++) {
rArray[j] = a[q+j+1];
}
int i = 0;
int j = 0;
switch(order) {
case ORDER_ND:
for(int k = p; k <= r; k++) {
if(j >= n2 || (i < n1 && lArray[i] <= rArray[j])) {
a[k] = lArray[i];
++i;
} else {
a[k] = rArray[j];
++j;
}
}
break;
case ORDER_NA:
for(int k = p; k <= r; k++) {
if(j >= n2 || (i < n1 && lArray[i] >= rArray[j])) {
a[k] = lArray[i];
++i;
} else {
a[k] = rArray[j];
++j;
}
}
break;
default: break;
}
free(lArray);
free(rArray);
}
void mergeSort(int a[], int p, int r, ORDER order) {
if(p < r) {
int q = (int)floor((p+r)/2);
mergeSort(a, p, q, order);
mergeSort(a, q+1, r, order);
merge(a, p, q, r, order);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char* argv[]){
// I suppose that I know the filenames and the number of rows
int n = 40;
//double tmp;
FILE* input_1;
FILE* input_2;
input_1 = fopen("matrix_from_matlab.txt", "r");
input_2 = fopen("vector_from_matlab.txt", "r");
//Matrix allocation
double **matrix = (double **)malloc(n * sizeof(double*));
for(int i = 0; i < n; i++){
matrix[i] = (double *)malloc(n*sizeof(double));
}
//Vector allocation
double* vector = (double *)malloc(n*sizeof(double*));
//Result allocation
double* result = (double *)malloc(n*sizeof(double*));
//Creating vector and matrix of 1's for testing ( I will take those from file)
for(int i = 0; i < n; i++){
vector[i] = 1;
for(int j = 0; j < n; j++){
matrix[i][j] = 0;
matrix[j][j] = 1;
}
}
fclose(input_1);
fclose(input_2);
for(int i = 0; i < n; i++){
result[i] = 0;
for(int j = 0; j < n; j++){
result[i] += matrix[i][j]*vector[j];
}
}
//Printing result
for(int i = 0; i < n; i++){
printf("%f\n", result[i]);
}
//Free the matrix
for(int i = 0; i < n; i++){
free(matrix[i]);
}
free(matrix);
//Free the vector
free(vector);
//Free the result
free(result);
return 0;
}
|
C
|
#include<stdio.h>
int main(void){
int n;
scanf("%d",&n);
int sa;
int ans;
if(n>=9){
sa=n-9;
ans=sa%7;
if(ans==0){
printf("sat\n");
}
if(ans==1){
printf("sun\n");
}
if(ans==2){
printf("mon\n");
}
if(ans==3){
printf("tue\n");
}
if(ans==4){
printf("wed\n");
}
if(ans==5){
printf("thu\n");
}
if(ans==6){
printf("fri\n");
}
}else{
sa=9-n;
ans=sa%7;
if(ans==0){
printf("sat\n");
}
if(ans==1){
printf("fri\n");
}
if(ans==2){
printf("thu\n");
}
if(ans==3){
printf("wed\n");
}
if(ans==4){
printf("tue\n");
}
if(ans==5){
printf("mon\n");
}
if(ans==6){
printf("sun\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
// Funo contagem
void naturais(n){
if(n==49){ // Caso base
printf("%d", n);
return; // Imprime ltimo valor e retorna vazio
}
printf("%d ", n);
naturais(n+1); // Imprime o nmero e chama a funo para o prximo
}
// Funo Principal
int main()
{
naturais(0); // Chamada da funo
}
|
C
|
/*
* Expresses Regulares
* Biblioteca POSIX
* Ver: https://www.educative.io/edpresso/how-to-write-regular-expressions-in-c
* lufer
**/
#include <stdio.h>
#include "regex.h"
#pragma warning (disable: 4996);
void printResult(int return_value) {
if (return_value == 0) {
printf("Pattern found.\n");
}
else if (return_value == REG_NOMATCH) {
printf("Pattern not found.\n");
}
else {
printf("An error occured.\n");
}
}
int main2() {
regex_t regex;
int return_value;
int return_value2;
return_value = regcomp(®ex, "ice", 0);
return_value = regexec(®ex, "icecream", 0, NULL, 0);
return_value2 = regcomp(®ex, "ice", 0);
return_value2 = regexec(®ex, "frozen yoghurt", 0, NULL, 0);
printResult(return_value);
printResult(return_value2);
char name[15];
// Taking a name as an input.
// name can only include alphabets
puts("Nome: ");
scanf("%[a-zA-Z ]", name);
printf("%s", name);
return 0;
}
|
C
|
/**
*_strstr - find occurence of a substring in a string
*@haystack: string to search in
*@needle: string searched
*Return: pointer to the begining of the located substring or a null
*/
char *_strstr(char *haystack, char *needle)
{
int i, j;
for (i = 0; haystack[i] != 0; i++)
{
for (j = 0; (needle[j] != '\0') && (haystack[i] == needle[0]); j++)
{
if (haystack[i + j] == needle[j])
continue;
else
break;
}
if (needle[j] != '\0')
j = 0;
else
return (&haystack[i]);
}
return (0);
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <memory.h>
#include <zconf.h>
#include <sys/types.h>
#include <sys/time.h>
int main(int argc, char * argv[]) {
if(argc<2){
printf("Błędne argumenty\n");
return -1;
}
int fifo = open(argv[1],O_WRONLY);
if(fifo==-1){
printf("Error\n");
return -1;
}
while(1){
int size = PIPE_BUF - sizeof(getpid()) - sizeof(time_t) - 10;
char bufor[size];
fgets(bufor,size,stdin);
time_t time_t1 = time(NULL);
char message[sizeof(getpid())+ strlen(bufor)+ sizeof(time_t)+10];
sprintf(message," - %d - %ld - %s",getpid(),time_t1,bufor);
write(fifo,message, strlen(message)+1);
}
}
|
C
|
/*
* Copyright (c) 2018, 2021-2022 Paul Mattes.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the names of Paul Mattes nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY PAUL MATTES "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 PAUL MATTES 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.
*/
/*
* xpopen_test.c
* Unit tests for xpopen.
*/
#include "globals.h"
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include "sa_malloc.h"
#include "utils.h"
#include "xpopen.h"
void
nothing(int ignored)
{
}
int
main(int argc, char *argv[])
{
char buf[1024];
char outfile[256];
char cmd[1024];
pid_t pid;
FILE *f;
char *s;
int rv, status;
bool verbose = false;
if (argc > 1 && !strcmp(argv[1], "-v")) {
verbose = true;
}
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, nothing);
/* Try an input stream. */
f = xpopen("cat /etc/hosts", "r", &pid);
if (f == NULL) {
perror("xpopen");
exit(1);
}
while ((s = fgets(buf, sizeof(buf), f)) != NULL) {
if (verbose) {
fputs(s, stdout);
}
}
rv = xpclose(f, 0);
if (rv != 0) {
fprintf(stderr, "child exited with status %d\n", rv);
exit(1);
}
if (verbose) {
printf("\n========\n\n");
}
/* Try an input stream with explicit wait. */
f = xpopen("cat /etc/hosts", "r", &pid);
if (f == NULL) {
perror("xpopen");
exit(1);
}
while ((s = fgets(buf, sizeof(buf), f)) != NULL) {
if (verbose) {
fputs(s, stdout);
}
}
xpclose(f, XPC_NOWAIT);
rv = waitpid(pid, &status, 0);
if (rv < 0) {
perror("waitpid");
}
if (status != 0) {
fprintf(stderr, "child exited with status %d\n", status);
exit(1);
}
if (verbose) {
printf("\n========\n\n");
}
/* Try an output stream. */
sprintf(outfile, "/tmp/xpopen.%d", getpid());
sprintf(cmd, "tr A-Z a-z >%s", outfile);
f = xpopen(cmd, "w", &pid);
if (f == NULL) {
perror("xpopen");
exit(1);
}
fputs("Mixed Case\n", f);
rv = xpclose(f, 0);
if (rv != 0) {
fprintf(stderr, "child exited with status %d\n", rv);
exit(1);
}
f = fopen(outfile, "r");
if (f == NULL) {
perror(outfile);
exit(1);
}
while ((s = fgets(buf, sizeof(buf), f)) != NULL) {
if (verbose) {
fputs(s, stdout);
}
}
fclose(f);
unlink(outfile);
sa_malloc_leak_check();
printf("PASS\n");
}
|
C
|
#ifndef UTIL_H_INCLUDED
#define UTIL_H_INCLUDED
float powi(float base, int exp)
{
if (exp == 0)
return 0;
else if (exp > 0)
{
while (exp - 1)
{
base*= base;
--exp;
}
return base;
}
else
{
exp = -exp;
while (exp - 1)
{
base/= base;
--exp;
}
return base;
}
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include "niuparser_sdk.h"
#include <assert.h>
#include <stdbool.h>
typedef void sigfunc(int);
void func_wait(int signo) {
pid_t pid;
int stat;
pid = wait(&stat);
printf( "child %d exit\n", pid );
return;
}
void func_waitpid(int signo) {
pid_t pid;
int stat;
while( (pid = waitpid(-1, &stat, WNOHANG)) > 0 ) {
printf( "child %d exit\n", pid );
}
return;
}
sigfunc* signal( int signo, sigfunc *func ) {
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if ( signo == SIGALRM ) {
#ifdef SA_INTERRUPT
act.sa_flags |= SA_INTERRUPT; /* SunOS 4.x */
#endif
} else {
#ifdef SA_RESTART
act.sa_flags |= SA_RESTART; /* SVR4, 4.4BSD */
#endif
}
if ( sigaction(signo, &act, &oact) < 0 ) {
return SIG_ERR;
}
return oact.sa_handler;
}
void str_echo( int cfd ) {
ssize_t n;
char buf[1024];
again:
memset(buf, 0, sizeof(buf));
while( (n = read(cfd, buf, 1024)) > 0 ) {
write(cfd, buf, n);
}
if( n <0 && errno == EINTR ) {
goto again;
} else {
printf("str_echo: read error\n");
}
}
int main()
{
int sockfd,new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size,ret=0;
pid_t child;
signal(SIGCHLD, &func_waitpid);
Switch_ST switcher; //声明开关 默认所有功能都是关闭状态
//开启所有功能
switcher.m_is_ws_on = true;
switcher.m_is_pos_on = false;
switcher.m_is_ner_on = false;
switcher.m_is_chk_on = false;
switcher.m_is_dp_on = false;
switcher.m_is_cp_on = false;
switcher.m_is_srl_on = false;
//初始化NiuParser
if(NiuParser_Create_Instance( &switcher) != NIUPARSER_RET_OK)
{
perror( "NiuParser Init Failed ! " );
exit(-1);
}
//建立TCP套接口
if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("create socket error");
perror("socket");
exit(1);
}
//初始化结构体,并绑定8080端口
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(8080);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
int on=1;
if((setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)))<0)
{
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
//绑定套接口
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(my_addr))==-1)
{
perror("bind socket error");
exit(1);
}
//创建监听套接口
if(listen(sockfd,20)==-1)
{
perror("listen");
exit(1);
}
//等待连接
while(1)
{
sin_size = sizeof(struct sockaddr_in);
//如果建立连接,将产生一个全新的套接字
if((new_fd = accept(sockfd,(struct sockaddr *)&their_addr,&sin_size))==-1)
{
perror("accept");
exit(1);
}
//printf("accept success.\n");
//生成一个子进程来完成和客户端的会话,父进程继续监听
if( (child=fork()) == 0 )
{
//printf("create new thred success.\n");
//读取客户端发来的信息
int numbytes;
char buff[2560];
char retbuff[2560];
memset( buff, 0x00, sizeof( buff ));
if((numbytes = recv(new_fd, buff, sizeof(buff),0))==-1)
{
perror("recv");
exit(1);
}
printf("%s\n",buff);
Seg_Result_ST seg_result;
ret = NiuParser_Segmenter_Sentence( buff , &seg_result);
assert(ret == NIUPARSER_RET_OK);
memset( retbuff, 0x00, sizeof( retbuff ));
for(unsigned int i=0;i<seg_result.m_word_num;i++)
{
strcat( retbuff, seg_result.m_word_array[i]);
strcat( retbuff, " " );
}
NiuParser_Release_Segment_Memory(&seg_result);
printf("%s\n",retbuff);
//将从客户端接收到的信息再发回客户端
if(send(new_fd,retbuff,sizeof(retbuff),0)==-1)
perror("send");
//str_echo( new_fd );
close(new_fd);
exit(0);
}
close(new_fd);
}
close(sockfd);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main () {
int length, n;
printf("Please enter the starting number of the Collatz sequence:\n");
scanf("%d",&n);
while(n != 1){
printf("%d, ",n);
if((n % 2) == 0) n /= 2;
else n = 3*n + 1;
}
printf("%d\n",n);
}
|
C
|
#define PLUS 1
#define MINUS -1
typedef struct node {
int num;
struct node *next, *prev;
}node;
typedef struct number {
int sign, dec;
node *head, *tail;
}number;
void initNumber(number *a);
void addDigit(number *a, char ch);
void printNumber(number a);
void destroyNumber(number *a);
void appendleft(number *a, int no);
int length(number a);
void remov(number *a, int pos);
void zeroRemov(number *a);
|
C
|
#include "piece.h"
#include <string.h>
#include <stdlib.h>
#include "AI/movesGen.h"
#include "board.h"
#include <stdio.h>
#include "validMoves.h"
#define MAX_COLUMN 8
#define MAX_RANK 8
int rookMoves(int start, int end)
{
if (start < MAX_RANK)
{
if (end % MAX_RANK == start)
return 1;
}
else
{
if(end % MAX_RANK == start % MAX_RANK)
return 1;
}
if (start < end)
{
if(start % 8 == 7) // Last row can't go to the right
return 0;
for(int i = start + 1; i < end; i++)
{
if(i % 8 == 0)
return 0;
}
return 2;
}
else
{
if(start % 8 == 0) // First row can't go to the left
return 0;
for(int i = start; i > end; i--)
{
if(i % 8 == 0)
return 0;
}
return 2;
}
return 0;
}
int rookLegal(int start, int end, int dir, struct Piece* board)
{
switch(dir)
{
// Vertical
case 1:
if(start < end)
{
for(int i = start + MAX_RANK; i < end; i += MAX_RANK)
{
if(board[i].type != NONE)
return 0;
}
}
else
{
//printf("start %i and end %i\n",start,end);
for(int i = start-8; i > end; i -= 8)
{
//printf("start: %i and end : %i || i : %i || board type %i\n",start, end, i, board[i].type);
if(board[i].type != NONE)
return 0;
}
}
return 1;
break;
// Horizontal
case 2:
if(start < end)
{
for(int i = start+1; i < end; i++)
{
if(board[i].type != NONE || i % 8 == 7)
return 0;
}
}
else
{
for(int i = start-1; i > end; i--)
{
if(board[i].type != NONE || i % 8 == 0)
return 0;
}
}
return 1;
break;
default:
return 0;
break;
}
}
int bishopMoves(int start,int end)
{
int b1 = 1;
int b2 = 1;
int b3 = 1;
int b4 = 1;
int x1 = start;
int x2 = start;
int x3 = start;
int x4 = start;
for(int n = 1; n < MAX_RANK; n++)
{
// it is not the end
// if we are on the edge of the board with must prevent this direction
if(x1 % 8 == 7 || x1 > 55) // Right edge or Bottom edge
b1 = 0;
if(x2 % 8 == 0 || x2 > 55) // Left edge or Bottom edge
b2 = 0;
if(x3 % 8 == 7 || x3 < 8) // Right edge or Top edge
b3 = 0;
if(x4 % 8 == 0 || x4 < 8) // Left edge or Top edge
b4 = 0;
if(end > start)
{
if(b1)
x1 += MAX_RANK + 1;
if(b2)
x2 += MAX_RANK - 1;
if(x1 == end && b1)
return 1;
if(x2 == end && b2)
return 2;
}
else if(end < start)
{
if(b3)
x3 += -MAX_RANK + 1;
if(b4)
x4 += -MAX_RANK - 1;
if(x3 == end && b3)
return 3;
if(x4 == end && b4)
return 4;
}
}
return 0;
}
int bishopLegal(int start, int end, int r, struct Piece board[])
{
if(r == 1)
{
int v = start;
for(int n = 1; n < MAX_RANK; n++)
{
v += MAX_RANK + 1;
if(v != end)
{
if(board[v].type != NONE)
{
return 0;
}
}
else
return 1;
n++;
}
return 1;
}
if(r == 2)
{
int v = start;
for(int n = 1; n < MAX_RANK; n++)
{
v += MAX_RANK - 1;
if(v != end)
{
if(board[v].type != NONE)
{
return 0;
}
}
else
return 1;
n++;
}
return 1;
}
if(r == 3)
{
int v = start;
for(int n = 1; n < MAX_RANK; n++)
{
v += -MAX_RANK + 1;
if(v != end)
{
if(board[v].type != NONE)
{
return 0;
}
}
else
return 1;
n++;
}
return 1;
}
if(r == 4)
{
int v = start;
for(int n = 1; n < MAX_RANK; n++)
{
v += - MAX_RANK - 1;
if(v != end)
{
if(board[v].type != NONE)
{
return 0;
}
}
else
{
return 1;
}
n++;
}
return 1;
}
return 0;
}
int pawnMoves(int start, int end, struct Piece pawn)
{
//printf("start : %i\n",start);
//printf("end : %i\n",end);
if(pawn.hasMoved) // Cannot move 2 up
{
if(pawn.color == WHITE)
{
if(start - MAX_RANK == end)
return 1;
//Take a piece
if(start - MAX_RANK - 1 == end || start - MAX_RANK + 1 == end)
return 3;
}
else // pawn is BLACK
{
if(start + MAX_RANK == end)
return 1;
// Take a piece
if(start + MAX_RANK - 1 == end || start + MAX_RANK + 1 == end)
return 3;
}
return 0;
}
else
{
if(pawn.color == WHITE)
{
if(start - MAX_RANK == end)
return 1;
if(start - 2*MAX_RANK == end)
return 2;
//Take a piece
if(start - MAX_RANK - 1 == end || start - MAX_RANK + 1 == end)
return 3;
}
else // pawn is BLACK
{
if(start + MAX_RANK == end)
return 1;
if(start + 2*MAX_RANK == end)
return 2;
// Take a piece
if(start + MAX_RANK - 1 == end || start + MAX_RANK + 1 == end)
return 3;
}
return 0;
}
}
int knightMoves(int start, int end)
{
/*if(end > start) // prevent knight from doing weird movements
{
if(end - start < MAX_RANK)
return 0;
}
else
{
if(start - end < MAX_RANK)
return 0;
}*/
// Critical positions
int left = 1;
int leftM = 1;
int right = 1;
int rightM = 1;
int up = 1;
int upM = 1;
int down = 1;
int downM = 1;
//
if(start % 8 < 2) //left
left = 0;
if(start % 8 == 0) // leftM
leftM = 0;
if(start % 8 > 5) // right
right = 0;
if(start % 8 == 7) // rightM
rightM = 0;
if(start < 16)
up = 0;
if(start < 8)
upM = 0;
if(start >= 48)
down = 0;
if(start >= 56)
down = 0;
//printf("start %i ; end %i \n left %i , leftM %i, right %i, rightM %i\nup %i, upM %i, down %i, downM %i\n",start,end,left,leftM,right,rightM,up,upM,down,downM);
if((start + 2*MAX_RANK + 1 == end && rightM && down)
|| (start + 2*MAX_RANK - 1 == end && leftM && down))
return 1;
if((start - 2*MAX_RANK + 1 == end && rightM && up)
|| (start - 2*MAX_RANK - 1 == end && leftM && up))
return 1;
if((start + MAX_RANK + 2 == end && right && downM)
|| (start + MAX_RANK - 2 == end && left && downM))
return 1;
if((start - MAX_RANK + 2 == end && right && downM)
|| (start - MAX_RANK - 2 == end && left && upM))
return 1;
return 0;
}
int queenMoves(int start, int end,Piece* board)
{
int b = bishopMoves(start,end);
int r = rookMoves(start,end);
if(b)
return bishopLegal(start,end,b,board);
if(r)
return rookLegal(start,end,r,board);
return b + r;
}
int kingMoves(int start, int end)
{
int left = 1;
int right = 1;
int up = 1;
int down = 1;
int castle = 0;
if(start % 8 == 0)
left = 0;
if(start % 8 == 7)
right = 0;
if(start > 55)
down = 0;
if(start < 8)
up = 0;
if(start == 60 || start == 4)
castle = 1;
if((start + 1 == end && right ) || (start - 1 == end && left))
return 1;
if((start + MAX_RANK == end && down) || (start - MAX_RANK == end && up))
return 1;
if((start + MAX_RANK + 1 == end && down && right)
|| (start + MAX_RANK - 1 == end && down && left))
return 1;
if((start - MAX_RANK + 1 == end && up && right)
|| (start - MAX_RANK - 1 == end && up && left))
return 1;
if((start + 3 == end || start - 4 == end) && castle)
return 2;
return 0;
}
int castleLegal(Chess chess, int start, int end)
{
if(chess.board[start].hasMoved || chess.board[end].hasMoved ||
(chess.board[start].color != chess.board[end].color) ||
chess.check)
return 0;
if(end > start) // Castle King side
{
if(chess.board[start+1].type != NONE || chess.board[start+2].type != NONE)
return 0;
return squareGeneration(chess,start+1,start) == 0 &&
squareGeneration(chess,start+2,start) == 0;
}
else // Castle Queen side
{
if(chess.board[start-1].type != NONE ||
chess.board[start-2].type != NONE ||
chess.board[start-3].type != NONE)
return 0;
return squareGeneration(chess,start-1,start) == 0 &&
squareGeneration(chess,start-2,start) == 0;
}
}
int pawnLegal(Piece* board, int r, int start, int end)
{
if (r != 0)
{
if(r == 3)
{
//printf("start : %i and end %i\n",start,end);
if(board[start].color == BLACK)
{
if(start + MAX_RANK + 1 == end)
{
if(board[start + MAX_RANK + 1].type != NONE &&
start % 8 != 7)
return 1;
}
if(start + MAX_RANK - 1 == end)
{
if(board[start + MAX_RANK - 1].type != NONE &&
start % 8 != 0)
return 1;
}
}
else
{
if(start - MAX_RANK + 1 == end)
{
if(board[start - MAX_RANK + 1].type != NONE &&
start % 8 != 7)
return 1;
}
if(start - MAX_RANK - 1 == end)
{
if(board[start - MAX_RANK - 1].type != NONE &&
start % 8 != 0)
return 1;
}
}
return 0;
}
if(board[start].color == WHITE)
{
if (r == 1)
{
if(board[start - MAX_RANK].type == NONE)
return 1;
}
if(r == 2)
{
if(board[start - MAX_RANK].type == NONE &&
board[start - 2*MAX_RANK].type == NONE)
return 1;
}
}
else
{
if (r == 1)
{
if(board[start + MAX_RANK].type == NONE)
return 1;
}
if(r == 2)
{
if(board[start + MAX_RANK].type == NONE &&
board[start + 2*MAX_RANK].type == NONE)
return 1;
}
}
return 0;
}
return 0;
}
int tryMove(Chess chess, int x1, int x2)
{
if(chess.board[x2].type == 0)
{
chess.board[x2].type = chess.board[x1].type;
chess.board[x2].color = chess.board[x1].color;
chess.board[x2].hasMoved = 1;
chess.board[x1].type = 0;
}
else
if(chess.board[x1].type == KING && chess.board[x2].type == ROOK &&
!chess.board[x1].hasMoved && !chess.board[x2].hasMoved)
{
if(x2 > x1) // Castle Kingside
{
chess.board[x1+1] = chess.board[x2];
chess.board[x1+1].hasMoved = 1;
chess.board[x1+2] = chess.board[x1];
chess.board[x1+2].hasMoved = 1;
chess.board[x1].type = NONE;
chess.board[x2].type = NONE;
}
else // Castle Queenside
{
chess.board[x1-1] = chess.board[x2];
chess.board[x1-2] = chess.board[x1];
chess.board[x1-1].hasMoved = 1;
chess.board[x1-2].hasMoved = 1;
chess.board[x1].type = NONE;
chess.board[x2].type = NONE;
}
}
else
if(chess.board[x2].type != 0 && chess.board[x2].color != chess.board[x1].color)
{
chess.board[x2].type = chess.board[x1].type;
chess.board[x2].color = chess.board[x1].color;
chess.board[x2].hasMoved = 1;
chess.board[x1].type = 0;
}
//printf("check after move : %i \n",check(chess,chess.board[x2].color));
return check(chess,chess.board[x2].color);
}
int legalMoves(Chess chess,int start, int end, int check)
{
int dir;
int r;
int canCastle;
struct Piece* board = chess.board;
//if((board[start].color == board[end].color && board[end].type == NONE) && piece.type != KING)
// return 0;
if(board[start].type != NONE && board[end].type != NONE)
{
if(board[start].color == board[end].color &&
!(board[start].type == KING && board[end].type == ROOK))
return 0;
}
switch(board[start].type)
{
case PAWN:
r = pawnMoves(start,end,board[start]);
dir = pawnLegal(chess.board,r,start,end);
if(dir == 0)
return 0;
break;
case KNIGHT:
dir = knightMoves(start,end);
if(dir == 0)
return 0;
break;
case BISHOP:
dir = bishopMoves(start,end);
dir = bishopLegal(start,end,dir,board);
if(dir == 0)
return 0;
break;
case ROOK:
dir = rookMoves(start,end);
dir = rookLegal(start,end,dir,board);
if(dir == 0)
return 0;
break;
case QUEEN:
dir = queenMoves(start,end,board);
//b = bishopLegal(start,end,dir,board);
//r = rookLegal(start,end,dir,board);
//printf("start %i, end %i\n",start,end);
//printf("dir : %i\n",dir);
if(dir == 0)
return 0;
break;
case KING:
dir = kingMoves(start,end);
canCastle = 0;
if(dir == 2)
{
if(!chess.turn && !chess.BC && !chess.check && start == 4)
canCastle = 1;
if(chess.turn && !chess.WC && !chess.check && start == 60)
canCastle = 1;
}
if(dir == 1)
{
if(squareGeneration(chess,end,start))
// cannot go on attacked square // self check
return 0;
break;
}
if(dir == 2 && !board[start].hasMoved && canCastle)
{
dir = castleLegal(chess,start,end);
if(dir == 0)
return 0;
break;
}
return 0;
break;
case NONE:
break;
}
// printf("I'm checked !\n");
Chess* cs = malloc(sizeof(Chess));
cs->check = chess.check;
cs->BC = chess.BC;
cs->WC = chess.WC;
Piece* bd = malloc(64*sizeof(Piece));
for(int i = 0; i < 64; i++)
bd[i] = chess.board[i];
cs->board = bd;
check = tryMove(*cs,start,end);
if(check)
return 0;
free(cs);
free(bd);
return 1;
}
int checkmate(Chess* chess)
{
// generate all moves from allies
// if any moves prevent checkmate return 0
int size = 0;
Move* moves = movesGeneration(*chess,&size);
for(int i = 0; i < size; i++)
{
Move move = moves[i];
Chess* chessCpy = malloc(sizeof(Chess));
Piece* bdCpy = malloc(sizeof(Piece));
memcpy(bdCpy,chess->board,64*sizeof(Piece));
memcpy(chessCpy,chess,sizeof(Chess));
chessCpy->board = bdCpy;
makeMove(chessCpy,move.start,move.end);
if(!chessCpy->check)
return 0;
}
return 1;
}
int check(Chess chess, int color)
{
for(int i = 0; i < 64; i++)
{
if(chess.board[i].type == KING && (int)chess.board[i].color == color)
{
//printf("pos of king %i and current check : %i\n",i,chess.check);
if(squareGeneration(chess,i,i))
{
return 1;
}
}
}
return 0;
}
void updateChess(Chess* chess)
{
chess->check = check(*chess,chess->turn);
}
|
C
|
#include<stdio.h>
typedef struct student
{
char name[40];
int age;
}STUDENT;
int main()
{
int i;
STUDENT s;
FILE *fp;
fp=fopen("120_para_5.dat","r");
for(i=0;i<=12;i++)
{
printf("i=%-2d,%d\n",i,ftell(fp));
fread(&s,sizeof(STUDENT),1,fp);
printf("%s,%d\n\n",s.name,s.age);
}
printf("i=%-2d,%d\n",i,ftell(fp));
fseek(fp,220,SEEK_SET);
printf("fseek -> %d",ftell(fp));
fclose(fp);
}
|
C
|
#include "vtsaddrtable_test.h"
#include "vtsaddrtable.h"
#include "vblock.h"
#include <unistd.h>
#include <stddef.h>
#define SMALL_POWER 4
#define SMALL_SIZE (1 << SMALL_POWER)
#define LARGE_POWER 16
#define LARGE_SIZE (1 << LARGE_POWER)
const char *test_vtsaddrtable_init()
{
struct vtsaddrtable *table;
table = vtsaddrtable_new(SMALL_POWER);
if (table == NULL)
return "Allocation failed.";
vtsaddrtable_delete(table);
return NULL;
}
const char *test_vtsaddrtable_basic_insertion()
{
struct vtsaddrtable *table;
struct vblock *block, *find;
size_t i;
block = vblock_new(NULL, 1, 0);
table = vtsaddrtable_new(SMALL_POWER);
vtsaddrtable_insert(table, block);
find = vtsaddrtable_find(table, block->pgstart);
if (find != block)
return "Searching for block using page start after insertion failed.";
for (i = 0; i < (size_t)sysconf(_SC_PAGE_SIZE); i++)
{
find = vtsaddrtable_find(table, block->pgstart + i);
if (find != block)
return "Searching for block using offset address failed.";
}
vtsaddrtable_delete(table);
vblock_delete(block);
return NULL;
}
const char *test_vtsaddrtable_expansion()
{
struct vtsaddrtable *table;
struct vblock *blocks[LARGE_SIZE], *find;
size_t i, j;
table = vtsaddrtable_new(SMALL_POWER);
for (i = 0; i < LARGE_SIZE; i++)
{
blocks[i] = vblock_new(NULL, 1, 0);
if (blocks[i] == NULL)
return "Failure occurred in basic block allocation.";
vtsaddrtable_insert(table, blocks[i]);
}
for (i = 0; i < LARGE_SIZE; i++)
{
for (j = 0; j < (size_t)sysconf(_SC_PAGE_SIZE); j += 1024)
{
find = vtsaddrtable_find(table, blocks[i]->pgstart + j);
if (find != blocks[i])
return "Searching for block using offset address failed";
}
}
vtsaddrtable_delete(table);
for (i = 0; i < LARGE_SIZE; i++)
vblock_delete(blocks[i]);
return NULL;
}
const char *test_vtsaddrtable_large_entries()
{
struct vtsaddrtable *table;
struct vblock *blocks[SMALL_SIZE], *find;
size_t i, j;
table = vtsaddrtable_new(SMALL_POWER);
for (i = 0; i < SMALL_SIZE; i++)
{
blocks[i] = vblock_new(NULL, i + 1, 0);
if (blocks[i] == NULL)
return "Failure occurred in basic block allocation.";
vtsaddrtable_insert(table, blocks[i]);
}
for (i = 0; i < SMALL_SIZE; i++)
{
for (j = 0; j < sysconf(_SC_PAGE_SIZE) * blocks[i]->npages; j += 1024)
{
find = vtsaddrtable_find(table, blocks[i]->pgstart + j);
if (find != blocks[i])
return "Searching for block using offset address failed.";
}
}
vtsaddrtable_delete(table);
for (i = 0; i < SMALL_SIZE; i++)
vblock_delete(blocks[i]);
return NULL;
}
|
C
|
/*复制并显示数组*/
#include <stdio.h>
int main (void){
int i;
int dgt[9] = {1,2,3,4,5,6,7,8,9};
int a[9] = {0};
for (i = 0;i < 9;i++) /*复制所有元素*/
a[i] = dgt[i];
for (i = 0;i < 9;i++) /*显示所有元素*/
printf("%d ",a[i]);
putchar('\n');
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_5__ TYPE_2__ ;
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
struct TYPE_4__ {scalar_t__ ptr; } ;
typedef TYPE_1__ nk_handle ;
struct TYPE_5__ {int /*<<< orphan*/ font; } ;
typedef TYPE_2__ NkAllegro5Font ;
/* Variables and functions */
float al_get_text_width (int /*<<< orphan*/ ,char*) ;
int /*<<< orphan*/ strncpy (char*,char const*,int) ;
__attribute__((used)) static float
nk_allegro5_font_get_text_width(nk_handle handle, float height, const char *text, int len)
{
NkAllegro5Font *font = (NkAllegro5Font*)handle.ptr;
if (!font || !text) {
return 0;
}
/* We must copy into a new buffer with exact length null-terminated
as nuklear uses variable size buffers and al_get_text_width doesn't
accept a length, it infers length from null-termination
(which is unsafe API design by allegro devs!) */
char strcpy[len+1];
strncpy((char*)&strcpy, text, len);
strcpy[len] = '\0';
return al_get_text_width(font->font, strcpy);
}
|
C
|
// This code is created by Ahmed A. Eltahan
/*
----------------------------- Program Description -----------------------------------------
*/
// Libraries
#include<stdio.h> // Library to include c functions for the compiler.
// Function prototype
// Declared Structures
struct students{
// elements
int ID;
float Age;
};
// Declared Functions
struct students Testing() // struct students can be though as a data type, so this function returns a structure of students defined above
{
struct students ID_Age; // create a struct students with name ID_Age
printf("Please assign Ahmed's ID: ");
scanf("%d", &ID_Age.ID);
printf("Please assign Ahmed's Age: ");
scanf("%f", &ID_Age.Age);
return ID_Age; // return the struct value
}
// Global variables (Declaration and Inintialization)
void main(void)
{
// Declaration and Inintialization
struct students Ahmed; // declare a structure students to return the output of the Testing function
Ahmed = Testing(); // == Ahmed = ID_Age
printf("Ahmed's ID is %d \n", Ahmed.ID);
printf("Ahmed's Age is %f", Ahmed.Age);
// Write your instructions here.
// infinite loop while(1){}
// Output
}
|
C
|
//#include "types.h"
//#include "interpreter.h"
//
//#include <uthash.h>
//
//#include <stdio.h>
//#include <stdlib.h>
//#include <stdbool.h>
//
//
//// [print x "a" 421]
//Box * print_fn(Node *args, Scope *local) {
// Node *cursor;
// with_resolved_args(args, local, cursor, {
// while (cursor != NULL) {
// Box *box = ((Resolution *) Node_advance(&cursor))->box;
//
// if (box->type == TYPE_STRING) {
// printf("%s", UNBOX(String, box)->data);
// } else if (box->type == TYPE_NUMBER) {
// printf("%f", *UNBOX(double, box));
// } else {
// printf("Box(%s)\n", Type_name(box->type));
// }
// }
// });
//
// return NULL;
//}
//
//// [def f [arg1 arg2] [do arg1 arg2]]
//Box * define_fn(Node *args, Scope *local) {
// Node *cursor = args;
//
// // Function definitions
// Box *name = (Box *) Node_advance(&cursor);
// List *arg_defs = UNBOX(List, Node_advance(&cursor));
// List *code = UNBOX(List, Node_advance(&cursor));
//
// DynamicFunction *new_function_def = DynamicFunction_new(
// name, arg_defs, code);
//
// Scope_put(local, UNBOX(String, name), Box_wrap(TYPE_DYNAMIC_FUNC, new_function_def));
//
// return NULL;
//}
//
//Box * accumulate_fn(Node *args, Scope *local) {
// Node *cursor = NULL;
// Box *value = NULL;
//
// with_resolved_args(args, local, cursor, {
// Box *next = ((Resolution *) Node_advance(&cursor))->box;
//
// if (value != NULL) {
// if (value->type == TYPE_STRING) {
// String *old_str = UNBOX(String, value);
//
// if (next->type == TYPE_STRING) {
// value->data = String_join(old_str, UNBOX(String, next));
// } else if (next->type == TYPE_NUMBER) {
// String *num_str = String_new(1024);
// String_resize(num_str, sprintf(num_str->data, "%f", *UNBOX(double, next)));
// value->data = String_join(old_str, num_str);
//
// String_free(num_str);
// } else {
// // ??
// }
//
// String_free(old_str);
// } else if (value->type == TYPE_NUMBER) {
// if (next->type == TYPE_STRING) {
// String *num_str = String_new(1024);
// String_resize(num_str, sprintf(num_str->data, "%f", *UNBOX(double, value)));
// value->data = String_join(num_str, UNBOX(String, next));
//
// String_free(num_str);
//
// } else if (value->type == TYPE_NUMBER) {
// String *num_str_a = String_new(1024);
// String *num_str_b = String_new(1024);
// String_resize(num_str_a, sprintf(num_str->data, "%f", *UNBOX(double, value)));
// String_resize(num_str_b, sprintf(num_str->data, "%f", *UNBOX(double, value)));
// value->data = String_join(old_str, UNBOX(String, next));
//
// String_free(num_str);
// } else {
// // ??
// }
// } else if (value->type == TYPE_LIST) {
// List *vlist = UNBOX(List, value);
//
// if (next->type == TYPE_LIST) {
// Node *append_cursor = UNBOX(List, next->data)->head;
//
// while (append_cursor != NULL) {
// List_append(vlist, Node_advance(&append_cursor));
// }
// } else {
// List_append(vlist, next);
// }
// } else {
// printf("Values not addable!");
// exit(1);
// }
// }
// });
//
// return value;
//}
//
//Box * subtract_fn(Node *args, Scope *local) {
// Node *cursor;
// double value;
//
// with_resolved_args(args, local, cursor, {
// double *a = RES_UNBOX(double, Node_advance(&cursor));
// double *b = RES_UNBOX(double, Node_advance(&cursor));
//
// value = *a - *b;
// });
//
// return Box_wrap_double(value);
//}
//
//Box * product_fn(Node *args, Scope *local) {
// Node *cursor;
// double value;
//
// with_resolved_args(args, local, cursor, {
// double *a = RES_UNBOX(double, Node_advance(&cursor));
// double *b = RES_UNBOX(double, Node_advance(&cursor));
//
// value = *a * *b;
// });
//
// return Box_wrap_double(value);
//}
//
//Box * quotient_fn(Node *args, Scope *local) {
// Node *cursor;
// double value;
//
// with_resolved_args(args, local, cursor, {
// double *a = RES_UNBOX(double, Node_advance(&cursor));
// double *b = RES_UNBOX(double, Node_advance(&cursor));
//
// value = *a / *b;
// });
//
// return Box_wrap_double(value);
//}
//
//static String ACCUMULATE = {1, "+"};
//static String SUBTRACT = {1, "-"};
//static String PRODUCT = {1, "*"};
//static String QUOTIENT = {1, "/"};
//
//static String DEF = {3, "def"};
//static String PRINT = {5, "print"};
//
//void load_std_grammar(Frame *frame) {
// Frame_put(frame, &ACCUMULATE, Box_wrap(TYPE_NATIVE_FUNC, &accumulate_fn));
// Frame_put(frame, &SUBTRACT, Box_wrap(TYPE_NATIVE_FUNC, &subtract_fn));
// Frame_put(frame, &PRODUCT, Box_wrap(TYPE_NATIVE_FUNC, &product_fn));
// Frame_put(frame, "IENT, Box_wrap(TYPE_NATIVE_FUNC, "ient_fn));
//
// Frame_put(frame, &DEF, Box_wrap(TYPE_NATIVE_FUNC, &define_fn));
// Frame_put(frame, &PRINT, Box_wrap(TYPE_NATIVE_FUNC, &print_fn));
//}
|
C
|
/* array.c -- runtime support of arrays */
#include "rts.h"
#include <stdarg.h>
static void slices ();
/*
* sr_init_array (locn, addr, elemsize, initvalue, ndim, lb1, ub1, ...)
* -- initialize an array.
*
* If addr is 0, first allocate it. If addr is -1, obtain from sr_new().
*
* If elemsize is zero or negative, it is the (negative) maxlength of
* a string, for which an initializer will be created internally.
*
* If ndim is negative, it is followed by two *pointers* to lb/ub arrays,
* instead of a list of lb and ub values.
*/
Array *
sr_init_array (
char *locn, Array *addr, int elemsize, Ptr initvalue, int ndim, ...)
{
va_list ap;
int alcsize, i, n;
Dim *d;
Ptr p, q;
int *lb, *ub, la[MAX_DIMENS], ua[MAX_DIMENS], size[MAX_DIMENS+1];
String s; /* for string initialization */
sr_check_stk (CUR_STACK);
/*
* Calculate the size of each dimension.
*/
va_start (ap, ndim);
if (ndim < 0) {
ndim = -ndim;
lb = va_arg (ap, int *);
ub = va_arg (ap, int *);
} else {
lb = la;
ub = ua;
for (i = 0; i < ndim; i++) {
lb[i] = va_arg (ap, int);
ub[i] = va_arg (ap, int);
if (ub[i] - lb[i] + 1 < 0)
sr_runerr (locn, E_ABND, lb[i], ub[i]);
}
}
va_end (ap);
DEBUG5 (D_ARRAY, "sr_init_array (%06lX, %ld, %06lX, %ld, ?, %ld, ...)",
addr, elemsize, initvalue, ndim, ub[0]);
/*
* Create a string initializer, if needed.
*/
if (elemsize <= 0) {
s.size = -elemsize + STRING_OVH;
s.length = -1;
elemsize = SRALIGN (s.size);
initvalue = (Ptr) &s;
}
/*
* Calculate the total size, and allocate.
*/
size[ndim] = elemsize;
for (i = ndim - 1; i >= 0; i--)
size[i] = (ub[i] - lb[i] + 1) * size[i+1];
alcsize = SRALIGN (size[0] + sizeof (Array) + sizeof (Dim) * ndim);
if (addr == NULL)
addr = (Array *) sr_alc (alcsize, 1);
else if (addr == (Array *) -1)
addr = (Array *) sr_new (locn, alcsize);
/*
* Initialize array headers.
*/
addr->offset = sizeof (Array) + ndim * sizeof (Dim);
addr->size = addr->offset + size[0];
addr->ndim = ndim;
/*
* Initialize dimension headers (in reverse order)
*/
for (i = ndim - 1, d = (Dim *)(addr + 1); i >= 0; i--, d++) {
d->lb = lb[i];
d->ub = ub[i];
d->stride = size[i+1];
}
/*
* Initialize data
*/
if (initvalue != NULL && size[0] > 0) {
p = ADATA (addr); /* destination */
q = p + size[0]; /* end */
memcpy (p, initvalue, elemsize); /* init first element */
initvalue = p; /* now copy from front of array */
p += elemsize; /* bump store pointer */
n = elemsize; /* bytes available to copy */
while (p + n < q) {
memcpy (p, initvalue, n);
p += n;
n *= 2;
}
memcpy (p, initvalue, q - p);
}
return addr;
}
/*
* Return the number of elements in an array.
*/
int
sr_acount (a)
Array *a;
{
Dim *d = (Dim *) (a + 1);
int i = a->ndim;
int n = 1;
while (i-- > 0) {
n *= d->ub - d->lb + 1;
d++;
}
return n;
}
/*
* Copy one array to another, returning the pointer to the destination array.
* Data is copied but the destination header is left alone.
*/
Array *
sr_acopy (locn, dest, src)
char *locn;
Array *dest, *src;
{
Dim *ld, *rd;
int i, ndim;
ndim = dest->ndim;
ld = (Dim *) (dest + 1) + ndim - 1;
rd = (Dim *) (src + 1) + ndim - 1;
for (i = 0; i < ndim; i++, ld--, rd--)
if (ld->ub - ld->lb != rd->ub - rd->lb)
sr_runerr (locn, E_ASIZ, ld, rd);
memcpy ((Ptr) dest + dest->offset, (Ptr) src + src->offset,
dest->size - dest->offset);
return dest;
}
/*
* Swap two arrays and return the address of the left side (value of R side).
*/
Array *
sr_aswap (locn, lside, rside)
char *locn;
Array *lside, *rside;
{
Dim *ld, *rd;
Ptr l, r;
char c;
int i, n, ndim;
ndim = lside->ndim;
ld = (Dim *) (lside + 1) + ndim - 1;
rd = (Dim *) (rside + 1) + ndim - 1;
for (i = 0; i < ndim; i++, ld--, rd--)
if (ld->ub - ld->lb != rd->ub - rd->lb)
sr_runerr (locn, E_ASIZ, ld, rd);
l = ADATA (lside); /* addrs of l and r data */
r = ADATA (rside);
n = lside->size - lside->offset; /* number of bytes to swap */
while (--n >= 0) { /* swap contents */
c = *l;
*l++ = *r;
*r++ = c;
}
return lside; /* return left side address */
}
/*
* Implement a clone operation by making duplicates beyond
* the first and incrementing the store address.
*/
Ptr
sr_clone (locn, addr, len, n)
char *locn;
Ptr addr;
int len, n;
{
Ptr new = addr;
if (n < 0)
sr_runerr (locn, E_AREP, n);
if (n == 0)
return new;
while (--n > 0)
memcpy (new += len, addr, len);
return new + len;
}
/*
* sr_slice (locn, a1, a2, elemsize, nbounds, lb1, ub1, ...)
*
* Extract or store into an array slice, handling multidimensional slicing.
* If a1 is zero, allocate and return a slice of a2.
* If a1 is nonzero, scatter a1 into a slice of a2.
*
* a1 is always the contiguous array; a2 is always the sliced array.
* nbounds is the number of (lb,ub) index pairs that follow.
* A ub value of SINGLEINDEX indicates a singly-indexed dimension of a2 only.
*
* Build an array of "slcinfo" structs and then call slices() to do the
* actual work; it recurses to handle multiple dimensions.
*/
struct slcinfo {
int n; /* number of elements in this dimension */
int d1; /* address incr in contigouous array (0 in last dim) */
int d2; /* address incr in array being sliced */
};
Ptr
sr_slice (char *locn, Array *a1, Array *a2, int elemsize, int nbounds, ...)
{
va_list ap;
int adim, lb[MAX_DIMENS], ub[MAX_DIMENS]; /* array dims*/
int nelem, telem, offset, scatter;
int i, j, k, l, u, z, o;
struct slcinfo s[MAX_DIMENS+1];
sr_check_stk (CUR_STACK);
/* get fixed arguments */
va_start (ap, nbounds);
if (elemsize == 0)
elemsize = STRIDE (a2, 0);
/* get index arguments */
telem = 1; /* total element count */
adim = 0; /* dimensionality of a1 */
offset = 0; /* offset into a2 */
for (i = 0; i < nbounds; i++) { /* for each dimension of a2 */
j = a2->ndim - i - 1;
l = va_arg (ap, int); /* get index bounds */
u = va_arg (ap, int);
if (l == ASTERISK) /* translate '*' into actual value */
l = LB (a2, j);
if (u == ASTERISK)
u = UB (a2, j);
o = l - LB (a2, j); /* get a zero-based index */
z = STRIDE (a2, j); /* element size of this dimension */
offset += z * o; /* adjust offset to first element */
if (u == SINGLEINDEX) {
if (o < 0 || l > UB (a2, j))
sr_runerr (locn, E_ASUB, l, & ADIM (a2, j));
} else {
/* this dimension is truly sliced */
nelem = u - l + 1; /* number of slice elements */
telem *= nelem; /* calc total elements */
if (o < 0 || nelem < 0 || u > UB (a2, j))
sr_runerr (locn, E_ASLC, l, u, & ADIM (a2, j));
if (a1 != NULL) {
k = a1->ndim - adim - 1;
if (UB (a1, k) - LB (a1, k) + 1 != nelem)
sr_runerr (locn, E_ACHG, l, u, & ADIM (a1, k));
}
lb[adim] = 1; /* save bounds for a1 */
ub[adim] = u - l + 1;
s[adim].n = nelem;
s[adim].d2 = z; /* size of element in a2 */
adim++; /* count the dimensions */
}
}
va_end (ap);
/* if loading into new array, need to allocate it */
scatter = (a1 != NULL);
if (!scatter)
a1 = sr_init_array (locn, (Array*) 0, elemsize, (Ptr) 0, -adim, lb, ub);
for (i = 0; i < adim; i++) /* calculate step sizes for a1 */
s[i].d1 = STRIDE (a1, adim - i - 1);
if (telem > 0) /* if no zero dimensions, copy elems */
slices (adim, ADATA (a1), ADATA (a2) + offset, s, scatter);
return (Ptr) a1; /* always return contiguous array */
}
/*
* slices (lv, p1, p2, s, scatter) -- copy slice data
*
* lv is the number of nesting levels
* p1, p2 are data pointers
* s is array of slice info (see above)
* scatter indicates direction of copy (nonzero for p1->p2)
*
* Copy s->n slice elements, recursing as needed for deeper levels.
*/
static void
slices (lv, p1, p2, s, scatter)
int lv;
Ptr p1, p2;
struct slcinfo *s;
int scatter;
{
int n, d1, d2;
n = s->n;
d1 = s->d1;
d2 = s->d2;
while (--n >= 0) {
if (lv > 1)
slices (lv - 1, p1, p2, s + 1, scatter);
else {
if (scatter)
memcpy (p2, p1, d1);
else
memcpy (p1, p2, d1);
}
p1 += d1;
p2 += d2;
}
}
/*
* Copy an array of strings, elementwise if necessary, into a slice
* (or the whole thing) of another string array. The maxlengths of
* the strings in the two arrays may differ.
*/
Array *
sr_strarr (locn, dest, lb, ub, src)
char *locn;
Array *dest;
int lb, ub;
Array *src;
{
int ndst, nsrc, i, nelem, maxl;
String *pdst, *psrc;
if (lb == ASTERISK)
lb = LB (dest, 0);
if (ub == ASTERISK)
ub = UB (dest, 0);
nelem = ub - lb + 1;
if (nelem < 0 || lb < LB (dest, 0) || ub > UB (dest, 0))
sr_runerr (locn, E_ASLC, lb, ub, dest);
if (UB (src, 0) - LB (src, 0) + 1 != nelem)
sr_runerr (locn, E_ACHG, lb, ub, src);
if (nelem == 0)
return dest; /* empty arrays */
psrc = (String *) ADATA (src); /* pointer to source element */
pdst = (String *) ADATA (dest); /* pointer to dest element */
nsrc = SRALIGN (psrc->size); /* distance between source elements */
ndst = SRALIGN (pdst->size); /* distance between dest elements */
pdst = (String *) ((Ptr) pdst + (lb - LB (dest, 0)) * ndst);
/* pointer to first destination strg */
if (psrc->size == pdst->size) { /* if maxlengths are the same */
/* block copy */
memcpy ((Ptr) pdst, (Ptr) psrc, nelem * ndst);
} else {
/* elementwise assignment */
maxl = MAXLENGTH (pdst); /* maxlength of dest element */
for (i = 0; i < nelem; i++) {
if (psrc->length > maxl)
sr_runerr (locn, E_SELM, LB (src, 0) + i, psrc->length, maxl);
memcpy (DATA (pdst), DATA (psrc), (pdst->length = psrc->length));
pdst = (String *) ((Ptr) pdst + ndst);
psrc = (String *) ((Ptr) psrc + nsrc);
}
}
return dest;
}
/*
* Allocate and initialize a string as a copy of a char array.
*/
Ptr
sr_astring (a)
Array *a;
{
String *s;
int n;
n = UB (a, 0) - LB (a, 0) + 1;
s = (String *) sr_alc (n + STRING_OVH, 1);
s->size = n + STRING_OVH;
s->length = n;
memcpy (DATA (s), ADATA (a), n);
return (Ptr) s;
}
/*
* Allocate and extract a string slice.
*/
Ptr
sr_sslice (locn, s, index1, index2)
char *locn;
String *s;
int index1, index2;
{
int nchars, nbytes;
String *r;
if (index1 == ASTERISK)
index1 = 1;
if (index2 == ASTERISK)
index2 = s->length;
nchars = index2 - index1 + 1;
if (nchars < 0 || index1 < 1 || index2 > s->length)
sr_runerr (locn, E_SSLC, index1, index2, s, s);
nbytes = nchars + STRING_OVH;
r = (String *) sr_alc (nbytes, 1);
r->size = nbytes;
r->length = nchars;
memcpy (DATA (r), DATA (s) + index1 - 1, nchars);
return (Ptr) r;
}
/*
* Change a string slice.
*/
String *
sr_chgstr (locn, s, index1, index2, v)
char *locn;
String *s;
int index1, index2;
String *v;
{
int nchars;
if (index1 == ASTERISK)
index1 = 1;
if (index2 == ASTERISK)
index2 = s->length;
nchars = index2 - index1 + 1;
if (nchars < 0 || index1 < 1 || index2 > s->length)
sr_runerr (locn, E_SSLC, index1, index2, s, s);
if (nchars != v->length)
sr_runerr (locn, E_SCHG, v, index1, index2);
memcpy (DATA (s) + index1 - 1, DATA (v), nchars);
return v;
}
|
C
|
/*
* Revision Control Information
*
* $Source: /users/pchong/CVS/sis/sis/pld/act_remove.c,v $
* $Author: pchong $
* $Revision: 1.1.1.1 $
* $Date: 2004/02/07 10:14:55 $
*
*/
#include "sis.h"
#include "pld_int.h"
/* free up ACTs
*/
int
p_actRemove(network, argc, argv)
network_t **network;
int argc;
char **argv;
{
int i, c, locality, input_size;
array_t *node_vec;
node_t *current_node;
locality = 0; /* default GLOBAL */
util_getopt_reset();
while((c = util_getopt(argc, argv, "lg"))!=EOF) {
switch(c) {
case 'l' : locality = 1; break;
case 'g' : locality = 0; break;
default: goto usage;
}
}
node_vec = com_get_nodes(*network, argc-util_optind+1, argv+util_optind-1);
input_size = array_n(node_vec);
for(i = 0; i<input_size; i++){
current_node = array_fetch(node_t *, node_vec, i);
p_actDestroy(&(ACT_SET(current_node)->act_num[locality]),
locality);
ACT_SET(current_node)->act_num[locality] = NIL (ACT_ENTRY);
}
array_free(node_vec);
return(0); /* ok exit */
usage:
(void) fprintf(siserr, "usage: act_remove [-l] [-g] nodelist\n -l local\n -g global\n");
return(1); /* error exit */
}
/* ARGSUSED */
void
p_actDestroy(act_set_entry_ptr, locality)
ACT_ENTRY_PTR *act_set_entry_ptr;
int locality;
{
ACT_ENTRY_PTR act_set_entry;
if (*act_set_entry_ptr == NULL) return;
act_set_entry = *act_set_entry_ptr;
if(act_set_entry!=NIL (ACT_ENTRY)){
if (act_set_entry->act->root != NIL (ACT_VERTEX))
p_dagDestroy(act_set_entry->act->root);
if ((act_set_entry->act->node_list != NIL (array_t)) && locality)
array_free(act_set_entry->act->node_list);
FREE(act_set_entry->act->node_name);
FREE(act_set_entry->act);
FREE(act_set_entry);
}
}
void
p_dagDestroy(dag)
ACT_VERTEX_PTR dag;
{
int num_var, i, j, list_size;
array_t *current_list;
ACT_VERTEX_PTR u;
if(dag != NIL (ACT_VERTEX)){
index_list_array = array_alloc(array_t *, 0);
num_var = dag->index_size;
for(i = 0; i <= num_var; i++){
current_list = array_alloc(ACT_VERTEX_PTR, 0);
array_insert(array_t *, index_list_array, i,
current_list);
}
traverse(dag, p_addLists);
for(i = num_var; i>=0; i--){
current_list = array_fetch(array_t *, index_list_array,
i);
list_size = array_n(current_list);
for(j = 0; j<list_size; j++){
u = array_fetch(ACT_VERTEX_PTR, current_list, j);
FREE(u);
}
array_free(current_list);
}
array_free(index_list_array);
}
}
|
C
|
#ifndef HKL_STRING_H
#define HKL_STRING_H
#include <stdint.h>
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
/**
@struct HklString A utf8-based string implementation.
Since utf-8 internally can use anywhere between 1 and 4 bytes per character
HklString acts as a wrapper for utf-8 data.
@authors Scott LaVigne
@date 9/7/2012
*/
typedef struct HklString
{
char* utf8_data;
size_t size;
size_t length;
size_t hash;
} HklString;
/**
Allocate a new HklString.
@retval HklString* A new HklString.
@brief Allocates a new empty HklString.
*/
HklString* hkl_string_new();
/**
Allocate a copy of another HklString.
@param string The string to make a copy of.
@retval HklString* A newly allocated copy of string.
*/
HklString* hkl_string_new_from_string(const HklString* string);
/**
Allocate a string representation of an integer.
@param integer The integer value to copy.
@retval HklString* A newly allocated string.
*/
HklString* hkl_string_new_from_integer(int integer);
/**
Allocate a string representation of a real number.
@param real The real value to copy.
@retval HklString* A newly allocated string.
*/
HklString* hkl_string_new_from_real(double real);
HklString* hkl_string_new_from_stream(FILE* stream);
/**
Allocate a new HklString using utf8 data.
@param utf8_data The null-terminated utf8 data to copy into the HklString.
@retval HklString* A new HklString.
@brief Allocates a new HklString, with an internal copy of a utf8 string.
*/
HklString* hkl_string_new_from_utf8(const char* utf8_data);
/**
Sets the utf8 data inside a HklString.
@param string The HklString to modify.
@param utf8_data The null-terminated utf8 data to copy into the HklString.
@brief Modifies string with a copy of a utf8 string.
*/
void hkl_string_set_utf8(HklString* string, const char* utf8_data);
/**
Concatinate a HklString.
@param string The HklString to add data to.
@param src The HklString to append.
@brief The string is modified in-place only reallocating internal data if needed.
*/
void hkl_string_cat(HklString* string, const HklString* src);
/**
Concatinate a HklString with utf8 data.
@param string The HklString to add data to.
@param utf8_data The null-terminated utf8 string to append.
@brief The string is modified in-place only reallocating internal data if needed.
*/
void hkl_string_cat_utf8(HklString* string, const char* utf8_data);
/**
Turns a HklString into an exact copy of another.
@param string The HklString to modify.
@param src The HklString to copy.
*/
void hkl_string_copy(HklString* string, const HklString* src);
/**
Compares two HklStrings.
@param string1 A HklString object.
@param string2 A second HklString object to compare with.
@retval int -1 If string1<string2 0 If string1==string2 1 If string1>string2
*/
int hkl_string_compare(const HklString* string1, const HklString* string2);
/**
Compares a HklString with utf8 data.
@param string A HklString object.
@param utf8_data A null-terminated utf8 string to compare.
@retval int -1 If string<utf8 0 If string==utf8 1 If string>utf8
*/
int hkl_string_compare_utf8(HklString* string, const char* utf8_data);
/**
Erase the contents of a HklString
@post The internal utf8 data is freed.
@param string The HklString to clear.
*/
void hkl_string_clear(HklString* string);
/**
Get the raw utf8_data within a HklString
@param string The HklString object.
@retval uint8_t* A pointer to the utf8 data within the string
*/
const char* hkl_string_get_utf8(HklString* string);
/**
Get the number of utf8 bytes in a HklString.
This does not include the null byte.
@param string The HklString object.
@retval size_t The number of bytes in the string.
*/
size_t hkl_string_get_size(const HklString* string);
/**
Get the number of characters in the HklString.
This does not include the null character.
@param string The HklString object.
@retval size_t The number of characters in the string.
*/
size_t hkl_string_get_length(const HklString* string);
/**
Free a HklString and releases any allocated resources it has.
@param string The HklString to free.
*/
void hkl_string_free(HklString* string);
#endif // HKL_STRING_H
|
C
|
/*************************************************************************
> File Name: queue_test.c
> Created Time: 2014年05月06日 星期二 13时21分12秒
************************************************************************/
#include <stdio.h>
#include "queue.h"
#include <assert.h>
int main(void)
{
int s[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9
};
struct queue *queue = (struct queue *)malloc(sizeof(*queue));
assert(queue != NULL);
queue_init(queue);
int i = 0;
for(; i < sizeof(s) / sizeof(s[0]); i++) {
queue->push(queue, s+i, sizeof(s[0]));
}
int ret = 0;
while(1) {
if (queue->pop(queue, &ret, sizeof(ret)) < 0) {
printf("end.\n");
break;
}
printf("%d ", ret);
}
queue_destroy(queue);
free(queue);
return 0;
}
|
C
|
#include <stdio.h>
void arraySort(int array[], int size) {
for ( int sorted = 0; sorted == 0; ) {
sorted = 1;
for ( int i = 0, j = 1; j < size; i++, j++ ) {
int current = array[i];
int next = array[j];
if ( current > next ) {
array[j] = current;
array[i] = next;
sorted = 0;
}
}
}
}
int main() {
int size = 10;
int array[] = {4, 3, 2, 1, 0, -1, -2, -3, -4, -5, '\0'};
int last = size - 1;
arraySort(array, size);
printf("{");
for ( int i = 0; i < last; i++ ) {
printf("%d, ", array[i]);
}
printf("%d}", array[last]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
inline void fastRead(int *a)
{
register char c=0;
while (c<33) c=getchar_unlocked();
*a=0;
while (c>33)
{
*a=*a*10+c-'0';
c=getchar_unlocked();
}
}
inline void fastWrite(int a)
{
char snum[20];
int i=0;
do
{
snum[i++]=a%10+48;
a=a/10;
}while(a!=0);
i=i-1;
while(i>=0)
putchar_unlocked(snum[i--]);
putchar_unlocked('\n');
}
int prime[2001]={0};
int chkprime(int n)
{
int i;
for(i=2;i<=n/2;i++)
if(n%i==0)
return -1;
return 1;
}
int genprime(int n)
{
while(prime[n]==0)
{
prime[n]=chkprime(n);
if(prime[n]==1)
return n;
n++;
}
while(prime[n]!=1)
n++;
return n;
}
int main()
{
int t;
int a,b;
int sum;
scanf("%d",&t);
while(t--)
{
//scanf("%d%d",&a,&b);
fastRead(&a);
fastRead(&b);
sum=a+b;
//printf("%d\n",genprime(sum+1)-sum);
fastWrite(genprime(sum+1)-sum);
}
return 0;
}
|
C
|
#include <stdio.h>
/* My solution to exercise 2, chapter 2 from "Vägen till C".
* Write a program to calculate how many km a car has been driven during a year
* a much fuel it consumes on avererage
*/
int main()
{
float km_today, km_lastyear, fuel;
printf("Odometer last year: ");
scanf("%f", &km_lastyear);
printf("Odometer today: ");
scanf("%f", &km_today);
printf("Total fuel consumed during the year: ");
scanf("%f", &fuel);
printf("\nTotal distance driven: %.1f\n", km_today-km_lastyear);
printf("Average fuel consumption: %.2f\n", fuel/(km_today-km_lastyear));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* set.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: juloo <juloo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/04/19 11:34:10 by juloo #+# #+# */
/* Updated: 2016/05/09 18:52:21 by jaguillo ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SET_H
# define SET_H
# include "ft/libft.h"
typedef struct s_set t_set;
typedef struct s_set_h t_set_h;
/*
** ========================================================================== **
** Set
*/
/*
** set object
** 'cmp' is used for comparing keys, take an element and the key to compare
** 'count' store the total element count
** 'flags':
** SET_ALLOW_DUP allow dupplicated keys on insert
** -
** SET(CMP, FLAGS) construct a set object
*/
struct s_set
{
void *data;
int (*cmp)(void const *element, void const *key);
uint32_t count;
uint32_t flags;
};
/*
** set element header
** -
** SET_HEAD() construct an element header
** -
** element's data have to be prefixed with the t_rb_node header
*/
struct s_set_h
{
void const *const data[3];
};
# define SET(CMP, FLAGS) ((t_set){NULL, V(CMP), 0, (FLAGS)})
# define SET_HEAD() ((t_set_h){{NULL, NULL, NULL}})
# define SET_ALLOW_DUP (1 << 1)
/*
** Search into the set
** 'key' is passed to the cmp function
** Return the matching element or NULL if not found
** If SET_ALLOW_DUP is set, see ft_set_first
*/
void *ft_set_get(t_set *set, void const *key);
void const *ft_set_cget(t_set const *set, void const *key);
/*
** Insert an element into the set
** 'key' is only used for comparaison
** Return true on success
** Return false on dupplicated key (if SET_ALLOW_DUP flag is not set)
*/
bool ft_set_insert(t_set *set, void *element, void const *key);
/*
** Remove an element
** 'element' have to be an element of 'set'
*/
void ft_set_remove(t_set *set, void *element);
/*
** Return the first/last element in sorted order
** If 'key' is not NULL, return the first/last element that match the key
** Return NULL if the set is empty
*/
void *ft_set_first(t_set *set, void const *key);
void const *ft_set_cfirst(t_set const *set, void const *key);
void *ft_set_last(t_set *set, void const *key);
void const *ft_set_clast(t_set const *set, void const *key);
/*
** Return the prev/next element in sorted order
** Return NULL after the last element
*/
void *ft_set_next(void *element);
void const *ft_set_cnext(void const *element);
void *ft_set_prev(void *element);
void const *ft_set_cprev(void const *element);
#endif
|
C
|
/**
* deadlock_demolition
* CS 241 - Fall 2020
*/
#include "graph.h"
#include "libdrm.h"
#include "set.h"
#include <pthread.h>
struct drm_t {
pthread_mutex_t mutex;
};
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
graph* graph_ = NULL;
set* visited_nodes_ = NULL;
// bool has_cycle(void* node) {
// if (visited_nodes_ == NULL) {
// visited_nodes_ = shallow_set_create();
// }
// if (set_contains(visited_nodes_, node)) {
// visited_nodes_ = NULL;
// return true;
// } else {
// set_add(visited_nodes_, node);
// vector* neighbor_nodes = graph_neighbors(graph_, node);
// for (size_t i = 0; i < vector_size(neighbor_nodes); i++) {
// if (has_cycle(vector_get(neighbor_nodes, i))) {
// return true;
// }
// }
// }
// visited_nodes_ = NULL;
// return false;
// }
/**
* Checks for a cycle in the resource allocations graph
**/
bool has_cycle(void* node) {
if (!visited_nodes_) {
visited_nodes_ = shallow_set_create();
}
if (set_contains(visited_nodes_, node)) {
return 1;
}
else {
set_add(visited_nodes_, node);
vector *neighbors = graph_neighbors(graph_, node);
for (size_t i = 0; i < vector_size(neighbors); i++) {
if (has_cycle(vector_get(neighbors, i))) {
return 1;
}
}
}
free(visited_nodes_);
visited_nodes_ = NULL;
return 0;
}
drm_t *drm_init() {
// create resource allocations graph
if (!graph_) {
graph_ = shallow_graph_create();
}
drm_t *d = malloc(sizeof(drm_t));
pthread_mutex_init(&(d->mutex), NULL);
pthread_mutex_lock(&lock);
graph_add_vertex(graph_, d);
pthread_mutex_unlock(&lock);
return d;
}
/**
* UNLOCK
* @return :
* 0 if the specified thread is not able to unlock the given drm.
* 1 if the specified thread is able to unlock the given drm.
**/
int drm_post(drm_t *drm, pthread_t *thread_id) {
pthread_mutex_lock(&lock);
if( !graph_contains_vertex(graph_, drm) || !graph_contains_vertex(graph_, thread_id)) {
pthread_mutex_unlock(&lock);
return 0;
}
if (graph_adjacent(graph_, drm, thread_id)) {
// Remove the appropriate edge from your Resource Allocation Graph.
graph_remove_edge(graph_, drm, thread_id);
pthread_mutex_unlock(&(drm->mutex));
}
pthread_mutex_unlock(&lock);
return 1;
}
/**
* LOCK
* @return :
* 0 if attempting to lock this drm with the specified thread would cause
* deadlock - happens if:
* - a thread trying to lock a mutex it already owns
* - if the newly added edge creates a cycle in the Resource Allocation Graph
* 1 if the drm can be locked by the specified thread.
*/
int drm_wait(drm_t *drm, pthread_t *thread_id) {
pthread_mutex_lock(&lock);
if (!graph_contains_vertex(graph_, thread_id)) graph_add_vertex(graph_, thread_id);
if (graph_adjacent(graph_, drm, thread_id)) {
pthread_mutex_unlock(&lock);
return 0;
}
// create the appropriate edge in your Resource Allocation Graph
graph_add_edge(graph_, thread_id, drm);
// if it creates a cycle, remove the edge and return 0
if (has_cycle(thread_id)) {
graph_remove_edge(graph_, thread_id, drm);
pthread_mutex_unlock(&lock);
return 0;
} else {
pthread_mutex_unlock(&lock);
pthread_mutex_lock(&(drm->mutex));
pthread_mutex_lock(&lock);
graph_remove_edge(graph_, thread_id, drm);
graph_add_edge(graph_, drm, thread_id);
pthread_mutex_unlock(&lock);
return 1;
}
return 0;
}
void drm_destroy(drm_t *drm) {
pthread_mutex_destroy(&lock);
pthread_mutex_destroy(&drm->mutex);
graph_remove_vertex(graph_, drm);
free(drm);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aihya <aihya@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/05 23:15:26 by aihya #+# #+# */
/* Updated: 2019/12/31 18:25:13 by aihya ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIBFT_H
# define LIBFT_H
# include <string.h>
# include <stdlib.h>
# include <unistd.h>
# define BUFF_SIZE 256
# define BEGINING 0
# define LAST_POS -1
typedef struct s_node
{
char *content;
struct s_node *next;
} t_node;
typedef struct s_list
{
void *content;
size_t content_size;
struct s_list *next;
} t_list;
typedef struct s_lst
{
char *cut;
int fd;
struct s_lst *next;
} t_lst;
size_t ft_char_count(char* str, char c);
int ft_strisempty(char *str);
char *ft_strappend(char **a_s1, char c, int overwrite);
int ft_isalphanumeric(char c);
void ft_print_chain(char ***a_chain, char *del);
char **ft_strsplit_del(char *str, char *del);
char *ft_next_word(char *str, char *del, int reset_val);
size_t ft_count_words(const char *str, const char *del);
int ft_strcount(char **s);
size_t ft_wordlen(const char *s, char c);
int ft_words(char const *s, char c);
int ft_abs(int n);
int ft_atoi(const char *str);
void ft_putendl_fd(char const *s, int fd);
void ft_putendl(char const *s);
char *ft_strjoin(char const *s1, char const *s2);
char *ft_strojoin(char **s1, char *s2, int overwrite);
char *ft_strtrim(char const *s);
char *ft_strrev(char const *s);
char *ft_strstr(const char *haystack, const char *needle);
int ft_strisnum(const char *str);
char **ft_new_chain(char **base);
char **ft_sort_chain(char **chain, int direction);
void ft_chain_push(char ***a_chain, char *entry);
size_t ft_chain_size(char **chain);
char **ft_chain_cpy(char **chain);
void ft_chain_free(char ***a_chain);
void *ft_memcpy(void *dst, const void *src, size_t n);
void *ft_memccpy(void *dst, const void *src, int c, size_t n);
int ft_memcmp(const void *s1, const void *s2, size_t n);
void *ft_memmove(void *dst, const void *src, size_t len);
void *ft_memchr(const void *s, int c, size_t n);
char *ft_strcat(char *s1, const char *s2);
char *ft_strncat(char *s1, const char *s2, size_t n);
size_t ft_strlcat(char *dst, const char *src, size_t size);
size_t ft_strlen(const char *s);
int ft_isalnum(int c);
int ft_isalpha(int c);
int ft_isascii(int c);
int ft_isdigit(int c);
int ft_isprint(int c);
int ft_intlen(int n);
char *ft_strchr(const char *s, int c);
char *ft_strrchr(const char *s, int c);
int ft_strcmp(const char *s1, const char *s2);
int ft_strncmp(const char *s1, const char *s2, size_t n);
int ft_toupper(int c);
int ft_tolower(int c);
char *ft_strdup(const char *s1);
char *ft_strcpy(char *dst, const char *src);
char *ft_strncpy(char *dst, const char *src, size_t len);
void ft_putchar(char c);
void ft_putstr(char const *s);
void *ft_memset(void *b, int c, size_t len);
void ft_bzero(void *s, size_t n);
char *ft_itoa(int n);
char *ft_itoa_base(long long value, int base);
char *ft_strnstr(const char *haystack, const char *needle,
size_t len);
void *ft_memalloc(size_t size);
void ft_memdel(void **ap);
char *ft_strnew(size_t size);
char *ft_ctos(const char c);
void ft_strdel(char **as);
void ft_strclr(char *s);
void ft_striter(char *s, void (*f)(char *));
void ft_striteri(char *s, void (*f)(unsigned int, char *));
char *ft_strmap(char const *s, char (*f)(char));
char *ft_strmapi(char const *s, char (*f)(unsigned int, char));
int ft_strequ(char const *s1, char const *s2);
int ft_strnequ(char const *s1, char const *s2, size_t n);
char *ft_strsub(char const *s, unsigned int start, size_t len);
void ft_putchar_fd(char c, int fd);
void ft_putstr_fd(char const *c, int fd);
void ft_putnbr(int n);
void ft_putnbr_fd(int n, int fd);
char *ft_strsjoin(const char *s1, const char *s2, const char *dl);
int ft_begins_with(const char *haystack, const char *needle);
char **ft_strsplit(char const *s, char c);
size_t ft_strmax(char **arr);
size_t ft_strmin(char **arr);
#endif
|
C
|
#include <stdlib.h>
#include "util.h"
#include "wayland.h"
#include "window.h"
struct wl_connection *
wayland_init()
{
debug("Connecting to Wayland");
struct wl_connection *conn = malloc(sizeof(struct wl_connection));
if (!conn)
die("Failed to allocate connection struct");
debug("Creating display");
conn->display = wl_display_create();
if (!conn->display)
die("Failed to create a Wayland display");
debug("Adding socket");
if (wl_display_add_socket(conn->display, NULL) != 0)
die("Failed to add a socket to the Wayland connection");
debug("Initializing swc");
if (!swc_initialize(conn->display, NULL, &manager))
die("Failed to initialize swc");
return conn;
}
void
wayland_run(struct wl_connection *conn)
{
debug("Getting event loop");
conn->event_loop = wl_display_get_event_loop(conn->display);
debug("Starting Wayland display");
wl_display_run(conn->display);
}
void
wayland_exit(struct wl_connection *conn)
{
debug("Terminating Wayland display");
wl_display_terminate(conn->display);
debug("Destroying Wayland display");
wl_display_destroy(conn->display);
}
|
C
|
/*
* https://www.spoj.com/problems/NSTEPS/
*/
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x,y,r,t;
scanf("%d", &t);
while(t--)
{
scanf("%d %d", &x, &y);
if(x==y)
{
if(x%2==0)
r=2*x;
else
r=2*x-1;
printf("%d\n", r);
}
else if(x==y+2)
{
if(x%2==0)
r=x+y;
else
r=x+y-1;
printf("%d\n", r);
}
else
printf("No Number\n");
}
}
|
C
|
#include "request.h"
#include <fcgi_stdio.h>
#include <string.h>
#include <stdlib.h>
#include "scythe/response.h"
#include "scythe/routes.h"
struct param {
char name[32];
char value[256];
struct param* next;
};
static struct param* head_cookie;
static struct param* head_param;
void process_request() {
set_cookies();
route_request();
free_params();
}
void set_cookies() {
char* ptr = getenv("HTTP_COOKIE");
char* term;
struct param* new_cookie;
int len;
if(ptr == NULL) {
return;
}
while(*ptr != '\0') {
new_cookie = (struct param*)malloc(sizeof(struct param));
// copy name portion into struct
term = strchr(ptr, '=');
len = term - ptr;
// prevent buffer overflow attack
if(len < 32) {
strncpy(new_cookie->name, ptr, len);
new_cookie->name[len] = '\0';
}
ptr = term + 1;
// copy value portion into struct
term = strchr(ptr, ';');
if(term == NULL) {
term = strchr(ptr, '\0');
}
len = term - ptr;
// prevent buffer overflow attack
if(len < 256) {
strncpy(new_cookie->value, ptr, len);
new_cookie->value[len] = '\0';
}
ptr = term;
if(new_cookie->name == NULL || new_cookie->value == NULL) {
// free if it failed buffer overflow checks
free(new_cookie);
}
else {
// add new cookie to linked list
new_cookie->next = head_cookie;
head_cookie = new_cookie;
}
// skip over delimiter and whitespace
if(*ptr == ';') {
ptr++;
}
while(*ptr == ' ') {
ptr++;
}
}
}
char* cookie(char* name) {
struct param* c = head_cookie;
while(c != NULL) {
if(strcmp(c->name, name) == 0) {
return c->value;
}
c = c->next;
}
return NULL;
}
void route_request() {
char* uri = getenv("REQUEST_URI");
struct route* route = determine_route(uri);
if(route != NULL) {
set_params_for_route(route, uri);
(*route->action)();
}
else {
print_404();
}
}
int set_param(char* name, char* value) {
struct param* new_param;
if(param(name) != NULL) {
return -1;
}
else {
// prevent buffer overflow attack
if(strlen(name) < 32 && strlen(value) < 256) {
new_param = (struct param*)malloc(sizeof(struct param));
strcpy(new_param->name, name);
strcpy(new_param->value, value);
new_param->next = head_param;
head_param = new_param;
return 0;
}
else {
return -2;
}
}
}
char* param(char* name) {
struct param* p = head_param;
while(p != NULL) {
if(strcmp(p->name, name) == 0) {
return p->value;
}
p = p->next;
}
return NULL;
}
void free_params() {
struct param* p = head_param;
struct param* oldp;
while(p != NULL) {
oldp = p;
p = p->next;
free(oldp);
}
p = head_cookie;
while(p != NULL) {
oldp = p;
p = p->next;
free(oldp);
}
head_param = NULL;
}
|
C
|
#pragma once
typedef struct darray{
int len;
int elem_size;
int allocsize;
void *elements;
}darray_t;
#define darray_len(darray) (darray)->len
#define darray_create(element_type) \
__darray_create(sizeof(element_type))
darray_t *__darray_create(int elem_size);
#define darray_append(darray, type, element) \
darray_add(darray, type, element, (darray)->len)
#define darray_add(darray, type, element, index) \
do{ \
if(((index+1) * (darray)->elem_size ) > (darray)->allocsize){\
(darray)->allocsize *= 2; \
(darray)->elements = realloc((darray)->elements, \
(darray)->allocsize * (darray)->elem_size); \
} \
((type*)(darray)->elements)[index] = element; \
(darray)->len++; \
}while(0);
#define darray_rm(darray, type, index) \
((type*)(darray)->elements)[index] = ((type*)(darray)->elements)[(darray)->len]; \
(darray)->len--;
#define darray_get(darray, type, index) \
((type*)(darray)->elements)[index]
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <mqueue.h>
int main ()
{
pid_t pid;
pid = fork ();
struct mq_attr attr;
attr.mq_msgsize = 100;
attr.mq_maxmsg = 5;
char buff[attr.mq_msgsize];
mqd_t mq_fd = mq_open ("/CREAT", O_CREAT | O_RDWR, 0666, &attr );
if (mq_fd == -1) {
printf ("Cannot create queue \n");
} else {
printf ("Queue created \n");
}
if (pid > 0) {
printf ("Parent process \n");
int fd = open ("file.txt", O_RDONLY);
if (fd == -1) {
printf ("Cannot open \n");
} else {
int num = read (fd, buff, 100);
if (mq_send (mq_fd, buff, num , 0)) {
printf ("Cannot send \n");
} else {
printf ("Sent \n");
}
}
wait (NULL);
} else if (pid == 0) {
printf ("Child process \n");
int fd = open ("output.txt", O_CREAT | O_RDWR, 0666);
if (fd == -1) {
printf ("cannot create \n");
} else {
char buff [attr.mq_msgsize];
int n = mq_receive (mq_fd, buff, attr.mq_msgsize, 0);
printf ("%s \n", buff);
n = write (fd, buff, n);
if (n == -1) {
printf ("cannot write \n");
} else {
printf ("write success \n");
}
}
} else {
printf ("no child \n");
}
return 0;
}
|
C
|
#include <stdio.h>
#define LOWER 0 /* lower limit */
#define UPPER 300 /* upper limit */
#define STEP 20 /* step size */
float f_to_c(int fahr);
/* Rewrite the temperature conversion program to use a function for conversion */
int main(void)
{
int fahr;
float celsius;
printf("Fahr Celsius\n");
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) {
celsius = f_to_c(fahr);
printf("%4d %6.1f\n", fahr, celsius);
}
}
float f_to_c(int fahr)
{
float c;
c = (5.0/9.0) * (fahr - 32);
return c;
}
|
C
|
#include <stdio.h>
#define SIZE 100
/*Main function starts*/
int main() {
/*Variable declarations*/
int i, j, n, index = 0, array[SIZE];
static int freq[SIZE][2];
printf("Please enter the number of elements: ");
scanf("%d", &n);
/*Read array*/
for (i = 0; i < n; i++) {
printf("\nPlease enter %d -th element: ", i+1);
scanf("%d", &array[i]);
}
for (i = 0; i < n; i++) {
j = 0;
while((j <= index) && (array[i] != freq[j][0]))
++j;
if (j > index) {
freq[index][0] = array[i];
freq[index][1]++;
++index;
} else {
freq[j][1]++;
}
}
for(i = 0; i < index; i++)
printf("\nNumber of %d:\t%d", freq[i][0], freq[i][1]);
return 0;
}
|
C
|
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
typedef char datatype;
typedef struct node
{
int weight;
datatype data;
int lchild,rchild,parent;
}hufmtree;
#define EPS 1e-5
int Counter(hufmtree tree[],hufmtree single,int deep){
static int num;
if(single.lchild == -1 && single.rchild == -1){
num += deep * single.weight;
}else{
Counter(tree,tree[single.lchild],deep+1);
Counter(tree,tree[single.rchild],deep+1);
}
return num;
}
void Create(int num){
int N,M;
int i,j,p1,p2;
int ch;
int small1,small2;
N = num;
M = num*2 - 1;
hufmtree tree[M];
for(i=0;i<M;i++){
tree[i].parent = -1;
tree[i].lchild = -1;
tree[i].rchild = -1;
tree[i].weight = 0;
tree[i].data = '0';
}
for(i=0;i<N;i++){
scanf("%d",&ch);
tree[i].weight = ch;
}
for(i=N;i<M;i++){
p1 = p2 = 0;
small1 = small2 = 10000;
for(j=0;j<i;j++){
if(tree[j].parent == -1){
if(tree[j].weight - small1 < EPS){
small2 = small1;
small1 = tree[j].weight;
p2 = p1;
p1 = j;
}else if(tree[j].weight - small2 < EPS){
small2 = tree[j].weight;
p2 = j;
}
}
}
tree[p1].parent = i;
tree[p2].parent = i;
tree[i].lchild = p1;
tree[i].rchild = p2;
tree[i].parent = -1;
tree[i].weight = tree[p1].weight + tree[p2].weight;
}
// for(j=0;j<M;j++){
// printf("%d ",tree[j].weight);
// }
int result;
result = Counter(tree,tree[M-1],0);
printf("%d\n",result);
}
int main(int argc, char const *argv[])
{
int num;
scanf("%d",&num);
Create(num);
return 0;
}
|
C
|
/**
* @file udp.h This file contains function definitions related to the UDP
* protocol.
*/
#ifndef UDPIPStack_udp_h
#define UDPIPStack_udp_h
#include "common.h"
#include "ip.h"
#include <stddef.h>
#include <stdint.h>
#define UDP_HEADER_LEN 8
#define UDP_DATAGRAM_MAX_LEN 65507
#define UDP_DATA_MAX_LEN (UDP_DATAGRAM_MAX_LEN - UDP_HEADER_LEN)
/**
* Sends data through the network using the UDP protocol.
* @param session The session object created by net_init().
* @param dst_ip The destination IP address for the data.
* @param dst_port The destination port for the data.
* @param data The data to be sent.
* @param data_len The length of data.
* @returns Number of sent bytes on success, 0 on error.
*/
size_t udp_send(session_t *session, const uint8_t dst_ip[], uint16_t dst_port,
const uint8_t data[], size_t data_len);
/**
* Receives data from the network using the UDP protocol.
* @param session The session object created by net_init().
* @param buffer The buffer into which to write received data.
* @param buffer_len The length of the buffer.
* @returns Number of bytes written into the buffer on success, 0 on error.
*/
size_t udp_recv(session_t *session, uint8_t buffer[], size_t buffer_len);
#endif
|
C
|
#include "score.h"
#include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
typedef struct buffer
{
int node_count; // p
int sample_count; // n
double *data; // X
int max_parents; // m
int prior;
int multinomial; // # categories TODO variable for each x_i?
int *n_ij; // used in BDe score
int *n_ijk; //
double fixed_alpha;
} BUFFER;
// internal function declarations
int count_nijk(BUFFER *, const int *, int, int);
double calc_bde(int *, double, const int *, int, int, int);
/* ##########################################################################*/
/**
* @brief
*
* @param data
* @param node_count
* @param sample_count
* @param categories
* @param max_parents
*
* @return
*/
/* ##########################################################################*/
void * score_init(double *data, int node_count, int sample_count, int categories, int max_parents)
{
BUFFER *buffer = Malloc(BUFFER, 1);
buffer->data = data;
buffer->node_count = node_count;
buffer->sample_count = sample_count;
buffer->multinomial = categories;
buffer->max_parents = max_parents;
buffer->prior = 0;
buffer->fixed_alpha = 1.0;
// |n_ij| = m * n
buffer->n_ij = Malloc(int, (max_parents * sample_count));
// |n_ijk| = n * r
buffer->n_ijk = Malloc(int, (sample_count * categories));
return buffer;
}
/* ##########################################################################*/
/**
* @brief
*
* @param buff
*/
/* ##########################################################################*/
void score_destroy_buff(void * buff)
{
BUFFER * bf = (BUFFER *) buff;
free(bf->n_ij);
free(bf->n_ijk);
free(buff);
}
/* ##########################################################################*/
/**
* @brief
*
* @param buffer
* @param child
* @param parents
* @param q
*
* @return
*/
/* ##########################################################################*/
double score_calc(void *buffer, const int child, const int *parents, const int q)
{
BUFFER *bf = (BUFFER *) buffer;
/* likelihood */
int count = count_nijk(bf, parents, q, child);
#ifdef DEBUG
fprintf(stderr, "BDE_score(): count = %d\n", count);
#endif
double score = calc_bde(bf->n_ijk, bf->fixed_alpha, parents, q, count,
bf->multinomial);
/* prior */
score = -2 * score;
return score;
}
/* ##########################################################################*/
/**
* @brief
*
* @param buff
* @param parents
* @param parents_count
* @param child
*
* @return
*/
/* ##########################################################################*/
int count_nijk(BUFFER *buff, const int *parents, int parents_count, int child)
{
int n_ij_count = 0;
for (int i = 0; i < buff->sample_count; ++i)
{
int j[parents_count];
for (int m = 0; m < parents_count; ++m)
{
//TODO rearrange indices??
j[m] = buff->data[i + parents[m] * buff->sample_count];
}
//printf("DONE\n");
/* Find 'stat vector' from n_ij */
int s = 0; /* stat vector position in n_ij */
while (s < n_ij_count)
{
const int * vec = buff->n_ij + s * buff->max_parents;
int flag2 = 0;
for (int ii = 0; ii < parents_count; ++ii)
{
if (j[ii] != vec[ii])
{
flag2 = -1;
break;
}
}
if (flag2 == 0)
break; /* found */
s++;
}
if (s == n_ij_count)
{
/* Not found. Creats a new element */
memcpy(buff->n_ij + s * buff->max_parents, j,
sizeof(int) * parents_count);
n_ij_count++;
bzero(buff->n_ijk + s * buff->multinomial,
sizeof(int) * buff->multinomial);
}
int xi = (int) buff->data[i + child * buff->sample_count];
buff->n_ijk[xi + s * buff->multinomial]++;
}
return n_ij_count;
}
/* ##########################################################################*/
/**
* @brief
*
* @param n_ijk
* @param fixed_alpha
* @param parents
* @param q
* @param count
* @param categories
*
* @return
*/
/* ##########################################################################*/
double calc_bde(int *n_ijk, double fixed_alpha, const int *parents, int q, int count, int categories)
{
double score = 0.0;
// forall N_ij states:
for (int j = 0; j < count; ++j)
{
double aij = fixed_alpha * categories;
double nij = 0;
// N_ij === SUM_{r_i}(N_ijk)
for (int k = 0; k < categories; ++k)
nij += n_ijk[categories * j + k];
double g_aij = lgamma(aij);
double g_aijnij = lgamma(nij + aij);
score += (g_aij - g_aijnij);
for (int k = 0; k < categories; ++k)
{
double g_a = lgamma(fixed_alpha + n_ijk[k + j * categories]);
double g_b = lgamma(fixed_alpha);
score += (g_a - g_b);
}
}/* for j < count */
return score;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(void){
int x , y , z , w , n , m , c , i , carrot;
int ptr , ssn;
char day[100];
scanf("%d" , &c);
for(i = 0 ; i < c ; i++){
scanf("%d %d %d %d %d %d" , &x , &y , &z , &w , &n , &m);
printf("x %d y %d z %d w %d n %d m %d \n" , x , y , z , w , n , m);
fgets(day , sizeof(day) , stdin);
fgets(day , sizeof(day) , stdin);
printf("%s" , day);
if(day[0] == '\n') printf("%d\n" , m);
else{
ptr = 0;
while(~sscanf(day + ptr , "%d%n" , &carrot , &ssn)){
ptr += ssn;
printf("-%d-\n" , carrot );
}
}
puts("");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
typedef struct body
{
int x;
int y;
struct body *pnext;
} BODY, *PBODY;
int begin(void);
int nxstep(PBODY phead);
void food(void);
void get_dir(void);
PBODY build_body(void);
void move(PBODY phead, int n);
int if_die(int x, int y);
void over(PBODY phead);
char direction = 'd';
int xnext, ynext, score = 0;
char map[40][40] = {
"# # # # # # # # # # # # # # # #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# # # # # # # # # # # # # # # #",
};
int main(void)
{
int speed;
PBODY phead = NULL, pfirst = NULL;
speed = begin();
phead = build_body();
food();
while (1)
{
pfirst = phead->pnext;
int n = nxstep(pfirst);
if (n == 1)
break;
if (n == 0 || n == 7)
move(phead, n);
int o, m;
system("cls");
for (m = 0; m <= 17; m++)
{
for (o = 0; o <= 31; o++)
printf("%c", map[m][o]);
printf("\n");
}
Sleep(720 / speed);
get_dir();
}
over(phead);
return 0;
}
PBODY build_body(void)
{
PBODY phead_ = NULL;
PBODY phead = (PBODY)malloc(sizeof(BODY));
phead_ = phead;
phead->pnext = (PBODY)malloc(sizeof(BODY));
phead = phead->pnext;
phead->x = 8;
phead->y = 9;
phead->pnext = (PBODY)malloc(sizeof(BODY));
phead = phead->pnext;
phead->x = 10;
phead->y = 9;
phead->pnext = NULL;
return phead_;
}
int if_die(int x, int y)
{
if (map[y][x] == '#')
return 1;
if (map[y][x] == 'o')
return 1;
if (map[y][x] == ' ')
return 0;
if (map[y][x] == '$')
return 7;
}
int begin(void)
{
int n;
printf("****************************\n\n");
printf(" ��ӭ����̰����\n\n");
printf(" ������a,b,cѡ���Ѷ�\n\n");
printf(" a.���� b.���� c.����\n\n");
printf(" #ʹ��wasd������λ#\n\n");
printf("****************************\n");
char ch = getch();
if (ch == 'a')
n = 12;
else if (ch == 'b')
n = 8;
else if (ch == 'c')
n = 3;
else
{
system("cls");
printf("��������abc�����˸�ɶ����\n");
Sleep(1000);
printf("���ˣ�����Ϸ���ʺ���\n");
Sleep(1000);
printf("����Ⱥ��");
Sleep(1000);
exit(-1);
}
system("cls");
printf("\n\n\n �����������ʼ");
getch();
return n;
}
void food(void)
{
int x, y;
srand((unsigned)time(NULL));
x = (rand() * 7 % 31) / 2;
x *= 2;
srand((unsigned)time(NULL));
y = rand() * 4 % 15 + 1;
while (if_die(x, y) == 1)
{
x = (rand() * 4 % 31) / 2;
x *= 2;
srand((unsigned)time(NULL));
y = rand() * 4 % 15 + 1;
}
map[y][x] = '$';
return;
}
void get_dir(void)
{
extern char direction;
char n;
if (kbhit())
{
n = getch();
if (n == 'w' && direction != 's')
direction = 'w';
else if (n == 'a' && direction != 'd')
direction = 'a';
else if (n == 's' && direction != 'w')
direction = 's';
else if (n == 'd' && direction != 'a')
direction = 'd';
else
return;
}
return;
}
void move(PBODY phead, int n)
{
PBODY phr, pArr;
phr = (PBODY)malloc(sizeof(BODY));
phr->pnext = phead->pnext;
pArr = phead->pnext;
phead->pnext = phr;
phr->x = xnext;
phr->y = ynext;
map[ynext][xnext] = '@';
while ((pArr->pnext)->pnext != NULL)
{
map[pArr->y][pArr->x] = 'o';
pArr = pArr->pnext;
}
if (n == 0)
{
map[(pArr->pnext)->y][(pArr->pnext)->x] = ' ';
free(pArr->pnext);
pArr->pnext = NULL;
}
if (n == 7)
{
pArr = pArr->pnext;
map[pArr->y][pArr->x] = 'o';
score++;
food();
}
return;
}
int nxstep(PBODY pfirst)
{
extern char direction;
int x = pfirst->x;
int y = pfirst->y;
switch (direction)
{
case 'w':
{
xnext = x;
ynext = y - 1;
}
break;
case 's':
{
xnext = x;
ynext = y + 1;
}
break;
case 'a':
{
xnext = x - 2;
ynext = y;
}
break;
case 'd':
{
xnext = x + 2;
ynext = y;
}
break;
}
int n;
n = if_die(xnext, ynext);
return n;
}
void over(PBODY phead)
{
printf("\n*****��Ϸ���������ĵ÷�Ϊ%d*****", score);
printf("\n ��q�˳�");
while (1)
{
char n = getch();
if (n == 'q')
exit(0);
}
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* runner( void* params);
int main()
{
int choice;
printf("Select a sched policy: 1) RR 2) FIFO 3)OTHER: ");
scanf("%d", &choice);
pthread_t tid[3];
pthread_attr_t attr;
pthread_attr_init(&attr);
// set schedule policy
switch(choice)
{
case 1:
printf("Set schedule policy RR\n");
pthread_attr_setschedpolicy(&attr, SCHED_RR);
break;
case 2:
printf("Set schedule policy FIFO\n");
pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
break;
case 3:
printf("Set schedule policy OTHER\n");
pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
break;
}
pthread_create(&tid[0], &attr, &runner, "./inv");
pthread_create(&tid[1], &attr, &runner, "./mul");
pthread_create(&tid[2], &attr, &runner, "./qs");
// join
for( int i=0; i<3; i++)
pthread_join(tid[i], NULL);
return 0;
}
void* runner (void* params)
{
char* exe = (char*) params;
system(exe);
pthread_exit(0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.