language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/************************************************************************* > File Name: hw_5_34.c > Author: RunRui_Li > Mail: [email protected] > Created Time: Tue 29 May 2018 07:42:48 PM CST ************************************************************************/ /** * 5.34❺试编写递归算法,逆转广义表中的数据元素。 * * 例如:将广义表 * (a, ((b, c), ()), (((d), e), f)) * 转成 * ((f, (e, (d))), ((), (c, b)), a)。 */ #ifndef MAIN #define MAIN #include "../test/test_EGList.c" Status reverse(EGList *L,EGList parent){ //L为当前节点,parent为该层的父节点 EGList next,p; if(*L == NULL || (((*L) -> tag == LIST)&&((*L) -> Union.hp == NULL)&&((*L) -> tp == NULL))) return OK; p = *L; if(parent == NULL){ //对于第一层来说,没有父节点 if(p -> tag == ATOM) return OK; if(!InitEGList(&parent)) exit(OVERFLOW); parent -> tag = LIST; parent -> tp = NULL; parent -> Union.hp = p; reverse(&p,parent); //反转第一层 *L = parent -> Union.hp; free(parent); }else{ if(p -> tag == LIST) { reverse(&(p -> Union.hp),p); } if(p -> tp == NULL){ //p指向最后一个节点了。 if(parent -> Union.hp != p){ parent -> Union.hp -> tp = NULL; //将首节点的下一跳设为NULL parent -> Union.hp = p; //更改首节点 } }else{ next = p -> tp; reverse(&next,parent); next -> tp = p; } } return OK; } int main(int argc,char **argv){ EGList L,g1,g2,g3; SString S1,S2,S3; char *s1 ="(((a,b,c),d,e),(b,c,d))"; StrAssign(S1,s1); if(CreateEGList(&g1,S1)){ Traverse_EGL(g1,visit); printf("\n"); reverse(&g1,NULL); Traverse_EGL(g1,visit); printf("\n"); } return 0; } #endif
C
#include <stdlib.h> #include <string.h> #include <dirent.h> #include <stdio.h> #include "csapp.h" #define MAXBUF 8192 #define MAXLINE 8192 char *sreplace(char *orig, char *rep, char *replacetxt); char *sinsert(char *orig, char *rep, char *replacetxt); int main(int argc, char const *argv[]) { struct dirent *dp; DIR *dir; char fname[100]; char dfname[100]; int fd; char buf[MAXBUF]; char replace[sizeof(argv[2])]; char rtxt[MAXLINE]; char find[sizeof(argv[1])]; char find2[sizeof(argv[3])]; strcpy(replace, argv[2]); strcpy(find,argv[1]); strcpy(find2,argv[3]); dir = opendir("./sub"); while ((dp = readdir(dir)) != NULL){ strcpy(fname,dp->d_name); if(strcmp(fname,"." ) && strcmp(fname,"..") ){ //Checks its not current Dir or parent dir strcpy(dfname,"./sub/"); strcat(dfname, fname); printf("%s\n", dfname ); fd = Open(dfname, O_RDONLY, 0); Rio_readn(fd, buf, MAXLINE); Close(fd); if (strstr(buf,find)) { strcpy(rtxt, sreplace(buf,find,replace)); printf("%s\n", rtxt); rtxt[0] = '\0'; buf[0] = '\0'; } else if(strstr(buf,find2)) { strcpy(rtxt, sinsert(buf,find2,replace)); printf("%s\n", rtxt ); rtxt[0] = '\0'; buf[0] = '\0'; } } } closedir(dir); /* code */ return 0; } char *sreplace(char *orig, char *rep, char *replacetxt) { char *result; char *insert; char *tmp; int len_rep; int len_replacetxt; int len_front; int count; // sanity checks and initialization len_rep = strlen(rep); if (len_rep == 0) return NULL; // empty rep causes infinite loop during count len_replacetxt = strlen(replacetxt); // count the number of replacements needed insert = orig; for (count = 0; tmp = strstr(insert, rep); ++count) { insert = tmp + len_rep; } tmp = result = malloc(strlen(orig) + (len_replacetxt - len_rep) * count + 1); if (!result) return NULL; // first time through the loop, all the variable are set correctly // from here on, // tmp points to the end of the result string // ins points to the next occurrence of rep in orig // orig points to the remainder of orig after "end of rep" while (count--) { insert = strstr(orig, rep); len_front = insert- orig; tmp = strncpy(tmp, orig, len_front) + len_front; tmp = strcpy(tmp, replacetxt) + len_replacetxt; orig += len_front + len_rep; // move to next "end of rep" } strcpy(tmp, orig); return result; } char *sinsert(char *orig, char *rep, char *replacetxt) { char *result; int len_replacetxt; int len_front; int count; char *insert; char *tmp; int len_rep; len_rep = strlen(rep); if (len_rep == 0) return NULL; // empty rep causes infinite loop during count len_replacetxt = strlen(replacetxt); // count the number of replacements needed insert = orig; for (count = 0; tmp = strstr(insert, rep); ++count) { insert = tmp + len_rep; } tmp = result = malloc(strlen(orig) + (len_replacetxt - len_rep) * count + 1); if (!result) return NULL; while (count--) { insert = strstr(orig, rep); len_front = insert - orig; tmp = strncpy(tmp, orig, len_front) + len_front +1; tmp = strcat(tmp, replacetxt) + len_replacetxt ; orig += len_front; // move to next "end of rep" } strcpy(tmp, orig); return result; }
C
#include<stdio.h> main() { int i=1; int dOne; int dMax; int dNumb; scanf("%d",&dOne); dMax=dOne; while (i<10){ scanf("%d",&dNumb); if(dNumb>dMax) {dMax=dNumb;}; i++;} printf("Max value is %d", dMax); return 0; }
C
#include <stdio.h> #include "sightglass.h" __attribute__((export_name("add"))) __attribute__((noinline)) int add(int a, int b) { return a + b; } int main() { bench_start(); int c = add(40, 2); bench_end(); printf("%d\n", c); }
C
void imp_mano(int array_cartas[], int cantidad_mano,int arriba_abajo,int carta_sel) { /*Permite imprimir cantidad determinada de cartas en horizontal * para evitar construir una mano fija hace un barrido de impresion * secuencial por un bucle y el uso de la funcion "fragmento_carta" */ short c; short c1; for(c1=0;c1<8;c1++){ for(c=0;c<cantidad_mano;c++){ if(array_cartas[c] == 49 || array_cartas[c] == 50)/*Si es comodin*/ { printf(" "); if(arriba_abajo) { fragmento_carta(0,c1,0,0); }else{ fragmento_carta(-1,c1,5,0); } }else if(array_cartas[c] >= 1 && array_cartas[c] <= 48) { printf(" "); if(arriba_abajo) { if(carta_sel == c) fragmento_carta(numero_de_carta(array_cartas[c]),c1,palo_de_carta(array_cartas[c]),1); else fragmento_carta(numero_de_carta(array_cartas[c]),c1,palo_de_carta(array_cartas[c]),0); }else{ fragmento_carta(-1,c1,5,0); } }else{ fragmento_carta(-1,c1,5,0); } } printf("\n"); } } void fragmento_carta(int numero,int parte,int tipo,int seleccionada) { char dibujo_basto[4][39] = { "| X | ", "| XX | ", "| XX> | ", "| X | " }; char dibujo_espada[4][39] = { "| * | ", "| * | ", "| <<*>> | ", "| ! | " }; char dibujo_copa[4][39] = { "| XXXXX | ", "| XXX | ", "| ! | ", "| XXX | " }; char dibujo_oro[4][39] = { "| *** | ", "| ** ** | ", "| ** ** | ", "| *** | " }; char dibujo_comodin[4][39] = { "| ##### | ", "|# | ", "|# | ", "| ##### | " }; char dibujo_abajo[4][39] = { "|XXXXXXX| ", "|XXXXXXX| ", "|XXXXXXX| ", "|XXXXXXX| " }; char dibujo_vacia[4][39] = { "| | ", "| | ", "| | ", "| | " }; switch(parte) { case 0: if(seleccionada){ printf(">-------< "); }else if(numero == -2){ printf("/.......\\ "); }else{ printf("+-------+ "); } break; case 1: if(numero>=10){ printf("|%d | ",numero); }else if(numero == 0){ printf("|? | "); }else if(numero == -1){ printf("|XXXXXXX| "); }else if(numero == -2){ printf("| | "); }else{ printf("|%d | ",numero); } break; case 2: switch(tipo){ case 0: printf("%s",dibujo_comodin[0]); break; case 1: printf("%s",dibujo_basto[0]); break; case 2: printf("%s",dibujo_espada[0]); break; case 3: printf("%s",dibujo_copa[0]); break; case 4: printf("%s",dibujo_oro[0]); break; case 5: printf("%s",dibujo_abajo[0]); break; case 6: printf("%s",dibujo_vacia[0]); break; default: printf("| | "); break; } break; case 3: switch(tipo){ case 0: printf("%s",dibujo_comodin[1]); break; case 1: printf("%s",dibujo_basto[1]); break; case 2: printf("%s",dibujo_espada[1]); break; case 3: printf("%s",dibujo_copa[1]); break; case 4: printf("%s",dibujo_oro[1]); break; case 5: printf("%s",dibujo_abajo[1]); break; case 6: printf("%s",dibujo_vacia[1]); break; default: printf("| | "); break; } break; case 4: switch(tipo){ case 0: printf("%s",dibujo_comodin[2]); break; case 1: printf("%s",dibujo_basto[2]); break; case 2: printf("%s",dibujo_espada[2]); break; case 3: printf("%s",dibujo_copa[2]); break; case 4: printf("%s",dibujo_oro[2]); break; case 5: printf("%s",dibujo_abajo[2]); break; case 6: printf("%s",dibujo_vacia[2]); break; default: printf("| | "); break; } break; case 5: switch(tipo){ case 0: printf("%s",dibujo_comodin[3]); break; case 1: printf("%s",dibujo_basto[3]); break; case 2: printf("%s",dibujo_espada[3]); break; case 3: printf("%s",dibujo_copa[3]); break; case 4: printf("%s",dibujo_oro[3]); break; case 5: printf("%s",dibujo_abajo[3]); break; case 6: printf("%s",dibujo_vacia[3]); break; default: printf("| | "); break; } break; case 6: if(numero>=10){ printf("| %d| ",numero); }else if(numero == 0){ printf("| ?| "); }else if(numero == -1){ printf("|XXXXXXX| "); }else if(numero == -2){ printf("| | "); }else{ printf("| %d| ",numero); } break; case 7: if(seleccionada){ printf(">-------< "); }else if(numero == -2){ printf("......... "); }else{ printf("+-------+ "); } break; } }; void imp_palo(int palo)//imprime palo str { /*Imprime un string del palo tomando como parametro * el id del palo correspondiente de la carta*/ switch(palo) { case 1: printf("Basto "); break; case 2: printf("Espada "); break; case 3: printf("Copa "); break; case 4: printf("Oro"); break; default: printf("Comodin?"); break; } } void ver_mazo(int mazo[],int *c_actual){ /*Imprime el mazo elegido*/ short c; for(c=0;c<CANTIDAD_CARTAS;c++) printf("%d ",mazo[c]); printf("\n"); } void ver_mano(int mano[]){ /*Imprime la mano elegida*/ short cnt; for(cnt=0;cnt<CANTIDAD_MANO;cnt++) printf("%d ",mano[cnt]); printf("\n"); } void logo_principal() { char titulo[15] = "El Chinchon"; printf(" <------------------------- %s ------------------------->\n",titulo); }
C
// // stdlib.h // // written by sjrct // #ifndef _STDLIB_H_ #define _STDLIB_H_ #include <stddef.h> typedef struct { int quot; int rem; } div_t; typedef struct { long quot; long rem; } ldiv_t; void srand(unsigned int seed); int rand(); void * malloc(unsigned size); void free(void * ptr); int abs(int); long labs(long); div_t div(int, int); ldiv_t ldiv(long, long); void exit(int status); #endif
C
#include <stdio.h> #define SEC_PER_MIN 60 int main(){ int min, sec , sec_left; printf("==========CONVERTING SECONDS TO MINUTES AND SECONDS===========\n\n"); printf("Enter the number of seconds you wish to convert:\n"); scanf("%d" , &sec); min = sec / SEC_PER_MIN; sec_left = sec % SEC_PER_MIN; printf("%d seconds is %d minutes and %d seconds" , sec , min , sec_left); }
C
/* DriverLib Includes */ #include "driverlib.h" /* Standard Includes */ #include <stdint.h> #include <stdbool.h> #include "Motor.h" #include "ST7735.h" uint16_t i = 0, j = 0, steps = 128, delay = 2; /********************************************************************** * Steps the motor 11.25 deg, 32 steps for a full 360deg rotation * It sets each bit to high, steps it to low, sets the next to high and * repeats this until 360 deg rotation occurs. * * 64 (ratio) x 8 (teeth) = 512 steps *********************************************************************/ void Motor_Lock(void){ for (j = 0 ; j < steps ; j++) { for (i = 0 ; i < 4 ; i++){ P8 -> OUT &=~ 0xF0; P8 -> OUT |= 0x10 << i; Delay1ms(delay); } } } /********************************************************************** * Steps the motor 11.25 deg, 32 steps for a full 360deg rotation * It sets each bit to high, steps it to low, sets the next to high and * repeats this until 360 deg rotation occurs. 64:1 gear ratio, * * 64 (ratio) x 8 (teeth) = 512 steps *********************************************************************/ void Motor_Unlock(void){ for (j = 0 ; j < steps ; j++){ for (i = 0 ; i < 4 ; i++){ P8 -> OUT &=~ 0xF0; P8 -> OUT |= 0x80 >> i; Delay1ms(delay); } } } /********************************************************************** * Initializes the Pins to be Output *********************************************************************/ void Motor_Init(void){ /* Sets the pins to output */ P8 -> DIR |= BIT4 | BIT5 | BIT6 | BIT7; }
C
#include <stdio.h> #include <stdlib.h> #define NOT_EXIST - 1 #define VISITED 0 #define FRESH 1 #define TREE 2 #define BACK 3 typedef int VertexIndex; typedef int EdgeIndex; typedef int ID; typedef struct Sack { VertexIndex v; struct Sack *next; }Sack; typedef struct Edge { int weight; VertexIndex endPoints[2]; int label; }Edge; typedef struct Vertex { int id; int label; }Vertex; typedef struct Graph { Vertex *vertices; Edge *edges; int verticesSize; int edgesSize; int edgeNowIndex; int **AdjacencyMatrix; }Graph; typedef struct QueueStruct { int key; // 간선의 무게 EdgeIndex elem; // 간선 }QueueStruct; typedef struct Queue { QueueStruct *Q; int f; int r; int n; }Queue; void kruskalMST(Graph *graph); int dfs(Graph *graph, VertexIndex v); void init(Graph *graph) { graph->vertices = (Vertex*)malloc(sizeof(Vertex)*graph->verticesSize); graph->edges = (Edge*)malloc(sizeof(Edge)*graph->edgesSize); for (int i = 0; i < graph->verticesSize; i++) { graph->vertices[i].id = i + 1; // id는 1~N graph->vertices[i].label = FRESH; } for (int i = 0; i < graph->edgesSize; i++) { graph->edges[i].weight = 0; graph->edges[i].endPoints[0] = NOT_EXIST; graph->edges[i].endPoints[1] = NOT_EXIST; graph->edges[i].label = FRESH; } //인접행렬 초기화 graph->AdjacencyMatrix = (int**)malloc(sizeof(int*)*graph->verticesSize); for (int i = 0; i < graph->verticesSize; i++) { graph->AdjacencyMatrix[i] = (int*)malloc(sizeof(int)*graph->verticesSize); } for (int i = 0; i < graph->verticesSize; i++) { for (int j = 0; j < graph->verticesSize; j++) { graph->AdjacencyMatrix[i][j] = NOT_EXIST; } } graph->edgeNowIndex = NOT_EXIST; } void insertEdge(Graph *graph, ID a, ID b, int weight) { graph->edgeNowIndex++; // 인덱스 1 증가시켜 간선 추가 graph->edges[graph->edgeNowIndex].endPoints[0] = a - 1; // 따로 id->index 변환함수 안넣음. 어차피 id - 1 = 인덱스라서 graph->edges[graph->edgeNowIndex].endPoints[1] = b - 1; graph->edges[graph->edgeNowIndex].weight = weight; graph->AdjacencyMatrix[a - 1][b - 1] = graph->edgeNowIndex; // 인접행렬에 간선 인덱스 넣어줌 graph->AdjacencyMatrix[b - 1][a - 1] = graph->edgeNowIndex; } // main ------------------------------------------- int main() { Graph *graph = (Graph*)malloc(sizeof(Graph)); int N = 0; int M = 0; scanf("%d %d", &N, &M); graph->verticesSize = N; graph->edgesSize = M; init(graph); for (int i = 0; i < graph->edgesSize; i++) { int a = 0, b = 0, weight = 0; scanf("%d", &a); scanf("%d", &b); scanf("%d", &weight); insertEdge(graph, a, b, weight); } kruskalMST(graph); int result = dfs(graph, 0); printf("\n%d", result); //free for (int i = 0; i < graph->verticesSize; i++) { free(graph->AdjacencyMatrix[i]); } free(graph->AdjacencyMatrix); free(graph->vertices); free(graph->edges); free(graph); return 0; } // 큐 구조체 전용 선택 정렬 // 큐라서 f부터 r까지 가면서 n기준으로 wrap around void selectionSort(QueueStruct *A, Queue *queue) { for (int pass = queue->f; pass < queue->r; pass = (pass + 1) % queue->n) { int minLoc = pass; for (int j = pass + 1; j <= queue->r; j = (j + 1) % queue->n) { if (A[minLoc].key > A[j].key) minLoc = j; // 키 값 기준으로 오름차순 정렬 } QueueStruct tmp = A[minLoc]; A[minLoc] = A[pass]; A[pass] = tmp; } } void enqueue(Queue *queue, int key, int elem) { queue->r = (queue->r + 1) % queue->n; queue->Q[queue->r].key = key; queue->Q[queue->r].elem = elem; } void QueueInit(Queue *queue, Graph *graph) { queue->n = graph->edgesSize + 1; queue->Q = (QueueStruct*)malloc(sizeof(QueueStruct)*queue->n); queue->f = 0; queue->r = queue->n - 1; for (int i = 0; i < graph->edgesSize; i++) { enqueue(queue, graph->edges[i].weight, i); // 키 = 간선의 무게, 원소 = 간선 인덱스 } selectionSort(queue->Q, queue); // 넣고 한번 정렬 } // removeMin = dequeue // init하고 replaceKey 실행할때마다 정렬되므로 // 결과적으로 dequeue하면 키가 제일 작은 값이 나옴 int removeMin(Queue *queue) { int tmp = queue->Q[queue->f].elem; queue->f = (queue->f + 1) % queue->n; return tmp; } int getSackIndex(Graph *graph, Sack **sack, VertexIndex v) // sack index 반환 { for (int i = 0; i < graph->verticesSize; i++) { Sack *p = sack[i]->next; while (p != NULL) // 배낭이 비어있지 않으면 { if (p->v == v) return i; // 배낭 내의 정점 인덱스와 입력된 정점 인덱스와 비교하여 같으면 // 그 배낭의 인덱스를 반환 p = p->next; } } } void MergeSack(Sack **sack, int uSackIndex, int vSackIndex) { Sack *p = sack[uSackIndex]->next; while (p->next != NULL) { p = p->next; } p->next = sack[vSackIndex]->next; // 한 배낭의 맨 끝 노드의 next에 다른 배낭의 첫 노드를 연결 sack[vSackIndex]->next = NULL; // 다른 배낭은 비어있게 됨 } void freeSack(Graph *graph, Sack **sack) { for (int i = 0; i < graph->verticesSize; i++) // 전체 배낭에 대해 { Sack *p = sack[i]; while (p->next != NULL) // 배낭 내용물 비우기 { Sack *tmp = p->next; free(p); p = tmp; } if(p!=NULL) free(p); // 각 배낭 없애기 } free(sack); } void kruskalMST(Graph *graph) { Sack **sack = (Sack**)malloc(sizeof(Sack*)*graph->verticesSize); for (int i = 0; i < graph->verticesSize; i++) // 정점 갯수 = 배낭 갯수(비어있는 배낭포함) { sack[i] = (Sack*)malloc(sizeof(Sack)); // 헤더 sack[i]->next = (Sack*)malloc(sizeof(Sack)); // 각각의 배낭 초기화 sack[i]->next->v = i; sack[i]->next->next = NULL; } Edge *edges = (Edge*)malloc(sizeof(Edge)*graph->verticesSize - 1); // 최소신장트리를 만들기위한 임시 간선배열 // 나중에 여기 모은 간선들로 트리를 새로 만듬 EdgeIndex edgeNowIndex = NOT_EXIST; Queue *queue = (Queue*)malloc(sizeof(Queue)); QueueInit(queue, graph); while (edgeNowIndex + 1 < (graph->verticesSize - 1)) // 큐가 안 비어있으면 { EdgeIndex e = removeMin(queue); // 큐(배낭 밖)에서 가장 작은 간선 무게를 가진 간선을 가져옴 VertexIndex u = graph->edges[e].endPoints[0]; // 간선의 양 끝점을 저장 VertexIndex v = graph->edges[e].endPoints[1]; int uSackIndex = getSackIndex(graph, sack, u); // 각 끝점의 배낭 인덱스 int vSackIndex = getSackIndex(graph, sack, v); if (uSackIndex != vSackIndex) // 배낭 인덱스가 서로 다른 경우 = 다른 배낭인 경우 { printf(" %d", graph->edges[e].weight); edgeNowIndex++; // 그 간선의 정보를 가지고 edges에 복사 edges[edgeNowIndex].endPoints[0] = graph->edges[e].endPoints[0]; edges[edgeNowIndex].endPoints[1] = graph->edges[e].endPoints[1]; edges[edgeNowIndex].weight = graph->edges[e].weight; MergeSack(sack, uSackIndex, vSackIndex); // 두 배낭을 합침 } } init(graph); // 기존 그래프를 지움 edgeNowIndex = NOT_EXIST; graph->edgesSize = graph->verticesSize - 1; for (int i = 0; i < graph->edgesSize; i++) // edges의 정보를 가지고 최소신장트리를 그림 { edgeNowIndex++; insertEdge(graph, edges[edgeNowIndex].endPoints[0] + 1, edges[edgeNowIndex].endPoints[1] + 1, edges[edgeNowIndex].weight); } freeSack(graph, sack); free(edges); free(queue->Q); free(queue); } int dfs(Graph *graph, VertexIndex v) { static int result = 0; graph->vertices[v].label = VISITED; // 방문으로 표시 for (int i = 0; i < graph->verticesSize; i++) // 모든 정점들에 대해 { if (graph->AdjacencyMatrix[v][i] != NOT_EXIST) // 간선이 존재하면 (부착 간선) { EdgeIndex e = graph->AdjacencyMatrix[v][i]; // 그 간선을 e라 함 if (graph->edges[e].label == FRESH) // e가 FRESH이면 { VertexIndex w = i; // e에 대한 반대 끝점을 w라 함 if (graph->vertices[w].label == FRESH) // w가 FRESH이면 { graph->edges[e].label = TREE; // e는 TREE result += graph->edges[e].weight; // 간선들의 무게를 다 더함 = 최소 비용 dfs(graph, w); // 반대끝점을 통하여 재귀 } else // e가 FRESH가 아니면 { graph->edges[e].label = BACK; // e는 BACK } } } } return result; }
C
#include <stdio.h> #include <stdlib.h> int main() { int x; printf("=======================================\n FACTOR NUMBER FINDER\n=======================================\n"); printf("Please insert integer: "); scanf("%d", &x); while (x <= 0) { printf("You insert number below than 0 or equal 0.\nPlease insert the new integer: "); scanf("%d", &x); } printf("\nThe factor numbers of '%d' are ", x); for(int i = 1; i <= x; i++) { if (x%i==0) { //It's factor if (i == x) { printf(" and %d\n", i); } else if (i == 1) { printf("%d", i); } else { printf(", %d", i); } } } creditTxt(); } void creditTxt() { printf("Coded by Palapon Soontornpas\n"); }
C
#include <stdio.h> #include <stdlib.h> #include "list.h" //=============================================== //将item拷贝进节点,此函数可根据Item的不同进行修改 //=============================================== static void CopyItem(Item item, struct node* pnode) { pnode->item = item; } //========================================================= //判断item是否和节点中的item相等,此函数可根据Item的不同修改 //========================================================= static byte ItemEqual(Item item, struct node* pnode) { byte result; if(pnode->item == item) result = 1; else result = 0; return result; } //====================== //初始化链表,带哨兵元素 //====================== byte ListInit(List *plist) { struct node * pnew; pnew = (struct node*)malloc(sizeof(struct node)); if(pnew == 0) return 0; //创建失败 pnew->next = pnew; *plist = pnew; return 1; } //================= //删除链表 //================= void ListDel(List *plist) { struct node* pscan; struct node* pdel; pscan = *plist; while(pscan->next != *plist) //不是哨兵元素 { pdel = pscan; pscan = pscan->next; //psacn 下移 free(pdel); } free(pscan); //删除哨兵元素 } //======================== //添加元素到链表尾 //成功,返回1;失败,返回0 //======================== byte ListAddItem(Item item, List *plist) { struct node *pnew; struct node *pscan = *plist; pnew = (struct node *)malloc(sizeof(struct node)); if(pnew == 0) return 0; CopyItem(item, pnew); pnew->next = *plist; while(pscan->next != *plist) pscan = pscan->next; pscan->next = pnew; return 1; }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: abdullah * * Created on December 28, 2017, 11:23 PM */ #include <stdio.h> #include <stdlib.h> //for exit() function #include "../src/ch1to10.h" #include "../src/ch11.h" #include "src/ch13.h" /* * */ int main(int argc, char** argv) { //COUNT NUMBER OF CHARACTERS IN A TEXT FILE // char read_char; // int character_count = 0; // // FILE* file_pointer; // char file_name[MAX_FILE_LENGTH]; // //// int file_name_size; //// //// file_name_size = get_file_name(file_name); // // puts("Please enter a filename below."); // get_string_input(file_name, MAX_FILE_LENGTH); // new_line(); // // if( (file_pointer = fopen(file_name, "r")) == NULL ) { //IF FAILED TO OPEN FILE WITH FOPEN() // puts("Can't open file. Bye."); // exit(EXIT_FAILURE); // } // // puts("Your file's characters:"); // while( (read_char = getc(file_pointer)) != EOF ) { //ECHO FILE CHARACTERS INTO OUTPUT UNTIL EOF // putc(read_char, stdout); // character_count++; // } // new_line(); // // if( fclose(file_pointer) ) { // puts("Failed to close file!"); // exit(EXIT_FAILURE); // } // // printf("File %s has %ul characters.\n", file_name, character_count); //QUICK CHECK FOR WHERE CURRENT DIRECTORY WOULD BE IF YOU RUN FROM TERMINAL //Make new file called currentD.txt and put some characters in it. // FILE* file; // if( (file = fopen("currentD.txt", "wx")) == NULL) { // puts("I couldn't create file. Sorry."); // exit(EXIT_FAILURE); // } // fprintf(file, "This is where the current directory of execution is."); // if(fclose(file)) { // puts("Error in closing file."); // exit(EXIT_FAILURE); // } // // //Open file and echo to stdout // FILE* file_check; // if( (file_check = fopen("currentD.txt", "r")) == NULL) { // puts("I couldn't open the file. Sorry."); // } // char input_char; // while( (input_char = getc(file_check)) != EOF ) { // putc(input_char, stdout); // } // if(fclose(file_check)) { // puts("Error in closing file."); // exit(EXIT_FAILURE); // } //COPY CONTENTS OF ONE FILE TO ANOTHER AND ACCEPTING COMMAND-LINE ARGUMENTS // FILE* input_file; // FILE* output_file; // char character_input; //// char input_file_name[MAX_FILE_LENGTH] = argv[1]; // char* input_file_name = malloc( 255 * sizeof(char) ); // input_file_name = argv[1]; // char output_file_name[MAX_FILE_LENGTH]; // int character_count = 0; // // //Check if filename was included // if(argc < 2) { // fprintf(stderr, "Usage: %s filename\n", argv[0]); // exit(EXIT_FAILURE); // } // // //Open file and check for success. // if( (input_file = fopen(input_file_name, "r")) == NULL ) { // fprintf(stderr, "I couldn't open the file \"%s\"\n", input_file_name); // exit(EXIT_FAILURE); // } // // //Set up output file. Here we will call it the same name but with a .red extension instead, hence - 5 // strncpy(output_file_name, input_file_name, MAX_FILE_LENGTH - 5); // output_file_name[MAX_FILE_LENGTH - 5] = '\0'; // strcat(output_file_name, ".red"); // // //Open output file and check for success // if( (output_file = fopen(output_file_name, "w")) == NULL ) { // fprintf(stderr, "Can't create output file.\n"); // exit(EXIT_FAILURE); // } // // //Write to output file // while( (character_input = getc(input_file)) != EOF ) { // if((character_count++ % 3) == 0) { //printing every 3rd character // putc(character_input, output_file); // } // } // // if(fclose(input_file) || fclose(output_file) ) { // fprintf(stderr, "Error in closing files.\n"); // exit(EXIT_FAILURE); // } //PRINT THE REVERSE CONTENTS OF A FILE USING FSEEK() AND FTELL() // char file_name[255]; // char character_read; // FILE* file; // long last; // // //Get filename // puts("Enter the name of the file to be processed below."); // //scanf("%80s", file_content); //--> NOT GOOD BECAUSE FILE NAMES CAN HAVE SPACES // if( get_string_input(file_name, 255) == NULL ) { // puts("Failed to read filename. Sorry."); // exit(EXIT_FAILURE); // } // // //Open file in READ BYTE MODE to be able to use fseek() properly // if( (file = fopen(file_name, "rb")) == NULL ) { // puts("Failed to open file. Sorry."); // exit(EXIT_FAILURE); // } // // //Set starting position // if( fseek(file, 0L, SEEK_END) ) { //seek_file() now does this check block. // puts("Failed to use fseek() on file."); // exit(EXIT_FAILURE); // } //Go to end of file // // last = ftell(file); // // //Start going from 1 byte before the last, because the last byte is EOF // for(int i=1L; i <= last; i++) { // seek_file(file, -i, SEEK_END); // character_read = getc(file); // if( (character_read != CTRL_Z) && (character_read != '\r') ) { //MS-DOS files // putchar(character_read); // } // } // putchar('\n'); // // //Close file // close_file(file); //PREVIOUS PROGRAM BUT WITH FGETPOS() AND FSETPOS() --> NOT SO STRAIGHTFORWARD. NEEDS WORK TO SET POSITION TO LAST BYTE. // char file_name[255]; // char character_read; // FILE* file; // long last; // // //Get filename // puts("Enter the name of the file to be processed below."); // //scanf("%80s", file_content); //--> NOT GOOD BECAUSE FILE NAMES CAN HAVE SPACES // if( get_string_input(file_name, 255) == NULL ) { // puts("Failed to read filename. Sorry."); // exit(EXIT_FAILURE); // } // // //Open file in READ BYTE MODE to be able to use fseek() properly // if( (file = fopen(file_name, "rb")) == NULL ) { // puts("Failed to open file. Sorry."); // exit(EXIT_FAILURE); // } // // //Set starting position // fpos_t file_position; // // if( fsetpos(file, file_position) ) { // puts("Failed to use fsetpos() on file."); // exit(EXIT_FAILURE); // } //Go to end of file // // last = ftell(file); // // //Start going from 1 byte before the last, because the last byte is EOF // for(int i=1L; i <= last; i++) { // seek_file(file, -i, SEEK_END); // character_read = getc(file); // if( (character_read != CTRL_Z) && (character_read != '\r') ) { //MS-DOS files // putchar(character_read); // } // } // putchar('\n'); // // //Close file // close_file(file); //READING THE BINARY FORM OF A LIBREOFFICE WRITER DOCUMENT --> DANGIT. DIDN'T WORK :( // FILE* file; // // //Open file // if( (file = fopen("C Notes.odt", "rb")) == NULL ) { // puts("Failed to open document."); // exit(EXIT_FAILURE); // } // // //Echo binary data up to 100th character // int count = 0; // char input_char; // while( (count++ < 100) && (input_char = getc(file)) ) { // putchar(input_char); // } // new_line(); // // if( fclose(file) ) { // puts("Failed to close file"); // exit(EXIT_FAILURE); // } //WRITING CHAR DATA TO A FILE THEN ECHOING IT TO STDOUT // FILE *file; // // //Create and open file. // if( (file = fopen("char_sample", "w+")) == NULL ) { //FINALLY SOLVED PROBLEM: "w" IS JUST WRITE. "w+" IS READ/WRITE. // puts("Failed to open file."); // exit(EXIT_FAILURE); // } // // //Write char data. // int i = 0; // while( i < 20 ) { // putc('a', file); // i++; // } // // //Reset active position in stream to start. // rewind(file); // // //Echo data to stdout // char input_char; // while( (input_char = getc(file)) != EOF ) { // putchar(input_char); // } //WRITING AND THEN READING BINARY DATA FROM A CREATED FILE // FILE* file; // // //Create and open file. // if( (file = fopen("sample_b_data", "w+")) == NULL ) { // puts("Failed to create and open file."); // exit(EXIT_FAILURE); // } // // //Write data to it. // char char_data[11] = "This is d."; // double double_data[6] = { 5.2, 1.00, 2.45, 12.6, 1982.11, 0.001 }; // int int_data[1] = { 9000 }; // // fwrite(char_data, sizeof(char), 11, file); // fwrite(double_data, sizeof(double), 6, file); // fwrite(int_data, sizeof(int), 1, file); // // //Echo data from file to stdout // rewind(file); // // puts("The character portion:"); // char char_buff[11]; // if( fread(char_buff, sizeof(char), 11, file) == 0 ) { // puts("Failed to read char from file."); // // if( feof(file) ) { // puts("It was an EOF."); // } // if ( ferror(file) ) { // puts("It was not an EOF."); // } // // exit(EXIT_FAILURE); // } // puts(char_buff); // new_line(); // // puts("The double portion:"); // double double_buff[6]; // if( fread(double_buff, sizeof(double), 6, file) == 0 ) { // puts("Failed to read double from file."); // exit(EXIT_FAILURE); // } // print_array_double(double_buff, 6); // new_line(); // // puts("The integer portion:"); // int int_buff[1]; // if( fread(int_buff, sizeof(int), 1, file) == 0 ) { // puts("Failed to read int from file."); // exit(EXIT_FAILURE); // } // print_array_int(int_buff, 1); // new_line(); // // if( getc(file) == EOF ) { // puts("SUCCESS!"); // } //READING CONTENT OF SOURCE FILES AND APPENDING TO AN OUTPUT FILE // FILE *source, *destination; // int files_read = 0; // char source_name[255]; // char destination_name[255]; // // //Get destination file name. // puts("Enter the name of the destination file below."); // get_string_input(destination_name, 255); // // //Open file. // //Clear File. // destination = fopen(destination_name, "w"); // close_file(destination); // //Start // if( (destination = fopen(destination_name, "a+")) == NULL ) { // puts("Unable to open/create destination file."); // exit(EXIT_FAILURE); // } // // //Set buffer for file // if( setvbuf(destination, NULL, _IOFBF, 4096) ) { // puts("Unable to create buffer for destination file."); // exit(EXIT_FAILURE); // } // // //Get source files and start appending. // puts("Enter name of source file (empty line to quit)."); // while( get_string_input(source_name, 255) && (source_name[0] != '\0') ) { // //If same file... // if(!strcmp(source_name, destination_name)) { // puts("Can't append file to itself."); // puts("Try again."); // continue; // } else if( (source = fopen(source_name, "r")) == NULL ) { // puts("Can't open source file."); // puts("Try again."); // continue; // } else { // if( setvbuf(source, NULL, _IOFBF, 4096) ) { // puts("Could not set buffer for source file."); // close_file(source); // continue; // } // // append(source, destination); // // if( ferror(source) ) { // puts("There was an error reading the file."); // puts("Try again."); // close_file(source); // continue; // } //// else if( feof(source) ) { //// puts("EOF reached."); //// } // // close_file(source); // files_read++; // puts("File appended."); // new_line(); // puts("Next."); // } // } // // //Reset active positive of destination stream to start. // rewind(destination); // // //Echo destination stream to stdout // char input_char; // while( (input_char = getc(destination)) != EOF ) { // putchar(input_char); // } //RANDOM ACCESS IN BINARY FILES double numbers[1000]; double val; int index; const char *file_name = "numbers.dat"; long position; FILE *file; //Initialize double array fill_double_array(numbers, 1000, 0, 10000, 0.0523); //Create and open file if( (file = fopen(file_name, "wb")) == NULL ) { puts("Could not create/open file."); exit(EXIT_FAILURE); } //Write array to file. fwrite(numbers, sizeof(double), 1000, file); //Close file so you can switch mode to read-only. close_file(file); //Open file again as read mode if( (file = fopen(file_name, "rb")) == NULL ) { puts("Could not reopen file."); exit(EXIT_FAILURE); } printf("Enter a number between 0 to 999: "); while( (scanf("%d", &index) == 1) && (index > 0) && (index < 999) ) { position = (long) (index * sizeof(double)); fseek(file, position, SEEK_SET); fread(&val, sizeof(double), 1, file); printf("The value there is: %.4f", val); new_line(); printf("Another one: "); } //Create text-readable version FILE *text_file; char *text_file_name = "numbers.txt"; if( (text_file = fopen(text_file_name, "w")) == NULL ) { puts("Failed to create text file."); exit(EXIT_FAILURE); } rewind(file); double double_val; char string_val[50]; while( fread(&double_val, sizeof(double), 1, file) ) { // printf("%.5f ", double_val); sprintf(string_val, "%.4f ", double_val); // fputs(string_val, text_file); if( fwrite(string_val, sizeof(char), strlen(string_val), text_file) == 0 ) { puts("Failed to write to text file."); exit(EXIT_FAILURE); } } puts("Done!"); return (EXIT_SUCCESS); }
C
// // Created by Howe Chen on 11/06/2018. // #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { int numbers[4] = {0}; char name[4] = {'Z', 'e', 'd', '\0'}; printf("numbers: %d %d %d %d\n", numbers[0], numbers[1], numbers[2], numbers[3]); for (int i = 0; i < sizeof(name) / sizeof(char); ++i) { printf("%c", name[i]); } char *another = "Zed"; printf("another: %s\n", another); printf("Size of another: %ld\n", sizeof(*another)); printf("Size of another: %ld\n", strlen(another)); }
C
// // recursive_pado.c // W01-Practical-New // // Created by apple on 2018/2/11. // Copyright © 2018年 Elsa Wei. All rights reserved. // #include <stdio.h> int padocalc(int n) { if (n == 0 || n == 1 || n == 2) { return 1; } else return padocalc(n-2) + padocalc(n - 3); }
C
#include<stdio.h> void lmn(int p) { if(p==4) return; lmn(p+1); printf("%d\n",p); } int main() { lmn(1); return 0; }
C
#include <malloc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> typedef int boolean; #define true 1 #define false 0 typedef void (*Func)(); typedef struct _St_A { Func *vt; } _class_A; _class_A *new_A(void); void _A_first( _class_A *this,int _pn ) { } Func VTClass_A[] = { ( void (*)() ) _A_first }; _class_A *new_A() { _class_A *t; if ( (t = malloc(sizeof(_class_A))) != NULL ) t->vt = VTClass_A; return t; } typedef struct _St_B { Func *vt; } _class_B; _class_B *new_B(void); void _B_second( _class_B *this ) { } Func VTClass_B[] = { ( void (*)() ) _A_first, ( void (*)() ) _B_second }; _class_B *new_B() { _class_B *t; if ( (t = malloc(sizeof(_class_B))) != NULL ) t->vt = VTClass_B; return t; } typedef struct _St_C { Func *vt; } _class_C; _class_C *new_C(void); void _C_third( _class_C *this ) { } Func VTClass_C[] = { ( void (*)() ) _A_first, ( void (*)() ) _B_second, ( void (*)() ) _C_third }; _class_C *new_C() { _class_C *t; if ( (t = malloc(sizeof(_class_C))) != NULL ) t->vt = VTClass_C; return t; } typedef struct _St_Program { Func *vt; } _class_Program; _class_Program *new_Program(void); void _Program_run( _class_Program *this ) { _class_A *_a; _class_B *_b; _class_C *_c; _a = new_A(); _b = new_B(); _c = new_C(); ( (void(*)(_class_A *, int)) _a->vt[0])(_a,0); ( (void(*)(_class_B *, int)) _b->vt[0])(_b,0); ( (void(*)(_class_C *, int)) _c->vt[0])(_c,0); ( (void(*)(_class_B *)) _b->vt[1])(_b); ( (void(*)(_class_C *)) _c->vt[1])(_c); ( (void(*)(_class_C *)) _c->vt[2])(_c); _a = (_class_A *) _b; _a = (_class_A *) _c; _b = (_class_B *) _c; } Func VTClass_Program[] = { ( void (*)() ) _Program_run }; _class_Program *new_Program() { _class_Program *t; if ( (t = malloc(sizeof(_class_Program))) != NULL ) t->vt = VTClass_Program; return t; } int main() { _class_Program *program; program = new_Program(); ( ( void (*)(_class_Program *) ) program->vt[0] )(program); return 0; }
C
/* * Title : Menghitung luas dan keliling segitiga * Name : Rahmat Sabilludin Nurmughni * NIM : A11.2016.09515 * Class : A11.4105 * Compile : Code::Blocks 16.01 Ubuntu (Linux) */ #include <stdio.h> #include <ctype.h> void menghitung(); void luas(); void keliling(); void keluar(); void main(){ menghitung(); } void menghitung(){ char pilihan = ""; printf("=============== Menghitung Luas dan Keliling Segitiga =============== \n\n"); printf("Anda ingin menghitung apa? \n"); printf("(A) Menghitung Luas Segitiga. \n"); printf("(B) Menghitung Keliling Segitiga. \n"); printf("(X) Keluar. \n\n"); printf("Menu yang anda pilih : \n"); scanf("%c",&pilihan); { if (toupper(pilihan) == 'A' ){ luas(); } else if (toupper(pilihan) == 'B'){ keliling(); } else if (toupper(pilihan) == 'X'){ keluar(); } else if (toupper(pilihan) != 'A' , 'B' , 'X'){ menghitung(); } } } void luas(){ float alas, tinggi; printf("======== Menghitung Luas Segitiga ========\n\n"); printf("Masukan nilai alas : "); scanf("%f",&alas); printf("Masukan nilai tinggi : "); scanf("%f",&tinggi); float hasil = 0.5*alas*tinggi; printf("Luas segitiga adalah %.2f \n",hasil); } void keliling(){ float sisi; printf("======== Menghitung Keliling Segitiga ========\n\n"); printf("Masukan nilai sisi : "); scanf("%f",&sisi); printf("Luas segitiga adalah %.2f \n",sisi+sisi+sisi); } void keluar(){ printf("=========== Terima Kasih ===========\n"); printf("++++++++++++++++++++++++++++++++++++\n"); }
C
/* ZZZZZZZZZZZZZZZZZZZZ 8888888888888 00000000000 ZZZZZZZZZZZZZZZZZZZZ 88888888888888888 0000000000000 ZZZZZ 888 888 0000 0000 ZZZZZ 88888888888888888 0000 0000 ZZZZZ 8888888888888 0000 0000 AAAAAA SSSSSSSSSSS MMMM MMMM ZZZZZ 88888888888888888 0000 0000 AAAAAAAA SSSS MMMMMM MMMMMM ZZZZZ 8888 8888 0000 0000 AAAA AAAA SSSSSSSSSSS MMMMMMMMMMMMMMM ZZZZZ 8888 8888 0000 0000 AAAAAAAAAAAA SSSSSSSSSSS MMMM MMMMM MMMM ZZZZZZZZZZZZZZZZZZZZZ 88888888888888888 0000000000000 AAAA AAAA SSSSS MMMM MMMM ZZZZZZZZZZZZZZZZZZZZZ 8888888888888 00000000000 AAAA AAAA SSSSSSSSSSS MMMM MMMM Copyright (C) Paulo Custodio, 2011-2012 Str : Dynamic-length strings based on http://uthash.sourceforge.net/utstring Using class.h for automatic garbage collection. Strings may contain zero byte, length is defined by separate field. */ /* $Header: /cvsroot/z88dk/z88dk/src/z80asm/dynstr.c,v 1.2 2012/11/03 17:39:36 pauloscustodio Exp $ */ /* $Log: dynstr.c,v $ /* Revision 1.2 2012/11/03 17:39:36 pauloscustodio /* astyle, comments /* /* Revision 1.1 2012/06/14 15:03:45 pauloscustodio /* CH_0014 : New Dynamic Strings that grow automatically on creation / concatenation /* /* /* */ #include <string.h> #include <ctype.h> #include "dynstr.h" /*----------------------------------------------------------------------------- * Constants *----------------------------------------------------------------------------*/ #define SIZE_MASK 0xFF /* size will increment in blocks of 256 */ /*----------------------------------------------------------------------------- * Class inplementation *----------------------------------------------------------------------------*/ DEF_CLASS( Str ); void Str_init( Str *self ) { Str_reserve( self, 0 ); Str_clear( self ); } void Str_copy( Str *self ) { char *data_copy = xmalloc( self->size ); memcpy( data_copy, self->data, self->size ); self->data = data_copy; } void Str_fini( Str *self ) { xfree( self->data ); } /*----------------------------------------------------------------------------- * expand if needed to store at least more num_chars plus a zero byte * increment size if blocks of SIZE_MASK (256) *----------------------------------------------------------------------------*/ void Str_reserve( Str *self, size_t num_chars ) { size_t need_size, new_size; if ( self->size == 0 ) /* empty data */ { need_size = num_chars + 1; } else /* append to existing string */ { need_size = self->len + num_chars + 1; } if ( self->size < need_size ) { /* round up in blocks of 256 */ new_size = need_size & ~SIZE_MASK; if ( new_size < need_size ) { new_size += SIZE_MASK + 1; } self->data = ( char * ) xrealloc( self->data, new_size ); self->size = new_size; } } /*----------------------------------------------------------------------------- * delete extra unused space *----------------------------------------------------------------------------*/ void Str_unreserve( Str *self ) { size_t need_size = self->len + 1; self->data = ( char * ) xrealloc( self->data, need_size ); self->size = need_size; } /*----------------------------------------------------------------------------- * set / cat from memory buffer, add always a zero byte after *----------------------------------------------------------------------------*/ void Str_bset( Str *self, char *source, size_t size ) { Str_clear( self ); Str_bcat( self, source, size ); } void Str_bcat( Str *self, char *source, size_t size ) { Str_reserve( self, size ); memcpy( self->data + self->len, source, size ); self->data[ self->len + size ] = 0; /* add zero terminator */ self->len += size; } /*----------------------------------------------------------------------------- * sprintf-like set / cat *----------------------------------------------------------------------------*/ void Str_vfset( Str *self, char *format, va_list argptr ) { Str_clear( self ); Str_vfcat( self, format, argptr ); } void Str_vfcat( Str *self, char *format, va_list argptr ) { int count; size_t free; /* print to string and expand if needed */ while ( 1 ) { free = self->size - self->len - 1; /* vsnprintf needs free > 0 */ if ( free > 0 ) { count = vsnprintf( self->data + self->len, free, format, argptr ); if ( count >= 0 ) { break; /* done */ } } /* increase the size by 256 and try again */ /* +1 -> overflow -> cause new block to be requested */ Str_reserve( self, self->size - self->len + 1 ); } self->len += count; } void Str_fset( Str *self, char *format, ... ) { va_list argptr; va_start( argptr, format ); /* init variable args */ Str_vfset( self, format, argptr ); } void Str_fcat( Str *self, char *format, ... ) { va_list argptr; va_start( argptr, format ); /* init variable args */ Str_vfcat( self, format, argptr ); }
C
#include <stdio.h> #include "myQue.h" bool qempty(qnode head){ if(head==NULL) return true; return false; } void qpop(qnode &head){ qnode tmp = head; head=head->nxt; free(tmp); } void qpush_back(qnode head,pthread_t n){ if(head==NULL){ head.data=n; head->nxt=NULL; qnode_n=1; return; } qnode newqnode; newqnode->nxt=NULL; newqnode->data=n; while(head->nxt!=NULL){ head=head->nxt; } head->nxt=newqnode; } pthread_t qfront(qnode head){ return head.data; } void clean(qnode head){ if(head->nxt!=NULL){ clean(head->nxt); } free(head); } void qclean(qnode head){ if(head->nxt!=NULL) clean(head->nxt); head=NULL; } int qsize(qnode head){ if(head==NULL) return 0; int n=1; while(head->nxt!=NULL){ ++n; head=head->nxt; } return n; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ncurses_players.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: atourner <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/13 12:35:51 by atourner #+# #+# */ /* Updated: 2018/06/15 16:02:28 by nvergnac ### ########.fr */ /* */ /* ************************************************************************** */ #include "vm.h" static char *str_chrreplace(char *str) { int i; char *name; name = ft_strnew(128); i = -1; while (str[++i]) if (str[i] == '\n') str[i] = ' '; else name[i] = str[i]; return (name); } static void wprint_player_and_stuff(WINDOW *player, t_info *info, int i, char *name) { mvwprintw(player, i * 4 + 1, 1, "Player %d -> %d", i + 1, info->players_info[i].number); mvwprintw(player, i * 4 + 2, 1, "\tName : %s", name); mvwprintw(player, i * 4 + 3, 1, "\tLive : %d", info->players_info[i].live); } static void wprint_proc(WINDOW *player, t_info *info, int i) { t_proc *act; int nb_pc; nb_pc = 0; act = info->first_processus; while (act) { if (act->alive >= 0) nb_pc += 1; act = act->next; } mvwprintw(player, i * 4 + 13, 1, "Total proc : %d", nb_pc); } void wprint_player(WINDOW *player, t_info *info, int g_wait_time) { int i; char *name; i = 0; while (i < info->players_nb) { wattron(player, COLOR_PAIR(5 + i)); name = str_chrreplace(info->players_info[i].name); wprint_player_and_stuff(player, info, i, name); ft_strdel(&name); i++; } wattron(player, COLOR_PAIR(1)); mvwprintw(player, --i * 4 + 5, 1, "Current period : %d / %d", info->countdown_to_die, info->cycles_to_die); mvwprintw(player, i * 4 + 6, 1, "Total cycles : %d", info->cycles); mvwprintw(player, i * 4 + 7, 1, "Check : %d / 9", info->check); mvwprintw(player, i * 4 + 9, 1, "Live(s) in current period : %d", info->total_lives); mvwprintw(player, i * 4 + 11, 1, "Wait time : %d ms", g_wait_time); wprint_proc(player, info, i); }
C
#include "lsm6ds33.h" #define ACCEL_DATARATE ACCEL_DR_104_Hz #define ACCEL_RANGE ACCEL_4G #define ACCEL_AA AA_50_Hz #define GYRO_DATARATE GYRO_DR_104_Hz #define GYRO_RANGE FS_245_DPS #define X_SIGN 0 #define Y_SIGN 0 #define Z_SIGN 0 #define ORIENTATION 0 /* * @brief: reads the 2 data registers and puts the raw value into output_high and output_low * * NOTE: REGISTERS ARE LITTLE ENDIAN, THEREFORE THE HIGH REGISTER IS THE MSB AND LOW REGISTER IS LSB * * @param I2C_HandleTypeDef *hi2c: I2C pointer * @param uint32_t dev_addr: device address to get data from * @param uint8_t addr_high: address of the high output register * @param uint8_t addr_low: address of the low output register * @param AxisData_t * axis: output variable as a union * * @return HAL_StatusTypeDef: returns HAL_OK if no errors **/ static HAL_StatusTypeDef readImuReg(I2C_HandleTypeDef * hi2c, uint16_t dev_addr, uint8_t addr_high, uint8_t addr_low, AxisData_t * output) { HAL_StatusTypeDef status; if ((status = HAL_I2C_Mem_Read(hi2c, dev_addr, addr_high, 1, &(output->high), 1, 100)) != HAL_OK) { return status; } if ((status = HAL_I2C_Mem_Read(hi2c, dev_addr, addr_low, 1, &(output->low), 1, 100)) != HAL_OK) { return status; } //OR the MSB with the data read from the register return HAL_OK; } /// @brief: Assign the orientation of the axes static HAL_StatusTypeDef orientImu(I2C_HandleTypeDef * hi2c, bool x_sign, bool y_sign, bool z_sign, uint8_t orientation) { uint8_t setup = x_sign << 5 | y_sign << 4 | z_sign << 3 | orientation; HAL_StatusTypeDef status = HAL_I2C_Mem_Write(hi2c, LSM6DS33_ADDR, ORIENT_CFG_G, 1, &setup, 1, 100); return status; } HAL_StatusTypeDef gyroInit(IMU_t * imu, GYRO_DATA_RATE data_rate, GYRO_FULL_SCALE full_scale, int high_pass_filter) { HAL_StatusTypeDef status; ImuSensor * gyro = &(imu->gyro); // if the device is not ready return error if ((status = HAL_I2C_IsDeviceReady(imu->i2c, LSM6DS33_ADDR, 2, 100)) != HAL_OK) { gyro->broke = 1; return status; } //set the sensitivity based on the full-scale selection switch (full_scale) { case (FS_245_DPS): gyro->conversion = 8.75; break; case (FS_500_DPS): gyro->conversion = 17.5; break; case (FS_1000_DPS): gyro->conversion = 35.0; break; case(FS_2000_DPS): gyro->conversion = 70.0; break; } gyro->conversion = gyro->conversion / 1000; uint8_t init = data_rate << 4 | full_scale << 2; /*Write to Gyro CTRL2 * Set bandwidth to max speed, enable XYZ axes, and enable Normal Mode*/ status = HAL_I2C_Mem_Write(imu->i2c, LSM6DS33_ADDR, CTRL2_G, 1, &init, 1, 100); if (status != HAL_OK) { gyro->broke = 1; return status; } // If the high_pass_filter flag is set, then write to CTRL7 to enable it; if (high_pass_filter) { init = 0x01 << 6; if ((status = HAL_I2C_Mem_Write(imu->i2c, LSM6DS33_ADDR, CTRL7_G, 1, &init, 1, 100)) != HAL_OK) { gyro->broke = 1; return status; } } gyro->broke = 0; return HAL_OK; } /*Read the gyro data for each axis and put that value into the struct's storage values * I2C_HandleTypeDef *hi2c -- pointer to i2c HandleTypeDef * retval: HAL_StatusTypeDef*/ HAL_StatusTypeDef readGyro(ImuSensor * gyro, I2C_HandleTypeDef *hi2c) { HAL_StatusTypeDef status; //read the X registers and write the raw values to the struct's x data point if ((status = readImuReg(hi2c, LSM6DS33_ADDR, OUTX_H_G, OUTX_L_G, &(gyro->x))) != HAL_OK) { gyro->broke = 1; return status; } //read the Y registers and write the raw values to the struct's y data point if ((status = readImuReg(hi2c, LSM6DS33_ADDR, OUTY_H_G, OUTY_L_G, &(gyro->y))) != HAL_OK) { gyro->broke = 1; return status; } //read the Z registers and write the raw values to the struct's z data point if ((status = readImuReg(hi2c, LSM6DS33_ADDR, OUTZ_H_G, OUTZ_L_G, &(gyro->z))) != HAL_OK) { gyro->broke = 1; return status; } return HAL_OK; } HAL_StatusTypeDef accelInit(IMU_t * imu, ACCEL_DATA_RATE data_rate, ACCEL_FS full_scale) { HAL_StatusTypeDef status; ImuSensor * accel = &(imu->accelerometer); if ((status = HAL_I2C_IsDeviceReady(imu->i2c, LSM6DS33_ADDR, 2, 100)) != HAL_OK) { accel->broke = 1; return status; } /*Set the conversion rate for the accelerometer readings based on the full-scale selection * Specified in LSB/mG*/ switch (full_scale) { case(ACCEL_2G): accel->conversion = 0.061; break; case(ACCEL_4G): accel->conversion = 0.122; break; case(ACCEL_8G): accel->conversion = 0.244; break; case(ACCEL_16G): accel->conversion = 0.488; break; default: accel->conversion = 0.122; break; } accel->conversion = accel->conversion / 1000; // init CTRL 1 uint8_t init = data_rate << 4 | full_scale << 2; status = HAL_I2C_Mem_Write(imu->i2c, LSM6DS33_ADDR, CTRL1_XL, 1, &init, 1, 10); if (status != HAL_OK) { accel->broke = 1; return status; } accel->broke = 0; return status; } /*Read the acceleration data for each axis and put that value into the struct's storage values * I2C_HandleTypeDef *hi2c -- pointer to i2c HandleTypeDef * retval: HAL_StatusTypeDef*/ HAL_StatusTypeDef readAccel(ImuSensor * accel, I2C_HandleTypeDef *hi2c) { HAL_StatusTypeDef status; //read the high register for the x axis, return status if error if ((status = readImuReg(hi2c, LSM6DS33_ADDR, OUTX_H_XL, OUTX_L_XL, &(accel->x))) != HAL_OK) { accel->broke = 1; return status; } //read the high register for the y axis, return status if error if ((status = readImuReg(hi2c, LSM6DS33_ADDR, OUTY_H_XL, OUTY_L_XL, &(accel->y))) != HAL_OK) { accel->broke = 1; return status; } //read the high register for the z axis, return status if error if ((status = readImuReg(hi2c, LSM6DS33_ADDR, OUTZ_H_XL, OUTZ_L_XL, &(accel->z))) != HAL_OK) { accel->broke = 1; return status; } return HAL_OK; } HAL_StatusTypeDef imuInit(IMU_t * imu, I2C_HandleTypeDef * hi2c) { imu->i2c = hi2c; HAL_StatusTypeDef status; status = accelInit(imu, ACCEL_DATARATE, ACCEL_RANGE); if (status != HAL_OK) { return status; } status = gyroInit(imu, GYRO_DATARATE, GYRO_RANGE, 0); if (status != HAL_OK) { return status; } // TODO figure out the orientations // orientImu(hi2c, X_SIGN, Y_SIGN, Z_SIGN, ORIENTATION); return HAL_OK; }
C
#include "kc_linearscroll.h" /* http://stackoverflow.com/questions/977233/ * warning-incompatible-implicit-declaration-of-built-in-function-xyz*/ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif float timeb_diff(struct timeb t1, struct timeb t2) { return t1.time - t2.time + (t1.millitm - t2.millitm) / 1000.0; } int sign(float f) { if (f > 0) return 1; else return f == 0 ? 0 : -1; } int positive(float f) { return f >= 0 ? 1 : 0; } /* I wanted to use the ^ operator, but sign() returns 1 or -1, you know, so... */ int diffsign(float a, float b) { return (a > 0 && b < 0) || (a < 0 && b > 0); } #define square(x) ((x) * (x)) #ifndef max #define max(a, b) (a > b ? a : b) #endif #ifndef min #define min(a, b) (a < b ? a : b) #endif float tottime(float v0, float a, float d) { return (fabsf(v0) - sqrt(max(v0*v0-2.0*a*fabsf(d), 0))) / a; } float beyond_dist(float s, float p) { if (p > 0) return p; else if (p < -s) return -p - s; else return 0; } const float REFRESH_INTERVAL = (float)(1 / 60.0); const float CONST_MIN_VELOCITY = 1000; const float CONST_TOUCH_MAX_DUR = 0.15; const float CONST_NORMAL_ACCEL = 1500; const float CONST_RELEASEOUT_DECEL = 4800; const float CONST_BOUNCEAWAY_DECEL = 15500; const float CONST_BOUNCEBACK_DUR = 0.3; const float CONST_BEYOND_DISTANCE = 150; const float CONST_BEYOND_DUR = 0.03; #define REFRESH_INTERVAL (CONST_REFRESH_INTERVAL * context->_rate) #define MIN_VELOCITY (CONST_MIN_VELOCITY * context->_rate) #define TOUCH_MAX_DUR (CONST_TOUCH_MAX_DUR * context->_rate) #define NORMAL_ACCEL (CONST_NORMAL_ACCEL * context->_rate) #define RELEASEOUT_DECEL (CONST_RELEASEOUT_DECEL * context->_rate) #define BOUNCEAWAY_DECEL (CONST_BOUNCEAWAY_DECEL * context->_rate) #define BOUNCEBACK_DUR (CONST_BOUNCEBACK_DUR * context->_rate) #define BEYOND_DISTANCE (CONST_BEYOND_DISTANCE * context->_rate) #define BEYOND_DUR (CONST_BEYOND_DUR * context->_rate) kc_linearscroll *kc_init() { kc_linearscroll *context = (kc_linearscroll *)malloc(sizeof(kc_linearscroll)); context->_refreshing = 0; context->_curpos = context->_v = 0; context->_rate = 1; context->_state.motion = STOPPED; context->_state.border = BORDER_NONE; memset(context->_tn, NUM_MOTIONSTATE, sizeof(float)); memset(context->_dn, NUM_MOTIONSTATE, sizeof(float)); memset(context->_vn, NUM_MOTIONSTATE, sizeof(float)); kc_inittouchdata(context, 0); return context; } void kc_setvisiblesize(kc_linearscroll *context, float new_size) { context->_visiblesize = new_size; if (new_size > context->_contentsize) context->_contentsize = new_size; } void kc_setcontentsize(kc_linearscroll *context, float new_size) { context->_contentsize = max(new_size, context->_visiblesize); } void kc_setuserdata(kc_linearscroll *context, void *data) { context->_userdata = data; } void kc_setcallback_0(kc_linearscroll *context, int index, kc_callback_0 callback) { context->call0[index] = callback; } void kc_setcallback_1(kc_linearscroll *context, int index, kc_callback_1 callback) { context->call1[index] = callback; } void kc_setcallback_2(kc_linearscroll *context, int index, kc_callback_2 callback) { context->call2[index] = callback; } void kc_setpos(kc_linearscroll *context, float pos) { context->_curpos = pos; (*context->call1[UPDATE_POSITION])(context->_userdata, context->_curpos); } float kc_getpos(kc_linearscroll *context) { return context->_curpos; } void kc_inittouchdata(kc_linearscroll *context, float pos) { struct timeb now; ftime(&now); int i; for (i = 0; i < TOUCHES_RECORDED; i++) { context->_ttime[i] = now; context->_tpos[i] = pos; } } void kc_startrefresh(kc_linearscroll *context) { if (context->_refreshing == 0) { (*context->call0[START_REFRESHING])(context->_userdata); context->_refreshing = 1; } } void kc_stoprefresh(kc_linearscroll *context) { if (context->_refreshing == 1) { (*context->call0[STOP_REFRESHING])(context->_userdata); context->_refreshing = 0; } } #define K 0.382 #define VS context->_visiblesize void kc_setmypos(kc_linearscroll *context, float pos) { float s = context->_contentsize - context->_visiblesize; if (pos > 0) pos = K*(sqrt(pos/VS+K*K*0.25)-K*0.5) * VS; else if (pos < -s) pos = -K*(sqrt(-(pos+s)/VS+K*K*0.25)-K*0.5) * VS - s; context->_curpos = pos; (*context->call1[UPDATE_POSITION])(context->_userdata, context->_curpos); } float kc_getmypos(kc_linearscroll *context) { float s = context->_contentsize - context->_visiblesize; float pos = context->_curpos; if (pos > 0) pos = (square(pos/(VS*K)+K*0.5)-K*K*0.25) * VS; else if (pos < -s) pos = -(square(-(pos+s)/(VS*K)+K*0.5)-K*K*0.25) * VS - s; return pos; } #undef K #undef VS int kc_activate(kc_linearscroll *context, int index, float arg) { float pos = arg; int i; float s, elapsed; switch (index) { case TOUCH_BEGAN: kc_stoprefresh(context); context->_v = 0; context->_state.motion = STOPPED; memset(context->_tn, NUM_MOTIONSTATE, sizeof(float)); memset(context->_dn, NUM_MOTIONSTATE, sizeof(float)); memset(context->_vn, NUM_MOTIONSTATE, sizeof(float)); kc_inittouchdata(context, pos); break; case TOUCH_MOVED: /* move the whole array left */ for (i = 0; i < TOUCHES_RECORDED - 1; i++) { context->_ttime[i] = context->_ttime[i + 1]; context->_tpos[i] = context->_tpos[i + 1]; } /* record current touch data */ ftime(&context->_ttime[TOUCHES_RECORDED - 1]); context->_tpos[TOUCHES_RECORDED - 1] = pos; /* if the touch changed the direction, re-initialise data */ if (diffsign( context->_tpos[TOUCHES_RECORDED-1] - context->_tpos[TOUCHES_RECORDED-2], context->_tpos[TOUCHES_RECORDED-2] - context->_tpos[TOUCHES_RECORDED-3])) kc_inittouchdata(context, pos); /* update position */ kc_setmypos(context, kc_getmypos(context) + context->_tpos[TOUCHES_RECORDED-1] - context->_tpos[TOUCHES_RECORDED-2]); break; case TOUCH_ENDED: /* get current time and save to the last touch data */ ftime(&context->_ttime[TOUCHES_RECORDED - 1]); /* get the current position */ s = context->_contentsize - context->_visiblesize; /* calculate the last velocity */ elapsed = timeb_diff(context->_ttime[TOUCHES_RECORDED-1], context->_ttime[0]); context->_v = (context->_tpos[TOUCHES_RECORDED-1] - context->_tpos[0]) / elapsed; if (context->_curpos > 0) { float S = kc_getpos(context); context->_state.motion = RELEASED_OUTSIDE; context->_state.border = BORDER_DOWN_LEFT; context->_v = 0; kc_startrefresh(context); /* 1/2*a*t^2 = s * therefore, t = sqrt(2s/a). */ context->_tn[RELEASED_OUTSIDE] = sqrt((S + S) / RELEASEOUT_DECEL); context->_dn[RELEASED_OUTSIDE] = kc_getpos(context); context->_vn[RELEASED_OUTSIDE] = context->_tn[RELEASED_OUTSIDE] * RELEASEOUT_DECEL; } else if (context->_curpos < -s) { float S = -kc_getpos(context) - s; context->_state.motion = RELEASED_OUTSIDE; context->_state.border = BORDER_UP_RIGHT; context->_v = 0; kc_startrefresh(context); context->_tn[RELEASED_OUTSIDE] = sqrt((S + S) / RELEASEOUT_DECEL); context->_dn[RELEASED_OUTSIDE] = kc_getpos(context); context->_vn[RELEASED_OUTSIDE] = context->_tn[RELEASED_OUTSIDE] * RELEASEOUT_DECEL; } else if (elapsed && elapsed <= TOUCH_MAX_DUR && fabsf(context->_v) >= MIN_VELOCITY) { float V = fabsf(context->_v); float P = kc_getpos(context); float VIP = positive(context->_v); /* velocity is positive? */ context->_state.motion = FREE_SCROLL; kc_startrefresh(context); context->_tn[FREE_SCROLL] = tottime(V, NORMAL_ACCEL, VIP ? -P : -P - s); context->_dn[FREE_SCROLL] = P; context->_vn[FREE_SCROLL] = V; context->_state.velocity = VIP ? BORDER_UP_RIGHT : BORDER_DOWN_LEFT; /* Calculate time for decelerating and getting away */ context->_vn[HIT_BORDER_AWAY] = V - context->_tn[FREE_SCROLL] * NORMAL_ACCEL; } else { context->_v = 0; kc_stoprefresh(context); } break; case REFRESH_TICK: context->_tn[TN_TOTAL] += arg; if (context->_state.motion == FREE_SCROLL) { float t = context->_tn[TN_TOTAL]; unsigned goon = FALSE; if (context->_tn[TN_TOTAL] >= context->_tn[FREE_SCROLL]) { context->_state.motion = HIT_BORDER_AWAY; t = context->_tn[FREE_SCROLL]; context->_tn[TN_TOTAL] -= context->_tn[FREE_SCROLL]; context->_tn[HIT_BORDER_AWAY] = fabsf(context->_vn[HIT_BORDER_AWAY]) <= 1e-4 ? 0 : tottime(context->_vn[HIT_BORDER_AWAY], BOUNCEAWAY_DECEL, BEYOND_DISTANCE); goon = TRUE; } float St = (context->_vn[FREE_SCROLL] - 0.5 * NORMAL_ACCEL * t) * t; if (context->_state.velocity == BORDER_DOWN_LEFT) /* Negative initial velocity (v0). */ kc_setpos(context, context->_dn[FREE_SCROLL] - St); else /* Positive initial velocity (v0). */ kc_setpos(context, context->_dn[FREE_SCROLL] + St); if (goon) context->_dn[HIT_BORDER_AWAY] = kc_getpos(context); } else if (context->_state.motion == HIT_BORDER_AWAY) { float t = context->_tn[TN_TOTAL]; unsigned goon = FALSE; if (context->_tn[TN_TOTAL] >= context->_tn[HIT_BORDER_AWAY]) { context->_state.motion = HIT_BORDER_BEYOND; t = context->_tn[HIT_BORDER_AWAY]; context->_tn[TN_TOTAL] -= context->_tn[HIT_BORDER_AWAY]; goon = TRUE; } if (context->_state.velocity == BORDER_DOWN_LEFT) kc_setpos(context, context->_dn[HIT_BORDER_AWAY] - t*(context->_vn[HIT_BORDER_AWAY] - 0.5*BOUNCEAWAY_DECEL*t)); else kc_setpos(context, context->_dn[HIT_BORDER_AWAY] + t*(context->_vn[HIT_BORDER_AWAY] - 0.5*BOUNCEAWAY_DECEL*t)); if (goon) { context->_dn[HIT_BORDER_BEYOND] = kc_getpos(context); context->_tn[HIT_BORDER_BEYOND] = context->_dn[HIT_BORDER_BEYOND] >= BEYOND_DISTANCE ? 0 : BEYOND_DUR; context->_vn[HIT_BORDER_BEYOND] = context->_vn[HIT_BORDER_AWAY] - context->_tn[HIT_BORDER_AWAY] * BOUNCEAWAY_DECEL; } } else if (context->_state.motion == HIT_BORDER_BEYOND) { float t = context->_tn[TN_TOTAL]; unsigned goon = FALSE; if (context->_tn[TN_TOTAL] >= context->_tn[HIT_BORDER_BEYOND]) { context->_state.motion = HIT_BORDER_BACK_ACC; t = context->_tn[HIT_BORDER_BEYOND]; context->_tn[TN_TOTAL] -= context->_tn[HIT_BORDER_BEYOND]; goon = TRUE; } if (context->_state.velocity == BORDER_DOWN_LEFT) kc_setpos(context, context->_dn[HIT_BORDER_BEYOND] - t*context->_vn[HIT_BORDER_BEYOND] * (1 - 0.5 * t / BEYOND_DUR)); else kc_setpos(context, context->_dn[HIT_BORDER_BEYOND] + t*context->_vn[HIT_BORDER_BEYOND] * (1 - 0.5 * t / BEYOND_DUR)); if (goon) { context->_dn[HIT_BORDER_BACK_ACC] = kc_getpos(context); float bd = beyond_dist( context->_contentsize - context->_visiblesize, context->_dn[HIT_BORDER_BACK_ACC]); context->_tn[HIT_BORDER_BACK_ACC] = /* See below */ context->_tn[HIT_BORDER_BACK_DEC] = BOUNCEBACK_DUR; context->_vn[HIT_BORDER_BACK_ACC] = 0; context->_vn[HIT_BORDER_BACK_DEC] = 0.5 * bd / context->_tn[HIT_BORDER_BACK_DEC]; } } else if (context->_state.motion == HIT_BORDER_BACK_ACC) { float t = context->_tn[TN_TOTAL]; unsigned goon = FALSE; if (context->_tn[TN_TOTAL] >= context->_tn[HIT_BORDER_BACK_ACC]) { context->_state.motion = HIT_BORDER_BACK_DEC; t = context->_tn[HIT_BORDER_BACK_ACC]; context->_tn[TN_TOTAL] -= context->_tn[HIT_BORDER_BACK_ACC]; goon = TRUE; } if (context->_state.velocity == BORDER_DOWN_LEFT) kc_setpos(context, context->_dn[HIT_BORDER_BACK_ACC] + context->_vn[HIT_BORDER_BACK_DEC] / context->_tn[HIT_BORDER_BACK_ACC] * t * t); else kc_setpos(context, context->_dn[HIT_BORDER_BACK_ACC] - context->_vn[HIT_BORDER_BACK_DEC] / context->_tn[HIT_BORDER_BACK_ACC] * t * t); if (goon) context->_dn[HIT_BORDER_BACK_DEC] = kc_getpos(context); } else if (context->_state.motion == HIT_BORDER_BACK_DEC) { float t = context->_tn[TN_TOTAL]; if (context->_tn[TN_TOTAL] >= context->_tn[HIT_BORDER_BACK_DEC]) { /* We stop here. */ kc_stoprefresh(context); context->_tn[TN_TOTAL] = 0; context->_state.motion = STOPPED; t = context->_tn[HIT_BORDER_BACK_DEC]; } if (context->_state.velocity == BORDER_DOWN_LEFT) kc_setpos(context, context->_dn[HIT_BORDER_BACK_DEC] + 2 * t * context->_vn[HIT_BORDER_BACK_DEC] * (1 - 0.5 * t / context->_tn[HIT_BORDER_BACK_DEC])); else kc_setpos(context, context->_dn[HIT_BORDER_BACK_DEC] - 2 * t * context->_vn[HIT_BORDER_BACK_DEC] * (1 - 0.5 * t / context->_tn[HIT_BORDER_BACK_DEC])); } else if (context->_state.motion == RELEASED_OUTSIDE) { float t = context->_tn[TN_TOTAL]; if (context->_tn[TN_TOTAL] >= context->_tn[RELEASED_OUTSIDE]) { kc_stoprefresh(context); t = context->_tn[RELEASED_OUTSIDE]; context->_tn[TN_TOTAL] = 0; } float St = (context->_vn[RELEASED_OUTSIDE] - 0.5 * RELEASEOUT_DECEL * t) * t; if (context->_state.border == BORDER_DOWN_LEFT) kc_setpos(context, context->_dn[RELEASED_OUTSIDE] - St); else kc_setpos(context, context->_dn[RELEASED_OUTSIDE] + St); } break; default: /* Invalid index. Return code 1 */ return 1; } return 0; }
C
#include"SeqHead.h" int Insert(SeqList* list,int n,mytype x)//插入元素到第n个,错误返回-1,成功返回1 { int i; if(n > list->len) { printf("erro"); return -1; } else if(list->len == MAXLEN) { printf("erro"); return -1; } else if(n < 0) { printf("erro"); return -1; } else { for(i = list->len;i > (n);i--) { list->array[i] = list->array[i-1]; } list->array[i] = x; list->len++; printf("插入成功1\n"); return 1; } return 1; }
C
#include<stdio.h> struct POINT{ int x,y; }; char left(struct POINT *ivst,struct POINT *p1,struct POINT *p2){ if(p1->x==p2->x&&p1->x<ivst->x) return 1; return 0; } char cross_threshold(struct POINT *ivst,struct POINT *p1,struct POINT *p2){ if(p1->y>=ivst->y&&p2->y<ivst->y) return 1; if(p2->y>=ivst->y&&p1->y<ivst->y) return 1; return 0; } char is_contain(struct POINT p[],struct POINT *ivst,int n_v){ char result=0; int next,i; for(i=0;i<n_v;i++){ next=(i+1)%n_v; if(cross_threshold(ivst,&p[i],&p[next])) if(left(ivst,&p[i],&p[next])) result=!result; } return result; } int main(){ int n_v,i; struct POINT p[1005],ivst; while(scanf("%d",&n_v),n_v){ for(i=0;i<n_v;i++) scanf("%d%d",&p[i].x,&p[i].y); scanf("%d%d",&ivst.x,&ivst.y); if(is_contain(p,&ivst,n_v)) puts("T"); else puts("F"); } return 0; }
C
#include <stdio.h> int main() { double journey, fee = 0; int time; scanf("%lf %d", &journey, &time); if(journey <= 3) fee = 10.0; else if(journey <= 10) fee = 10.0 + (journey - 3.0) * 2.0; else fee = 24.0 + (journey - 10.0) * 3.0; if(time >= 5) fee += time / 5 * 2; printf("%.0lf", fee); return 0; }
C
#include <unp.h> int main(int argc, char ** argv) { if (argc < 2) err_quit("wrong parametes"); in_addr_t addr; addr = inet_addr(argv[1]); printf("%x\n", addr); struct in_addr addr_stru; addr_stru.s_addr = addr; printf("convert back: %s\n", inet_ntoa(addr_stru)); return 0; }
C
#include <stdio.h> int main() { int x;int factorial=1; printf("please enter any number\n"); scanf("%d" , &x); for (int i=1;i<=x;i++) { factorial = factorial*i;} printf("factorial =%d\n",factorial); return 0; }
C
/****************************************************************************** Heat Equation Richardson's Method - Algorithm 12.2C ******************************************************************************* To approximate the solution of the Parabolic partial-differential equation u(x,t)/t - u(x,t)/x = 0, 0 < x < l, 0 < t < T, subject to the boundry conditions u(0,t) = u(l,t) = 0, 0 < t < T, and the initial conditions u(x,0) = f(x), 0 x l: INPUT endpoint l; maximum time T; constant ; integers m, N; the functions u(), and f(). OUTPUT approximations w(i,t(j)) to u(x(i),t(j)) for each i = 1,...,m-1 and j = 1,...,N. NOTE: This method has serious stability problems. NOTE: This algorithm was included as a "Homework Helper." See p. 632, Exercise Set 12.3, Problem *** 6 ***. ******************************************************************************* * Written by: Harold A. Toomey, CARE-FREE SOFTWARE, 3Q 1991, v4.2 * ******************************************************************************/ /* ** Set the EQ_EVAL flag to TRUE in "naautil.c" to use the Equation Evaluator. */ #include "naautil.c" /* Numerical Analysis Algorithms Utilities. */ char *outfile = "122c.out"; /* Customized default output file name. */ char *eq_text_f = "f(x) = sin(PI*x)"; /* Needs updating $ */ double *w, *wprev, *wprev2, f(); double h, k, ll, T, lambda, alpha; double w_APPROX(), w_TRUE(); int m, N; /*****************************************************************************/ /* f(x) - Initial condition function, f(x). Needs updating $. */ /*****************************************************************************/ double f(x) double x; { if ((x == 0.0) || (x == ll)) return (0.0); /* Boundary conditions. */ else { if (eqeval) return (eval_eq(x)); /* Use the Equation Evaluator */ else return (sin(PI*x)); /* Use the default function. */ } } /*****************************************************************************/ /* w_TRUE(x,t) - True solution function, w_TRUE(x,t). Needs updating $. */ /*****************************************************************************/ double w_TRUE(x,t) double x,t; { return (exp(-PI*PI*t)*sin(PI*x)); } /*****************************************************************************/ main() { int i, j; /********** * INPUTS * **********/ NAA_do_first(outfile); /* NAA initialization procedure. */ printf2("Heat Equation Richardson's Method - Algorithm 12.2C\n\n"); printf2("u(x,t)/t - u(x,t)/x = 0\n\n"); printf2("%s\n", eq_text_f); printf("Enter endpoint l: "); scanf("%lf", &ll); printf("Enter maximum time, T: "); scanf("%lf", &T); fprintf(file_id, "u(0,t) = u(l,t) = 0, 0 < t < T = %lG\n", T); fprintf(file_id, "u(x,0) = f(x), 0 x l = %lG\n\n", ll); printf("Enter : "); scanf("%lf", &alpha); fprintf(file_id, " = %lG\n", alpha); do { printf("Enter number of space intervals, m: "); scanf("%d", &m); if (m <= 0) printf("ERROR - m must be greter than zero.\n"); } while (m <= 0); fprintf(file_id, "Number of space intervals, m = %d\n", m); do { printf("Enter number of time intervals, N: "); scanf("%d", &N); if (N <= 0) printf("ERROR - N must be greter than zero.\n"); } while (N <= 0); fprintf(file_id, "Number of time intervals, N = %d\n\n", N); /* Dynamically allocate memory for the needed arrays. */ w = dvector(0,m); wprev = dvector(0,m); /* Solution at t(i-1). */ wprev2 = dvector(0,m); /* Solution at t(i-2). */ /************* * ALGORITHM * *************/ /* STEP #1 */ h = ll/m; /* x = i*h */ k = T/N; /* t = j*k */ lambda = (alpha*alpha*k) / (h*h); /* STEP #2 */ for (i=0;i<=m;i++) { /* Initial values. */ wprev2[i] = f(i*h); /* May be incorrect, but close, since we do */ /* not know the initial conditions at t(-1). */ wprev[i] = f(i*h); } printf2("t = %lG\n", 0.0); printf2(" i\t x(i)\t w(i)"); /* Print table header. */ printf2("\n---------------------------------------\n"); printf2(" %d\t % 8.8lG\t% 8.8lG\n", 0, 0.0, 0.0); for (i=1;i<m;i++) printf2(" %d\t % 8.8lG\t% 8.8lG\n", i, i*h, wprev[i]); printf2(" %d\t % 8.8lG\t% 8.8lG\n\n\n", m, m*h, 0.0); /* ** Step #4 does away with solving for a tridiagonal matrix if you state ** the boundary conditions in w_APPROX(). Much easier to program for. */ /* STEP #3 */ for (j=0;j<N;j++) { /* STEP #4 */ for (i=0;i<=m;i++) /* Compute points for t>t0. */ w[i] = w_APPROX(i); /*********** * OUTPUTS * ***********/ /* STEP #5 */ printf2("t = %lG\n", (j+1)*k); printf2(" i\t x(i)\t w(i)"); printf2("\n---------------------------------------\n"); printf2(" %d\t % 8.8lG\t% 8.8lG\n", 0, 0.0, 0.0); for (i=1;i<m;i++) printf2(" %d\t % 8.8lG\t% 8.8lG\n", i, i*h, w[i]); printf2(" %d\t % 8.8lG\t% 8.8lG\n\n\n", m, m*h, 0.0); /* STEP #6 */ for (i=0;i<=m;i++) { /* Prepare for next "time" iteration. */ wprev2[i] = wprev[i]; wprev[i] = w[i]; } } /* Free the memory that was dynamically allocated for the arrays. */ free_dvector(wprev2,0,m); free_dvector(wprev,0,m); free_dvector(w,0,m); NAA_do_last(outfile); /* NAA finish-up procedure. */ } /* STEP #7 */ /* STOP - Procedure is complete. */ /*****************************************************************************/ /* w_APPROX(i) - Approximates the solution with a difference equation. */ /* See Richardson's Method, p.628 */ /*****************************************************************************/ double w_APPROX(i) int i; { if ((i == 0) || (i == m)) /* Boudary conditions. */ return (0.0); else /* Forward Difference Equation. */ return (2*lambda * (wprev[i+1] - 2*wprev[i] + wprev[i-1]) + wprev2[i]); } /*****************************************************************************/ /* Copyright (C) 1988-1991, Harold A. Toomey, All Rights Reserved. */ /*****************************************************************************/
C
#include <msp430.h> #define S1 P2IN&BIT1 #define S2 P1IN&BIT1 /** * main.c */ int main(void) { //WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer //interfacing LED 1 and LED 2 as outputs P1DIR |= BIT0; //P1.0 Output direction P4DIR |= BIT7; //P4.7 Output direction P1OUT &= ~BIT0; //led 1 is OFF P4OUT |= BIT7; //led 2 is ON P2DIR &= ~BIT1; P2REN |= BIT1; P2OUT |= BIT1; P1DIR &= ~BIT1; P1REN |= BIT1; P2OUT |= BIT1; unsigned int i = 0; while(1) { if((S1) == 0) { for(i = 0; i < 2000; i++); if((S1) == 0) { P4OUT &= ~BIT7; while((S1) == 0) { for(i = 0; i < 50000; i++); P1OUT ^= BIT0; } P1OUT &= ~BIT0; P4OUT |= BIT7; } P1OUT &= ~BIT0; P4OUT |= BIT7; } if((S2) == 0) { for(i = 0; i < 2000; i++); if((S2) == 0) { P1OUT |= BIT0; while((S2) == 0) { for(i = 0; i < 20000; i++); P4OUT ^= BIT7; } P1OUT &= ~BIT0; P4OUT |= BIT7; } P1OUT &= ~BIT0; P4OUT |= BIT7; } else { P1OUT &= ~BIT0; P4OUT |= BIT7; } P1OUT &= ~BIT0; P4OUT |= BIT7; } }
C
#include<stdio.h> int main() { // 13, 21, 52 - n kolejnych liczb int n; printf("Podaj liczbę n: "); scanf("%d", &n); int i=1; int suma=0; /* for (i=1; i<=n; i++) if (i%100 == 13 || i%100 == 21 || i%100 == 52) { suma = suma + i; } else n++; while (i<=n) { if (i%100 == 13 || i%100 == 21 || i%100 == 52) { suma = suma + i; } else n++; i++; } */ do { if (i%100 == 13 || i%100 == 21 || i%100 == 52) { suma = suma + i; printf("%d\n", i); } else n++; i++; } while (i<=n); printf("%d\n", suma); return 0; }
C
#include<stdio.h> #include"libstack.h" /* xの値を表示する関数 */ void print_x(int x) { printf("the valule of x: %d\n", x); } int main() { struct cell * init=NULL; int x; /* stackの状態を表示 */ printstack(init); /* stackに2をpushして,更新後のstackへのポインタを受け取る */ printf("push(init, 2)\n"); init = push(init, 2); printstack(init); // stackの状態を表示 /* stackに4をpushして,更新後のstackへのポインタを受け取る */ printf("push(init, 4)\n"); init = push(init, 4); printstack(init); // stackの状態を表示 /* stackに1をpushして,更新後のstackへのポインタを受け取る */ printf("push(init, 1)\n"); init = push(init, 1); printstack(init); // stackの状態を表示 /* stackからpopして,popされた値を表示する */ printf("pop(init)\n"); x = top(init); print_x(x); init = pop(init); printstack(init); /* stackからpopして,popされた値を表示する */ printf("pop(init)\n"); x = top(init); print_x(x); init = pop(init); printstack(init); /* stackからpopして,popされた値を表示する */ printf("pop(init)\n"); x = top(init); print_x(x); init = pop(init); printstack(init); /* 終了 */ return 0; }
C
#include <stdio.h> #include <string.h> #define SEC_PER_HOUR 3600. /*************************************************************************/ /* */ /* File: calc_stress.c */ /* */ /* Date: December 2015 */ /* */ /* Description: Use the time (in seconds) spent in each heart rate */ /* to approximate the physiological stress */ /* each <time> tag. */ /* */ /* Inputs: */ /* */ /*************************************************************************/ void calc_stress(int *zone_bin, float *total_stress) { // I adapted the following stress correlation from djconnel.blogspot.com // Units are in [1/hr] float stress_correlation[7] = {12., 24., 45., 100., 120., 160., 220.}; float zone_bin_hour[7] = {0}; int ii = 0; // Convert the time in each zone (passed in with units [seconds]) to [hours] // calculate stress for each zone and sum for(ii = 0;ii < 6;ii++) { zone_bin_hour[ii] = zone_bin[ii] / SEC_PER_HOUR; *total_stress = *total_stress + zone_bin_hour[ii] * stress_correlation[ii]; } }
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 */ /* Type definitions */ struct preloaded_file {struct file_metadata* f_metadata; } ; struct file_metadata {size_t md_size; int md_type; struct file_metadata* md_next; int /*<<< orphan*/ md_data; } ; /* Variables and functions */ int /*<<< orphan*/ bcopy (void*,int /*<<< orphan*/ ,size_t) ; struct file_metadata* malloc (int) ; void file_addmetadata(struct preloaded_file *fp, int type, size_t size, void *p) { struct file_metadata *md; md = malloc(sizeof(struct file_metadata) - sizeof(md->md_data) + size); if (md != NULL) { md->md_size = size; md->md_type = type; bcopy(p, md->md_data, size); md->md_next = fp->f_metadata; } fp->f_metadata = md; }
C
#include <stdio.h> #pragma warning (disable:4996) int second(int num1); int second(num1) { int h, m, s; printf(" Է: "); scanf("%d", &num1); h = num1 / 3600; m = (num1%3600) / 60; s = num1 % 60; printf("%d %d %d", h, m, s); } void main() { int num1=0; second(num1); }
C
#include <stdio.h> int main(void){ int n,m,l,p,q,r,ans=0; scanf("%d%d%d%d%d%d",&n,&m,&l,&p,&q,&r); if ( (n/p)*(m/q)*(l/r)>ans){ ans=(n/p)*(m/q)*(l/r); } if ( (n/p)*(m/r)*(l/q)>ans){ ans=(n/p)*(m/r)*(l/q); } if ( (n/q)*(m/p)*(l/r)>ans){ ans=(n/q)*(m/p)*(l/r); } if ( (n/q)*(m/r)*(l/p)>ans){ ans=(n/q)*(m/r)*(l/p); } if ( (n/r)*(m/p)*(l/q)>ans){ ans=(n/r)*(m/p)*(l/q); } if ( (n/r)*(m/q)*(l/p)>ans){ ans=(n/r)*(m/q)*(l/p); } printf("%d\n",ans); return 0; } ./Main.c: In function main: ./Main.c:4:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d%d%d%d%d%d",&n,&m,&l,&p,&q,&r); ^
C
#include "space.h" #include "thread.h" #include <string.h> #include <math.h> typedef struct ZGridCell { unsigned count; unsigned first_agent_i; } ZGridCell; static inline int4 _position_to_cell_indices(float4 pos, float4 orig, float4 sizes, int dims) { int4 indices; switch (dims) { case 1: { indices.x = (int)floorf((pos.x - orig.x) / sizes.x); } break; case 2: { indices.x = (int)floorf((pos.x - orig.x) / sizes.x); indices.y = (int)floorf((pos.y - orig.y) / sizes.y); } break; case 3: { indices.x = (int)floorf((pos.x - orig.x) / sizes.x); indices.y = (int)floorf((pos.y - orig.y) / sizes.y); indices.z = (int)floorf((pos.z - orig.z) / sizes.z); } break; default: { indices.x = (int)floorf((pos.x - orig.x) / sizes.x); indices.y = (int)floorf((pos.y - orig.y) / sizes.y); indices.z = (int)floorf((pos.z - orig.z) / sizes.z); indices.w = (int)floorf((pos.w - orig.w) / sizes.w); }; } return indices; } static inline unsigned _cell_indices_to_cell_index(int4 idx, int dims) { if (dims == 1) { return idx.x; } else if (dims == 2) { /* 16 bits */ unsigned x = idx.x; unsigned y = idx.y; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y = (y | (y << 8)) & 0x00FF00FF; y = (y | (y << 4)) & 0x0F0F0F0F; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); } else if (dims == 3) { /* 10 bits */ unsigned x = idx.x; unsigned y = idx.y; unsigned z = idx.z; x = (x | (x << 16)) & 0x030000FF; x = (x | (x << 8)) & 0x0300F00F; x = (x | (x << 4)) & 0x030C30C3; x = (x | (x << 2)) & 0x09249249; y = (y | (y << 16)) & 0x030000FF; y = (y | (y << 8)) & 0x0300F00F; y = (y | (y << 4)) & 0x030C30C3; y = (y | (y << 2)) & 0x09249249; z = (z | (z << 16)) & 0x030000FF; z = (z | (z << 8)) & 0x0300F00F; z = (z | (z << 4)) & 0x030C30C3; z = (z | (z << 2)) & 0x09249249; return x | (y << 1) | (z << 2); } else { /* not implemented */ return 0; } } static inline int4 _cell_index_to_cell_indices(unsigned i, int dims) { unsigned x, y, z; if (dims == 1) { x = i; } else if (dims == 2) { x = i & 0x55555555; x = (x | (x >> 1)) & 0x33333333; x = (x | (x >> 2)) & 0x0f0f0f0f; x = (x | (x >> 4)) & 0x00ff00ff; x = (x | (x >> 8)) & 0x0000ffff; y = (i >> 1) & 0x55555555; y = (y | (y >> 1)) & 0x33333333; y = (y | (y >> 2)) & 0x0f0f0f0f; y = (y | (y >> 4)) & 0x00ff00ff; y = (y | (y >> 8)) & 0x0000ffff; } else if (dims == 3) { x = i & 0x09249249; x = (x | (x >> 2)) & 0x030c30c3; x = (x | (x >> 4)) & 0x0300f00f; x = (x | (x >> 8)) & 0xff0000ff; x = (x | (x >> 16)) & 0x000003ff; y = (i >> 1) & 0x09249249; y = (y | (y >> 2)) & 0x030c30c3; y = (y | (y >> 4)) & 0x0300f00f; y = (y | (y >> 8)) & 0xff0000ff; y = (y | (y >> 16)) & 0x000003ff; z = (i >> 2) & 0x09249249; z = (z | (z >> 2)) & 0x030c30c3; z = (z | (z >> 4)) & 0x0300f00f; z = (z | (z >> 8)) & 0xff0000ff; z = (z | (z >> 16)) & 0x000003ff; } else { /* not implemented */ } return (int4){x, y, z}; } static inline unsigned _round_down_to_power_of_2(unsigned v) { unsigned n = 0u; while ((1u << (n + 1u)) <= v) ++n; return n; } static inline unsigned _round_up_to_power_of_2(unsigned v) { unsigned n = 0u; while ((1u << n) <= v) ++n; return n; } static inline unsigned _powi(unsigned v, int dims) { unsigned p = 1u; for (int i = 0; i < dims; ++i) p *= v; return p; } void cpu_z_grid_on_simulation_start(Space *space) { CpuZGrid *grid = &space->cpu_z_grid; grid->cells = space->shared; grid->max_cells = space->shared_size / (unsigned)sizeof(ZGridCell); memset(space->cpu_z_grid.cells, 0, space->cpu_z_grid.max_cells * sizeof(ZGridCell)); } void cpu_z_grid_sort(TayGroup *group) { Space *space = &group->space; CpuZGrid *grid = &space->cpu_z_grid; space_update_box(group); unsigned n = 0; for (int i = 0; i < space->dims; ++i) { float cell_size = space->min_part_sizes.arr[i]; float space_size = space->box.max.arr[i] - space->box.min.arr[i] + cell_size * 0.001f; unsigned cells_count = (unsigned)floorf(space_size / cell_size); unsigned side_n = _round_down_to_power_of_2(cells_count); if (side_n > n) n = side_n; } while (_powi(1u << (n + 1u), space->dims) > grid->max_cells) --n; grid->origin = space->box.min; for (int i = 0; i < space->dims; ++i) { float cell_size = space->min_part_sizes.arr[i]; float space_size = space->box.max.arr[i] - space->box.min.arr[i] + cell_size * 0.001f; grid->cell_counts.arr[i] = 1u << n; grid->cell_sizes.arr[i] = space_size / (float)grid->cell_counts.arr[i]; } grid->cells_count = _powi(1u << n, space->dims); /* ............................ */ for (unsigned i = 0; i < space->count; ++i) { TayAgentTag *agent = (TayAgentTag *)(group->storage + group->agent_size * i); float4 p = float4_agent_position(agent); int4 indices = _position_to_cell_indices(p, grid->origin, grid->cell_sizes, space->dims); unsigned cell_i = _cell_indices_to_cell_index(indices, space->dims); ZGridCell *cell = grid->cells + cell_i; agent->part_i = cell_i; agent->cell_agent_i = cell->count++; } unsigned first_agent_i = 0; for (unsigned cell_i = 0; cell_i < grid->cells_count; ++cell_i) { ZGridCell *cell = grid->cells + cell_i; cell->first_agent_i = first_agent_i; first_agent_i += cell->count; } for (unsigned i = 0; i < space->count; ++i) { TayAgentTag *src = (TayAgentTag *)(group->storage + group->agent_size * i); unsigned sorted_agent_i = grid->cells[src->part_i].first_agent_i + src->cell_agent_i; TayAgentTag *dst = (TayAgentTag *)(group->sort_storage + group->agent_size * sorted_agent_i); memcpy(dst, src, group->agent_size); } void *storage = group->storage; group->storage = group->sort_storage; group->sort_storage = storage; } void cpu_z_grid_unsort(TayGroup *group) { memset(group->space.cpu_z_grid.cells, 0, group->space.cpu_z_grid.cells_count * sizeof(ZGridCell)); } typedef struct { unsigned beg; unsigned end; } ZGridKernelCell; void cpu_z_grid_see_seen(TayPass *pass, AgentsSlice seer_slice, Box seer_box, int dims, struct TayThreadContext *thread_context) { CpuZGrid *seen_grid = &pass->seen_group->space.cpu_z_grid; int4 min_indices = _position_to_cell_indices(seer_box.min, seen_grid->origin, seen_grid->cell_sizes, dims); int4 max_indices = _position_to_cell_indices(seer_box.max, seen_grid->origin, seen_grid->cell_sizes, dims); for (int i = 0; i < dims; ++i) { if (min_indices.arr[i] < 0) min_indices.arr[i] = 0; if (max_indices.arr[i] < 0) max_indices.arr[i] = 0; if (min_indices.arr[i] >= seen_grid->cell_counts.arr[i]) min_indices.arr[i] = seen_grid->cell_counts.arr[i] - 1; if (max_indices.arr[i] >= seen_grid->cell_counts.arr[i]) max_indices.arr[i] = seen_grid->cell_counts.arr[i] - 1; } AgentsSlice seen_slice; seen_slice.agents = pass->seen_group->storage; seen_slice.size = pass->seen_group->agent_size; int4 indices; switch (dims) { case 1: { } break; case 2: { } break; case 3: { for (indices.x = min_indices.x; indices.x <= max_indices.x; ++indices.x) { for (indices.y = min_indices.y; indices.y <= max_indices.y; ++indices.y) { for (indices.z = min_indices.z; indices.z <= max_indices.z; ++indices.z) { unsigned seen_cell_i = _cell_indices_to_cell_index(indices, dims); ZGridCell *seen_cell = seen_grid->cells + seen_cell_i; seen_slice.beg = seen_cell->first_agent_i; seen_slice.end = seen_cell->first_agent_i + seen_cell->count; pass->pairing_func(seer_slice, seen_slice, pass->see, pass->radii, dims, thread_context); } } } } break; default: { }; } } static inline unsigned _min(unsigned a, unsigned b) { return (a < b) ? a : b; } static void _see_func(TayThreadTask *task, TayThreadContext *thread_context) { TayPass *pass = task->pass; TayGroup *seer_group = pass->seer_group; TayGroup *seen_group = pass->seen_group; CpuZGrid *seer_grid = &seer_group->space.cpu_z_grid; int min_dims = (seer_group->space.dims < seen_group->space.dims) ? seer_group->space.dims : seen_group->space.dims; TayRange seers_range = tay_threads_range(pass->seer_group->space.count, task->thread_i); unsigned seer_i = seers_range.beg; while (seer_i < seers_range.end) { TayAgentTag *seer = (TayAgentTag *)(seer_group->storage + seer_group->agent_size * seer_i); ZGridCell *seer_cell = seer_grid->cells + seer->part_i; int4 seer_cell_indices = _cell_index_to_cell_indices(seer->part_i, min_dims); Box seer_box; for (int i = 0; i < min_dims; ++i) { float min = seer_grid->origin.arr[i] + seer_cell_indices.arr[i] * seer_grid->cell_sizes.arr[i]; seer_box.min.arr[i] = min - pass->radii.arr[i]; seer_box.max.arr[i] = min + seer_grid->cell_sizes.arr[i] + pass->radii.arr[i]; } unsigned cell_end_seer_i = _min(seer_cell->first_agent_i + seer_cell->count, seers_range.end); AgentsSlice seer_slice = { seer_group->storage, seer_group->agent_size, seer_i, cell_end_seer_i, }; pass->seen_func(pass, seer_slice, seer_box, min_dims, thread_context); seer_i = cell_end_seer_i; } } void cpu_z_grid_see(TayPass *pass) { space_run_thread_tasks(pass, _see_func); }
C
#pragma once #include <cx/cx.h> #include "futex.h" #include "aspin.h" // Event: Similar to auto-reset events on Windows. // Basically a semaphore that has a maximum value of 1, but includes some extra // features such as releasing an arbitrary number of threads on demand. // Also can be locked in a signaled state that turns it into the equivalent of // a manual-reset event. This is useful for things like thread shutdown, where // you want to avoid any potential races without having to spam the event. CX_C_BEGIN typedef struct UIEvent UIEvent; typedef struct Event { // Futex values: // 0 - Event is not signaled, any thread will have to wait // 1 - Event is signaled // >1 - Event is signaled for multiple waiters to wake up // -1 - Event is locked, all waits will complete instantly Futex ftx; atomic(int32) waiters; AdaptiveSpin aspin; UIEvent *uiev; } Event; enum EVENTINITFUNC_FLAGS { EV_Spin = 1, // Use adaptive spinloop instead of going straight to sleep EV_UIEvent = 2, // May be woken up early by platform-specific UI events }; // Events normally do not use the adaptive spin framework. // This is because we assume that events are used for occasional signaling between threads, // and when a thread waits on an event it's more likely than not to need to sleep. It would // be a waste of CPU for the event to spin waiting for a signal that is very unlikely to // come before the spinloop ends. // // For events used by high-performance queues or other situations where it is expected that // there will usually be work to do, the caller should initialize the Event with a "Spin" flag, // which will cause the event to use adaptive spinning. bool _eventInit(Event *e, uint32 flags); #define eventInit(e, ...) _eventInit(e, opt_flags(__VA_ARGS__)) #define eventSignal(e) eventSignalMany(e, 1) bool eventSignalMany(Event *e, int32 count); bool eventSignalAll(Event *e); bool eventWaitTimeout(Event *e, uint64 timeout); _meta_inline bool eventWait(Event *e) { return eventWaitTimeout(e, timeForever); } // signals the event and locks it in the signaled state, so threads attempting to wait on it // always return immediately bool eventSignalLock(Event *e); // manually reset the event to an unsignaled state bool eventReset(Event *e); void eventDestroy(Event *e); CX_C_END
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "utn.h" #include "pantalla.h" #define OCUPADO 0 #define LIBRE 1 #define TIPO_LED 0 #define TIPO_LCD 1 static int proximoId(); static int generarId(void){ static int id=-1; id++; return id; } int pantalla_inicializar(Pantalla* arrayPantalla, int limite){ int retorno = -1; int i; if(limite > 0 && arrayPantalla != NULL) { retorno = 0; for(i=0;i<limite;i++) { arrayPantalla[i].id = -1; arrayPantalla[i].tipo = -1; strcpy(arrayPantalla[i].nombrePantalla,""); strcpy(arrayPantalla[i].direccionPantalla,""); arrayPantalla[i].isEmpty = LIBRE; } } return retorno; } int pantalla_buscarPorId(Pantalla* arrayPantalla,int limite, int id) { int retorno = -1; int i; if(limite > 0 && arrayPantalla != NULL) { retorno = -2; for(i=0;i<limite;i++) { if(arrayPantalla[i].isEmpty == OCUPADO && arrayPantalla[i].id == id) { retorno = i; break; } } } return retorno; } int pantalla_alta(Pantalla* arrayPantalla, int limite, int index){ int retorno = -1; char nombreAux[50]; int tipoAux; char direccionAux[128]; if(getStringLetras("Ingrese nombre: ",nombreAux)){ if(!getValidInt("Ingrese tipo de pantalla:\n\t1)LED\n\t2)LCD\n","Opcion no valida",&tipoAux,1,2,2)){ if(getStringLetras("Ingrese direccion: ",direccionAux)){ strcpy(arrayPantalla[index].nombrePantalla,nombreAux); strcpy(arrayPantalla[index].direccionPantalla,direccionAux); arrayPantalla[index].tipo = tipoAux; arrayPantalla[index].isEmpty = OCUPADO; arrayPantalla[index].id = generarId(); retorno = 0; } } } return retorno; } int pantalla_baja(Pantalla* arrayPantalla, int limite,int index){ int retorno = -1; int indice; indice = pantalla_buscarPorId(arrayPantalla,limite,index); if(indice >= 0) { retorno = 0; arrayPantalla[indice].isEmpty = LIBRE; } else{ printf("\nID no encontrado"); } return retorno; } int pantalla_modificacion(Pantalla* arrayPantalla, int limite,int index){ int indice; int retorno = -1; char nombreAux[50]; int tipoAux; char direccionAux[128]; indice = pantalla_buscarPorId(arrayPantalla,limite,index); if(indice >= 0) { retorno = 0; if(getStringLetras("Ingrese nombre: ",nombreAux)){ if(!getValidInt("Ingrese tipo de pantalla:\n\t1)LED\n\t2)LCD\n","Opcion no valida",&tipoAux,1,2,2)){ if(getStringLetras("Ingrese direccion: ",direccionAux)){ strcpy(arrayPantalla[indice].nombrePantalla,nombreAux); strcpy(arrayPantalla[indice].direccionPantalla,direccionAux); arrayPantalla[indice].tipo = tipoAux; arrayPantalla[indice].isEmpty = OCUPADO; arrayPantalla[indice].id = generarId(); retorno = 0; //printf("%d",arrayPantalla[indice].isEmpty); } } } } else{ printf("\nID no encontrado"); } return retorno; } int pantalla_buscarLugarLibre(Pantalla* arrayPantalla,int limite) { int retorno = -1; int i; if(limite > 0 && arrayPantalla != NULL) { retorno = -2; for(i=0;i<limite;i++) { if(arrayPantalla[i].isEmpty == LIBRE) { retorno = i; break; } } } return retorno; } int pantalla_altaForzada(Pantalla* arrayPantalla,int limite,char* nombrePantalla,int tipo, char* direccionPantalla) { int retorno = -1; int i; if(limite > 0 && arrayPantalla != NULL) { i = pantalla_buscarLugarLibre(arrayPantalla,limite); if(i >= 0) { retorno = 0; strcpy(arrayPantalla[i].nombrePantalla,nombrePantalla); arrayPantalla[i].tipo = tipo; strcpy(arrayPantalla[i].direccionPantalla,direccionPantalla); //------------------------------ //------------------------------ arrayPantalla[i].id = proximoId(); arrayPantalla[i].isEmpty = OCUPADO; } retorno = 0; } return retorno; } int pantalla_mostrar(Pantalla* arrayPantalla,int limite) { int retorno = -1; int i; if(limite > 0 && arrayPantalla != NULL) { retorno = 0; printf("\n\tNombre\t\tDireccion\tID"); for(i=0;i<limite;i++) { if(!arrayPantalla[i].isEmpty) { //printf("\n\t%s - %d - %s - %d - %d",arrayPantalla[i].nombrePantalla,arrayPantalla[i].tipo,arrayPantalla[i].direccionPantalla,arrayPantalla[i].isEmpty,arrayPantalla[i].id); printf("\n\t%s\t\t%s\t%d",arrayPantalla[i].nombrePantalla,arrayPantalla[i].direccionPantalla,arrayPantalla[i].id); } } } return retorno; } static int proximoId() { static int ultimoId = -1; ultimoId++; return ultimoId; }
C
#include "caves.h" #include "terrain.h" static int caveNoiseHeight; static int getPosCaves(int x, int y) {return x*caveNoiseHeight + y;} static void fillRandom(char* noise, int width, int height, PerlinNoise2D perlin2D); //static int surroundings(char* noise, int posX, int posY); //static void automatonStep(char* noise, int width, int height); void fillRandom(char* noise, int width, int height, PerlinNoise2D perlin2D) { int x, y; for(x = 0; x < width; x++) { for(y = 1; y < height-1; y++) { float seuil = (float)y / height * 0.2f - 0.5f; noise[getPosCaves(x, y)] = perlinNoise2D(perlin2D, x, y) > seuil; } noise[getPosCaves(x, 0)] = 1; noise[getPosCaves(x, height-1)] = 1; } for(y = 1; y < height-1; y++) { noise[getPosCaves(0, y)] = 1; noise[getPosCaves(width-1, y)] = 1; } } /*int surroundings(char* noise, int posX, int posY) { int sum = noise[getPosCaves(posX-1, posY-1)]; sum += noise[getPosCaves(posX-1, posY)]; sum += noise[getPosCaves(posX-1, posY+1)]; sum += noise[getPosCaves(posX, posY-1)]; sum += noise[getPosCaves(posX, posY+1)]; sum += noise[getPosCaves(posX+1, posY-1)]; sum += noise[getPosCaves(posX+1, posY)]; sum += noise[getPosCaves(posX+1, posY+1)]; return sum; }*/ /*void automatonStep(char* noise, int width, int height) { int i, j; for(i = 1; i < width-1; i++) { for(j = 1; j < height-1; j++) { int entour = surroundings(noise, i, j); if(noise[getPosCaves(i, j)]) { if(entour < 3) { noise[getPosCaves(i, j)] = 0; } } else { if(entour >= 6) { noise[getPosCaves(i, j)] = 1; } } } } }*/ void generateCaves(Terrain* terrain) { char* noise = malloc(terrain->width * terrain->height * sizeof(char)); caveNoiseHeight = terrain->height; #ifdef PERFLOG int t1 = SDL_GetTicks(); #endif // PERFLOG PerlinNoise2D perlin2D = initPerlin2D(terrain->width, terrain->height, 8, 16); fillRandom(noise, terrain->width, terrain->height , perlin2D); int x, y; for(x = TERRAIN_BORDER; x < terrain->width - TERRAIN_BORDER; x++) { for(y = TERRAIN_BORDER; y < terrain->height - TERRAIN_BORDER; y++) { if(getBlock(terrain, x, y).type != 0 && noise[getPosCaves(x, y)] == 0) getBlockPtr(terrain, x, y)->type = 0; } } int i; for(i = 0; i < CELLULAR_STEPS; i++) { //etapeAutomate(noise); } //savePerlinNoise2D(perlin2D); #ifdef PERFLOG int t2 = SDL_GetTicks(); printf("Caves generation : %d\n", t2 - t1); #endif // PERFLOG destroyPerlinNoise2D(perlin2D); free(noise); }
C
#include <babybird.h> void babybird_eat(int babyID, int num_of_worms_to_eat, int* total_birds, struct mutex_t *room_lock, struct mutex_t *someone_eating, struct cond_v_t *plate_empty, struct cond_v_t *plate_full, int *dish, struct cond_v_t *my_turn) { int i = 0; char message[200]; while (i < num_of_worms_to_eat) { mutex_lock(room_lock); while(*dish == 0){ cond_signal(plate_empty); cond_wait(plate_full, room_lock); } *dish = *dish - 1; i = i + 1; sprintf(message, "Baby bird %d ate a worm! (%d total)\n", babyID, i); write(stdout, message, strlen(message) + 1); cond_signal(my_turn); if (*total_birds != 1 && i < num_of_worms_to_eat) cond_wait(my_turn, room_lock); mutex_unlock(room_lock); } *total_birds = *total_birds - 1; if (*total_birds == 0 || *dish == 0) cond_signal(plate_empty); } void parentbird_fetch(int num_of_worms_mother_fetches, pid32 main_pid, int* total_birds, struct mutex_t *room_lock, struct cond_v_t *plate_empty, struct cond_v_t *plate_full, int *dish) { char message[200]; sprintf(message, "Parent bird filled the dish with %d worms!\n", num_of_worms_mother_fetches); write(stdout, message, strlen(message) + 1); while (*total_birds > 0) { mutex_lock(room_lock); cond_wait(plate_empty, room_lock); if (*total_birds == 0) break; *dish = *dish + num_of_worms_mother_fetches; sprintf(message, "Parent bird filled the dish with %d worms!\n", num_of_worms_mother_fetches); write(stdout, message, strlen(message) + 1); cond_broadcast(plate_full); mutex_unlock(room_lock); } ready(main_pid); }
C
#ifndef ARRAYEMPLOYEES_H_INCLUDED #define ARRAYEMPLOYEES_H_INCLUDED #define TRUE 0 #define FALSE -1 typedef struct { int id; char name[51]; char lastName[51]; int sector; float salary; int isEmpty; } eEmployee; int addEmployee(eEmployee* lista, int len, int id, char name[],char lastName[],float salary,int sector); int menuDeOpciones(); int promedioSalary(eEmployee* lista, int len); int findEmployeeById(eEmployee* lista, int len , int id); int initEmployees(eEmployee* lista, int len); int buscarLugarLibre(eEmployee* lista, int len); int mostrarUnEmpleado(eEmployee* lista, int indice); int modifyEmployee(eEmployee*lista,int len, int id); int sortEmployees(eEmployee* lista, int len); int removeEmployee(eEmployee* lista, int len, int id); int printEmployees(eEmployee* lista, int len); #endif
C
#include "Game.h" #include "Ball.h" #include <math.h> #include <time.h> void start_position_of_ball(struct Ball *b) { b->speed=0.6f; b->dx=cos(90 * 22/7)*b->speed; b->dy=sin(90 * 22/7)*b->speed; b->x=SCREEN_W/2-10; /*dla obrazka*/ b->y=SCREEN_H-72; /*dla obrazka*/ } void set_new_direction(struct Ball *b) { srand(time(NULL)); int angle,dir=rand()%2; if(dir==0) angle=230+rand()%30; else angle=310-rand()%30; b->dx=cos(angle * 3.141592 / 180)*b->speed; b->dy=sin(angle * 3.141592 / 180)*b->speed; } void ball_movement(struct Ball *b) { b->x+=b->dx;/*dla obrazka*/ b->y+=b->dy;/*dla obrazka*/ b->x1+=b->dx;/*dla kolidera*/ b->x2+=b->dx;/*dla kolidera*/ b->y1+=b->dy;/*dla kolidera*/ b->y2+=b->dy;/*dla kolidera*/ if(b->x + b->radius<=20 || b->x + b->radius>=SCREEN_W-5) b->dx *= -1; if(b->y + b->radius<=20) b->dy *= -1; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <pthread.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include "omp.h" #include <time.h> void main(int argc, char*argv[]){ srand((unsigned)time(NULL)); int result= 0; int numberOfPoints = atoi(argv[1]); //Let omp use the best number of threads for the job int systemNThreads = omp_get_num_threads(); int shotsForEachThread = floor(numberOfPoints/systemNThreads); //Delimeters the last thread number of points, used by first or last thread int halper = numberOfPoints - (shotsForEachThread * (systemNThreads -1)); long counter = 0; int i; #pragma omp parallel for for(i=0; i< shotsForEachThread; i++){ if(omp_get_thread_num() == 0){ if(i < halper){ //gerarpontos random -> same logic float x = (float)rand()/RAND_MAX; float y = (float)rand()/RAND_MAX; if((x*x) + (y*y) <=1){ counter++; } } }else{ //gerarpontos random float x = (float)rand()/RAND_MAX; float y = (float)rand()/RAND_MAX; if((x*x) + (y*y) <=1){ counter++; } } } float pi= (float)((float)counter/(float)numberOfPoints) * 4; printf("Total Number of poits: %d \n", numberOfPoints); printf("Total Number of threads: %d \n", systemNThreads); printf("Points within the circle: %ld \n", counter); printf("Pi estimation: %.5f \n", pi); }
C
#include <stdio.h> #define N 5 int captura(); int ordenacion(); int imprime(); int masalto(); int impresion(); int main () { int clave[N]; char nombre[N][100]; int est[2][N]; captura (clave, nombre, est); ordenacion(nombre); imprime(clave,nombres,est) masalto(est) impresion(est) return 0; } int captura (int clave[N], char nombre[N][100], int est[2][N]) { for (int i = 0; i < N; i++) { printf ("Cual es la clave del empleado "); scanf ("%d", &clave[i]); printf ("Cual es el nombre del empleado"); scanf ("%c", &nombre[i][100]); printf ("Cual es la estatura del empleado"); scanf ("%d", &est[1][N]); printf ("Cual es el sueldo del empleado"); scanf ("%d", &est[2][N]); } } int ordenacion(int est[2][N]) int i,j,aux for(i=0;i<5;i++) { for(j=0;j<5;j++) { if(est[2][j] > est[2][j+1] ) { aux = est[2][j]; est[2][j] = est[2][j+1]; est[2][j+1] = aux; } } } int imprime (int clave[N], char nombre[N][100], int est[2][N]) { int i printf("Clave Nombre Estatura Sueldo") for(i = 0; i < N; i ++) { printf("%d %d %d %d", clave[i], nombre[i][100], est[1][i], est[2][i]) } } int masalto(int est [2][N],int *p) { int m= int est[2][0] int i; for(i = 0; i < N ; i++) { if(est[2][i]> m) { m = arr[i]; *p = i; } } return m; } int impresion(m,*p) { printf ("El empleado de mayor estatura tiene %d en la posicion %d", m, *p); }
C
#include <stdio.h> int main() { int num1, num2; printf("Enter the first number: "); scanf("%d", &num1); printf("Enter the second number: "); scanf("%d", &num2); if (num1 > 100 && num2 > 100) printf("Both Are Greater Than 100.\n"); else if (num1 > 100 && num2 < 100) printf("Only One Is Greater Than 100.\n"); else if (num1 < 100 && num2 > 100) printf("Only One Is Greater Than 100.\n"); else printf("Both Are Less Than 100.\n"); return 0; }
C
#include <stdio.h> // add first n natural numbers using recursion int total(int num); int main() { int num; puts(" enter the limit "); scanf("%d" ,&num); printf("the sum of first n natural numbers = %d \n" ,total(num)); return 0; } int total(int num) { if(num == 1) return 1; else return (total(num -1) + num); }
C
#include<stdio.h> #include<string.h> main() { int i,ctr=0; char c; char s[30]; printf("enter word: \n"); gets(s); printf("enter character to be searched: \n"); scanf("%c",&c); for(i=0;s[i]!='\0';i++) { if(s[i]==c) { ctr++; } } printf("answer: %d \n",ctr); }
C
#include "TLPI_include.h" int main(int argc, char* argv[]) { struct sigaction sigstruc; memset(&sigstruc, 0, sizeof(sigstruc)); sigemptyset(&sigstruc.sa_mask); sigstruc.sa_handler = SIG_IGN; if(sigaction(SIGCHLD,&sigstruc, NULL) == -1) { errorExit("error in sigaction"); } // sigset_t sigset, befor; // sigemptyset(&sigset); // sigaddset(&sigset, SIGCHLD); // if(sigprocmask(SIG_SETMASK, &sigset, &befor) == -1) { // errorExit("Err in sigproc"); // } for(int i = 0; i< 10; i++) { int fd = fork(); if(fd < 0) { errorExit("err in fork"); } else if (fd > 0) { sleep(3); printf("exit: %d\n", getpid()); exit(1); } } // if(sigprocmask(SIG_SETMASK, &befor, NULL) == -1) { // errorExit("Err in sigproc"); // } int f = wait(NULL); if(f == -1) { errorExit("err in wait"); } return 0; }
C
#include "holberton.h" /** *print_alphabet -print alpha *@void: no argument **/ void print_alphabet(void) { char ch; ch = 'a'; while (ch <= 'z') { _putchar(ch); ch++; } _putchar('\n'); }
C
#include <stdio.h> #include <stdlib.h> int main() { while (1) { int c = getchar(); // windows ctrl+z // linux ctrl+d if (c == EOF) { break; } if (c >= 'a' && c <= 'z') { putchar(c - ('a' - 'A')); } else if (c >= 'A' && c <= 'Z') { putchar(c + ('a' - 'A')); } else if (c >= '0' && c <= '9') { continue; } else{ putchar(c); } } system("pause"); return 0; }
C
#ifndef _SYS_INTERRUPT_H_ #define _SYS_INTERRUPT_H_ #include <sys/cdefs.h> #include <sys/queue.h> #include <sys/spinlock.h> #include <sys/priority.h> typedef struct ctx ctx_t; typedef struct device device_t; /*! \brief Disables hardware interrupts. * * Calls to \fn intr_disable can nest, you must use the same number of calls to * \fn intr_enable to actually enable interrupts. * * In most scenarios threads should not switch out when interrupts are disabled. * However it should behave correctly, since context switch routine restores * interrupts state of target thread. * * If you need to disable preemption refer to \fn preempt_disable. * * \sa preempt_disable() */ void intr_disable(void); /*! \brief Enables interrupts. */ void intr_enable(void); /*! \brief Checks if interrupts are disabled now. */ bool intr_disabled(void); /* Two following functions are workaround to make interrupt disabling work with * scoped and with statement. */ static inline void __intr_disable(void *data) { intr_disable(); } static inline void __intr_enable(void *data) { intr_enable(); } #define SCOPED_INTR_DISABLED() \ SCOPED_STMT(void, __intr_disable, __intr_enable, NULL) #define WITH_INTR_DISABLED WITH_STMT(void, __intr_disable, __intr_enable, NULL) typedef struct intr_event intr_event_t; typedef struct intr_handler intr_handler_t; typedef enum { IF_STRAY = 0, /* this device did not trigger the interrupt */ IF_FILTERED = 1, /* the interrupt has been handled and can be EOId */ IF_DELEGATE = 2, /* the handler should be run in private thread */ } intr_filter_t; /* * The filter routine is run in primary interrupt context and may not * block or use regular mutexes. The filter may either completely * handle the interrupt or it may perform some of the work and * defer more expensive work to the regular interrupt handler. */ typedef intr_filter_t ih_filter_t(void *); typedef void ih_service_t(void *); typedef void ie_action_t(intr_event_t *); /* Software representation of interrupt line. */ typedef struct intr_event { spin_t ie_lock; TAILQ_ENTRY(intr_event) ie_link; /* link on list of all interrupt events */ TAILQ_HEAD(, intr_handler) ie_handlers; /* sorted by descending ih_prio */ ie_action_t *ie_disable; /* called before ithread delegation (mask irq) */ ie_action_t *ie_enable; /* called after ithread delagation (unmask irq) */ void *ie_source; /* additional argument for actions */ const char *ie_name; /* individual event name */ unsigned ie_irq; /* physical interrupt request line number */ thread_t *ie_ithread; /* associated interrupt thread */ } intr_event_t; intr_event_t *intr_event_create(void *source, int irq, ie_action_t *disable, ie_action_t *enable, const char *name); intr_handler_t *intr_event_add_handler(intr_event_t *ie, ih_filter_t *filter, ih_service_t *service, void *arg, const char *name); void intr_event_remove_handler(intr_handler_t *ih); void intr_event_run_handlers(intr_event_t *ie); typedef void (*intr_root_filter_t)(ctx_t *ctx, device_t *dev, void *arg); void intr_root_claim(intr_root_filter_t filter, device_t *dev, void *arg); void intr_root_handler(ctx_t *ctx); #endif /* !_SYS_INTERRUPT_H_ */
C
#ifndef __CONVOLUTION5x5Fp16ToFp16_H__ #define __CONVOLUTION5x5Fp16ToFp16_H__ #include <mv_types.h> #include <mvcv_macro.h> //!@{ /// This kernel performs a convolution on the fp16 input image using the given 5x5 matrix /// @param[in] in - Input lines, 16-bits floating point /// @param[in] out - Output line, 16-bits floating point /// @param[in] conv - 25 elements array with fp16 values containing the 5x5 convolution matrix /// @param[in] inWidth - Width of input line MVCV_FUNC(void, mvcvConvolution5x5Fp16ToFp16, half** in, half** out, half conv[25], u32 inWidth) //!@} #ifdef MOVICOMPILE_OPTIMIZED extern "C" { void mvcvConvolution5x5Fp16ToFp16_opt(half** in, half** out, half conv[25], u32 inWidth); } #endif #endif //__CONVOLUTION5x5_H__
C
/* Streamlined hash table implementation, with emphasis on lookup performance. * Key and value sizes are fixed. Lookup is thread-safe, but update is not. */ #ifndef _HTABLE_H_ #define _HTABLE_H_ #include <stdint.h> #include <rte_config.h> #include <rte_hash_crc.h> #include "simd.h" /* tunable macros */ #define INIT_NUM_BUCKETS 4 #define INIT_NUM_ENTRIES 16 /* 4^MAX_CUCKOO_PATH buckets will be considered to make a empty slot, * before giving up and expand the table. * Higher number will yield better occupancy, but the worst case performance * of insertion will grow exponentially, so be careful. */ #define MAX_CUCKOO_PATH 3 /* non-tunable macros */ #define ENTRIES_PER_BUCKET 4 /* 4-way set associative */ #define DEFAULT_HASH_INITVAL UINT32_MAX typedef int32_t ht_keyidx_t; /* compatible with DPDK's */ typedef uint32_t (*ht_hash_func_t)(const void *key, uint32_t key_len, uint32_t init_val); /* if the keys are identical, should return 0 */ typedef int (*ht_keycmp_func_t)(const void *key, const void *key_stored, size_t key_size); struct ht_params { size_t key_size; size_t value_size; size_t key_align; size_t value_align; uint32_t num_buckets; /* must be a power of 2 */ int num_entries; /* >= 4 */ ht_hash_func_t hash_func; ht_keycmp_func_t keycmp_func; }; struct ht_bucket { uint32_t hv[ENTRIES_PER_BUCKET]; ht_keyidx_t keyidx[ENTRIES_PER_BUCKET]; } __ymm_aligned; struct htable { /* bucket and entry arrays grow independently */ struct ht_bucket *buckets; void *entries; /* entry_size * num_entries bytes */ ht_hash_func_t hash_func; ht_keycmp_func_t keycmp_func; /* # of buckets == mask + 1 */ uint32_t bucket_mask; int cnt; /* current number of entries */ ht_keyidx_t num_entries; /* current array size (# entries) */ /* Linked list head for empty key slots (LIFO). NO_NEXT if empty */ ht_keyidx_t free_keyidx; /* in bytes */ size_t key_size; size_t value_size; size_t value_offset; size_t entry_size; }; /* -errno, or 0 for success */ int ht_init(struct htable *t, size_t key_size, size_t value_size); int ht_init_ex(struct htable *t, struct ht_params *params); void ht_close(struct htable *t); void ht_clear(struct htable *t); /* returns NULL or the pointer to the data */ void *ht_get(const struct htable *t, const void *key); /* identical to ht_get(), but you can supply a precomputed hash value "pri" */ void *ht_get_hash(const struct htable *t, uint32_t pri, const void *key); /* -ENOMEM on error, 0 for succesful insertion, or 1 if updated */ int ht_set(struct htable *t, const void *key, const void *value); /* -ENOENT on error, or 0 for success */ int ht_del(struct htable *t, const void *key); /* Iterate over key pointers. * NULL if it reached the end of the table, or the pointer to the key. * User should set *next to 0 when starting iteration */ void *ht_iterate(const struct htable *t, uint32_t *next); /* from the stored key pointer, return its value pointer */ static inline void *ht_key_to_value(const struct htable *t, const void *key) { return (void *)(key + t->value_offset); } /* from DPDK */ static inline uint32_t ht_hash_secondary(uint32_t primary) { uint32_t tag = primary >> 12; return primary ^ ((tag + 1) * 0x5bd1e995); } #define INVALID_KEYIDX INT32_MAX #if __AVX__ static inline ht_keyidx_t _get_keyidx_vec(const struct htable *t, uint32_t pri) { struct ht_bucket *bucket = &t->buckets[pri & t->bucket_mask]; __m128i v_pri = _mm_set1_epi32(pri); __m128i v_hv = _mm_load_si128((__m128i *)bucket->hv); __m128i v_cmp = _mm_cmpeq_epi32(v_hv, v_pri); int mask = _mm_movemask_epi8(v_cmp); int ffs = __builtin_ffs(mask); if (ffs > 0) return bucket->keyidx[ffs >> 2]; uint32_t sec = ht_hash_secondary(pri); bucket = &t->buckets[sec & t->bucket_mask]; v_hv = _mm_load_si128((__m128i *)bucket->hv); v_cmp = _mm_cmpeq_epi32(v_hv, v_pri); mask = _mm_movemask_epi8(v_cmp); ffs = __builtin_ffs(mask); if (ffs > 0) return bucket->keyidx[ffs >> 2]; return INVALID_KEYIDX; } #else #define _get_keyidx_vec _get_keyidx #endif /* actually works faster for very small tables */ static inline ht_keyidx_t _get_keyidx(const struct htable *t, uint32_t pri) { struct ht_bucket *bucket = &t->buckets[pri & t->bucket_mask]; for (int i = 0; i < ENTRIES_PER_BUCKET; i++) { if (pri == bucket->hv[i]) return bucket->keyidx[i]; } uint32_t sec = ht_hash_secondary(pri); bucket = &t->buckets[sec & t->bucket_mask]; for (int i = 0; i < ENTRIES_PER_BUCKET; i++) { if (pri == bucket->hv[i]) return bucket->keyidx[i]; } return INVALID_KEYIDX; } /* This macro provides an inlined (thus much faster) version for the lookup * operations. For example, suppose you have a custom hash table type "foo": * * HT_DECLARE_INLINED_FUNCS(foo, uint64_t) * * where uint64_t is the key type (the same type used for ht_init()) * With this, you are required to define two functions (starting with "foo") * as follows: * * static inline int foo_keyeq(const uint64_t *key, * const uint64_t *key_stored, size_t key_len) * { * // should return 0 if the two keys are identical, or a nonzero. * ... * } * * static inline uint32_t foo_hash(const key_type *key, uint32_t key_len, * uint32_t init_val) * { * // * ... * } * * NOTE: You can ignore key_len, if you already know the size of key_type * * Once you define these functions, you can use ht_foo_hash(), which is a * faster version of ht_hash() with the same function prototype. */ #define HT_DECLARE_INLINED_FUNCS(name, key_type) \ \ static inline int \ name##_keycmp(const key_type *key, const key_type *key_stored, \ size_t key_len); \ \ static inline uint32_t \ name##_hash(const key_type *key, uint32_t key_len, uint32_t init_val); \ \ static inline void *ht_##name##_get(const struct htable *t, \ const void *_key) \ { \ const key_type *key = _key; \ uint32_t pri = name##_hash(key, t->key_size, \ DEFAULT_HASH_INITVAL); \ pri |= (1u << 31); \ pri &= ~(1u << 30); \ \ ht_keyidx_t k_idx = (t->cnt >= 2048) ? \ _get_keyidx_vec(t, pri) : _get_keyidx(t, pri); \ if (k_idx == INVALID_KEYIDX) \ return NULL; \ \ key_type *key_stored = t->entries + t->entry_size * k_idx; \ \ /* Go to slow path if false positive. */ \ if (likely(!name##_keycmp(key, key_stored, t->key_size))) \ return (void *)key_stored + t->value_offset; \ else \ return ht_get_hash(t, pri, key); \ } \ \ static inline void ht_##name##_get_bulk(const struct htable *t, \ int num_keys, const void **_keys, void **values) \ { \ const key_type **keys = (const key_type **)_keys; \ uint32_t bucket_mask = t->bucket_mask; \ void *entries = t->entries; \ size_t key_size = t->key_size; \ size_t entry_size = t->entry_size; \ size_t value_offset = t->value_offset; \ \ for (int i = 0; i < num_keys; i++) { \ struct ht_bucket *pri_bucket; \ struct ht_bucket *sec_bucket; \ \ uint32_t pri = name##_hash(keys[i], key_size, \ DEFAULT_HASH_INITVAL); \ pri |= (1u << 31); \ pri &= ~(1u << 30); \ pri_bucket = &t->buckets[pri & bucket_mask]; \ \ uint32_t sec = ht_hash_secondary(pri); \ sec_bucket = &t->buckets[sec & bucket_mask]; \ \ union { \ __m256i v; \ uint32_t a[8]; \ } keyidx; \ \ __m256i v_pri = _mm256_set1_epi32(pri); \ __m256i v_pri_bucket = _mm256_load_si256( \ (__m256i *)pri_bucket); \ __m256i v_sec_bucket = _mm256_load_si256( \ (__m256i *)sec_bucket); \ __m256i v_hv = _mm256_permute2f128_si256( \ v_pri_bucket, v_sec_bucket, 0x20); \ keyidx.v = _mm256_permute2f128_si256( \ v_pri_bucket, v_sec_bucket, 0x31); \ \ __m256 v_cmp = _mm256_cmp_ps((__m256)v_pri, \ (__m256)v_hv, _CMP_EQ_OQ); \ \ int mask = _mm256_movemask_ps(v_cmp); \ int ffs = __builtin_ffs(mask); \ \ if (!ffs) { \ values[i] = NULL; \ continue; \ } \ \ ht_keyidx_t k_idx = keyidx.a[ffs - 1]; \ key_type *key_stored = entries + entry_size * k_idx; \ if (!name##_keycmp(keys[i], key_stored, key_size)) \ values[i] = (void *)key_stored + value_offset; \ else \ values[i] = ht_get_hash(t, pri, keys[i]); \ } \ } /* with non-zero 'detail', each item in the hash table will be shown */ void ht_dump(const struct htable *t, int detail); #endif
C
#include<stdio.h> #include<string.h> #include<stdlib.h> struct Customer_details { char name[30]; char gender; char _grp[4]; char city[10]; char address[100]; int id; long long contact_no; char _bank[30]; }Customer; void insert() { system("clear"); printf("===Welcome To Customer Registration Page===\n"); FILE *fp1; fp1=fopen("details.dat","a"); if(fp1==NULL) { printf("Sorry, Techincal fault, Try later!\n"); return; } printf("Enter your Name\n"); gets(Customer.name); gets(Customer.name); printf("Enter your gender\n Press M for Male and F for Female\n"); scanf(" %c",&Customer.gender); printf("Enter your Bank Branch\n"); scanf("%s",Customer._grp); printf("Enter your City Name\n"); scanf(" %s",Customer.city); printf("Enter your Permanent Address \n"); gets(Customer.address); gets(Customer.address); printf("Enter your Customer ID\n"); scanf("%d",&Customer.id); printf("Enter your Contact Number\n"); scanf("%lld",&Customer.contact_no); printf("Enter the name of the Bank you would affiliate \n"); gets(Customer._bank); gets(Customer._bank); fwrite(&Customer,sizeof(Customer),1,fp1); fclose(fp1); } void search() { char sname[3]; FILE* fp; int flag=0; fp=fopen("details.dat","r"); if(fp==NULL) { printf("Sorry, can't Open this file\n"); return; } printf("ENTER THE Bank Branch :->"); scanf("%s",sname); while(fread(&Customer,sizeof(Customer),1,fp)) { if(strcmp(sname,Customer._grp)==0) { flag=1; printf("\n\t\t%s\t\t%lld\t\t%s\t\t%s\n",Customer.name,Customer.contact_no,Customer.city,Customer._bank); } } fclose(fp); if(flag==0) { printf("No Such Customer exists\n"); } return; } void display() { printf(===Customer DETAILS===\n"); FILE* fp; fp=fopen("details.dat","r"); if(fp==NULL) { printf("Sorry, can't Open this file\n"); return; } while(fread(&Customer,sizeof(Customer),1,fp)) { printf("%s\t\t%d\t\t%s\t\t%s\t\t%lld\t\t%s\n",Customer.name,Customer.id,Customer._grp,Customer.city,Customer.contact_no,Customer._bank); } fclose(fp); printf("\n"); return; } int main() { int ch; do { printf("-- WELCOME TO BANK MANAGEMENT SYSTEM--"); printf("\n\n"); printf("Press 1 for New Customer registration.\n"); printf("Press 2 to Display All Records of Customers.\n"); printf("Press 3 to Search Customer of a particular Branch.\n"); printf("Press 4 to exit.\n "); printf("Enter your choice.\n"); scanf("%d",&ch); switch(ch) { case 1: insert(); break; case 2: display(); break; case 3: search(); break; default: break; } }while(ch!=4); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* skip.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ielbadao <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/25 14:56:59 by ielbadao #+# #+# */ /* Updated: 2021/05/23 11:51:46 by ielbadao ### ########.fr */ /* */ /* ************************************************************************** */ #include "../parser.h" static void help(t_string command) { if (command[g_container->counter] == '\\' && command[g_container->counter + 1] != '\'' && g_container->gchar != '\'') g_container->counter += 2; while (greate_question(command)) { if (check_quote(command[g_container->counter])) { g_container->gchar = command[g_container->counter++]; while (command[g_container->counter] != g_container->gchar) g_container->counter++; } g_container->counter++; } } void skip_word(t_string command) { if (g_container->gchar > 0) { while (command[g_container->counter] != g_container->gchar) { if (command[g_container->counter] == '\\' && command[g_container->counter + 1] != '\'' && g_container->gchar != '\'') { g_container->counter += 2; continue ; } g_container->counter++; } g_container->counter++; help(command); } else help(command); } void skip_spaces(t_string command) { while (command[g_container->counter] == ' ') g_container->counter++; } void skip_redirection(t_string command) { if (command[g_container->counter] == '>' && command[g_container->counter + 1] == '>') g_container->counter += 2; else g_container->counter++; }
C
/* Копирайте съдържанието на файл1 във файл2 */ #include <fcntl.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char* argv[]) { if (argc != 3){ write(2,"Incorrect arguments count\n",30); exit(-1); } int file_d1; int file_d2; char c; if ( ( file_d1 = open(argv[1], O_RDONLY) ) == -1 ) { write(2, "File failed to open in read mode\n", 33); exit(-1); } if ( ( file_d2 = open(argv[2], O_CREAT | O_WRONLY, 0644) ) == -1 ){ write(2, "File failed to open in write mode\n", 34); close(file_d1); exit(-1); } while ( read(file_d1, &c, 1) ){ write(file_d2, &c, 1); } close(file_d1); close(file_d2); exit(0); }
C
#include <stdio.h> #include <stdlib.h> //定义存放最小值的stack的每一个结点 struct MStack_ { int value; struct MStack_* next; int end; }; typedef struct MStack_ * MStack; //初始化存有最小值得stack MStack MstackInit(); //压栈 MStack MPush(MStack stack, int value); //出栈 MStack MPop(MStack stack, int* mData);
C
#include <stdio.h> #include <stdlib.h> int main() { float pi,total,k,p; pi = 3.1416; printf(" informe o raio de um circulo aqui:"); scanf("%f",&k); p =2*pi*k; total=pi*(k*k); printf("a area do circulo e : %f \n E seu perimetro e: %f", total,p ); return 0; }
C
#include <stdio.h> void change(int* arr, int len) { printf("%d\n",sizeof(arr)); for(int i=0; i<len; i++) { arr[i]++; } } int main(int argc, char *argv[]) { int a[5]={0, 1, 2, 3, 4}; printf("a=%d\n",sizeof(a)); //printf("%d\n",sizeof(a[0])); int len=sizeof(a)/sizeof(a[0]); change(a, len); for(int i=0; i<len; i++) { printf("%d\t", a[i]); } printf("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int is_substring( char* a, char* b); int main() { // Create a program which asks for two strings and stores them // Create a function which takes two strings as parameters and // returns 1 if the shorter string is a substring of the longer one and // returns 0 otherwise // If the two strings has the same lenght than the function should return -1 char a_string[100]= ""; char b_string[100]= ""; printf("Give me please a string: \n"); gets(a_string); printf("Give me please another string: \n"); gets(b_string); printf("%d\n", is_substring(a_string, b_string)); return 0; } int is_substring( char* a, char* b){ char* short_one = b; char* long_one = a; if (strlen(a) < strlen(b)){ short_one = a; long_one = b; } else if (strlen(a) == strlen(b)){ return -1; } if(strstr(long_one, short_one) != NULL){ return 1; }else{ return 0; } }
C
#include<stdio.h> int main(){ long int a,b,i,j,k,n; double x,y,z,p,q,r,s; scanf("%d",&n); for(i=0;i<n;i++){ j=0; scanf("%ld%ld%lf%lf",&a,&b,&x,&y); p=a; q=b; for(;;){ if(p>q) break; p=p+((p*x)/100); q=q+((q*y)/100); j++; if(j>100){ printf("Mais de 1 ceculo.\n"); break;} } if(j<=100){ printf("%d anos.\n",j);} }}
C
#include "main.h" struct Node* CreateNode () { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (!newNode) { printf("Memory didn't allocated, cannot continue\n"); return NULL; } newNode->data = 0; newNode->prevEntry = NULL; newNode->nextEntry = NULL; return newNode; } struct Node* CreateNodeWithValue (int var) { struct Node* newNode = CreateNode(); if (!newNode) { return NULL; } newNode->data = var; return newNode; } struct Node* CreateEmptyNode () // Remove { struct Node* newNode = CreateNode(); if (!newNode) { return NULL; } return newNode; } int insertNodeAtIndex(int var, struct List* list, int indx) { if (indx < 0 || indx > list->listSize) { printf("Wrong index provided please use value beetween %d and %d\n", 0, list->listSize); return 0; } struct Node* newNode = CreateNodeWithValue(var); if (!newNode) { return 0; } if (list->listSize == 0) { list->listHead = newNode; list->listTail = newNode; } else if (indx == list->listSize) { list->listTail->nextEntry = newNode; newNode->prevEntry = list->listTail; list->listTail = newNode; } else { struct Node* targetNode = getNodeAtIndex(list, indx); if (!targetNode) { printf("No node at index cannot proceed\n"); // Memory leak return 0; } if (targetNode->prevEntry) { targetNode->prevEntry->nextEntry = newNode; } if (indx == 0) { list->listHead = newNode; } newNode->prevEntry = targetNode->prevEntry; targetNode->prevEntry = newNode; newNode->nextEntry = targetNode; } list->listSize++; return 1; } int insertAtBegin (int var, struct List* list) { return insertNodeAtIndex(var, list, 0); } int insertAtEnd (int var, struct List* list) { return insertNodeAtIndex(var, list, list->listSize); } int deleteNodeAtIndex (struct List* list, int indx) { if(indx >= list->listSize) { printf("Wrong index provided, nothing to delete\n"); return 0; } else { struct Node* head = list->listHead; struct Node* tail = list->listTail; struct Node* valueToDelete; if (head && tail) { if (list->listSize != 1) { if (indx != 0 && indx != list->listSize - 1) { struct Node* iter = head; for(int i = 0; i < indx; i++) { iter = iter->nextEntry; } iter->prevEntry->nextEntry = iter->nextEntry; iter->nextEntry->prevEntry = iter->prevEntry; valueToDelete = iter; } else if (indx == 0) { list->listHead = head->nextEntry; list->listHead->prevEntry = NULL; valueToDelete = head; } else if (indx == list->listSize - 1) { list->listTail = tail->prevEntry; list->listTail->nextEntry = NULL; valueToDelete = tail; } } else { valueToDelete = head; list->listHead = NULL; list->listTail = NULL; } free(valueToDelete); if (!valueToDelete) { printf("Memory didn't freed, cannot continue\n"); return 0; } } else { printf("Nothing do delete - list is empty\n"); return 0; } list->listSize--; return 1; } } int deleteSpecifiedNode (struct List* list, struct Node* node) { struct Node* head = list->listHead; struct Node* tail = list->listHead; if (head == node) { return deleteNodeAtIndex(list, 0); } else if (tail == node) { return deleteNodeAtIndex(list, list->listSize - 1); } else { struct Node* iter = head; int nodeIsFound = 0; int indx = 0; while(!nodeIsFound && indx != list->listSize) { if (iter == node) { nodeIsFound = 1; } else { indx++; iter=iter->nextEntry; } } if(nodeIsFound) { return deleteNodeAtIndex(list, indx); } else { printf("No such node in list\n"); return 0; } } } struct Node* getNodeAtIndex (struct List* list, int indx) { if (indx >= list->listSize || indx < 0) { printf("Wrong index for get\n"); return NULL; } struct Node* iter = list->listHead; for(int i = 0; i < indx; i++) { iter=iter->nextEntry; } return iter; } int deleteNodeAtBegin (struct List* list) { return deleteNodeAtIndex(list, 0); } int deleteNodeAtEnd (struct List* list) { int listSize = list->listSize; return deleteNodeAtIndex(list, listSize - 1); } void printList (struct List* list) { struct Node* head = list->listHead; if (!head) { printf("Seems to be nothing to print\n"); return; } struct Node* iterPtr = head; while(iterPtr) { printf("%d\n", iterPtr->data); iterPtr = iterPtr->nextEntry; } return; } void printListReverse (struct List* list) { struct Node* head = list->listHead; if (!head) { printf("Seems to be nothing to print\n"); return; } // Looking for last node in list struct Node* iterPtr = head; while(iterPtr->nextEntry) { iterPtr = iterPtr->nextEntry; } // Printing in reverse while(iterPtr) { printf("%d\n", iterPtr->data); iterPtr = iterPtr->prevEntry; } } struct List* createList () { struct List* list = (struct List*)malloc(sizeof(struct List)); if (!list) { printf("Cannot allocate list, exit"); return NULL; } list->listHead = NULL; list->listTail = NULL; list->listSize = 0; if (ListsHeadNode) { struct List* tailList = ListsHeadNode; while(tailList->nextList) { tailList = tailList->nextList; } tailList->nextList = list; list->prevList = tailList; list->nextList = NULL; } else { ListsHeadNode = list; list->nextList = NULL; list->prevList = NULL; } return list; } int main () { struct List* list = createList(); printf("current size is %d\n", list->listSize); insertAtBegin(0, list); printf("current size is %d\n", list->listSize); insertAtBegin(2, list); printf("current size is %d\n", list->listSize); insertAtEnd(3, list); printf("current size is %d\n", list->listSize); printf("List in usual direction \n"); printList(list); printf("List in reverse direction \n"); printListReverse(list); printf("current size is %d\n", list->listSize); deleteNodeAtBegin(list); printf("current size is %d\n", list->listSize); printList(list); deleteNodeAtEnd(list); printf("Deleted one node at begin and one at end\n"); printList(list); printf("current size is %d\n", list->listSize); deleteNodeAtEnd(list); printf("Deleted last node in list\n"); printf("current size is %d\n", list->listSize); printf("Will try ot delete more values that exists\n"); deleteNodeAtEnd(list); printf("current size is %d\n", list->listSize); printf("################################\n"); struct Node* secondNode = getNodeAtIndex(list, 1); // Demonstrate delete at index if (secondNode) { printf("data of elem at indx 1 is %d\n", secondNode->data); } else { printf("No data in list\n"); } insertAtBegin(5, list); insertAtBegin(4, list); insertAtBegin(3, list); insertAtBegin(2, list); insertAtBegin(1, list); struct Node* thirdNode = getNodeAtIndex(list, 1); if (thirdNode) { printf("data of elem at indx 3 is %d\n", thirdNode->data); } else { printf("No data in list\n"); exit(1); } printf("################################\n"); printf("Printing list in usual direction\n"); printList(list); printf("################################\n"); printf("Deleting founded node with value - %d\n", thirdNode->data); deleteSpecifiedNode(list, thirdNode); printf("################################\n"); printf("Printing list in usual direction\n"); printList(list); }
C
#include <stdio.h> #include <stdio_ext.h> #include <string.h> #include <stdlib.h> typedef struct{ int cod; char nome[20]; float preco; }Produto; typedef struct _nodo{ Produto info; struct _nodo *prox; struct _nodo *ant; }Nodo; typedef struct lista{ int nItens; Nodo *pri; Nodo *ult; }Lista; Lista *push(Lista *lista){ Nodo *v=(Nodo *)malloc(sizeof(Nodo)); v->prox=lista->pri; v->ant=lista->ult; printf("Digite o nome do produto:\n"); __fpurge(stdin); fgets(v->info.nome,20,stdin); printf("Digite o codigo do produto:\n"); scanf("%d",&v->info.cod); printf("Digite o preço do produto:\n"); scanf("%f",&v->info.preco); if(lista->nItens==0){ lista->ult=v; lista->pri=v; }else{ lista->pri->ant=v; lista->pri=v; } lista->nItens++; return lista; } Lista *pop(Lista *lista){ int cod; Nodo *a; printf("Digite o codigo do produto que deseja extrair\n"); scanf("%d",&cod); for(a=lista->pri;a!=NULL;a=a->prox){ if(a->info.cod==cod){ break; } }if(a==NULL){ printf("Não encontrado\n"); }else if(lista->nItens==1){ lista->pri=NULL; lista->ult=NULL; }else if(a==lista->pri){ lista->pri=a->prox; printf("Produto extraido.\n"); }else if(a==lista->ult){ lista->ult=a->ant; }else{ a->prox->ant=a->ant; a->ant->prox=a->prox; printf("Produto extraido.\n"); } lista->nItens--; return lista; } void imprime(Lista *lista){ Nodo *p; if(lista->pri==NULL){ printf("Lista vazia\n"); } else{ for(p=lista->pri;p!= NULL;p=p->prox){ printf("Produto: %s",p->info.nome); printf("Codigo:%d\n", p->info.cod); printf("Preço: %.2f\n",p->info.preco); printf("------------------------------------\n"); } } } int main(){ Lista *lista=(Lista*)malloc(sizeof(Lista)); lista->pri=NULL; lista->ult=NULL; lista->nItens=0; int finalizador=0,num; for(;;){ if(finalizador==1) break; printf("======================================================\n"); printf("Digite 1 para inserir um produto na lista\n"); printf("Digite 2 para extrair um produto da lista\n"); printf("Digite 3 para mostrar os produtos da lista\n"); printf("Digite 0 para sair.\n"); printf("======================================================\n"); scanf("%d", &num); switch(num){ case 1: system("clear"); lista=push(lista); break; case 2: system("clear"); lista=pop(lista); break; case 3: system("clear"); imprime(lista); break; case 0: finalizador++; free(lista); break; } } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define SLEN 50 struct nameect { char *fname; char *lname; int letters; } maria; void getinfo(struct nameect *pst) { char temp[SLEN]; printf("Please enter your first name.\n"); gets(temp); /* allocate memory to hold name */ pst->fname = (char *)malloc(strlen(temp) + 1); /* copy name to allocated memory */ strcpy(pst->fname, temp); printf("Please enter your first name.\n"); gets(temp); pst->lname = (char *)malloc(strlen(temp) + 1); strcpy(pst->lname, temp); } int main() { struct nameect *p_maria; p_maria = (struct nameect *)malloc(sizeof(maria) + 1); getinfo(p_maria); printf("fname: %s, lname: %s\n", p_maria->fname, p_maria->lname); return 0; }
C
struct foobar { char foo; char bar; }; char a; int b; void c; void main() { char ab; int bc; void cd; func_call(); b = func_call(); while (a) { while_a(); } if (a) { if (b) { do_b(); } else { else_b(); } } else { else_a(); } } void main(int foo, char bar) { char ab; int bc; void cd; func_call(foo, bar, baz); b = func_call(); sum_thing = func_call(1,2,3,4, "string", 'c'); while (x) -x; while (x) if (x) return x; while ((x%4)) { arr[5].field = *((int)arr[6].field2%2) + foo.bar[4] + sizeof(int) + sizeof(int*); funcall(*((int)arr[6].field2%2) + foo.bar[4] + sizeof(int) + sizeof(int*)); } while (*((int)arr[6].field2%2) + foo.bar[4] + sizeof(int) + sizeof(int*)) { return *((int)arr[6].field2%2) + foo.bar[4] + sizeof(int) + sizeof(int*); } if (*((int)arr[6].field2%2) + foo.bar[4] + sizeof(int) + sizeof(int*)) x = 5; else p = *((int)arr[6].field2%2) + foo.bar[4] + sizeof(int) + sizeof(int*)%2 != 5 + "string "; }
C
/***************** C3.2. c file ********************/ #include <stdio.h> int main() { int pid = fork(); // fork a child if (pid){ // PARENT printf("PARENT %d CHILD =%d\n", getpid(), pid); // sleep( 1); // sleep 1 second = = > let child run next printf(" PARENT %d EXIT\n", getpid()); } else{ // child printf(" child %d msgSend my parent =%d\n", getpid(), getppid()); // sleep( 2); // sleep 2 seconds = > let parent die first printf(" child %d exit my parent =%d\n", getpid(), getppid()); } }
C
#include <stdio.h> int main() { int a=100 ; a-=10 ; //equivalent to a=a-10 ; printf("Updated value of a %d",a); }
C
#include "ESP8266.h" #include "string.h" void ESP8266_Init(void) { POINT_COLOR=RED; while(atk_8266_send_cmd("AT","OK",20)){ LCD_ShowString(19,57,200,16,16,"wifi is no online"); } delay_ms(20); u2_printf("ATE0\r\n"); //رջ delay_ms(20); while(atk_8266_send_cmd("AT+CIPMUX=1","OK",50)){ LCD_ShowString(19,57,200,16,166,"cipmux wait"); } //λ ESP8266-WIFIģʽ delay_ms(20); while(atk_8266_send_cmd("AT+CIPSERVER=1,8086","OK",50)){ LCD_ShowString(19,57,200,16,16,"tcpserver wait"); } //λ ESP8266-WIFITCP SERVER delay_ms(20); while(atk_8266_send_cmd("AT+CIPSTO=6400","OK",50)){ LCD_ShowString(19,57,200,16,16,"overtime wait");} //λ ESP8266-WIFIʱģʽ delay_ms(20); POINT_COLOR=LIGHTGREEN; LCD_ShowString(15,57,200,16,16," esp8266 init successful"); POINT_COLOR=BLUE; memset(USART2_A_BUF,0,sizeof(USART2_A_BUF)); USART2_A_STA=0;USART2_RX_STA=0; //б־λ } //ATK-ESP8266 //cmd:͵ַ //ack:ڴӦ,Ϊ,ʾҪȴӦ //waittime:ȴʱ(λ:10ms) //ֵ:0,ͳɹ(õڴӦ) // 1,ʧ uint8_t atk_8266_send_cmd(uint8_t *cmd,uint8_t *ack,uint16_t waittime) { uint8_t res=0; USART2_A_STA=0; u2_printf("%s\r\n",cmd); //1 if(ack&&waittime) //ҪȴӦ { while(--waittime) //ȴʱ { delay_ms(50); if(USART2_A_STA&0X8000)//յڴӦ { if(atk_8266_check_cmd(ack)) { //u0_printf("ack:%s",(uint8_t*)ack); break;//õЧ } USART2_A_STA=0; } } if(waittime==0)res=1; } return res; } //ATK-ESP8266,յӦ //str:ڴӦ //ֵ:0,ûеõڴӦ // ,ڴӦλ(strλ) uint8_t atk_8266_check_cmd(uint8_t *str) { uint8_t strx=0; if(USART2_A_STA&0X8000) //յһ { USART2_A_BUF[USART2_RX_STA&0X3FFF]=0;//ӽ B: 0011 strx=strcmp((const char*)USART2_A_BUF,(const char*)str); } return strx; }
C
#ifndef ERROR_H_ #define ERROR_H_ #include <stdio.h> #include <stdarg.h> #define MAX_ERR_LEN 128 typedef enum { TODO_OK, TODO_ENOMEM, TODO_ENOID, TODO_ENOTXT, TODO_EALRDYEXISTS, TODO_EINVALIDCMD, TODO_ESTYLE, TODO_ESTYLENOFILE, TODO_ESTYLENOACTV, TODO_ESTYLEPARSE, TODO_ESTYLECRNUM, TODO_ESTYLEBGNUM, TODO_ESTYLESPNUM, TODO_ESTYLEWFRMT, TODO_ESTYLEVMSNG, TODO_ESTYLEWORDR, TODO_NUMERR } todo_error_t; static const char *error_msg_table[MAX_ERR_LEN] = { [TODO_ENOMEM] = "todo: Malloc failed", [TODO_ENOID] = "todo: ID %d not found\n", [TODO_ENOTXT] = "todo: Can't find todo.txt\n", [TODO_EALRDYEXISTS] = "todo: Todo.txt already exists in current folder\n", [TODO_EINVALIDCMD] = "todo: %s\n", //err str supplied by parser [TODO_ESTYLE] = "todo: Error parsing styles\n", [TODO_ESTYLENOFILE] = "todo: Can't open file todoStyles.json\n", [TODO_ESTYLENOACTV] = "todo: Active style '%s' is not defined\n", [TODO_ESTYLEPARSE] = "todo: Error parsing styles\n", [TODO_ESTYLECRNUM] = "todo: style '%s': Color value out of bounds (0-7 allowed)\n", [TODO_ESTYLEBGNUM] = "todo: style '%s': Background color value out of bounds (0-7 allowed)\n", [TODO_ESTYLESPNUM] = "todo: style '%s': Special value out of bounds (0-2 allowed)\n", [TODO_ESTYLEWFRMT] = "todo: style '%s': Style contains more than one of each $(N) $(P) and $(T)\n", [TODO_ESTYLEVMSNG] = "todo: style '%s': One of the variables $(N) $(P) $(T) is missing\n", [TODO_ESTYLEWORDR] = "todo: style '%s': Variables $(N) $(P) $(T) is in wrong order\n" }; static inline void print_user_error(todo_error_t errnum, ...) { va_list args; va_start(args, errnum); vprintf(error_msg_table[errnum], args); va_end(args); } #endif
C
// LEVEL 2 #include "func2.c" extern int WR; #define BLKSIZE 1024 truncate(struct MINODE *mip){ int dev = mip->dev; int blocks = mip->ip.i_blocks/2; int *i_blocks = (int *)mip->ip.i_block; int i, j, k, l, m; char buf[BLKSIZE]; char ibuf[BLKSIZE]; char iibuf[BLKSIZE]; if(debug) printf("starting loop with %d blocks...\n", blocks); for(i=0;i<blocks;i++){ if(debug) printf("dallocing block %d...", i); j=i; //printf("j=%d\n", j); if(i>65803){ m=14; l=((i-65803)/256)/256; k=((i-65803)/256)%256; j=(i-65803)%256; get_block(dev, i_blocks[m], iibuf); int *ininindir=(int *)iibuf; get_block(dev, ininindir[l], ibuf); int *inindir=(int *) ibuf; get_block(dev, inindir[k], buf); int *indir=(int *) buf; dballoc(dev, indir[j]); if(debug) printf("success!\n"); continue; } if(i>267){ l=13; k=(i-267)/256; j=(i-267)%256; get_block(dev, i_blocks[l], ibuf); int *inindir=(int *) ibuf; get_block(dev, inindir[k], buf); int *indir=(int *) buf; dballoc(dev, indir[j]); if(debug) printf("success!\n"); continue; } if(i>12){ k=12; j=(i-12); get_block(dev, i_blocks[k], buf); int *indir=(int *) buf; dballoc(dev, indir[j]); if(debug) printf("success!\n"); continue; } //printf("j=%d\n", j); dballoc(dev, i_blocks[j]); if(debug) printf("success!\n"); } if(debug) printf("complete\n"); mip->ip.i_atime = mip->ip.i_mtime = time(0L); mip->ip.i_size = 0; int d; for(d=0;d<15;d++) mip->ip.i_block[d]=0; mip->dirty = 1; if(debug) printf("mip written to!\n"); } int getMode(char *c){ if(debug) printf("opening with mode %s\n", c); if(!strcmp(c, "0")||!strcmp(c, "R")||!strcmp(c, "r")){ if(debug) printf("opening for read\n"); return 0; } if(!strcmp(c, "1")||!strcmp(c, "W")||!strcmp(c, "w")){ if(debug) printf("opening for write\n"); return 1; } if(!strcmp(c, "2")||!strcmp(c, "RW")||!strcmp(c,"rw")){ if(debug) printf("opening for read/write\n"); return 2; } if(!strcmp(c, "3")||!strcmp(c, "APPEND")||!strcmp(c, "append")){ if(debug) printf("opening for append\n"); return 3; } } myopen(char *filename, int OPENMODE){ if(!strlen(filename)) return -1; //printf("Not implemented yet\n"); // MIP = iget int dev; int ino; /* INODE sip;// starting ip if(filename[0]=='/'){ dev = root->dev; sip = root->ip; } else{ dev = running->cwd->dev; sip = running->cwd->ip; } ino = searchfile(dev, &sip, filename); */ dev = getdev(running->cwd->dev, filename); ino = getinof(running->cwd->dev, filename); if(!ino){ printf("File not found\n"); return -1; } struct MINODE *mip = iget(dev, ino); INODE pp=mip->ip;//permissions ip /*if(OPENMODE > 0){ if(!(pp.i_mode&S_IWOTH)){ if(pp.i_uid!=running->uid&&pp.i_gid!=running->gid){ if(debug) printf("ip->uid=%d\n", pp.i_uid); printf("You do not have permission to edit this file\n"); iput(mip); return -1; } if(!(pp.i_uid==running->uid&&(pp.i_mode&S_IWUSR))|| !(pp.i_gid==running->gid&&(pp.i_mode&S_IWGRP))){ if(debug) printf("ip->uid=%d\n", pp.i_uid); printf("You do not have permission to edit this file\n"); iput(mip); return -1; } } } else if(!OPENMODE){ if(!(pp.i_mode&S_IROTH)){ if(pp.i_uid!=running->uid&&pp.i_gid!=running->gid){ if(debug) printf("ip->uid=%d\n", pp.i_uid); printf("You do not have permission to edit this file\n"); iput(mip); return -1; } if(!(pp.i_uid==running->uid&&(pp.i_mode&S_IRUSR))|| !(pp.i_gid==running->gid&&(pp.i_mode&S_IRGRP))){ if(debug) printf("ip->uid=%d\n", pp.i_uid); printf("You do not have permission to edit this file\n"); iput(mip); return -1; } } }*/ if(debug){ printf("preparing file at mip->dev=%d ->ino=%d", mip->dev, mip->ino); printf(" with mode=%d\n", OPENMODE); } // we know it's a file from searchfile // implement permission checking later // CHECK IF FILE IS OK FOR MODE if(!OFTRdRdy(mip)){ iput(mip); return -1; } //int i = getFreeOFT();//i = oft index // ALLOC OFT struct OFT *oftp = (struct OFT *)malloc(sizeof(struct OFT)); oftp->mode = OPENMODE; oftp->refCount = 1; oftp->mip = mip; if(debug) printf("setting write mode %d\n", OPENMODE); // SET OFFSET switch(OPENMODE){ case 0: oftp->offset = 0; break; // R: start from 0 case 1: oftp->offset = 0; if(WR) truncate(mip); break; // W: truncate file case 2: oftp->offset = 0; break; // RW: no truncation case 3: oftp->offset = mip->ip.i_size; // APPEND break; // start at end default: printf("invalid mode\n");return -1;//should never happen } if(debug) printf("finding free oft\n"); // PUT IT IN RUNNING PROC's FD (SMALLEST FD[FD]) int j; for(j=0;j<10;j++) if(running->fd[j]->refCount==0){ running->fd[j]=oftp; break; } if(debug) printf("found free oft at %d\n", j); // if j > fd.size, NO MEMORY // UPDATE INODE TIME if(!OPENMODE) mip->ip.i_atime = time(0L); else mip->ip.i_atime = mip->ip.i_mtime = time(0L); mip->dirty = 1; // RETURN WHERE YOU PUT IT IN RUNNING->FD return j; // assign file to running proc // create oft // unless already open // open file for reading and assign it to oft } open_file(){ int fd = myopen(pathname, getMode(parameter)); if(fd<0) printf("File can't be opened\n"); } myclose(struct PROC *p, int fd){ if(fd > 10||fd<0){ printf("No file to close\n"); return -1; } if(p->fd[fd]->refCount==0){ printf("No file to close\n"); return -1; } struct OFT *op = p->fd[fd]; p->fd[fd] = nullfd(); op->refCount--; if(op->refCount>0) return 0; struct MINODE *mip = op->mip; iput(mip); return 0; } int getNum(char *param){ if(!strcmp(param, "")) return -1; int i; int j=0; for(i=0;i<strlen(param);i++){ if(!isdigit(param[i])) return -1; j = j*10; j+=(param[i]-'0'); } return j; } close_file(){ //printf("Not implemented yet\n"); // GET FD myclose(running, getNum(pathname)); // delete file from running proc // if reference number isn't 0 //close file } pfd(){ //printf("Not implemented yet\n"); printf(" fd mode offset inode\n"); int i; for(i=0;i<10;i++){ struct OFT *oftp = running->fd[i]; if(oftp->refCount>0){ printf(" %2d ", i); switch(oftp->mode){ case 0: printf(" R"); break; case 1: printf(" W"); break; case 2: printf(" RW"); break; case 3: printf("APPEND"); break; default:printf(" ERROR"); } printf(" %8d [%d, %2d]\n", oftp->offset, oftp->mip->dev, oftp->mip->ino); } } // just go through all the fds and print them all } myseek(int fd, int position){ if(fd<0||position<0){ if(debug) printf("value not valid\n"); return -1; } struct OFT *op = running->fd[fd]; struct MINODE *mip = op->mip; int size = mip->ip.i_size; iput(mip); int retval = op->offset; if(position>size){ printf("Cannot seek past file's size\n"); return -1; } else{ op->offset = position; return retval; } } lseek_file(){ //printf("Not implemented yet\n"); // just lseek on the file myseek(getNum(pathname), getNum(parameter)); } access_file(){ printf("Not implemented yet\n"); // ?? } myread(int fd, char rbuf[], int nbytes){ printf("fd=%d, nbytes=%d ", fd, nbytes); if(running->fd[fd]->refCount>0) if(running->fd[fd]->mode!=0 && running->fd[fd]->mode!=2) return -1; struct OFT *oftp = running->fd[fd]; int dev = oftp->mip->dev; int ino = oftp->mip->ino; int offset = oftp->offset; int lblk = offset / BLKSIZE; int start = offset % BLKSIZE; int avil = oftp->mip->ip.i_size-offset; int bytesread = 0; if(nbytes<(BLKSIZE-start)) bytesread=nbytes; else bytesread=BLKSIZE-start; if(bytesread>avil) bytesread=avil; int blk; // get datablock //int blk = oftp->mip->ip.i_block[lbk]; if((oftp->mip->ip.i_blocks/2)<lblk) return 0; int *i_blocks = (int *)oftp->mip->ip.i_block; int i, j, k, l, m; char buf[BLKSIZE]; char ibuf[BLKSIZE]; char iibuf[BLKSIZE]; i=lblk; j=i; //printf("lblk=%d 1111111111111111111111111111111111111111111111\n", lblk); //printf("blocks=%d\n", oftp->mip->ip.i_blocks/2); if(i>65803){ m=14; l=((i-65803)/256)/256; k=((i-65803)/256)%256; j=(i-65803)%256; get_block(dev, i_blocks[m], iibuf); int *ininindir=(int *)iibuf; get_block(dev, ininindir[l], ibuf); int *inindir=(int *) ibuf; get_block(dev, inindir[k], buf); int *indir=(int *) buf; blk=indir[j]; } else if(i>267){ l=13; k=(i-267)/256; j=(i-267)%256; get_block(dev, i_blocks[l], ibuf); int *inindir=(int *) ibuf; get_block(dev, inindir[k], buf); int *indir=(int *) buf; blk=indir[j]; } else if(i>11){ k=12; j=(i-12); get_block(dev, i_blocks[k], buf); int *indir=(int *) buf; blk=indir[j]; } else blk=i_blocks[j]; printf("blk=%d\n", blk); char tbuf[BLKSIZE];//temptorary buf get_block(dev, blk, tbuf); strncpy(rbuf, &tbuf[start], bytesread); oftp->offset+=bytesread; return bytesread; } read_file(){ int fd = getNum(pathname); int nbytes = getNum(parameter); int n; char buf[BLKSIZE]; if(fd>10||fd<0) return; int c; while(n=myread(fd, buf, nbytes)){ for(c=0;c<n;c++) putchar(buf[c]); nbytes-=n; } putchar('\n'); // get_block? } writeblock(struct OFT *oftp){ oftp->mip->ip.i_blocks+=2; oftp->mip->dirty=1; //iput(oftp->mip); int blk = balloc(oftp->mip->dev); if(blk < 0){ printf("RAN OUT OF SPACE\n"); exit(1); } printf("\nallocated block %d\n", blk); //getchar(); char clr[BLKSIZE]; int i; for(i=0;i<BLKSIZE;i++) clr[i]=0; put_block(oftp->mip->dev, blk, clr); return blk; } mywrite(int fd, char wbuf[], int nbytes){ if(debug) printf("writing data to disk....\n"); if(running->fd[fd]->refCount>0){ if(running->fd[fd]->mode!=1 && running->fd[fd]->mode!=2&& running->fd[fd]->mode!=3) return -1; } else return -1; struct OFT *oftp = running->fd[fd]; int dev = oftp->mip->dev; int ino = oftp->mip->ino; int offset = oftp->offset; int lblk = offset / BLKSIZE; int start = offset % BLKSIZE; int byteswritten = 0; int size = oftp->mip->ip.i_size; if(nbytes<(BLKSIZE-start)) byteswritten=nbytes; else byteswritten=BLKSIZE-start; oftp->mip->ip.i_size+=byteswritten; int blk; // get datablock //int blk = oftp->mip->ip.i_block[lbk]; int *i_blocks = (int *)oftp->mip->ip.i_block; int i, j, k, l, m; char buf[BLKSIZE]; char ibuf[BLKSIZE]; char iibuf[BLKSIZE]; i=lblk; j=i; if(i>65803){ m=14; l=((i-65803)/256)/256; k=((i-65803)/256)%256; j=(i-65803)%256; if(i_blocks[m]==0) i_blocks[m]=writeblock(oftp); get_block(dev, i_blocks[m], iibuf); int *ininindir=(int *)iibuf; if(ininindir[l]==0) ininindir[l]=writeblock(oftp); get_block(dev, ininindir[l], ibuf); int *inindir=(int *) ibuf; if(inindir[k]==0) inindir[k]=writeblock(oftp); get_block(dev, inindir[k], buf); int *indir=(int *) buf; if(indir[j]==0) indir[j]=writeblock(oftp); blk=indir[j]; strcpy(buf, (char *)indir); put_block(dev, inindir[k], buf); strcpy(ibuf, (char *)inindir); put_block(dev, ininindir[l], ibuf); strcpy(iibuf, (char *)ininindir); put_block(dev, i_blocks[m], iibuf); } else if(i>267){ l=13; k=(i-267)/256; j=(i-267)%256; if(i_blocks[l]==0) i_blocks[l]=writeblock(oftp); get_block(dev, i_blocks[l], ibuf); int *inindir=(int *) ibuf; if(inindir[k]==0) inindir[k]=writeblock(oftp); get_block(dev, inindir[k], buf); int *indir=(int *) buf; if(indir[j]==0) indir[j]=writeblock(oftp); blk=indir[j]; strcpy(buf, (char *)indir); put_block(dev, inindir[k], buf); strcpy(ibuf, (char *)inindir); put_block(dev, i_blocks[l], ibuf); } else if(i>11){ k=12; j=(i-12); if(i_blocks[k]==0) i_blocks[k]=writeblock(oftp); printf("out\n"); printf("block=%d\n", i_blocks[k]); get_block(dev, i_blocks[k], buf); int *indir=(int *) buf; if(indir[j]==0) indir[j]=writeblock(oftp); blk=indir[j]; strcpy(buf, (char *)indir); put_block(dev, i_blocks[k], buf); } else{ if(i_blocks[j]==0) i_blocks[j]=writeblock(oftp); blk=i_blocks[j]; } char dbuf[BLKSIZE];//raw data block //if((oftp->mip->ip.i_blocks/2)<lblk){ //balloc(dev); //oftp->mip->ip.i_blocks+=2; // strcpy(dbuf, ""); //} //else get_block(dev, blk, dbuf); //if(WR) // iput(oftp->mip); //char tbuf[BLKSIZE];// temporary //strncpy(tbuf, dbuf, start);// an extra bit is written at the beggining //tbuf[strlen(tbuf)-1]=0;// This removes that extra bit strncat(dbuf, wbuf, byteswritten); //strcpy(dbuf, tbuf); if(debug) printf("writing \"%s\" to disk\n", dbuf); put_block(dev, blk, dbuf); //if(strlen(wbuf)>byteswritten){ // strncpy( wbuf, wbuf[byteswritten], strlen(wbuf)-byteswritten); //} //else // strcpy(wbuf, ""); oftp->offset+=byteswritten; if(debug){ printf("nbytes=%d\n", nbytes); printf("offset=%d\n", oftp->offset); printf("byteswritten=%d\n", byteswritten); } oftp->mip->dirty=1; if(strlen(wbuf)<byteswritten) return byteswritten-strlen(wbuf); return byteswritten; } writehelper(int fd, char *buf, int nbytes){ char tbuf[strlen(buf)];//temporary buf int i; for(i=0;i<strlen(buf);i++) tbuf[i]=0; strncpy(tbuf, buf, strlen(buf)); int n=0; while(nbytes>0){ n=mywrite(fd, buf, nbytes); if(n<0){ printf("File not open for writing\n"); return; } nbytes-=n; if(nbytes>0){ strncpy(tbuf, &buf[n], strlen(buf)-n); strcpy(buf, tbuf); if(debug){ printf("nbytes=%d\n", nbytes); printf("looping with %s\n", buf); } } if(debug) printf("END OF BUF\n"); } } write_file(){ int fd = getNum(pathname); if(fd<0){ printf("Usage: write <fd> <text>\n"); } char strval[BLKSIZE]; if(WR) writehelper(fd, parameter, strlen(parameter)); } cat_file(){ int fd = myopen(pathname, 0); if(fd<0) return; int n; char buf[BLKSIZE]; int c; while(n=myread(fd, buf, BLKSIZE)){ for(c=0;c<n;c++) putchar(buf[c]); getchar(); } putchar('\n'); myclose(running, fd); } mycp(char *path, char *param){ if(!strlen(param)||!strlen(path)){ printf("usage: cp <file> <newfile>\n"); return; } int fd = myopen(path, 0); int gd = myopen(param, 1); //cat_file(); if(fd<0){ printf("invalid source\n"); return; } if(gd<0){ printf("creating file\n"); make(0, param); gd = myopen(param, 1); } char buf[BLKSIZE]; int n; printf("reading\n"); while(n=myread(fd, buf, BLKSIZE)){ if(debug) printf("coppying %d \"%s\"...\n", n, buf); if(n==-1){ printf("ERROR\n"); return; } mywrite(gd, buf, n); } myclose(running, fd); myclose(running, gd); // read file in chunks // print it in chucnks in new file } cp_file(){ mycp(pathname, parameter); } mymv(char *path, char *param){ int dev0; int dev1; /*if(path[0]=='/') dev0=root->dev; else dev0=running->cwd->dev; if(param[1]=='/') dev1=root->dev; else dev1=running->cwd->dev;*/ dev0 = getdev(running->cwd->dev, path); dev1 = getdev(running->cwd->dev, param); // LOOK THROUGH THE PATH // IF ANOTHER DEV IS ON THE PATH // CHANGE THE DEV if(dev0==dev1){ ln(1, path, param); rm(2, path); } else{ mycp(path, param); rm(2, path); } } mv_file(){ mymv(pathname, parameter); }
C
/* Copyright (C) 1991,92,97,2000,02 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <stdlib.h> /* Perform a binary search for KEY in BASE which has NMEMB elements of SIZE bytes each. The comparisons are done by (*COMPAR)(). */ void * bsearch (const void *key, const void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *)) { size_t l, u, idx; const void *p; int comparison; l = 0; u = nmemb; while (l < u) { idx = (l + u) / 2; p = (void *) (((const char *) base) + (idx * size)); comparison = (*compar) (key, p); if (comparison < 0) u = idx; else if (comparison > 0) l = idx + 1; else return (void *) p; } return NULL; }
C
int* plusOne(int* digits, int digitsSize, int* returnSize) { int tmp = 1, idx = digitsSize - 1 ; while(tmp && idx >= 0) { digits[idx] += tmp; if(digits[idx] >= 10) { tmp = 1; digits[idx] -= 10; } else { tmp = 0; } idx--; } int *result; if(tmp) { *returnSize = digitsSize+1; result = malloc(sizeof(int) * (*returnSize)); memcpy(result + 1, digits, digitsSize * sizeof(int)); result[0] = 1; } else { *returnSize = digitsSize; result = digits; } return result; }
C
#include <stdio.h> #include <io.h> #include <sys/types.h> #include <sys/stat.h> int main( int argc, char *argv[]) { const char *name = "\\.."; struct stat st; int rc; printf("Testing stat() for [\\..]...\n"); rc = stat( name, &st ); printf("%s: [%s], rc = %d(%d).\n", rc == 0 ? "FAILED" : "PASSED", name, rc, -1 ); return rc == 0; }
C
#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct Node *PtrToNode; struct Node { ElementType Data; PtrToNode Next; }; typedef PtrToNode List; List Read(); /* 细节在此不表 */ void Print( List L ); /* 细节在此不表 */ List Reverse( List L ); int main() { List L1, L2; L1 = Read(); L2 = Reverse(L1); Print(L1); Print(L2); return 0; } List Reverse( List L ){ if(!L || !L->Next) return L; List L1=L->Next; L->Next=NULL; List L2=L1->Next; while (L2) { L1->Next=L; L=L1; L1=L2; L2=L2->Next; } L1->Next=L; L=L1; return L; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <assert.h> #include <string.h> #include <math.h> #include <ctype.h> typedef struct QueueNode { int data; struct QueueNode* next; }QN; typedef struct Queue { QN* front; QN* back; }Q; typedef struct { Q q1; Q q2; } MyStack; void QueueInit(Q* q) { q->front = NULL; q->back = NULL; } void QueuePush(Q* q, int x) { QN* newnode = (QN*)malloc(sizeof(QN)); newnode->data = x; newnode->next = NULL; if (q->back == NULL) { q->back = newnode; q->front = newnode; } else { QN* back = q->back; q->back = newnode; back->next = newnode; } } void QueuePop(Q* q) { if (q->front->next == NULL) { free(q->front); q->front = NULL; q->back = NULL; } else { QN* newfront = q->front->next; free(q->front); q->front = NULL; } } int QueueTop(Q* q) { return q->front->data; } //Ԫظ int QueueSize(Q* q) { QN* cur = q->front; int n = 0; while (cur != NULL) { n++; cur = cur->next; } return n; } //շ0 //ǿշԪظ int QueueEmpty(Q* q) { return QueueSize(q); } //ȡͷԪ int QueueFront(Q* q) { assert(q); return q->front->data; } //ȡβԪ int QueueBack(Q* q) { assert(q); return q->back->data; } void QueueDestroy(Q* q) { QN* cur = q->front; while (cur) { QN* next = cur->next; free(cur); cur = next; } q->front = NULL; q->back = NULL; } /** Initialize your data structure here. */ MyStack* myStackCreate() { MyStack* st = (MyStack*)malloc(sizeof(MyStack)); QueueInit(&st->q1); QueueInit(&st->q2); return st; } /** Push element x onto stack. */ void myStackPush(MyStack* obj, int x) { if (!QueueEmpty(&obj->q1)) QueuePush(&obj->q2, x); else QueuePush(&obj->q1, x); } /** Removes the element on top of the stack and returns that element. */ int myStackPop(MyStack* obj) { Q* empty = &obj->q1; Q* not_empty = &obj->q2; if (!QueueEmpty(&obj->q2)) { not_empty = &obj->q1; empty = &obj->q2; } while (QueueSize(not_empty) > 1) { QueuePush(empty, QueueFront(not_empty)); QueuePop(not_empty); } int top = QueueBack(not_empty); QueuePop(not_empty); return top; } /** Get the top element. */ int myStackTop(MyStack* obj) { if (!QueueEmpty(&obj->q1)) return QueueBack(&obj->q2); else return QueueBack(&obj->q1); } /** Returns whether the stack is empty. */ bool myStackEmpty(MyStack* obj) { if (QueueSize(&obj->q1) || QueueSize(&obj->q2)) return false; else return true; } void myStackFree(MyStack* obj) { QueueDestroy(&obj->q1); QueueDestroy(&obj->q2); free(obj); } /** * Your MyStack struct will be instantiated and called as such: * MyStack* obj = myStackCreate(); * myStackPush(obj, x); * int param_2 = myStackPop(obj); * int param_3 = myStackTop(obj); * bool param_4 = myStackEmpty(obj); * myStackFree(obj); */
C
#include <stdio.h> int main() { int array[10]= {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // p指向数组的的地址(数组中第一个元素的地址) int *p = array; int i; for(i = 0; i < 10; i++) { printf("%d ",*(p + i)); } printf("\n"); return 0; }
C
#include <stdio.h> int get_num(int numbers[]){ int c; int i = 0; int sum = 0; while ( (c = getchar()) != EOF){ if ( c >= '0' && c <= '9'){ sum = sum * 10 + c - '0'; } else if ( c == '\n'){ numbers[i++] = sum; sum = 0; } } return i; } int gcd(int a ,int b){ if ( b == 0){ return a; } else{ return gcd(b ,a % b); } } int lcm(int a ,int b){ int mul ,div; int res; mul = a * b; div = gcd(a ,b); res = mul / div; return res; } int main(void){ int numbers[100]; int r ,i; i = get_num(numbers); int res_gcd ,result_gcd; int res_lcm ,result_lcm; result_gcd = numbers[0]; for (r = 1;r < i;++r){ res_gcd = gcd(result_gcd ,numbers[r]); result_gcd = res_gcd; } result_lcm = numbers[0]; for (r = 1;r < i;++r){ res_lcm = lcm(result_lcm, numbers[r]); result_lcm = res_lcm; } printf("GCD: %d\n" ,res_gcd); printf("LCM: %d\n" ,res_lcm); return 0; }
C
#include "watchuser.h" // thread that will monitor our user linked list void *watchuser_thread(void *param){ while(1){ // we may make changes to the user list so be sure to lock pthread_mutex_lock(&lock); watchuserElement *temp = watchuserHead; while (temp != NULL){ setutxent(); /* start at beginning of users*/ while (up = getutxent()) /* get an entry */ { if (up->ut_type == USER_PROCESS) /* only care about users */ { if (strcmp(up->ut_user, temp->username) == 0 && temp->watched == 0){ printf("\n%s has logged on %s from %s\n", up->ut_user, up->ut_line, up ->ut_host); temp->watched = 1; } } } temp = temp->next; } pthread_mutex_unlock(&lock); sleep(10); } }
C
#include<stdio.h> void main() { int i; for(i=6;i<9;i++) { if(i%2==0&&i!=6) { printf("%d ",i); } }
C
#include <stdlib.h> #include <stdio.h> int main() { int n, i = 0; int *arr = (int *)calloc(1000, sizeof(int)); while(scanf("%d",&n)) { arr[i++] = n; if(getchar() == '\n') break; } int num = i; i = 1; int j = 0; while(i < num) { if(arr[i-1] == 0 || arr[i] == 0) i += 2; else { arr[j++] = arr[i-1]*arr[i]; arr[j++] = arr[i]-1; i += 2; } } --j; if(j > 0) { for(i = 0; i < j; ++i) { printf("%d ", arr[i]); } printf("%d", arr[j]); } else printf("0 0"); return 0; }
C
#include "helpers.h" #include <math.h> #include <string.h> // Convert image to grayscale void grayscale(int height, int width, RGBTRIPLE image[height][width]) { float turnGray; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { turnGray = round((image[j][i].rgbtBlue + image[j][i].rgbtGreen + image[j][i].rgbtRed) / 3.00); image[j][i].rgbtBlue = turnGray; image[j][i].rgbtGreen = turnGray; image[j][i].rgbtRed = turnGray; } } } int setMaxValue(int RGB) { if (RGB > 255) { RGB = 255; } return RGB; } // Convert image to sepia void sepia(int height, int width, RGBTRIPLE image[height][width]) { float sepiaBlue; float sepiaGreen; float sepiaRed; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { sepiaBlue = setMaxValue(round(.272 * image[j][i].rgbtRed + .534 * image[j][i].rgbtGreen + .131 * image[j][i].rgbtBlue)); sepiaGreen = setMaxValue(round(.349 * image[j][i].rgbtRed + .686 * image[j][i].rgbtGreen + .168 * image[j][i].rgbtBlue)); sepiaRed = setMaxValue(round(.393 * image[j][i].rgbtRed + .769 * image[j][i].rgbtGreen + .189 * image[j][i].rgbtBlue)); image[j][i].rgbtBlue = sepiaBlue; image[j][i].rgbtGreen = sepiaGreen; image[j][i].rgbtRed = sepiaRed; } } } // Reflect image horizontally void reflect(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE temp; for (int i = 0; i < height; i++) { for (int j = 0; j < width/2; j++) { temp = image[i][j]; image[i][j] = image[i][width - j - 1]; image[i][width - j - 1] = temp; } } } // Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE aux[height][width]; memcpy(aux, image, sizeof(RGBTRIPLE) * height * width); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { float average = 0.00; int red = 0; int green = 0; int blue = 0; for (int k = -1; k < 2; k++) { for (int l = -1; l < 2; l++) { if ((i + k != height && j + l != width) && (i + k != -1 && j + l != -1)) { red += aux[i + k][j + l].rgbtRed; green += aux[i + k][j + l].rgbtGreen; blue += aux[i + k][j + l].rgbtBlue; average++; } } } image[i][j].rgbtRed = round(red / average); image[i][j].rgbtGreen = round(green / average); image[i][j].rgbtBlue = round(blue / average); } } }
C
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include <conio.h> #include "invader.h" struct INVASOR inv [6]; struct INVASOR inv2 [6]; void cria_invader () //cria primeira fila de invaders { int i,n=0; for(i=0; i<6; i++) { inv[i].x_invasor = 5+n; inv[i].y_invasor = 3; n+=8; } } void cria_invader2 () //cria segunda fila de invaders { int i,n=0; for(i=0; i<6; i++) { inv2[i].x_invasor = 5+n; inv2[i].y_invasor = 6; n+=8; } } void desenhainvader() //desenha primeira fila de invaders { int i; for(i = 0; i<6 ; i++) { if(inv[i].x_invasor!=-3) { gotoxy(inv[i].x_invasor, inv[i].y_invasor); invader(inv[i].x_invasor, inv[i].y_invasor); } } } void desenhainvader2() //desenha segunda fila de invaders { int i; for(i = 0; i<6 ; i++) { if(inv2[i].x_invasor!=-3) { gotoxy(inv2[i].x_invasor, inv2[i].y_invasor); invader(inv2[i].x_invasor, inv2[i].y_invasor); } } } void mov_invaderx() //faz movimento da primeira fila de invaders { int i; if (inv[i].y_invasor<26) { for(i = 0; i<6 ; i++) { if(inv[i].x_invasor!=-3) { inv[i].x_invasor++; switch (i) { case 0: if (inv[i].x_invasor==23) { apagainvader(); movxmenos(); } break; case 1: if (inv[i].x_invasor==31) { apagainvader(); movxmenos(); } break; case 2: if (inv[i].x_invasor==39) { apagainvader(); movxmenos(); } break; case 3: if (inv[i].x_invasor==47) { apagainvader(); movxmenos(); } break; case 4: if (inv[i].x_invasor==55) { apagainvader(); movxmenos(); } break; case 5: if (inv[i].x_invasor==63) { apagainvader(); movxmenos(); } break; } } } } } void mov_invader2x() //faz movimento da segunda fila de invaders { int i; if (inv2[i].y_invasor<26) { for(i = 0; i<6 ; i++) { if(inv2[i].x_invasor!=-3) { inv2[i].x_invasor++; switch (i) { case 0: if (inv2[i].x_invasor==23) { apagainvader2(); movxmenos2(); } break; case 1: if (inv2[i].x_invasor==31) { apagainvader2(); movxmenos2(); } break; case 2: if (inv2[i].x_invasor==39) { apagainvader2(); movxmenos2(); } break; case 3: if (inv2[i].x_invasor==47) { apagainvader2(); movxmenos2(); } break; case 4: if (inv2[i].x_invasor==55) { apagainvader2(); movxmenos2(); } break; case 5: if (inv2[i].x_invasor==63) { apagainvader2(); movxmenos2(); } break; } } } } } void movxmenos() // desce os invaders da primeira fileira { int k; for(k=0; k<6; k++) { if(inv[k].x_invasor!=-3) { inv[k].y_invasor+=2; apagainvader(); gotoxy(inv[k].x_invasor+2,inv[k].y_invasor-2); printf(" "); gotoxy(inv[k].x_invasor+2,inv[k].y_invasor-1); printf(" "); if (inv[k].x_invasor==-3) { inv[k].y_invasor=-3; } } } for (k=0; k<6; k++) { if(inv[k].x_invasor!=-3) { inv[k].x_invasor-=18; apagainvader(); } } } void movxmenos2() //desce os invaders da segunda fileira { int k; for(k=0; k<6; k++) { if(inv2[k].x_invasor!=-3) { inv2[k].y_invasor+=2; apagainvader2(); gotoxy(inv2[k].x_invasor,inv2[k].y_invasor-2); printf(" "); gotoxy(inv2[k].x_invasor+1,inv2[k].y_invasor-2); printf(" "); gotoxy(inv2[k].x_invasor+2,inv2[k].y_invasor-2); printf(" "); gotoxy(inv2[k].x_invasor,inv2[k].y_invasor-1); printf(" "); gotoxy(inv2[k].x_invasor+1,inv2[k].y_invasor-1); printf(" "); gotoxy(inv2[k].x_invasor+2,inv2[k].y_invasor-1); printf(" "); if (inv2[k].x_invasor==-3) { inv2[k].y_invasor=-3; } } } for (k=0; k<6; k++) { if(inv2[k].x_invasor!=-3) { inv2[k].x_invasor-=18; apagainvader2(); } } } void apagainvader() //apaga rastro da primeira fila de invaders { int i; for (i=0; i<6; i++) { if(inv[i].x_invasor!=-3) { gotoxy(inv[i].x_invasor-1,inv[i].y_invasor); printf(" "); gotoxy(inv[i].x_invasor-1,inv[i].y_invasor+1); printf(" "); } if (inv[i].y_invasor>3) { if(i==0&&inv[i].x_invasor<45) { gotoxy(inv[i].x_invasor+17,inv[i].y_invasor-1); printf(" "); gotoxy(inv[i].x_invasor+17,inv[i].y_invasor-2); printf(" "); } if(i==0&&inv[i].x_invasor<45) { gotoxy(60,inv[i].y_invasor-1); printf(" "); gotoxy(60,inv[i].y_invasor-2); printf(" "); } gotoxy(inv[i].x_invasor,inv[i].y_invasor-1); printf(" "); gotoxy(inv[i].x_invasor,inv[i].y_invasor-2); printf(" "); gotoxy(inv[i].x_invasor+1,inv[i].y_invasor-1); printf(" "); gotoxy(inv[i].x_invasor+1,inv[i].y_invasor-2); printf(" "); } } } void apagainvader2() //apaga rastro da segunda fila de invaders { int i; for (i=0; i<6; i++) { if(inv2[i].x_invasor!=-3) { gotoxy(inv2[i].x_invasor-1,inv2[i].y_invasor); printf(" "); gotoxy(inv2[i].x_invasor-1,inv2[i].y_invasor+1); printf(" "); if(inv2[i].x_invasor<55) { gotoxy(inv2[i].x_invasor+3,inv2[i].y_invasor-2); printf(" "); } } if (inv2[i].y_invasor>3) { gotoxy(inv2[i].x_invasor,inv2[i].y_invasor-1); printf(" "); gotoxy(inv2[i].x_invasor+1,inv2[i].y_invasor-1); printf(" "); } } } void invader(int x_invader, int y_invader) // printa a matriz do invader { int i, j; char n [2][3]= {{178,178,178}, {178,178,178} }; gotoxy(x_invader, y_invader); for(i=0; i<2; i++) { for (j=0; j<3; j++) { textcolor(11); printf("%c", n[i][j] ); } gotoxy(x_invader, y_invader+1); } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> void main(int argc, char **argv) { char **param=(char**)malloc(sizeof(char*)*8); //char *trunk=(char*)malloc(sizeof(char)*8*25); int i=0, idx=0, next_idx=0; char *cmds=(char*)malloc(sizeof(char)*200); char *cmd=(char*)malloc(sizeof(char)*25); int param_idx=0; char *tmp=(char*)malloc(sizeof(char)*25); unsigned int freq=0, symrate=0, tuner_idx=0; unsigned char mod=0; for (i=0; i<8; i++){ //memset((char*)trunk, '\0', sizeof(char)*25); //param[i]=trunk; //trunk+=25; param[i]=(char*)malloc(sizeof(char)*25); memset((char*)param[i], '\0', sizeof(param[i])); } printf("please input your cmds\n"); fgets(cmds, 200, stdin); i=0; while(cmds[i] != ';'){ if(cmds[i] == ' '){ //i+=1; printf("param %d, i=%d, idx=%d,\n", param_idx, i, idx); snprintf(param[param_idx], i-idx+1, "%s", cmds+idx); printf("%s\n", param[param_idx]); //memset(tmp, '\0', sizeof(char)*25); idx=i+1; param_idx+=1; }/*else{ i+=1; }*/ i+=1; } printf("%s\n", param[0]); if(!strcmp(param[0], "FE_SAT_TUNE")){ printf("It's sat tune\n"); freq=atoi(param[2]); symrate=atoi(param[3]); tuner_idx=atoi(param[1]); printf("freq:%d, symrate:%d, tuner_idx:%d\n", freq, symrate, tuner_idx); if(!strcmp(param[4], "FE_MOD_DVB")){ mod=1; }else if(!strcmp(param[4], "FE_MOD_DVBS2")){ mod=2; }else{ printf("wrong modulation\n"); } printf("mod:%d\n", mod); }else{ printf("It's ter tune\n"); } /* for(i=0; i <= param_idx; i++){ printf("%s\n", param[param_idx]); }*/ free(cmds); for(i=0; i<8; i++){ free(param[i]); } /*for(i=0; i<8; i++){ param[i]=NULL; } free(trunk);*/ free(param); }
C
#include <stdio.h> #include <winsock2.h> //need winsock for int and u_char in pcap.h #define HAVE_REMOTE #include <pcap.h> //Winpcap #include "device_display.h" #include "utils.h" #pragma comment(lib, "wpcap.lib") //For winpcap #pragma comment(lib, "ws2_32.lib") //For winsock //#define IPTOSBUFFERS 12 enum displayInterfacesRetvals { SUCCESS, NO_INTERFACES_FOUND, WINPCAP_NOT_INSTALLED }; char* iptos(u_long in) { /* Converts the input u_long to a decimal IP address. Note that if the returned value isn't NULL, the user must free it after use. */ u_char* p; char* decimalIP; int decimalIPLen = 3 * 4 + 3 + 1; //4 3-digit nunmbers + 3 dots + \x00 int decimaLIPCharCount = decimalIPLen - 1; //4 3-digit nunmbers + 3 dots and no tailing \x00 decimalIP = malloc(sizeof(char) * (decimalIPLen)); if (decimalIP != NULL) { p = (u_char*)&in; _snprintf_s(decimalIP, sizeof(char) * (decimalIPLen), decimaLIPCharCount, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); } return decimalIP; } char* ip6tos(struct sockaddr* sockaddr) { /* Converts the input u_long to a IPv6 address. Note that if the returned value isn't NULL, the user must free it after use. */ char* address; int addrlen = 50; socklen_t sockaddrlen; address = malloc(sizeof(char) * addrlen); sockaddrlen = sizeof(struct sockaddr_in6); if (getnameinfo(sockaddr, sockaddrlen, address, addrlen, NULL, 0, NI_NUMERICHOST) != 0) { free(address); return NULL; } return address; } int displayInterfaces() { int i; BOOLEAN should_break = FALSE; u_char errbuf[PCAP_ERRBUF_SIZE]; pcap_if_t* alldevs, * d; struct pcap_addr* address; char* printableAddr; char ip6str[128] = { 0 }; threadSafeFprintf(stdout, "Enamurating Devices:\n"); /* Retrieve the local device list */ if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) { threadSafeFprintf(stderr, "*** FATAL! Error in pcap_findalldevs_ex: %s\n", errbuf); return NO_INTERFACES_FOUND; } i = 0; /* Print the list */ for (d = alldevs; d; d = d->next) { threadSafeFprintf(stdout, "%d. ", ++i); if (d->description) { threadSafeFprintf(stdout, "%s\n", d->description); } else { threadSafeFprintf(stdout, "No description available.\n"); } if (d->addresses) { for (address = d->addresses; address; address = address->next) { if (address->addr) { printableAddr = NULL; should_break = FALSE; switch (address->addr->sa_family) { case AF_INET: printableAddr = iptos(((struct sockaddr_in*)address->addr)->sin_addr.s_addr); break; case AF_INET6: printableAddr = ip6tos(address->addr); break; default: threadSafeFprintf(stdout, "\tError in address enumuration!\n"); should_break = TRUE; break; } if (should_break) { continue; } if (printableAddr != NULL) { threadSafeFprintf(stdout, "\tAddress: %s\n", printableAddr); free(printableAddr); } else { threadSafeFprintf(stdout, "\tError translating IP address!\n"); } } } } else { threadSafeFprintf(stdout, "No Addresses found.\n"); } threadSafeFprintf(stdout, "\t%s\n", d->name); } if (i == 0) { threadSafeFprintf(stderr, "No interfaces found!\n"); return NO_INTERFACES_FOUND; } return SUCCESS; }
C
//This is a calculator program #include<stdio.h> void main() { int a,b,c; //Add calculator functions here } int add(int p,int q) { } int subtract(int p,int q) { return p-q; }
C
#include "Planificador.h" #include <string.h> void crear(T_Planificador *planif) { *planif = NULL; } void insertar_tarea(T_Planificador *planif, int pri, char * id) { T_Planificador aux = malloc(sizeof(struct TNodo)); aux->id = id; aux->pri = pri; aux->sig = NULL; T_Planificador ptr = *planif, ant = NULL; int ok = 0; if (*planif == NULL) { *planif = aux; } else { while (ptr != NULL && !ok) { if (ptr->pri > aux->pri) { ant = ptr; ptr = ptr->sig; } else if (ptr->pri < aux->pri) { if (ant != NULL) { ant->sig = aux; aux->sig = ptr; } else { aux->sig = ptr; *planif = aux; } ok = 1; } else { aux->sig = ptr->sig; ptr->sig = aux; ok = 1; } } if (!ok) { aux->sig = NULL; ant->sig = aux; } } } void mostrar(T_Planificador planificador) { T_Planificador aux = planificador; while (aux != NULL) { printf("ID: %s, Prior: %d \n", aux->id, aux->pri); aux = aux->sig; } printf("- \n"); } void eliminar_tarea(T_Planificador *planif, char * id, unsigned * ok) { T_Planificador aux = *planif, ant = NULL; while (aux != NULL && (*ok)==0) { if (strcmp(id, aux->id) != 0) { ant = aux; aux = aux->sig; } else { if (ant != NULL) { ant->sig = aux->sig; } else { *planif = aux->sig; } free(aux); *ok = 1; } } } void planificar(T_Planificador *planif) { T_Planificador aux = *planif; aux = aux->sig; *planif = aux; } void destruir(T_Planificador *planif) { T_Planificador ptr = *planif; while (ptr != NULL) { T_Planificador aux = ptr; ptr = ptr->sig; free(aux); } crear(planif); }
C
#include "lineprocess.h" #include "symbollist.h" #include "symbol.h" int instructions_memory = 0; int data_memory = 0; char ** entry_list = NULL; extern int get_instructions_counter(int size); extern int get_data_counter(int size); extern bool is_command(char * command); extern int calculate_command_space(char ** commandline); extern void reset_instructions_counter(); extern void reset_data_counter(); extern void instruction_to_bits(char ** words); extern void data_to_bits(char ** words); char ** convert_line_to_words_array(char *line); bool is_external(char word[]); bool is_entry(char word[]); bool is_macro(char word[]); bool is_symbol_assign(char ** words); void handle_external_symbol(char ** words); void handle_macro_symbol(char ** words); void handle_symbol_assign(char ** words); void handle_command(char ** words); void add_to_entry_list(char * entry); void convert_symbol_assign_to_ouput_item(char ** words); void convert_command_to_output_item(char ** words); void convert_data_to_output_item(char ** words); void reset_memory_counters(); void reset_entry_list(); void first_loop_process(char *line) { char ** words = convert_line_to_words_array(line); if(is_entry(words[0])) {/* ignore entry type symbols */ return; }else if(is_external(words[0])) {/* handle external symbols */ handle_external_symbol(words); return; }else if(is_macro(words[0])) {/* handle macro symbols */ handle_macro_symbol(words); return; }else if(is_symbol_assign(words)) { /* handle symbol assign */ handle_symbol_assign(words); return; } else if(is_command(words[0])) { /* handle commands */ handle_command(words); return; } return; } void second_loop_process(char *line) { char ** words = convert_line_to_words_array(line); if (is_macro(words[0])) {/* ignore macro */ return; }else if(is_entry(words[0])) { /* add to entry list */ add_to_entry_list(words[1]); return; } else if (is_symbol_assign(words)) {/* handle symbols */ convert_symbol_assign_to_ouput_item(words); return; } else if (is_command(words[0])) {/* handle commands */ convert_command_to_output_item(words); return; } } /** * converts a string to an array of words without the whitespaces */ char ** convert_line_to_words_array(char *line) { char * nextWord; char ** wordArray; int i = 0; char *lineClone; wordArray = NULL; /* allocate space same as line */ lineClone = (char *) malloc((strlen(line)+1)* sizeof(char)); /* clone line */ strcpy(lineClone, line); /*grabs the next word from the string (without whitespaces)*/ nextWord = strtok(lineClone, WORD_SPLIT_TOKENS); while (nextWord != NULL) { /*reallocating space from the next word in the array*/ wordArray = (char **) realloc(wordArray, (i + 1) * sizeof(char *)); /* allocate space for the incoming word*/ wordArray[i] = (char *) malloc(sizeof(nextWord) * sizeof(char)); /* actually setting the word */ wordArray[i] = nextWord; /* grabing the next word from the string */ nextWord = strtok (NULL, WORD_SPLIT_TOKENS); i++; } /* add NULL to last index to indicate the end of the array */ wordArray = (char **) realloc(wordArray, i * sizeof(char *)); wordArray[i] = (char *) malloc(sizeof(nextWord) * sizeof(char)); wordArray[i] = NULL; /* free alloctated spaces */ lineClone = NULL; free(lineClone); free(nextWord); return wordArray; } /** * checks weather sign is the .external key word */ bool is_external(char word[]) { if(strcmp(EXTERNAL_SIGN, word) == 0) { return true; } return false; } /** * checks weather sign is the .entry key word */ bool is_entry(char word[]) { if(strcmp(ENTRY_SIGN, word) == 0) { return true; } return false; } /** * checks weather sign is the .define key word */ bool is_macro(char word[]) { if(strcmp(MACRO_SIGN, word) == 0) { return true; } return false; } /** * checks weather sign a regular symbol assign */ bool is_symbol_assign(char ** words) { int i = 0; char * word; unsigned wordLength; while(words[i]) { word = words[i]; wordLength = strlen(words[i]); /* checks if the line is variable assign command */ if(word[wordLength-1] == SYMBOL_ASSIGN_SIGN) { return true; } i++; } return false; } /** * adds symbol to list */ void handle_external_symbol(char ** words) { Symbol symbol; /* create symbol */ symbol.name = words[1]; symbol.type = EMPTY; symbol.value = EXTERNAL_ADDRESS_VALUE; symbol.size = 0; symbol.isMacro = false; symbol.isExternal = true; /* add to symbols list */ add_symbol_to_list(symbol); } /** * adds symbol to list */ void handle_macro_symbol(char ** words) { int i = 0; Symbol symbol; int macroValue; /* prepare macro valus */ while(words[i]) { /* get value after "=" sign */ if(strcmp(words[i], "=") == 0) { macroValue = atoi(words[i+1]); break; } i++; } /* prepare symbol */ symbol.name = words[1]; symbol.type = EMPTY; symbol.value = macroValue; symbol.size = 1; symbol.isMacro = true; symbol.isExternal = false; /* add to symbols list */ add_symbol_to_list(symbol); } void handle_symbol_assign(char ** words) { Symbol symbol; char * symbolName; SymbolType symbolType; int size; int value; symbolName = get_symbol_name(words); symbolType = get_symbol_type(words); size = calculate_symbol_memory_size(words, symbolType, symbolName); /* differrent value for data and instructions */ if (symbolType == COMMAND) { value = get_instructions_counter(size); } else if (symbolType == DATA) { value = get_data_counter(size); } /* create symbol */ symbol.name = symbolName; symbol.type = symbolType; symbol.value = value; symbol.size = size; symbol.isMacro = false; symbol.isExternal = false; add_symbol_to_list(symbol); /* free allocated space */ symbolName = NULL; free(symbolName); } void handle_command(char ** words) { int size = calculate_command_space(words); /* only increment counter */ get_instructions_counter(size); } void update_data_symbols_addresses() { int ic = get_instructions_counter(0); symbolListPtr current = symbolListHead; while(current != NULL) { /* only data symbols */ if (current->symbol.type == DATA) { /* updates adres after end of ic*/ current->symbol.value += ic; } current = current->next; } } void reset_counters() { reset_instructions_counter(); reset_data_counter(); } void set_saved_memory_cells(int instructions, int data) { instructions_memory = instructions; data_memory = data; } void add_to_entry_list(char * entry) { int i = 0; if (entry_list != NULL) { while(entry_list[i]) { i++; } } entry_list = (char **) realloc(entry_list, (i + 1) * sizeof(char *)); entry_list[i] = (char *) malloc(sizeof(entry)); entry_list[i] = entry; return; } void convert_symbol_assign_to_ouput_item(char ** words) { char * name; char ** action; name = get_symbol_name(words); action = remove_symbol_name(words, name); if (is_command(action[0])) { convert_command_to_output_item(action); } else { /* is data symbol */ convert_data_to_output_item(action); } } void convert_command_to_output_item(char ** words) { instruction_to_bits(words); } void convert_data_to_output_item(char ** words) { data_to_bits(words); } void reset_memory_counters() { instructions_memory = 0; data_memory = 0; reset_entry_list(); } void reset_entry_list() { int i = 0; if (entry_list) { while(entry_list[i]) { entry_list[i] = NULL; free(entry_list[i]); i++; } } }
C
#ifndef Signal_H #define Signal_H #define IO_PIN 4 #define CLK_PIN 4 /* * @brief set pin to high * @param pinNo is the pin to set high */ void setPinHigh(int pinNo); /* * @brief set pin to low * @param pinNo is the pin to set low */ void setPinLow(int pinNo); /* *read the pin state pinNO is the pin read from return 1 if pin is high, otherwise 0 */ int readPin(int pinNo); /* *brief the pin as output *return pinNo is the pin set as output */ void setPinToOutput (int pinNo); /* *brief set pin as input *param pinNo is the pin set as input */ void setPinToInput (int pinNo); #endif // Signal_H
C
#include <stdio.h> #define INT_STACK_MAX 1024 struct int_stack { int data[INT_STACK_MAX]; int size; }; typedef struct int_stack int_stack; void int_stackInit(int_stack *s){ s->size=0; } int int_stackTop(int_stack *s){ if(s->size==0){ fprintf(stderr, "Error: int_stack empty\n"); return -1; } return s->data[(s->size - 1)]; } void int_stackPush(int_stack *s, int data){ if (s->size < INT_STACK_MAX) s->data[s->size++] = data; else fprintf(stderr, "Error: int_stack full\n"); } int int_stackPop(int_stack *s){ if (s->size == 0){ fprintf(stderr, "Error: int_stack empty\n"); return -1; } return s->data[--s->size]; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { int pid; if ((pid = fork()) < 0) { printf("Error with forking process\n"); exit(1); } else if (pid == 0) { printf("Child process calling\n"); char *args[] = {"ls", "-l", NULL}; int status = execvp("/bin/ls", args); if (status == -1) { printf("Error occured while calling execp\n"); } } else { printf("parent calling\n"); } return 0; }
C
#include<stdio.h> #include<string.h> int main() { char str[]="REverseMe",t; int i,j,n; printf("\nEnter the string :"); i = 0; j = strlen(str) - 1; n=strlen(str); while (i < j) { t = str[i]; str[i] = str[j]; str[j] = t; i++; j--; } for(i=0;i<n;i++) { if(str[i]!='a' && str[i]!='e' && str[i]!='i' && str[i]!='o' && str[i]!='u') { printf("%c",str[i]); } } return 0; }
C
#include <stdio.h> void printchar(char c[128], int n) { int i; for(i=0;i<n;i++) { printf("%s", c); } printf("\n"); } int main() { printchar("*", 10); }
C
#include <stdio.h> int total, sum, n; int ss( int set[], int prev ) //prev is the previous number index which was added to the set { int i; int flag; for(i=prev+1 ;i<n; i++) { total+=set[i]; printf("\nNumber: %d Total: %d",set[i],total); if(total>sum) //Backtrack { total-=set[i]; printf("\tBacktrack Total: %d",total); return 0; } if(total==sum) //Found a subset { printf("\nSuccess\n"); printf(" %d ", set[i]); return 1; } if(i==(n-1)) //Last number, cant move further so backtrack { total-=set[i]; return 0; } flag = ss(set,i); //Returns 0 for backtracking, 1 for success if(flag==0) { total-=set[i]; printf("\nBacktrack Total: %d",total); } if(flag==1) { printf("%d ", set[i]); return 1; } } } int main() { int set[]={ 2,3,5,7,10 }; sum=25; n=5; ss(set,-1); return 0; }
C
#ifndef G_CONSOLE_H #define G_CONSOLE_H #include <Ethernet2.h> // Telnet listens on port 23 EthernetServer telnet(23); // Client needs to have global scope so it can be called // from functions outside of loop, but we don't know // what client is yet, so creating an empty object EthernetClient telnetClient = 0; //we'll use a flag separate from client.connected boolean telnet_connectFlag = 0; //time in milliseconds of last activity unsigned long timeOfLastActivity; //five minutes unsigned long allowedConnectTime = 300000; Stream *console; void console_init(){ telnet.begin(); console = &Serial; } void telnet_stop(){ telnetClient.stop(); } void console_check(){ // check new connection // if (telnet.available() && !telnet_connectFlag) { telnet_connectFlag = 1; telnetClient = telnet.available(); Serial.println(F("Telnet: Connected")); telnetClient.println(F(PROP_NAME " (telnet)")); } // check disconnected // if ((telnetClient.status() == 0x1C) && telnet_connectFlag) { Serial.println(F("Telnet: Disconnected")); telnetClient.stop(); telnet_connectFlag = 0; } // select stream // if (!telnet_connectFlag) console = &Serial; else console = &telnetClient; } #endif
C
#include "drum_utils.h" #include <stdint.h> // Code based off ThatOneTeam's code from last year void hitDrum(int hit){ R_T(); // toggle Red LED // two stick instruments #ifdef DOUBLE_STICK static uint8_t hitLeft = 0x0; if (hitLeft) { LEFT_PORT |= LEFT_H; LEFT_PORT &= ~LEFT_R; RIGHT_PORT &= ~RIGHT_H; RIGHT_PORT |= RIGHT_R; R_ON(); } else { RIGHT_PORT |= RIGHT_H; RIGHT_PORT &= ~RIGHT_R; LEFT_PORT &= ~LEFT_H; LEFT_PORT |= LEFT_R; R_OFF(); } hitLeft = !hitLeft; // single stick instruments #else //hit if(hit) { LEFT_PORT |= LEFT_H; LEFT_PORT &= ~LEFT_R; } //retract else { LEFT_PORT &= ~LEFT_H; LEFT_PORT |= LEFT_R; } #endif }
C
#include <stdio.h> #include <conio.h> #include<stdlib.h> typedef struct Node CSL; struct Node { int data; CSL *next; }*head1 = NULL; CSL *head2=NULL; CSL *head3=NULL; void insertion_in_end(int data,CSL **head){ CSL * new_node=(CSL*)malloc(sizeof(CSL)); new_node->data=data; new_node->next=NULL; if(*head==NULL){ *head=new_node; (*head)->next=*head; } else{ CSL *temp=(*head); while((temp)->next!=(*head)){ temp=(temp)->next; } (temp)->next=new_node; new_node->next=(*head); } } void display(CSL *head){ if(head==NULL){ printf("LIST IS EMPTY"); } else{ CSL *temp=head; do { printf("%d",temp->data); temp = temp->next; if(temp!=head){ printf(","); } }while(temp!=head); printf("\n"); } } int main(){ printf("<<<<<<------MERGING OF CSL---->>>>>\n"); start1: printf("ENTER THE NUMBER OF NODE THAT U WANT TO INSERT IN FIRST CSLL="); int n; scanf("%d",&n); int pre=0; int data=0; for(int i=0;i<n;i++){ pre=data; printf("ENTER DATA="); scanf("%d",&data); if(pre>data&&i!=0){ head1=NULL; printf("\n!!!!!!!THE LIST MUST BE IN ASCENIDNG ORDER!!!!!!! \n<<<PLEASE RE_ENTER THE LIST>>>\n"); goto start1; } insertion_in_end(data,&head1); } printf("ELEMENT IN FIRST CSLL="); display(head1); start2: printf("ENTER THE NUMBER OF NODE THAT U WANT TO INSERT IN SECOND CSLL="); int n1; scanf("%d",&n1); int pre1=0; int data1=0; for(int i=0;i<n1;i++){ pre1=data1; printf("ENTER DATA="); scanf("%d",&data1); if(pre1>data1&&i!=0){ head2=NULL; printf("\n!!!!!!!THE LIST MUST BE IN ASCENIDNG ORDER!!!!!!!\n <<<PLEASE RE_ENTER THE LIST>>>\n"); goto start2; } insertion_in_end(data1,&head2); } printf("ELEMENT IN SECOND CSLL="); display(head2); int count1=0; int count2=0; CSL *temp1=head1; CSL *temp2=head2; while(1){ if(temp1->data>temp2->data){ insertion_in_end(temp2->data,&head3); count2++; if(temp2->next==head2){ temp2=temp2->next; break; } temp2=temp2->next; } else { insertion_in_end(temp1->data,&head3); count1++; if(temp1->next==head1){ temp1=temp1->next; break; } temp1=temp1->next; } } while(temp1!=head1||count1==0){ insertion_in_end(temp1->data,&head3); temp1=temp1->next; count1++; } while(temp2!=head2||count2==0){ insertion_in_end(temp2->data,&head3); temp2=temp2->next; count2++; } printf("ELEMENT OF CSLL AFTER MERGING BOTH CSLL="); display(head3); }
C
#include <stdio.h> int isPrimo(int primo); int main(int argc, char **argv) { int numero; printf("Inserisci il numero:\n"); scanf("%d", &numero); if(isPrimo(numero)){ printf("E\' un numero primo.\n"); } else { printf("Non e\' un numero primo.\n"); } return 0; } int isPrimo(int numero){ int flag = 1; for(int i = 2; i < numero; i++){ if(numero % i == 0){ return flag = 0; } } return flag; }
C
#include "../includes/push_swap.h" void first_node(t_frame *frame, t_struct *tmpA, long int num) { frame->stack_a = (t_struct *)malloc(sizeof (t_struct)); tmpA = frame->stack_a; tmpA->num = num; tmpA->next = NULL; tmpA->previous = NULL; } void add_to_stack(t_frame *frame, char stack_name, long int num) { t_struct *tmpA; t_struct *last_elem; frame->stack_len++; if (frame->stack_a == NULL) first_node(frame, tmpA, num); else { tmpA = frame->stack_a; while (tmpA->next != NULL) { last_elem = tmpA; tmpA = tmpA->next; tmpA->previous = last_elem; } tmpA->next = (t_struct *) malloc(sizeof(t_struct)); last_elem = tmpA; tmpA = tmpA->next; tmpA->previous = last_elem; tmpA->num = num; tmpA->next = NULL; frame->tail = tmpA; } }
C
/* * Big thanks for helping me out to: BitPuffin http://bitpuffin.com */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define car(p) ((p).pair->atom[0]) #define cdr(p) ((p).pair->atom[1]) #define nilc(p) ((p).type == AtomType_Nil) char* slurp(const char* path) { FILE* file; char* buf; file = fopen(path, "r"); if (!file) return NULL; fseek(file, 0, SEEK_END); long length = ftell(file); fseek(file, 0, SEEK_SET); buf = malloc(length); if (!buf) return NULL; fread(buf, 1, length, file); fclose(file); return buf; } static char* _strdup(const char* value) { size_t len = strlen(value); char* buffer = malloc(len + 1); strcpy(buffer, value); buffer[len] = '\0'; return buffer; } typedef struct Atom Atom; typedef int (*Builtin) (struct Atom args, struct Atom *result); struct Atom { enum { AtomType_Nil, AtomType_Integer, AtomType_Pair, AtomType_Symbol, AtomType_Builtin, AtomType_Closure, } type; const char* symbol; long integer; Builtin builtin; struct Pair* pair; }; typedef enum { Error_OK = 0, Error_Syntax = 1, Error_Unbound = 3, Error_Args = 4,/* A list exp was shorter or longer than expected */ Error_Type = 5 /* An object in an exp was of different type than expected */ } Error; struct Pair { struct Atom atom[2]; }; static const Atom nil = { AtomType_Nil }; static Atom sym_table = { AtomType_Nil }; /* Allocate a pair on the heap and assign its two elements. */ static Atom cons(Atom car_value, Atom cdr_value) { Atom p; p.type = AtomType_Pair; p.pair = malloc(sizeof(struct Pair)); car(p) = car_value; cdr(p) = cdr_value; return p; } static Atom make_int(long value) { Atom a; a.type = AtomType_Integer; a.integer = value; return a; } static Atom make_symbol(const char* value) { Atom a, p; p = sym_table; /* * Keep track of all symbols created * and return the same created atom * if found. */ while (!nilc(p)) { a = car(p); if (strcmp(a.symbol, value) == 0) return a; p = cdr(p); } /* * If we have not found the symbol * then it means we have a new one * so we must create it and store it. */ a.type = AtomType_Symbol; a.symbol = _strdup(value); sym_table = cons(a, sym_table); return a; } static int listc(Atom expr) { while(!nilc(expr)) { if (expr.type != AtomType_Pair) return 0; expr = cdr(expr); } return 1; } static int make_closure(Atom env, Atom args, Atom body, Atom* result) { /* * (define symbol (lambda (args) (body))) */ Atom p; if (!listc(args) || !listc(body)) return Error_Syntax; /* args must be symbols */ p = args; while(!nilc(p)) { if (car(p).type != AtomType_Symbol) return Error_Type; p = cdr(p); } *result = cons(env, cons(args, body)); result->type = AtomType_Closure; return Error_OK; } /* Read a single object and return error status and a pointer to the reminder of the input. */ static int read_expr(const char* input, const char** end, Atom* result); /* * Returns the start and the end of the next token in a string * eg: (foo bar) -> |(| |foo| |bar| |)| , 4 different tokens */ static int lexer(const char* str, const char** start, const char** end) { const char* ws = " \t\n"; const char* delim = " ()\t\n"; const char* prefix = "()\'"; str += strspn(str, ws); /* * In the example from above str[0] will be: * ( * f * f * b * b * ) */ /* * If it hits the end of a string * without finding a token return a syntax error. */ if (str[0] == '\0') { *start = *end = NULL; return Error_Syntax; } *start = str; /* * Look for () and return what comes after ( or ) */ if (strchr(prefix, str[0]) != NULL) { *end = str + 1; } else { *end = str + strcspn(str, delim); } return Error_OK; } static int parse_simple(const char* start, const char* end, Atom* result) { char *buf, *p; /* Integer? */ long val = strtol(start, &p, 10); if (p == end) { result->type = AtomType_Integer; result->integer = val; return Error_OK; } /* NIL or symbol */ buf = malloc(sizeof(char) * (end - start + 1)); p = buf; while (start != end) { *p++ = toupper(*start); ++start; } *p = '\0'; if (strcmp(buf, "NIL") == 0) *result = nil; else *result = make_symbol(buf); free(buf); return Error_OK; } static int read_list(const char* start, const char** end, Atom* result) { Atom p; *end = start; p = *result = nil; for (;;) { const char* token; Atom item; Error err; err = lexer(*end, &token, end); if (err) return err; if (token[0] == ')') return Error_OK; if (token[0] == '.' && *end - token == 1) { /* Improper list */ if (nilc(p)) return Error_Syntax; err = read_expr(*end, end, &item); if (err) return err; cdr(p) = item; /* Read the closing ')' */ err = lexer(*end, &token, end); if (!err && token[0] != ')') err = Error_Syntax; return err; } err = read_expr(token, end, &item); if (err) return err; if (nilc(p)) { /* First item */ *result = cons(item, nil); p = *result; } else { cdr(p) = cons(item, nil); p = cdr(p); } } return Error_OK; } static int read_expr(const char* input, const char** end, Atom* result) { const char* token; Error err; err = lexer(input, &token, end); if (err) return err; if (token[0] == '(') return read_list(*end, end, result); else if (token[0] == ')') return Error_Syntax; else if (token[0] == '\'') { *result = cons(make_symbol("QUOTE"), cons(nil, nil)); return read_expr(*end, end, &car(cdr(*result))); } else return parse_simple(token, *end, result); } /* * HOW AN ENVIRONMENT WORKS ? * * To associate identifiers with objects we * need an environment. This binds each * identifier with its corresponding value. * eg: * Identifier | Value * FOO | 97 * BAR | NIL * BOR | (X Y Z) * * (parent ( identifier . value ) ... ) */ /* * Create an empty environment with a specific parent (can be NIL) */ static Atom env_create(Atom parent) { return cons(parent, nil); } static int env_get(Atom env, Atom symbol, Atom* result) { Atom parent = car(env); Atom bs = cdr(env); while (!nilc(bs)) { Atom b = car(bs); if (car(b).symbol == symbol.symbol) { *result = cdr(b); return Error_OK; } bs = cdr(bs); } /* * eg: foo , here the indentifier,foo, needs a value! */ if (nilc(parent)) return Error_Unbound; return env_get(parent, symbol, result); } /* * Look if we have @symbol inside @env and if we do * return it. * If @symbol is not found in @env we add the new @symbol + its @value * to the tail of @env */ static int env_set(Atom env, Atom symbol, Atom value) { Atom next = cdr(env); Atom b = nil; /* * First look if we already have * this symbol stored so we can * change its value */ while (!nilc(next)) { b = car(next); if (car(b).symbol == symbol.symbol) { cdr(b) = value; return Error_OK; } next = cdr(next); } b = cons(symbol, value); cdr(env) = cons(b, cdr(env)); return Error_OK; } static Atom copy_list(Atom list) { Atom a, p; if (nilc(list)) return nil; a = cons(car(list), nil); p = a; list = cdr(list); while (!nilc(list)) { cdr(p) = cons(car(list), nil); p = cdr(p); list = cdr(list); } return a; } static int eval_expr(Atom expr, Atom env, Atom* result); /* * Right now it only calls the builtin func with a list of arguments */ static int apply(Atom fn, Atom args, Atom* result) { if (fn.type == AtomType_Builtin) return (*fn.builtin)(args, result); else if (fn.type != AtomType_Closure) return Error_Type; Atom env, arg_names, body; env = env_create(car(fn)); arg_names = car(cdr(fn)); body = cdr(cdr(fn)); //printf("%s %s %s \n", env.symbol, arg_names.symbol, body.symbol); while (!nilc(arg_names)) { if (nilc(args)) return Error_Args; env_set(env, car(arg_names), car(args)); arg_names = cdr(arg_names); args = cdr(args); } if (!nilc(args)) return Error_Args; while (!nilc(body)) { Error err = eval_expr(car(body), env, result); if (err) return err; body = cdr(body); } return Error_OK; } static int eval_expr(Atom expr, Atom env, Atom* result) { Atom op, args; Error err; /* * Eg: * After we have defined a variable like this: * (define foo 1) * when we call foo to get its value * we execute this part of code */ if (expr.type == AtomType_Symbol) { return env_get(env, expr, result); } else if (expr.type != AtomType_Pair) { *result = expr; return Error_OK; } if (!listc(expr)) return Error_Syntax; op = car(expr); args = cdr(expr); if (op.type == AtomType_Symbol) { if ( strcmp(op.symbol, "QUOTE") == 0 ) { /* * eg: * 1) quote - no arguments so fail * 2) quote foo (bar pep)) - too many arguments */ if (nilc(args) || !nilc(cdr(args))) return Error_Args; *result = car(args); return Error_OK; } else if ( strcmp(op.symbol, "DEFINE") == 0 ) { if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args))) ) return Error_Args; Atom sym, val; sym = car(args); /* expecting lambda */ if (sym.type == AtomType_Pair) { err = make_closure(env, cdr(sym), cdr(args), &val); sym = car(sym); if (sym.type != AtomType_Symbol) return Error_Type; } else if (sym.type == AtomType_Symbol) { if (!nilc(cdr(cdr(args)))) return Error_Args; err = eval_expr(car(cdr(args)), env, &val); } else return Error_Type; if (err) return err; *result = sym; return env_set(env, sym, val); } else if ( strcmp(op.symbol, "LAMBDA") == 0 ) { if (nilc(args) || nilc(cdr(args))) return Error_Args; return make_closure(env, car(args), cdr(args), result); } else if (strcmp(op.symbol, "IF") == 0) { /* * (if test true_exp false_exp) */ if (nilc(args) || nilc(cdr(args)) || nilc(cdr(cdr(args))) || !nilc(cdr(cdr(cdr(args))))) return Error_Args; Atom cond, val; err = eval_expr(car(args), env, &cond); if (err) return err; val = nilc(cond) ? car(cdr(cdr(args))) : car(cdr(args)); return eval_expr(val, env, result); } } // SYMBOL Atom p; /* * At this point we assume what's below is a function */ /* * Evaluate operator */ err = eval_expr(op, env, &op); if (err) return err; /* * Evaluate arguments */ args = copy_list(args); p = args; while(!nilc(p)) { err = eval_expr(car(p), env, &car(p)); if (err) return err; p = cdr(p); } return apply(op, args, result); } /* * Functions */ static Atom make_builtin(Builtin fn) { Atom a; a.type = AtomType_Builtin; a.builtin = fn; return a; } static int builtin_car(Atom args, Atom* result) { if (nilc(args) || !nilc(cdr(args))) return Error_Args; if (nilc(car(args))) *result = nil; else if (car(args).type != AtomType_Pair) return Error_Type; else *result = car(car(args)); return Error_OK; } static int builtin_cdr(Atom args, Atom* result) { if (nilc(args) || !nilc(cdr(args))) return Error_Args; //(set foo 42) //(cdr foo) if (nilc(car(args))) *result = nil; else if (car(args).type != AtomType_Pair) return Error_Type; else *result = cdr(car(args)); return Error_OK; } static int builtin_cons(Atom args, Atom* result) { /* * (set foo 1) * (set bar 2) * (cons foo bar) * -> (1 2) */ if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args))) ) return Error_Args; *result = cons(car(args), car(cdr(args))); return Error_OK; } static int builtin_add(Atom args, Atom* result) { //(+ 1 2) if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args)))) return Error_Args; Atom a, b; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Type; *result = make_int(a.integer + b.integer); return Error_OK; } static int builtin_sub(Atom args, Atom* result) { if (nilc(args)) return Error_Args; /* * case 1) (- 6) * case 2) (- 6 3) */ Atom a; a = car(args); // case 1) if (nilc(cdr(args))) { if (a.type != AtomType_Integer) return Error_Type; *result = make_int(-a.integer); return Error_OK; } // case 2) Atom b; b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Type; *result = make_int(a.integer - b.integer); return Error_OK; } static int builtin_div(Atom args, Atom* result) { Atom a, b; if (nilc(args) || nilc(cdr(args))) return Error_Args; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Type; *result = make_int(a.integer / b.integer); return Error_OK; } static int builtin_modulo(Atom args, Atom* result) { Atom a, b; if (nilc(args) || nilc(cdr(args))) return Error_Args; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Type; *result = make_int(a.integer % b.integer); return Error_OK; } static int builtin_mul(Atom args, Atom* result) { Atom a, b; if (nilc(args) || nilc(cdr(args))) return Error_Args; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Type; *result = make_int(a.integer * b.integer); return Error_OK; } static int bultin_eq(Atom args, Atom* result) { /* * (= 1 1) */ if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args)))) return Error_Args; Atom a, b; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Args; *result = (a.integer == b.integer) ? make_symbol("T") : nil; return Error_OK; } static int builtin_less(Atom args, Atom* result) { /* * (< 2 3) */ if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args)))) return Error_Args; Atom a, b; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Args; *result = (a.integer < b.integer) ? make_symbol("T") : nil; return Error_OK; } static int builtin_more(Atom args, Atom* result) { /* * (> 3 6) */ if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args)))) return Error_Args; Atom a, b; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Args; *result = (a.integer > b.integer) ? make_symbol("T") : nil; return Error_OK; } static int builtin_more_eq(Atom args, Atom* result) { /* * (>= 3 6) */ if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args)))) return Error_Args; Atom a, b; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Args; *result = (a.integer >= b.integer) ? make_symbol("T") : nil; return Error_OK; } static int builtin_less_eq(Atom args, Atom* result) { /* * (<= 3 6) */ if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args)))) return Error_Args; Atom a, b; a = car(args); b = car(cdr(args)); if (a.type != AtomType_Integer || b.type != AtomType_Integer) return Error_Args; *result = (a.integer <= b.integer) ? make_symbol("T") : nil; return Error_OK; } static int builtin_eq_obj(Atom args, Atom* result) { /* * https://stackoverflow.com/questions/16299246/what-is-the-difference-between-eq-eqv-equal-and-in-scheme */ if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args)))) return Error_Args; int eq = 0; Atom a, b; a = car(args); b = car(cdr(args)); /* (eq? (cons 1 2) (cons 4 5)) * ((lambda (x) (eq? x x)) (cons 1 2)) */ if (a.type == b.type) { switch(a.type) { case AtomType_Nil: eq = 1; break; case AtomType_Pair: case AtomType_Closure: eq = (a.pair == b.pair); break; case AtomType_Symbol: eq = (a.symbol == b.symbol); break; case AtomType_Integer: eq = (a.integer == b.integer); break; case AtomType_Builtin: eq = (a.builtin == b.builtin ); break; } } *result = (eq == 1) ? make_symbol("T") : nil; return Error_OK; } static int builtin_pair(Atom args, Atom* result) { /* (pair? a b) */ if (nilc(args) || nilc(cdr(args)) || !nilc(cdr(cdr(args)))) return Error_Args; *result = (car(args).type == AtomType_Pair && car(cdr(args)).type == AtomType_Pair) ? make_symbol("T") : nil; return Error_OK; } static void print_expr(Atom atom); static int builtin_print(Atom args, Atom* result) { /* (print atom) */ if (nilc(args) || !nilc(cdr(args))) return Error_Args; Atom a; a = car(args); print_expr(a); return Error_OK; } static void print_expr(Atom atom) { switch (atom.type) { case AtomType_Nil: printf("NIL"); break; case AtomType_Integer: printf("%ld", atom.integer); break; case AtomType_Symbol: printf("%s", atom.symbol); break; case AtomType_Builtin: printf("#<BUILTIN:%p>", atom.builtin); break; case AtomType_Pair: putchar('('); print_expr(car(atom)); atom = cdr(atom); while(!nilc(atom)) { if (atom.type == AtomType_Pair) { putchar(' '); print_expr(car(atom)); atom = cdr(atom); } else { printf(" . "); print_expr(atom); break; } } putchar(')'); break; default: break; } } void load_file(Atom env, const char* path) { char* file; printf("Reading file: %s\n", path); file = slurp(path); if (file) { const char* p = file; Atom expr; while (read_expr(p, &p, &expr) == Error_OK) { Atom result; Error err = eval_expr(expr, env, &result); if (err) { printf("Error in expression: \n"); print_expr(expr); putchar('\n'); } else { print_expr(result); putchar('\n'); } } } else printf("Couldn't open up path: %s \n", path); free(file); } int main(int argc, char* argv[]) { /* * Test unit Atom a; a = make_int(1997); print_expr(a); a = make_symbol("Hello"); print_expr(a); a = cons( make_int(1), cons( make_int(2), cons(make_int(3), nil ))); print_expr(a); */ Atom env; env = env_create(nil); /* Set up init env */ env_set(env, make_symbol("FIRST"), make_builtin(builtin_car)); env_set(env, make_symbol("CAR"), make_builtin(builtin_car)); env_set(env, make_symbol("CDR"), make_builtin(builtin_cdr)); env_set(env, make_symbol("REST"), make_builtin(builtin_cdr)); env_set(env, make_symbol("CONS"), make_builtin(builtin_cons)); env_set(env, make_symbol("+"), make_builtin(builtin_add)); env_set(env, make_symbol("-"), make_builtin(builtin_sub)); env_set(env, make_symbol("*"), make_builtin(builtin_mul)); env_set(env, make_symbol("/"), make_builtin(builtin_div)); env_set(env, make_symbol("MODULO"), make_builtin(builtin_modulo)); env_set(env, make_symbol("T"), make_symbol("T")); env_set(env, make_symbol("="), make_builtin(bultin_eq)); env_set(env, make_symbol("<"), make_builtin(builtin_less)); env_set(env, make_symbol(">"), make_builtin(builtin_more)); env_set(env, make_symbol(">="), make_builtin(builtin_more_eq)); env_set(env, make_symbol("<="), make_builtin(builtin_less_eq)); env_set(env, make_symbol("EQ?"), make_builtin(builtin_eq_obj)); env_set(env, make_symbol("PAIR?"), make_builtin(builtin_pair)); env_set(env, make_symbol("PRINT"), make_builtin(builtin_print)); load_file(env, "libdeea.deea"); char buffer[1024]; while (fgets(buffer, 1024, stdin) != NULL) { Error err; Atom expr, result; const char* p = buffer; err = read_expr(p, &p, &expr); if (!err) err = eval_expr(expr, env, &result); switch(err) { case Error_OK: print_expr(result); putchar('\n'); break; case Error_Syntax: puts("Syntax error!"); break; case Error_Unbound: puts("Symbol not bound!"); break; case Error_Args: puts("Wrong number of arguments!"); break; case Error_Type: puts("Wrong type!"); break; } } return EXIT_SUCCESS; }
C
#include "cachelab.h" #include "getopt.h" #include "stdlib.h" #include "stdio.h" #include "string.h" #include "assert.h" #include "unistd.h" // Wei Chen, [email protected] /****************************************************** * Types ******************************************************/ typedef struct cache_line cache_line; typedef struct cache_set cache_set; typedef struct cache cache; typedef unsigned long long addr_t; // support 64 bit address /* a cache line */ struct cache_line { int valid; addr_t tag; int age; // the time from its last access }; /* a cache set */ struct cache_set { int lsize; cache_line *lines; }; /* cache */ struct cache { int ssize; cache_set *sets; }; int setw = -1, blockw = -1, associw = -1; int verbose = 0, debug = 0; int miss_count = 0, eviction_count = 0, hit_count = 0; int LRU(cache_set *set); /****************************************************** * Helpers ******************************************************/ void csim_verbose(char *msg) { if (verbose) printf("%s", msg); } /* parse cache set index */ int get_setindex(addr_t addr) { addr_t t = 0; return (~(~t << setw)) & (addr >> blockw); } /* parse cache line tag */ addr_t get_tag(addr_t addr) { addr_t t = 1; addr_t mask = (t << (setw + blockw)) - 1; return addr & ~mask; } /* parse memory address from text line */ addr_t parse_addr(char *line) { char *c; addr_t a; while (line != NULL && *line == ' ') { line++; } line += 2; a = strtoull(line, &c, 16); return a; } /* get line from text file */ int csim_getline(char **lineptr, size_t *n, FILE *fs) { char tmp[256]; int c, l = 0; do { c = fgetc(fs); tmp[l] = c; l++; } while(c != '\n' && c != EOF); if (c == EOF) { return -1; } else { (*lineptr) = (char*)malloc(l); strncpy(*lineptr, tmp, l-1); *n = l; return 0; } } /* find matched cache line of an address */ int find_match(cache_set *s, addr_t addr) { addr_t tag = get_tag(addr); int i, r = -1; cache_line *cur = s->lines; for (i = 0; i < s->lsize; ++i, ++cur) { if (cur->valid && cur->tag == tag) { r = i; break; } } return r; } /* return the index of the cache line, if not found, return -1 */ int find_empty(cache_set *s) { int i, r = -1; cache_line *cur = s->lines; for (i = 0; i < s->lsize; ++i, ++cur) { if (!cur->valid) { r = i; break; } } return r; } /****************************************************** * Cache operation ******************************************************/ /* save_cacheline block data into the cache line */ void save_cacheline(cache_line *l, addr_t addr) { l->valid = 1; l->age = 0; l->tag = get_tag(addr); } /* return the cache line index that matches */ int index_in_cache(cache *c, addr_t addr) { int si = get_setindex(addr); cache_set *set = (c->sets) + si; int li = find_match(set, addr); return li; } /* check whether the cache contains a block */ int is_in_cache(cache *c, addr_t addr) { int li = index_in_cache(c, addr); return li >= 0; } /* called when cache hit, since our solution don't actually need the data, we * return void */ void fetch_from_cache(cache *c, addr_t addr, int li) { // update age field in every cache line int si = get_setindex(addr); cache_set *s = (c->sets) + si; cache_line *cur = s->lines; int i; for (i = 0; i < s->lsize; ++i, ++cur) { if (i == li) { cur->age = 0; } else { cur->age += 1; } } // return nothing. } /* called when cache misses, load a block into the cache */ void load(cache *c, addr_t addr) { // load from lower cache, pass here int si = get_setindex(addr); cache_set *s = (c->sets) + si; int ei = find_empty(s); if (ei != -1) { // we have empty line here cache_line *l = (s->lines) + ei; save_cacheline(l, addr); } else { // the cache set is filled, so we have to evict a line int ri = LRU(s); cache_line *replace = (s->lines) + ri; eviction_count++; csim_verbose("eviction "); save_cacheline(replace, addr); } } /* determine which cache line to evict *, return the index of the line */ int LRU(cache_set *set) { int oldest = -1; int i, result = -1; cache_line *cur = set->lines; for (i = 0; i < set->lsize; ++i, ++cur) { if (cur->age > oldest) { oldest = cur->age; result = i; } } assert(result >= 0); return result; } void init(cache **cp) { int i; cache_set *si = NULL; *cp = (cache*)malloc(sizeof(cache)); (*cp)->ssize = 1 << setw; (*cp)->sets = (cache_set*)malloc(((*cp)->ssize) * sizeof(cache_set)); si = (*cp)->sets; for (i = 0; i < (*cp)->ssize; ++i, ++si) { si->lsize = associw; si->lines = (cache_line*)malloc(associw * sizeof(cache_line)); int j; for (j = 0; j < si->lsize; ++j) { (si->lines + j)->valid = 0; } } } void clean(cache *cp) { int i; cache_set *curs = cp->sets; for (i = 0; i < cp->ssize; ++i, ++curs) { free(curs->lines); } free(cp->sets); free(cp); } /****************************************************** * Memory operation ******************************************************/ void load_action(cache *, addr_t); void store_action(cache *, addr_t); void modify_action(cache *, addr_t); void load_action(cache *c, addr_t addr) { int is_hit = is_in_cache(c, addr); if (is_hit) { hit_count++; csim_verbose("hit "); } else { miss_count++; csim_verbose("miss "); load(c, addr); } // it should return the data, while we don't need it now. // but it update the age field of very cache line int li = index_in_cache(c, addr); fetch_from_cache(c, addr, li); } void store_action(cache *c, addr_t addr) { int is_hit = is_in_cache(c, addr); if (is_hit) { hit_count++; csim_verbose("hit "); } else { miss_count++; csim_verbose("miss "); load(c, addr); } int li = index_in_cache(c, addr); fetch_from_cache(c, addr, li); } void modify_action(cache *c, addr_t addr) { load_action(c, addr); store_action(c, addr); } /* action dispatcher, main will call it every time it wants to execute an action */ void process(cache *c, addr_t addr, char action) { switch (action) { case ' ': // instruction load, ignored break; case 'M': modify_action(c, addr); break; case 'L': load_action(c, addr); break; case 'S': store_action(c, addr); break; } } int main(int argc, char *argv[]) { int opt, l; char *tfile = NULL, *line = NULL; size_t len = 0, read; FILE *fp = NULL; cache *c; /* process option */ while ((opt = getopt(argc, argv, "hvds:E:b:t:")) != -1) { switch (opt) { case 's': setw = atoi(optarg); break; case 'b': blockw = atoi(optarg); break; case 'E': associw = atoi(optarg); break; case 't': l = strlen(optarg); tfile = (char*)malloc(l + 1); strcpy(tfile, optarg); break; case 'v': verbose = 1; break; case 'd': debug = 1; break; case 'h': fprintf(stderr, "Usage: %s [-hv] -s <s> -E <E> -b <b> -t <tracefile>\n", argv[0]); exit(0); default: /* '?' */ fprintf(stderr, "Usage: %s [-hv] -s <s> -E <E> -b <b> -t <tracefile>\n", argv[0]); exit(EXIT_FAILURE); } } /* read file */ fp = fopen(tfile, "r"); if (fp == NULL) { fprintf(stderr, "File (%s) open failed\n", tfile); exit(EXIT_FAILURE); } /* initilize cache */ init(&c); /* process each line */ while ((read = csim_getline(&line, &len, fp)) != -1) { addr_t addr; addr = parse_addr(line); char l[255]; if (line[1] != ' ') { strncpy(l, line + 1, len - 1); if (verbose) { printf("%s ", l); } process(c, addr, line[1]); csim_verbose("\n"); } } if (setw < 0 || associw < 0 || blockw < 0 || tfile == NULL) { fprintf(stderr, "Missing some required options!!\n"); exit(EXIT_FAILURE); } printSummary(hit_count, miss_count, eviction_count); free(tfile); fclose(fp); clean(c); return 0; }