language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/************************************************************************* > File Name: 01test.c > Author: scc_embedclub > Mail: [email protected] > Created Time: 2015年08月10日 星期一 11时03分36秒 > Version: 1.0 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<sys/types.h> #include<fcntl.h> int main(void) { int i; for (i = 0; i <= 60; i++) { printf("\b\b\b%2d ", i); sleep(1); } }
C
#include "common/test.h" #include "platform/gl.h" #include "common/gl.h" #include "common/scene_setup.h" #include <stdlib.h> typedef struct { ShaderPair shads; SceneFramebuffer fb; Geometry geo; SceneAttribLocs sceneAttribLocs; SceneUniformLocs sceneUniformLocs; GLuint tex; } Private; static TestError setup(TestData* data) { Private* priv = malloc(sizeof(Private)); if (!priv) return OUT_OF_MEMORY; data->priv = priv; TestError err = SUCCESS; err = SetupDepthAndColorFbo(&priv->fb); if (err != SUCCESS) { return err; } err = CompileSceneShaders(&priv->shads); if (err != SUCCESS) return err; err = GetSceneUniformAndAttribLocs(priv->shads.prg, &priv->sceneAttribLocs, &priv->sceneUniformLocs); if (err != SUCCESS) return err; err = GenAndBindBuffers(&priv->geo); if (err != SUCCESS) return err; priv->geo.indexCnt = (SCENE_VERTEX_HEIGHT-1)*(SCENE_VERTEX_WIDTH-1)*6; err = bufferDataSceneVertexGrid(SCENE_VERTEX_WIDTH, SCENE_VERTEX_HEIGHT); if (err != SUCCESS) return err; err = CreateTexture(&priv->tex); if (err != SUCCESS) return err; glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDepthFunc(GL_LEQUAL); glClearColor(1.0f, 0.0f, 0.5f, 1.0f); glViewport(0, 0, WIDTH, HEIGHT); return SUCCESS; } static void DrawFrame(Private* priv) { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); BindSceneShader(priv->shads.prg, priv->tex, &priv->sceneAttribLocs, &priv->sceneUniformLocs); DrawGeo(&priv->geo); glFlush(); } static TestError warmup(const TestData* data) { Private* priv = (Private*) data->priv; for (int i = 0; i < WARMUP_ITERS; i++) { DrawFrame(priv); } glFinish(); return SUCCESS; } static TestError run(TestData* data) { Private* priv = (Private*) data->priv; for (int i = 0; i < TEST_ITERS; i++) { DrawFrame(priv); glFinish(); } return SUCCESS; } static TestError report(const TestData* data, TestReport* out) { out->unit = PIXELS; out->count = WIDTH*HEIGHT*TEST_ITERS; return SUCCESS; } static TestError teardown(TestData* data) { if (!data) return NULL_POINTER; Private* priv = data->priv; if (!priv) return NULL_POINTER; DeleteSceneFramebuffer(&priv->fb); DeleteGeometry(&priv->geo); DeleteShaderPair(&priv->shads); glDeleteTextures(1, &priv->tex); free(priv); data->priv = NULL; return SUCCESS; } const TestCase vertex_lighting = { .name = "vertex_lighting", .setup = setup, .warmup = warmup, .run = run, .report = report, .teardown = teardown, };
C
/* ----------------------------------------------------------------------- *Test great_hall card * * cardtest4: cardtest4.c dominion.o rngs.o * gcc -o cardtest4 -g cardtest4.c dominion.o rngs.o $(CFLAGS) * ----------------------------------------------------------------------- */ #include "dominion.h" #include "dominion_helpers.h" #include <string.h> #include <stdio.h> #include <assert.h> #include "rngs.h" int main() { int seed = 1000; int numPlayer = 2; int finalActions; struct gameState state; int *bonus = 0; int card_set_1[10] = {adventurer, council_room, feast, gardens, mine , remodel, smithy, village, baron, great_hall}; initializeGame(numPlayer, card_set_1, seed, &state); finalActions = state.numActions + 1; printf("Now testing great_hall\n"); //Sole card in hand will be great_hall state.hand[0][0] = great_hall; state.handCount[0] = 1; cardEffect(great_hall, 0, 0, 0, &state, 0, bonus); if (state.handCount[0] != 1) { printf("TEST FAILED: Handcount incorrect!\n"); } //Check number of actions if (finalActions != state.numActions) { printf("TEST FAILED: Wrong number of actions!\n"); } //Check for victory point if (scoreFor(0, &state) != 1) { printf("score was %d\n", scoreFor(0, &state)); printf("TEST FAILED: Should provide one victory point!\n"); //Catches bug - scoreFor fails to check playedCards } printf("Testing great_hall complete!\n\n"); return 0; }
C
#include <omp.h> #include <stdio.h> #include <stdlib.h> #define NUM_STEPS 1000 #define NUM_OPS 50 int main() { int num = 0; #pragma omp parallel for num_threads(4) for (int i = 0; i < NUM_STEPS; i++) { for (int j = 0; j < NUM_OPS; j++) { #pragma omp atomic num++; } for (int j = 0; j < NUM_OPS; j++) { #pragma omp atomic num--; } } printf("num = %d\n", num); }
C
#include "../include/msg.h" #include <stdio.h> uint8_t calc_parity_bit(client_msg_t msg) { uint8_t counter = 0; msg &= ~PARITY_BIT; while (msg) { counter += msg % 2; msg >>= 1; } return counter % 2; } uint8_t get_parity_bit(client_msg_t msg) { debug_print("Get parity bit of %04x\n", msg); return (uint8_t)msg >> PARITY_POS; } bool check_parity(client_msg_t msg) { return calc_parity_bit(msg) == get_parity_bit(msg); } client_msg_t set_parity_bit(client_msg_t msg, client_msg_t parity_bit) { parity_bit <<= PARITY_POS; msg &= ~parity_bit; msg |= parity_bit; return msg; } coordinate_t get_coordinates(client_msg_t msg) { coordinate_t c; c.col = (uint8_t)((msg >> X_COORDINATE_OFFSET) & COORDINATE_BITS); c.row = (uint8_t)(msg & COORDINATE_BITS); return c; } status_t get_status(server_msg_t msg) { return (status_t)(msg & 0xc); } hit_report_t get_hit_report(server_msg_t msg) { return (hit_report_t)(msg & (server_msg_t)3); }
C
#include<stdio.h> #include<string.h> int main(void) { int str[100] = {0}; int i,j,k,n,max,min; int num; scanf("%d", &num); for(n=0;n < num;n++) scanf("%d",&str[n]); j = k = 0; max = str[0]; min = str[0]; for(i=0;i < num;i++) if(str[i] < min) { min = str[i]; j=i; } else if(str[i] > max) { max = str[i]; k=i; } printf("%d %d\n",max,k); printf("%d %d\n",min,j); return 0; }
C
#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* next; }; void push(struct node **head,int data) { struct node *ptr1 = (struct node*)malloc(sizeof(struct node)); struct node *temp = *head; ptr1->data = data; ptr1->next = *head; if(*head != NULL) { while(temp->next != *head) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; *head = ptr1; } void deletenode(struct node **head, int key) { struct node* temp = *head, *prev; if (temp != NULL && temp->data == key) { prev = *head; while(prev->next != *head) prev = prev->next; *head = temp->next; prev->next = temp->next; free(temp); return; } while (temp != *head && temp->data != key) { prev = temp; temp = temp->next; } if (temp == *head) return; prev->next = temp->next; free(temp); } void reverselist(struct node **head_ref) { struct node *prev = NULL; struct node *current = *head_ref; struct node *next = NULL; if(*head_ref == NULL) { printf("list is empty\n"); return ; } while( next != *head_ref) { next = current->next; current->next = prev; prev = current ; current = next; } next->next = prev; *head_ref = prev; } void print(struct node *head) { struct node *temp = head; if( head == NULL) { printf("list is empty\n"); } if (head != NULL) { do { printf("%d \n", temp->data); temp = temp->next; } while (temp != head); } } int countnode(struct node *head) { struct node *temp = head; int count = 0; while(temp->next != head) count++; count++; return count; } int main() { struct node* head = NULL; printf("enter your choice\n"); printf("1 : push\n"); printf("2 : delete\n"); printf("3 : reverse the list\n"); printf("4 : count the number node in the list\n"); printf("5 : print the list\n"); printf("6 : exit\n"); int n ; scanf("%d",&n); printf("\n\n"); while( n != 6) { if(n == 1) { printf("enter the number : "); int t; scanf("%d",&t); push(&head,t); } if(n == 2) { printf("enter the number : "); int t; scanf("%d",&t); deletenode(&head,t); } if(n==3) { reverselist(&head); } if(n == 4) { printf("number node in the list is : %d\n",countnode(head)); } if(n == 5) { print(head); } printf("\n\n"); printf("1 : push\n"); printf("2 : delete\n"); printf("3 : reverse the list\n"); printf("4 : count the number of node in list\n"); printf("5 : print the list\n"); printf("6 : exit\n"); scanf("%d",&n); } return 0; }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #define MAXLINE 256 int main(){ int n; int fd[2]; pid_t pid; char line[MAXLINE]; if(pipe(fd)<0) printf("pipe error\n"); if((pid=fork())<0) printf("fork error\n"); else if(pid>0){ //parent pid close(fd[0]); write(fd[1],"hello world\n",12); }else{ //children pid close(fd[1]); n = read(fd[0],line,MAXLINE); write(STDOUT_FILENO,line,n); } exit(0); }
C
#include<stdio.h> #include<stdlib.h> int cmp(const void*a,const void *b) { return *(int*)a-*(int*)b; } int main() { int n,*arr,i,temp,counter; scanf("%d",&n); arr=(int*)malloc(sizeof(int)*n); for(i=0;i<n;i++) scanf("%d",&arr[i]); qsort(arr,n,sizeof(int),cmp); counter=0; for(i=0;i<n;) { counter++; temp=arr[i]; i++; while(arr[i]<=temp+4) i++; } printf("%d\n",counter); free(arr); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <time.h> #include <pthread.h> #include "sem.h" int num_children = 1; int iterations = 3; pid_t pids[1000]; int i,j; int n = 10; int pid; int count = 0; char phil_args1[5]; char phil_args2[5]; int main(int argc, char *argv[]){ int fd_state,fd_count; struct stat mystat; char *map_state; semaphore_t *semap_mutex; semaphore_t *semap[atoi(argv[1])]; int pid_parent = getpid(); int processes = atoi(argv[1]); char string[] = "./semaphore"; char filename[50]; printf("pid ==== %d\n", getpid() ); system("rm -rf sema* state.txt"); //Creating a state file fd_state = open("state.txt", O_RDWR | O_CREAT | O_EXCL, 0666); if (fd_state == -1){ perror("Open error in state file"); exit(1); } char temp[processes]; int i; for( i = 0; i < processes; i++){ temp[i] = 'T'; } write(fd_state, temp, processes); if (fstat(fd_state,&mystat) < 0){ perror("fstat"); close(fd_state); exit(1); } map_state = mmap(0,mystat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd_state, 0); if (map_state == MAP_FAILED){ perror("mmap"); close(fd_state); exit(1); } //Create initial state as thinking for( i = 0 ; i < processes ; i++){ map_state[i] = 'T'; } semap_mutex = semaphore_create(string,1,99); for(i=0 ; i < processes; i++){ sprintf(filename,"%s%d",string,i); semap[i] = semaphore_create(filename,0,i + 1); } //Creating the processes(philosophers) for (i = 0; i < processes; ++i) { sprintf(phil_args1,"%d",atoi(argv[2])); sprintf(phil_args2,"%d",i); if ((pids[i] = fork()) < 0) { perror("fork"); abort(); }else if (pids[i] == 0) { printf("PROCESS NO ====== %d CREATED \n", i + 1 ); sleep(1); if(execlp("./phil","philosopher",&phil_args1,&phil_args2,argv[1],NULL) == -1){ printf("Error\n"); exit(1); } } count++; } //Wait for all child processes to end if (getpid() == pid_parent){ for (i = 0; i < processes; ++i) { waitpid(-1, NULL, 0); } munmap((void *) map_state, sizeof(map_state)); close (fd_state); printf("\n\n--------------------------------DINNER COMPLETE------------------------------\n\n\n"); exit(0); } }
C
// CBSD Project, 2018 // [email protected] #include <stdio.h> #include "output.h" #include <unistd.h> #include <string.h> #include <stdlib.h> #include <syslog.h> #include <sys/time.h> #include "var.h" #include "input.h" #include "logger.h" /* Low level logging. To use only for very big messages, otherwise * serverLog() is to prefer. */ void serverLogRaw(int level, const char *msg) { const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING }; const char *c = ".-*#"; FILE *fp; char buf[64]; int rawmode = (level & LL_RAW); level &= 0xff; /* clear flags */ if (level < verbosity) return; if ((cbsd_logfile!=NULL)&&(strlen(cbsd_logfile)>1)) { fp = fopen(cbsd_logfile,"a"); if (!fp) return; if (rawmode) { fprintf(fp,"%s",msg); } else { int off; struct timeval tv; //pid_t pid = getpid(); gettimeofday(&tv,NULL); off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec)); snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000); fprintf(fp,"%d:%s %c %s\n", (int)getpid(), buf,c[level],msg); } fflush(fp); fclose(fp); } if (syslog_enabled) { syslog(syslogLevelMap[level], "%s", msg); } } int init_logvars() { char *cbsd_syslog_enabled = NULL; char *cbsd_syslog_verbosity = NULL; cbsd_syslog_enabled=lookupvar("CBSD_SYSLOG_ENABLED"); cbsd_syslog_verbosity=lookupvar("CBSD_SYSLOG_VERBOSITY"); if (cbsd_syslog_enabled) { syslog_enabled=atoi(cbsd_syslog_enabled); } if (cbsd_syslog_verbosity) { if (!strcmp("DEBUG",cbsd_syslog_verbosity)) verbosity=LL_DEBUG; else if(!strcmp("VERBOSE",cbsd_syslog_verbosity)) verbosity=LL_VERBOSE; else if(!strcmp("NOTICE",cbsd_syslog_verbosity)) verbosity=LL_NOTICE; else if(!strcmp("WARNING",cbsd_syslog_verbosity)) verbosity=LL_WARNING; else { out1fmt("Unknown verbosity: %s. Should be: [DEBUG|VERBOSE|NOTICE|WARNING]\n",cbsd_syslog_verbosity); return 1; } } cbsd_logfile=lookupvar("CBSD_LOGFILE"); if ((!syslog_enabled)&&(strlen(cbsd_logfile)<2)) return 1; return 0; } /* Like serverLogRaw() but with printf-alike support. This is the function that * is used across the code. The raw version is only used in order to dump * the INFO output on crash. */ int cbsdloggercmd(int argc, char **argv) { int level=0; char msg[LOG_MAX_LEN]; int i; int res = 0; i = init_logvars(); if (i!=0) return 1; if (argc<3) { out1fmt("cbsdlogger [DEBUG|VERBOSE|NOTICE|WARNING] msg\n"); return 1; } if (!strcmp("DEBUG",argv[1])) level=LL_DEBUG; else if(!strcmp("VERBOSE",argv[1])) level=LL_VERBOSE; else if(!strcmp("NOTICE",argv[1])) level=LL_NOTICE; else if(!strcmp("WARNING",argv[1])) level=LL_WARNING; else { out1fmt("cbsdlogger [DEBUG|VERBOSE|NOTICE|WARNING] msg\n"); return 1; } if ((level&0xff) < verbosity) return 0; for (i = 2; i < argc; i++) res += strlen(argv[i]) + 1; if (res) { memset(msg,0,sizeof(msg)); for (i = 2; i < argc; i++) { strcat(msg, argv[i]); strcat(msg," "); } } serverLogRaw(level,msg); return 0; } void cbsdlog(int level, const char *fmt, ...) { va_list ap; char msg[LOG_MAX_LEN]; int i; i = init_logvars(); if(i!=0) return; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); serverLogRaw(level,msg); }
C
/* ** xclose.c for my_xclose in /home/mille_j//42sh/src/tools ** ** Made by john mille ** Login <[email protected]> ** ** Started on Sat Dec 18 20:39:39 2010 john mille ** Last update Sat Dec 18 20:47:41 2010 john mille */ #include <stdlib.h> #include <unistd.h> int my_xclose(const int fd) { int xclose; xclose = close(fd); if (xclose == -1) return (EXIT_SUCCESS); return (EXIT_SUCCESS); }
C
/* : ڽ ¶ ̵ ״ ϴ α׷ ۼϽÿ. */ #include <stdio.h> int main() { printf("3\n"); printf("ironhak1106\n"); return 0; }
C
#include<stdio.h> int main() { char c; int lowercasevowel, uppercasevowel; printf("enter a alphabet"); scanf("%c",&c); lowercasevowel=(c == 'a'|| c == 'e'|| c == 'i'|| c == 'o' || c == 'u'); uppercasevowel=(c == 'A'|| c == 'E' || c == 'I'|| c == 'O'|| c == 'U'); if(lowercasevowel||uppercasevowel) { printf("vowel:%c",c); } else{ printf("consonate: %c",c); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct celula{ char *dado; struct celula *prox; }celula; typedef struct fila{ int tam; celula *head; celula *tail; }fila; celula *criaCelula(){ celula *l = malloc(sizeof(celula)); l->dado = malloc(26 * sizeof(char)); l->prox = NULL; return l; } fila *criaFila(){ fila *f = malloc(sizeof(fila)); f->head = NULL; f->tail = NULL; f->tam = 0; return f; } void enfileira(fila *f, celula *l){ if(l){ if(f->tam == 0){ f->head = l; f->tail = l; } else{ f->tail->prox = l; f->tail = l; } f->tam++; } } void organizaLista(fila *f){ for(celula *p=f->head; p->prox!=NULL; p=p->prox) if(p->prox->dado[0] == p->dado[strlen(p->dado)-1]-32){ celula *aux = p->prox; p->prox = aux->prox; aux->prox = NULL; enfileira(f,aux); f->tam--; } } void imprimeList(fila *f){ for(celula *p=f->head; p!=NULL; p=p->prox) printf("%s\n",p->dado); } int main(){ fila *fila = criaFila(); celula *l; char city[26]; int aux; do { l = criaCelula(); aux = scanf("%s",l->dado); if(aux==EOF) break; else enfileira(fila,l); } while(aux != EOF); organizaLista(fila); imprimeList(fila); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <sys/time.h> #define MAX 8 double A[MAX][MAX]= {1,2,3,2,5,2,3,1, 5,9,3,4,5,6,7,4, 4,4,7,7,8,4,3,1, 1,2,4,5,7,8,9,2, 1,2,3,8,9,7,1,2, 1,2,1,2,4,3,3,8, 8,3,6,4,5,8,6,3, 1,2,3,1,2,9,8,4 }; double b[MAX]={2,4,6,8,10,14,18,20}; void PLU(void); void LU(void); int main() { struct timeval plu_begin,plu_end,lu_begin,lu_end; gettimeofday(&lu_begin, NULL); LU(); gettimeofday(&lu_end, NULL); printf("LU分解耗时:%lld 毫秒",(long long)lu_end.tv_usec-lu_begin.tv_usec); gettimeofday(&plu_begin, NULL); PLU(); gettimeofday(&plu_end, NULL); printf("PLU分解耗时:%lld 毫秒",(long long)plu_end.tv_usec-plu_begin.tv_usec); return 0; } void PLU() { double u[MAX][MAX] = { 0 }; double l[MAX]={0}; double X[MAX]; int i,j,k,column; double max,A_temp,b_temp,mik,sum; for (i = 0; i<MAX; i++) { for (j=0; j<MAX; j++) { u[j][i] = A[j][i]; } } for (i = 0; i<MAX; i++) { l[i]=b[i]; } for(k=0; k<MAX-1; k++) { column=k; max=0; for(i=k; i<MAX; i++) { if(fabs(u[i][k])>max) { max=fabs(u[i][k]); column=i; } } for(j=k; j<MAX; j++) { A_temp = u[k][j]; u[k][j] = u[column][j]; u[column][j] = A_temp; } b_temp = l[k]; l[k] = l[column]; l[column] = b_temp; for(i=k+1; i<MAX; i++)//消元过程 { mik = u[i][k]/u[k][k]; for(j=k; j<MAX; j++) u[i][j]-=mik*u[k][j]; l[i]-= mik*l[k]; } } X[MAX-1]=l[MAX-1]/u[MAX-1][MAX-1]; for(i=MAX-2; i>=0; i--) { sum = 0; for(j=i+1; j<MAX; j++) sum+=u[i][j]*X[j]; X[i]=(l[i]-sum)/u[i][i]; } printf("PLU分解结果X:\n"); for(i=0; i<MAX; i++) { printf("x[%d]:%lf\n",i,X[i]); } return; } void LU() { double l[MAX][MAX] = { 0 }; double u[MAX][MAX] = { 0 }; int i, r, k; for (i = 0; i<MAX; i++) { u[0][i] = A[0][i]; } for (i = 1; i<MAX; i++) { l[i][0] = A[i][0] / u[0][0]; } for (r = 1; r<MAX; r++) { for (i = r; i <MAX; i++) { double sum1 = 0; for (k = 0; k < r; k++) { sum1 += l[r][k] * u[k][i]; //cout << "" << r << "" << sum1 << endl; } u[r][i] = A[r][i] - sum1; } if(r!=MAX) for(i=r+1;i<MAX;i++) { double sum2 = 0; for (k = 0; k<r; k++) { sum2 += l[i][k] * u[k][r]; } l[i][r] = (A[i][r] - sum2) / u[r][r]; } } double y[MAX] = { 0 }; y[0] = b[0]; for (i = 1; i<MAX; i++) { double sum3 = 0; for (k = 0; k<i; k++) sum3 += l[i][k] * y[k]; y[i] = b[i] - sum3; } double x[MAX] = { 0 }; x[MAX - 1] = y[MAX - 1] / u[MAX - 1][MAX - 1]; for (i = MAX - 2; i >= 0; i--) { double sum4 = 0; for (k = i + 1; k<MAX; k++) sum4 += u[i][k] * x[k]; x[i] = (y[i] - sum4) / u[i][i]; } printf("LU分解结果X:\n"); for (i = 0; i<MAX; i++) { printf("x[%d]:%lf\n",i,x[i]); } return; }
C
#include <OS.h> #include "timer.h" #define UCLOCKS_PER_SEC 1000000 static long long cpu_speed = 0; static inline long long read_rdtsc(void) { long long result; asm volatile("rdtsc" :"=A" (result)); return(result); } static long long get_cpu_speed() // based on mame { long long a, b, start, end; a = system_time(); do { b = system_time(); } while (a == b); start = read_rdtsc(); do { a = system_time(); } while (a - b < UCLOCKS_PER_SEC/4); end = read_rdtsc(); return (end - start) * 4; } unsigned long gettime() { return system_time() / 1000; } void init_timer() { cpu_speed = get_cpu_speed(); } void GetPerformanceFrequency(long long *freq) { *freq = cpu_speed; } void GetPerformanceCounter(long long *now) { *now = read_rdtsc(); }
C
#include "lists.h" /** * check_cycle - checks if a linked list has a loop * @list: the linked list to check * Return: 0 - the linked list has no loop. * 1 - the linked list has a loop. */ int check_cycle(listint_t *list) { listint_t *snail, *cheetah; snail = cheetah = list; while (snail && cheetah && cheetah->next ) { snail = snail->next; cheetah = cheetah->next->next; if (snail == cheetah) return (1); } return (0); }
C
#include <stdio.h> int ft_str_is_uppercase(char *str) { int i; i = 0; while (str[i] != '\0') { if (((str[i] < 'A') || (str[i] > 'Z'))) { return (0); } i++; } return(1); } /*int main(void) { char *str; char number; str = "za"; number = ft_str_is_uppercase(str); printf("%d", number); }*/
C
/*---------------------------------------------------------------- * * Programacion avanzada: Funciones Estandar de E/S * Fecha: 22-Feb-2019 * Autor: A01700820 Carlos Roman Rivera * *--------------------------------------------------------------*/ #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <time.h> #include <pwd.h> #include <grp.h> #include <sys/stat.h> #include <dirent.h> #include <string.h> #include <float.h> #define PATH_MAX 4096 #define NAME_MAX 255 void normalize(char *origin, char *destination, char* program) { // File manipulation. FILE* file_read; FILE* file_write; // Auxiliary variables for normalization. int aux, total, i; float num, max, min, x; // Open origin directory, otherwise throw error. file_read = fopen(origin, "r"); if (!file_read) { perror(program); exit(-1); } // Open destination directory, otherwise throw error. file_write = fopen(destination, "w"); if (!file_read) { perror(program); exit(-1); } // Iterate through each line of the file. Discard first two elements. while (fscanf(file_read, "%i,%i", &aux, &total) > 0) { fprintf(file_write, "%i,%i", aux, total); // Set auxiliary variables to initial values. total = total * total; max = FLT_MIN; min = FLT_MAX; float arr[total + 1]; // Iterate through input file to get min and max values. for (i = 0; i < total; i++) { fscanf(file_read, ",%f", &num); arr[i] = num; if(num < min){ min = num; } else if (num > max) { max = num; } } // Update values. for (i = 0; i < total; i++) { x = (arr[i] - min) / (max - min); fprintf(file_write, ",%.4f", x); } // Reset variables and insert newline to output file. total = 0; fprintf(file_write, "\n"); } fclose(file_read); fclose(file_write); } void list(char *origin, char *destination, char* program) { // Directory manipulation. DIR* dir; DIR* dir2; struct dirent* direntry; // File names and paths. char file_read[PATH_MAX + NAME_MAX + 1]; char file_write[PATH_MAX + NAME_MAX + 1]; if ( (dir = opendir(origin)) == NULL ) { perror(program); exit(-1); } if ( (dir2 = opendir(destination)) == NULL ) { perror(program); exit(-1); } // Iterate through the given directory. while ( (direntry = readdir(dir)) != NULL ) { if (strcmp(direntry->d_name, ".") != 0 && strcmp(direntry->d_name, "..") != 0) { // Get absolute path for input and output files. sprintf(file_read, "%s/%s", origin, direntry->d_name); sprintf(file_write, "%s/%s", destination, direntry->d_name); // Normalize data from input file and write in output file. normalize(file_read, file_write, program); } } printf("Done.\n"); } int main(int argc, char* argv[]) { // Directory manipulation. char dir_name[NAME_MAX + 1]; char origin[PATH_MAX + NAME_MAX + 1]; char destination[PATH_MAX + NAME_MAX + 1]; // Check correct usage. if (argc != 3) { fprintf(stderr, "usage: %s input_directory output_directory\n", argv[0]); return -1; } getcwd(dir_name, NAME_MAX); // Build absolute path for origin and destination directories. sprintf(origin, "%s/%s", dir_name, argv[1]); sprintf(destination, "%s/%s", dir_name, argv[2]); // Iterate through the origin directory. list(origin, destination, argv[0]); return 0; }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* export.c :+: :+: */ /* +:+ */ /* By: JKCTech <[email protected]> +#+ */ /* +#+ */ /* Created: 2020/11/30 11:51:43 by JKCTech #+# #+# */ /* Updated: 2020/12/01 12:33:14 by JKCTech ######## odam.nl */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <libft.h> #include "environment.h" static void swap(char **arg1, char **arg2) { char *tmp; tmp = *arg1; *arg1 = *arg2; *arg2 = tmp; } static void sort(char *args[], size_t len) { size_t i; size_t pvt; if (len <= 1) return ; pvt = 0; swap(args + 1, args + len - 1); i = 0; while (i < len - 1) { if (ft_strcmp(args[i], args[len - 1]) < 0) { swap(args + i, args + pvt); pvt++; } i++; } swap(args + pvt, args + len - 1); sort(args, pvt); pvt++; sort(args + pvt, len - pvt); } static char *prepare(char *var) { size_t i; i = 0; while (var[i] != '\0' && var[i] != '=') i++; var[i] = '\0'; return (var + i + 1); } int export_empty(t_env *env) { size_t len; t_env *new; char *value; len = 0; while (env->vars[len] != NULL) len++; new = env_init(env->vars); if (new == NULL) return (EXIT_FAILURE); sort(new->vars, len); len = 0; while (new->vars[len] != NULL) { value = prepare(new->vars[len]); ft_printf("declare -x %s=\"%s\"\n", new->vars[len], value); len++; } env_free(new); return (EXIT_SUCCESS); }
C
#include "holberton.h" #include <stdlib.h> /** * free_grid - frees a 2 dimensional grid previously created * by alloc_grid * @grid: to be freed * @height: number of columns of grid * * Return: nothing */ void free_grid(int **grid, int height) { int i = 0; while (i < height) { free(grid[i]); i++; } free(grid); }
C
#include <msp430.h> /** * main.c */ int main(void) { WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer P1DIR |= 0x41; //Set path output to LED Port 1.0 and LED Port 1.6 P1REN |= BIT3; //enable resistor to connect LED and button P1OUT |= BIT3; //Enable button as output P1OUT &= ~BIT0; // Start the LED off while(1) { if(P1IN & BIT3)//If the button is not pressed. { P1OUT &= ~BIT0;//Turn off the RED LED P1OUT |= BIT6;//Turn on the Green LED } else { P1OUT &= ~BIT6;//Turn off the Green LED P1OUT |= BIT0;//Turn on the Red LED } } }
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 stat {int st_mode; scalar_t__ st_uid; } ; /* Variables and functions */ int S_ISVTX ; int /*<<< orphan*/ W_OK ; scalar_t__ access (char const*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ stat (char const*,struct stat*) ; scalar_t__ userid ; __attribute__((used)) static int checkwriteperm(const char *file, const char *directory) { struct stat stats; if (access(directory, W_OK) == 0) { stat(directory, &stats); if (stats.st_mode & S_ISVTX) { stat(file, &stats); if(stats.st_uid == userid) { return(0); } } else return(0); } return(-1); }
C
class Set { // Simple set class, storing ints in a bit vector. Assumes 32-bit words. public: Set() : els(0) {} Set(int len) : els((len+30)/31) {} int size() const { return els.size(); } void init(int len) { els.resize((len+30)/31); } Set& operator= (const Set &a) { els.resize(size()); for(int i=0;i<size();i++) els[i] = a.els[i]; return *this; } friend int operator== (const Set &a, const Set &b) { for(int i=0;i<a.size();i++) if(a.els[i] != b.els[i]) return 0; return 1; } friend int operator!= (const Set &a, const Set &b) { for(int i=0;i<a.size();i++) if(a.els[i] != b.els[i]) return 1; return 0; } friend int operator<(const Set &a, const Set &b) { return a.cmp(b)<0; } friend int operator>(const Set &a, const Set &b) { return a.cmp(b)>0; } void clear() { for(int i=0;i<size();i++) els[i] = 0; } void singleton(const int n, int len) { els.clear(); els.resize((len+30)/31,0); els[(n-1)/31] = (1 << (30 - ((n-1) % 31))); } unsigned int hash() const { unsigned int n = els[0]; for(int i=1;i<size();i++) { n += els[i]; //n ^= els[i]; } return n; } void myunion(const Set &a, const Set &b) { els.resize(a.size()); for(int i=0;i<a.size();i++) els[i] = a.els[i] | b.els[i]; } void difference(const Set &a, const Set &b) { els.resize(a.size()); for(int i=0;i<a.size();i++) els[i] = a.els[i] & ~b.els[i]; } int subset(const Set &a) const { for(int i=0;i<size();i++) if(els[i] & ~a.els[i]) return 0; return 1; } void print(ostream &out) const { static unsigned int bit = (1 << 30); int first = 1; unsigned int n; int low = 0, high; out << "{"; for(int i=0;i<size();i++) { n = els[i]; for(int j=1;j<32;j++,n<<=1) if(n & bit) { int k = j+31*i; if(low==0) low = high = k; else if (high==k-1) high = k; else { printRange(out,low,high,first); low = high = k; first = 0; } } } if(low!=0) printRange(out,low,high,first); out << "}"; } void printElements(ostream& c) { static unsigned int bit = (1 << 30); for(int i=0;i<size();i++) { unsigned int n = els[i]; for(int j=1;j<32;j++,n<<=1) if(n & bit) c << setw(12) << " " << setw(3) << j+31*i << endl; } } void printHex(ostream& c) { for(int i=0;i<size();i++) c << hex << els[i] << " "; c << dec << endl; } private: vector<unsigned int> els; int cmp(const Set &a) const { int c; for(int i=0;i<size();i++) if((c=els[i]-a.els[i])!=0) return c; return 0; } void printRange(ostream &out, int low, int high, int first) const { if(!first) out << ","; out << low; if(high-low>0) out << "-" << high; } };
C
/* compute distance between two points on a sphere (sDistance) or an ellipsiod (gDistance) . Units are degrees and km. for testing compile with -DTEST Link: -lproj -lm (C) Einar Kjartansson, November 2016 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <geodesic.h> #include "ray.h" #define A 6378.137 #define F 1.0/298.257223563 /* WGS84 */ #define deg2rad M_PI/180.0 #define earthRadius 6391.57 /* best fit around 64.5 degrees latitude */ struct geod_geodesic distance_g ; int distance_I = 1 ; double gDistance(double la1, double la2, double dlon) { /* geodesic on surface of an ellipsoid */ double dist,az1,az2 ; if( distance_I ) { geod_init(&distance_g,A,F) ; distance_I = 0 ; } geod_inverse(&distance_g,la1,0.0,la2,dlon,&dist,&az1,&az2) ; return dist ; } double sDistance(double la1, double la2, double dlon) { /* spherical approximation */ double b1,b2,dlo,x1,z1,co2,x2,y2,z2,xp,yp,zp,sind,cosd,dist ; b1 = la1 * deg2rad ; b2 = la2 * deg2rad ; dlo = dlon * deg2rad ; x1 = cos(b1) ; z1 = sin(b1) ; co2 = cos(b2) ; x2 = co2*cos(dlo) ; y2 = co2*sin(dlo) ; z2 = sin(b2) ; xp = -z1*y2 ; yp = z1*x2 - x1*z2 ; zp = x1*y2 ; sind = sqrt(xp*xp + yp*yp + zp*zp) ; cosd = x1*x2 + z1*z2 ; dist = earthRadius * atan2(sind,cosd) ; return(dist) ; } #ifdef TEST speedTest() { double la1,la2,dist,dlon ; int i,j ; dlon = 100 ; for( i = 0 ; i < 2000 ; i++ ) { la1 = 10 + 0.01*i ; for( j = 0 ; j < 5000 ; j++ ) { la2 = 70 + 0.01*j ; dist = gDistance(la1,la2,dlon) ; } } /* time for 10M distance calculations is about 7 seconds for gDistance and 1.25 seconds for sDistance */ } main() { float la1,la2,dlon ; speedTest() ; la1 = 64 ; la2 = 65 ; dlon = 2.3 ; la1 = 64 ; la2 = 66 ; dlon = 4.6 ; float distg,dists,distx, a1,a2 ; distg = gDistance(la1,la1,dlon) ; dists = gDistance(la1,la2,0) ; distx = gDistance(la1,la2,dlon) ; printf("distg=%10.3f dists=%10.3f distx=%10.3f\n",distg,dists,distx) ; distg = sDistance(la1,la1,dlon) ; dists = sDistance(la1,la2,0) ; distx = sDistance(la1,la2,dlon) ; printf("distg=%10.3f dists=%10.3f distx=%10.3f\n",distg,dists,distx) ; } #endif
C
#include<stdio.h> void main() { char string[5][20],rk[20]; int i,j; printf("Enter names of things \n"); //while(i<5) //scanf("%s",string[i++]); for(i=0;i<5;i++) scanf("%s",string[i]); for(i=0;i<4;i++) { for(j=0;j<=4-i;j++) { if(strcmp(string[j-1],string[j])>0) { strcpy(rk,string[j-1]); strcpy(string[j-1],string[j]); strcpy(string[j],rk); } } } printf("alphabetical oder of given things\n"); for(i=0;i<5;i++) printf("%s\n",string[i]); } /*sorting of names i.e arranging in alphantical oder*/
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: agusev <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/03 16:10:06 by agusev #+# #+# */ /* Updated: 2019/04/25 22:22:35 by agusev ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int ft_sprintf(char **s, const char *format, ...) { va_list av; int result; va_start(av, format); result = vaprintf(s, format, av); va_end(av); return (result); } int ft_printf(const char *format, ...) { char *s; va_list av; int result; va_start(av, format); result = vaprintf(&s, format, av); va_end(av); write(1, s, result); free(s); return (result); } int ft_printf_fd(int fd, const char *format, ...) { char *s; va_list av; int result; va_start(av, format); result = vaprintf(&s, format, av); va_end(av); write(fd, s, result); free(s); return (result); } char *ft_ssprintf(const char *format, ...) { va_list av; char *s; s = NULL; va_start(av, format); vaprintf(&s, format, av); va_end(av); return (s); }
C
#include <sys/msg.h> #include <sys/ipc.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <signal.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <unistd.h> #include "headers.h" int client_id; int self_id = -1; void client_exit(){ printf("Finishing client process...\n"); msgctl(client_id, IPC_RMID, NULL); exit(0); } void sigint(int signo){ client_exit(); } void read_stdin(char *text, char *type){ char buf[256]; if (fgets(buf, MSGTXTLEN, stdin) == NULL) perror("fgets"); char *str = strstr(buf, " "); if(str != NULL){ *str = 0; strcpy(type, buf); str++; strcpy(text, str); text[strlen(text)-1]=0; } else { strcpy(type, buf); text[0] = 0; } } int main(){ signal(SIGINT, &sigint); printf("Initalizing client...\n"); printf("Creating key... "); key_t key = ftok(getenv("HOME"), SERVER_ID); printf("OK\n"); printf("Connecting to the main queue... "); int server_id = msgget(key, MSGPERM); if(server_id < 0){ printf("%s\n", strerror(errno)); return 1; } int end = 0, rc; char line[MSGTXTLEN], type[MSGTXTLEN]; struct msg snd; printf("OK\n"); printf("Creating private queue... "); client_id = msgget(IPC_PRIVATE, MSGPERM | IPC_CREAT); if(client_id< 0){ printf("%s\n", strerror(errno)); return 1; } printf("OK\n"); printf("Sending request for accept to server... "); snd.msg_type = REQ_CLIENT_START; sprintf(snd.msg_text, "%d", client_id); rc = msgsnd(server_id, &snd, MSGTXTLEN, 0); if(rc < 0){ printf("%s\n", strerror(errno)); } printf("OK\n"); rc = msgrcv(client_id, &snd, MSGTXTLEN, 0, 0); if(rc < 0){ printf("%s\n", strerror(errno)); } self_id = atoi(snd.msg_text); printf("Received id from server: %d\n", self_id); printf("Client initialized\n\n"); while(!end){ int send = 1; read_stdin(line, type); switch(type[0]){ case 'M': snd.msg_type = REQ_MIRROR; break; case 'C': snd.msg_type = REQ_CALC; break; case 'T': snd.msg_type = REQ_TIME; break; case 'E': snd.msg_type = REQ_END; break; case 'S': client_exit(); break; default: printf("Unrecognized type: %s\n\n", type); send = 0; } sprintf(snd.msg_text, "%c%s", self_id, line); if(send){ if(msgsnd(server_id, &snd, MSGTXTLEN, 0) < 0){ printf("%s\n", strerror(errno)); } msgrcv(client_id, &snd, MSGTXTLEN, 0, 0); printf("Server response: %s\n", snd.msg_text); } } }
C
#include<stdio.h> #include<limits.h> typedef unsigned float_bits; float_bits float_i2f(int i); unsigned leftmost_one_loc(unsigned i); float_bits f2u(float f); float u2f(float_bits f); int main() { for(int i = INT_MIN; i <= INT_MAX; i++) { float myself_cast = u2f(float_i2f(i)); float normal_cast = (float)i; if(myself_cast != normal_cast) { printf("Failed\n%x: %x, %x\n", i, f2u(normal_cast), f2u(myself_cast)); break; } } return 0; } float_bits float_i2f(int i) { if(i == 0) return 0; unsigned sign = i & INT_MIN; unsigned exp; unsigned frac; unsigned ui = (unsigned)i; if(sign == INT_MIN) { ui = ~ui + 1; } unsigned loc = leftmost_one_loc(ui); if(loc > 24) { unsigned abadon = ui & (1 << (loc - 25)); unsigned end = ui & (1 << (loc - 24)); if(abadon != 0) { if(end != 0 && (ui & ~(~0 << (loc - 25))) == 0) { ui += end; } else if((ui & ~(~0 << (loc - 25))) != 0){ ui += (1 << (loc - 24)); } } loc = leftmost_one_loc(ui); frac = (ui >> (loc - 24)) & 0x7fffff; } else { frac = (ui << (24 - loc)) & 0x7fffff; } exp = loc - 1 + 127; return sign | (exp << 23) | frac; } unsigned leftmost_one_loc(unsigned i) { int count = 0; while(i != 0) { count++; i >>= 1; } return count; } float_bits f2u(float f) { return *((unsigned *)&f); } float u2f(float_bits f) { return *((float *)(&f)); }
C
#define _CRT_SECURE_NO_WARNINGS //파일 입출력 명령어 그대로 쓰기 위해 define #include <stdio.h> #include <stdlib.h> #define MAX_VERTEX 50 #define MAX_STACK_SIZE 1000 typedef struct GraphNode { int vertex; GraphNode *link; }GraphNode; typedef struct GraphType { int n; //정점의 개수 GraphNode *adj_list[MAX_VERTEX]; }GraphType; //노드 번호를 넣었다가 출력할 스택 선언 typedef struct { int stack[MAX_STACK_SIZE]; int top; } StackType; //그래프 초기화 함수 void init_graph(GraphType *g) { for (int i = 0; i < MAX_VERTEX; i++) g->adj_list[i] = NULL; //g의 adj_list 내용을 모두 비우고 g->n = 0; //n값을 0으로 초기화 } //vertex 삽입 함수 void insert_vertex(GraphType *g) { if ((g->n) + 1 > MAX_VERTEX) //노드 개수가 adj_list의 인덱스보다 많다면 { printf("정점의 수가 많아 스택에 담을 수 없습니다.\n"); //에러메세지 출력 exit(-1); //종료 } //아니라면 g->n++; //n+1 } //edge 삽입 함수 void insert_edge(GraphType *g, int u, int v) //파라미터로 graphtype 참조변수와 메모장의 정수 두 개를 받는다 { //만약 (에지가 출발하는) 정점의 번호가 n보다 크거나, (에지가 도착하는) 정점의 번호가 n보다 클 경우 if (u >= g->n || v >= g->n) { //정점의 번호가 틀렸으므로 에러 메세지 출력 printf("정점 번호가 올바르지 않습니다.\n"); exit(-1);//종료 } //node에 메모리 동적 할당 GraphNode *node = (GraphNode*)malloc(sizeof(GraphNode)); if (!node) //만약 node가 비어있다면 { printf("메모리 할당 에러\n"); exit(-1); } //메모리 할당이 제대로 이루어졌다면 node->vertex = v; //node의 vertex에 v값을 대입 node->link = g->adj_list[u]; //node의 link에 g의 adj_list[(에지가 도착하는)정점의 번호]를 대입 g->adj_list[u] = node; //adj_list[(에지가 도착하는)정점의 번호]에 node를 대입 } //스택 초기화 함수 void init(StackType *s) { //스택의 초기화는 top을 가장 밑으로 내리는 것 s->top = -1; } //스택이 비어있는지 확인하는 함수 int is_empty(StackType *s) { //스택의 top이 -1이 맞는지 아닌지를 반환 return (s->top == -1); } //스택이 꽉 차있는지 확인하는 함수 int is_full(StackType *s) { //스택의 top이 최대사이즈-1과 같은지 다른지를 반환 return (s->top == (MAX_STACK_SIZE - 1)); } //스택 안에 원소를 넣는 함수 void push(StackType *s, int num) { //만약 스택이 꽉 차있으면 원소를 넣을 수 없으므로 체크 if (is_full(s)) { fprintf(stderr, "스택 포화 에러\n"); return; } //스택이 비어있다면 top+1의 인덱스에 원소 num 넣기 else s->stack[++(s->top)] = num; } //스택 안에서 원소를 꺼내는 함수 int pop(StackType *s) { //스택이 비어있으면 꺼낼 원소가 없으므로 체크 if (is_empty(s)) { fprintf(stderr, "스택 공백 에러\n"); exit(1); } //만약 스택 안에 꺼낼 원소가 있다면 먼저 top의 인덱스의 원소를 반환한 후 top-1 else return s->stack[(s->top)--]; } //위상정렬함수 int top_sort(GraphType *g) { int i, u, v; StackType s; //스택 선언 GraphNode *node; int *in_degree = (int*)malloc(sizeof(int)*g->n); //각 정점의 차수를 계산하기 위한 배열. 메모리 동적할당 for (i = 0; i < g->n; i++) in_degree[i] = 0; // 모든 배열의 값 0으로 초기화 for (i = 0; i < g->n; i++) { node = g->adj_list[i]; //node에 adj_list[i]의 값을 대입하는데 while (node != NULL) //node가 null이 아니면 { in_degree[node->vertex]++; // 정점 i에 도착하는 간선수(차수) +1 node = node->link; //다음 link로 건너가서 null을 만날 때까지 이 과정 반복 } } //스택 초기화 init(&s); for (i = 0; i < g->n; i++) { if (in_degree[i] == 0) push(&s, i);// 차수가 0인 정점을 스택에 저장 } printf("위상 정렬 결과 = "); while (!is_empty(&s)) // 결과를 출력하려면 스택이 비어있지 않아야 { v = pop(&s); // 진입 차수가 없는 정점 v printf("%d ", v); //정점(vertex) v 출력 node = g->adj_list[v]; // 차수가 0인 정점을 출력했으므로 해당 정점은 사라진 것과 마찬가지. 정점의 차수 변경 while (node != NULL) { u = node->vertex; //node의 정점을 u에 대입 in_degree[u]--; // u의 차수 감소하고(v에서 u로 도착하는 간선이었는데 v가 이제 없으니까) if (in_degree[u] == 0) { push(&s, u); //정점 u를 스택에 저장 } node = node->link; // 연결된 모든 간선을 제거 } } if (in_degree[u] != 0) //아직 모든 정점을 출력하지 않았는데 내향 차수가 0인 정점이 없는 경우 printf("불가능"); //불가능 메세지 출력 free(in_degree); //다 끝난 후 동적 할당 해제 return 0; } //메인함수 int main() { GraphType graph; //graph 선언 init_graph(&graph); //graph 초기화 int n, e, v, u; FILE *fp;//파일포인터 선언 fp = fopen("파일경로\\dag1.txt", "r"); //메모장 열기 fscanf(fp, "%d %d", &n, &e); //첫 줄의 n은 총 정점의 수, e는 총 에지의 수 for (int i = 0; i < n; i++) insert_vertex(&graph); //총 정점의 개수 n만큼 정점 추가 for (int i = 0; i < e; i++) { //총 에지의 개수 e만큼 반복 fscanf(fp, "%d %d", &v, &u); //메모장의 수를 두 개씩 불러와 각각 저장하고 insert_edge(&graph, v, u); //해당 에지 삽입 } top_sort(&graph); //삽입이 끝난 후 위상정렬 fclose(fp); //파일 닫기 return 0; }
C
/** * Implements a dictionary's functionality. */ #include <stdbool.h> #include <ctype.h> #include <stdio.h> #include <cs50.h> #include <string.h> #include <stdlib.h> #include "dictionary.h" /** * Returns true if word is in dictionary else false. */ bool check(const char *word) { // Initialise check pointer to the root check_ptr= root; // Iterate through the characters in the word for (int j=0; j<strlen(word); j++) { //Store the character in temp char temp = word[j]; if (temp=='\'') { check_ptr= check_ptr -> children[26]; } else { // Character is an uppercase alphabet if (temp >= 'A' && temp <= 'Z') { // Convert to lowercase temp = temp + 32; } // Convert the alphabet into an integer i with the corresponding number (A=0, B=1 ... Z=25) int k = temp - 'a'; check_ptr= check_ptr -> children[k]; } // Check if NULL if (check_ptr==NULL) { return false; } } if (check_ptr -> is_word) { return true; } return false; } /** * Loads dictionary into memory. Returns true if successful else false. */ bool load(const char *dictionary) { // Open file and check for errors FILE* fp = fopen(dictionary, "r"); if (fp == NULL) { fprintf(stderr, "Could not open the dictionary file.\n"); return false; } // Allocate memory for root root= calloc(1, sizeof(node)); load_ptr= root; // Iterate through dictionary until EOF int c; dic_count=0; while ((c = fgetc(fp)) != EOF) { // Character is an alphabet (assuming lowercase) if (c >= 97 && c <= 122) { // Convert the alphabet into an integer i with the corresponding number (A=0, B=1 ... Z=25) int i = c - 'a'; // Check if there is already a node at the address, if not, create a node at that location and allocate it the required memory if (load_ptr -> children[i] == NULL) { load_ptr -> children[i]= calloc(1, sizeof(node)); // Check if malloc was successfull if (load_ptr -> children[i] == NULL) { fprintf(stderr, "Malloc Error"); return 1; } load_ptr= load_ptr -> children[i]; } else { load_ptr= load_ptr -> children[i]; } } // Else if the character is an apostrophe, check if the 26th children is null, if it isn't, allocate a node. else if (c=='\'') { // Check if there is already a node at the address, if not, create a node at that location and allocate it the required memory if (load_ptr -> children[26] == NULL) { load_ptr -> children[26]= calloc(1, sizeof(node)); // Check if malloc was successfull if (load_ptr -> children[26] == NULL) { fprintf(stderr, "Malloc Error"); return 1; } } load_ptr = load_ptr -> children[26]; } else { // Set load pointer to true load_ptr -> is_word=true; // Increase dictionary count dic_count++; // Reset load pointer load_ptr = root; } } // Close file pointer fclose(fp); return true; } /** * Returns number of words in dictionary if loaded else 0 if not yet loaded. */ unsigned int size(void) { if (dic_count !=0) { return dic_count; } return 0; } // Clean void freeit (node *ptr) { // Iterate over the children for(int i = 0; i < 27; i++) { // If node has children if(ptr->children[i] != NULL) { // Call recursively freeit (ptr->children[i]); } } free(ptr); } /** * Unloads dictionary from memory. Returns true if successful else false. */ bool unload(void) { // Create a node pointer 'curr' to point to the first node unload_ptr = root; freeit(unload_ptr); return true; }
C
#include <stdio.h> #include <string.h> #define STACK_SIZE 10 char stack[STACK_SIZE]; int top = -1; int isEmpty() { return top == -1; } int isFull() { return top == STACK_SIZE - 1; } char peek() { return stack[top]; } char pop() { if (!isEmpty()) { return stack[top--]; } else { printf("Stack is Full\n"); return '\0'; } } void push(char ele) { if (!isFull()) { stack[++top] = ele; } else { printf("Stack is Full\n"); } } int isBalanced(char str[]) { int i, len = strlen(str); char curValue, topValue; for (i = 0; i < len; i++) { curValue = str[i]; if (curValue == '(' || curValue == '{' || curValue == '[') { push(curValue); } if (curValue == ')' || curValue == '}' || curValue == ']') { if (isEmpty()) { return 0; } topValue = pop(); if ((curValue == ')' && topValue != '(') || (curValue == '}' && topValue != '{') || (curValue == ']' && topValue != '[')) { return 0; } } } return isEmpty(); } int main() { char str[100]; printf("Enter a string > "); scanf("%100[^\n]s", str); if (isBalanced(str)) { printf("Balanced\n"); } else { printf("Not Balanced\n"); } return 0; }
C
//Jan 24, 17 // //Illustrates getopt() command. // // /* scene 1: -d option with an arguement. dguai:~/workspace/Head First C/ch 3 $ ./a.out -d now deliver now. scene 2: -d option without an arguement dguai:~/workspace/Head First C/ch 3 $ ./a.out -d ./a.out: option requires an argument -- 'd' Wrong argument. scene 3: invalid arguement -z dguai: ~/workspace/Head First C/ch 3 $ ./a.out -z ./a.out: invalid option -- 'z' Wrong argument. scene 4: valid arguement with ingredients. dguai:~/workspace/Head First C/ch 3 $ ./a.out -dtmrw -t mushroom pineapple Make it thick. deliver tmrw. Ingredients are ... mushroom pineapple */ #include <stdio.h> #include <unistd.h> int main( int argc, char *argv[] ) { const char *delivery = ""; //Note that const or no const make a difference. // Must be initialized with empty string in case // there is no -d arguement. //If there is no empty string assignment, this will result in //segmentation error when checking for delivery[0]. char ch; int count; //delivery[0] = 'f'; //This is illegal since delivery is a const. //printf("I. address of delivery is %p\n", &delivery[0]); while( ( ch = getopt( argc, argv, "d:t" )) != EOF ){ //: following d implies that there must be arguement. //t implies that this is another valid arguement. switch(ch) { case 'd': delivery = optarg; //printf("II. address of delivery is %p\n", &delivery[0]); break; case 't': printf( "Make it thick.\n" ); break; default: printf( "Wrong argument.\n" ); break; } } //decrement num of arguements by number of optind. argc = argc - optind; //argv is an array of char pointers. //Advance the pointer by the number of optind. argv = argv + optind; if (delivery[0]){ printf( "deliver %s.\n", delivery ); } if (argc > 0 ) { printf("Ingredients are ... \n"); for( count = 0; count < argc; count ++ ) printf( "%s\n", argv[count] ); } return 0; }
C
// Demonstrates usage of TEveJetCone class. // Author: Jochen Thaeder const char* esd_geom_file_name = "http://root.cern.ch/files/alice_ESDgeometry.root"; void jetcone() { TEveManager::Create(); using namespace TMath; TRandom r(0); // -- Set Constants Int_t nCones = 10; Int_t nTracks = 200; Float_t coneRadius = 0.4; Float_t length = 300.; // -- Define palette gStyle->SetPalette(1, 0); TEveRGBAPalette* pal = new TEveRGBAPalette(0, 500); // ----------------------------------------------------------------------- // -- Line sets // ----------------------------------------------------------------------- // -- Define cone center TEveStraightLineSet* axis = new TEveStraightLineSet("Cone Axis"); axis->SetLineColor(kGreen); axis->SetLineWidth(2); TEveStraightLineSet* tracksXYZ = new TEveStraightLineSet("StraightLinesXYZ"); tracksXYZ->SetLineColor(kRed); tracksXYZ->SetLineWidth(2); TEveStraightLineSet* tracksEtaPhi = new TEveStraightLineSet("StraightLinesEtaPhi"); tracksEtaPhi->SetLineColor(kYellow); tracksEtaPhi->SetLineWidth(2); TEveStraightLineSet* tracksSeedEtaPhi = new TEveStraightLineSet("StraightLinesEtaPhiSeed"); tracksSeedEtaPhi->SetLineColor(kBlue); tracksSeedEtaPhi->SetLineWidth(2); // ----------------------------------------------------------------------- // -- Draw track distribution in XYZ in TPC Volume +/-250, +/-250, +/-250 // ----------------------------------------------------------------------- for ( Int_t track=0; track < nTracks ; track++ ) { Float_t trackX = r.Uniform(-250.0, 250.0); Float_t trackY = r.Uniform(-250.0, 250.0); Float_t trackZ = r.Uniform(-250.0, 250.0); Float_t trackR = Sqrt(trackX*trackX + trackY*trackY + trackZ*trackZ); TEveVector trackDir(trackX/trackR, trackY/trackR ,trackZ/trackR); TEveVector trackEnd = trackDir * length; tracksXYZ->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ ); } // ----------------------------------------------------------------------- // -- Draw track distribution in eta phi in TPC Volume +/-0.9, {0, 2Pi} // ----------------------------------------------------------------------- for ( Int_t track=0; track < nTracks ; track++ ) { Float_t trackEta = r.Uniform(-0.9, 0.9); Float_t trackPhi = r.Uniform(0.0, TwoPi()); TEveVector trackDir( GetTEveVector(trackEta, trackPhi) ); TEveVector trackEnd = trackDir * length; if ( trackEta > coneRadius || trackEta < -coneRadius ) tracksEtaPhi->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ); else tracksSeedEtaPhi->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ); } // ----------------------------------------------------------------------- // -- Draw cones // ----------------------------------------------------------------------- for ( Int_t iter = 0; iter < nCones; ++iter ) { // -- Get Random ( eta ,phi ) Float_t coneEta = r.Uniform(-0.9, 0.9); Float_t conePhi = r.Uniform(0.0, TwoPi() ); // -- Primary vertx as origin TEveVector coneOrigin(0.0,0.0,0.0); // -- Get Cone Axis - axis line 10% longer than cone height TEveVector coneAxis ( GetTEveVector( coneEta, conePhi) ); coneAxis *= length * 1.1; axis->AddLine( 0., 0., 0., coneAxis.fX, coneAxis.fY, coneAxis.fZ ); // -- Draw jet cone TEveJetCone* jetCone = new TEveJetCone("JetCone"); jetCone->SetPickable(kTRUE); jetCone->SetCylinder( 250., 250. ); if ( (jetCone->AddCone( coneEta, conePhi, coneRadius ) ) != -1) gEve->AddElement( jetCone ); } // ----------------------------------------------------------------------- // -- Add cone axis gEve->AddElement(axis); // -- Add lines // gEve->AddElement(tracksXYZ); gEve->AddElement(tracksSeedEtaPhi); gEve->AddElement(tracksEtaPhi); // -- Load TPC geometry geomGentleTPC(); gEve->Redraw3D(kTRUE); return; } //___________________________________________________________________________ TEveVector GetTEveVector( Float_t& eta, Float_t& phi ) { TEveVector vec( (Float_t) Cos ( (Double_t) phi)/ CosH( (Double_t) eta ), (Float_t) Sin ( (Double_t) phi)/ CosH( (Double_t) eta ), (Float_t) TanH( (Double_t) eta ) ); return vec; } //__________________________________________________________________________ void geomGentleTPC() { // Simple geometry TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD"); if (!geom) return; TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle"); TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse, 0); geom->Close(); delete geom; gEve->AddGlobalElement(gsre); TEveElement* elTRD = gsre->FindChild("TRD+TOF"); elTRD->SetRnrState(kFALSE); TEveElement* elPHOS = gsre->FindChild("PHOS"); elPHOS->SetRnrState(kFALSE); TEveElement* elHMPID = gsre->FindChild("HMPID"); elHMPID->SetRnrState(kFALSE); }
C
/** * @brief Funcion Borrar un Registro * @param Recibe como primer parametro la estructura Personas y como segundo parametro un valor entero * @param busca en el array, buscando el dni, si lo encuentra nos avisa que persona es y la borra de manera logica * @return No devuelve valor. */ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> #include <ctype.h> #include "funciones.h" #define ON 0 #define OFF 1 #define TAM 4 void borrarPersona(Personas per[],int dni) { int i; int index; i = pideDato(); index = buscaDni(per,i); if(index !=-1) { per[index].est=ON; per[index].dni=ON; printf("\nEL REGISTRO HA SIDO ELIMINADO.-\n\n\n\n"); } else { printf("Persona no encontrada!!!\n"); } }
C
#include "holberton.h" /** * read_textfile - read text file * @filename: path to file * @letters: buffer size * Return: num of bytes */ ssize_t read_textfile(const char *filename, size_t letters) { ssize_t num = 0; char *buffer; int fd; if (filename == NULL) { return (0); } buffer = malloc(sizeof(char) * letters); if (buffer == NULL) return (0); fd = open(filename, O_RDONLY); if (fd == -1) { free(buffer); return (0); } num = read(fd, buffer, letters * sizeof(char)); if (num == -1) { free(buffer); close(fd); return (0); } num = write(STDOUT_FILENO, buffer, num); if (num == -1) { free(buffer); close(fd); return (0); } else { free(buffer); close(fd); return (num); } }
C
#include<stdio.h> int main(){ int T,tcase=1; scanf("%d",&T); while(T--){//notice long long a,b,c; scanf("%lld%lld%lld",&a,&b,&c); if(a+b>c){ printf("case #%d:true\n",tcase++); } else{ printf("Case #%d:false\n",tcase++); } } return 0; }
C
/* * network/network.c: implementation of the MNP process. * * CS60, March 2018. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> #include <signal.h> #include <netdb.h> #include <assert.h> #include <sys/utsname.h> #include <pthread.h> #include <unistd.h> #include "../common/constants.h" #include "../common/pkt.h" #include "../common/seg.h" #include "../topology/topology.h" #include "network.h" #include "nbrcosttable.h" #include "dvtable.h" #include "routing_table.h" /**************** constants ****************/ #define NETWORK_WAITTIME 60 /**************** global variables ****************/ int overlay_connection; //connection to the overlay int transport_connection; //connection to the transport nbr_cost_entry_t *nbr_cost_table; //neighbor cost table dv_t *dv_table; //distance vector table pthread_mutex_t *dv_mutex; //dvtable mutex routingtable_t *routing_table; //routing table pthread_mutex_t *routingtable_mutex; //routing_table mutex /**************** local function prototypes ****************/ int connectToOverlay(); void *routeupdate_daemon(void *arg); void *pkthandler(void *arg); void waitTransport(); void network_stop(); /**************** main function ****************/ /* TODO: entry point for the network: * 1) initialize neighbor cost table, distance vector table, mutex * routing table, connections to overlay and transport * 2) print out the three tables * 3) set up signal handler for SIGINT * 4) set up overlay connection * 5) create packet handling thread * 6) create route update thread * 7) wait NETWORK_WAITTIME for routes to be established and then * print routing table * 8) wait for the MRT process to connect (waitTransport()) */ int main(int argc, char *argv[]) { printf("network layer is starting, pls wait...\n"); nbr_cost_table = nbrcosttable_create(); dv_table = dvtable_create(); routing_table = routingtable_create(); nbrcosttable_print(nbr_cost_table); dvtable_print(dv_table); routingtable_print(routing_table); /* register a signal handler which is sued to terminate the process */ signal(SIGINT, network_stop); // mutex dv_mutex = malloc(sizeof(*dv_mutex)); pthread_mutex_init(dv_mutex, NULL); routingtable_mutex = malloc(sizeof(*routingtable_mutex)); pthread_mutex_init(routingtable_mutex, NULL); // connections overlay_connection = -1; transport_connection = -1; // connect to overlay overlay_connection = connectToOverlay(); if(overlay_connection == -1) perror("try to connect to overlay\n"); // threads pthread_t pkt_handle; pthread_t route_update; pthread_create(&pkt_handle, NULL, pkthandler, (void *)0); pthread_create(&route_update, NULL, routeupdate_daemon, (void *)0); sleep(NETWORK_WAITTIME); // wait connection from MRT process printf("final dvtable + routingtable\n"); dvtable_print(dv_table); routingtable_print(routing_table); printf("waiting for connection from MRT process...\n"); waitTransport(); return 0; } /**************** local functions *************/ // This function is used to for the network layer process to // connect to the local overlay process on port OVERLAY_PORT. // return connection descriptor if success, -1 otherwise. // Pseudocode // 1) Fill in sockaddr_in for socket // 2) Create socket // 3) return the socket descriptor int connectToOverlay() { struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(OVERLAY_PORT); int overlay_conn = socket(AF_INET, SOCK_STREAM, 0); if (overlay_conn < 0) return -1; if (connect(overlay_conn, (struct sockaddr *) &servaddr, sizeof(servaddr)) != 0) return -1; // successfully connected return overlay_conn; } // TODO: This thread handles incoming packets from the ON process. // Pseudocode // 1) while recv packet from overlay connection // 2) if it is a ROUTE_UPDATE packet // 3) fetch data (distance vector) and src node ID // 4) lock dv table and update dv table // 5) update routing table if necessary with lock // 6) release locks // 7) if it is a MNP packet to itself // 8) forward it to MRT layer w/ forwardsegToMRT() // 9) if it is a MNP packet to others // 10) find the node ID of the next hop based on the routing table // 11) send it to the next hop w/ overlay_sendpkt() // 2) close overlay conn // 3) exit thread void *pkthandler(void *arg) { // initialize some variables struct packet pkt; int myID = topology_getMyNodeID(); int nextNodeID; while(overlay_recvpkt(&pkt, overlay_connection) == 1){ if(pkt.header.type == ROUTE_UPDATE){ // obtain route update from pkt struct pktrt *ru; ru = (struct pktrt*)pkt.data; int src_nodeID = pkt.header.src_nodeID; int entryNum = ru->entryNum; //lock dvtable pthread_mutex_lock(dv_mutex); // update dv_table for(int i = 0; i < entryNum; i++){ if(ru->entry[i].cost < dvtable_getcost(dv_table, src_nodeID, ru->entry[i].nodeID)){ if(dvtable_setcost(dv_table, src_nodeID, ru->entry[i].nodeID, ru->entry[i].cost) == -1) printf("dvtable_setcos failed!\n"); } int new_dist = dvtable_getcost(dv_table, myID, src_nodeID) + ru->entry[i].cost; if(new_dist < dvtable_getcost(dv_table, myID, ru->entry[i].nodeID)){ if(dvtable_setcost(dv_table, myID, ru->entry[i].nodeID, new_dist) == -1) printf("dvtable_setcos failed!\n"); // update routingtable pthread_mutex_lock(routingtable_mutex); routingtable_setnextnode(routing_table, ru->entry[i].nodeID, src_nodeID); pthread_mutex_unlock(routingtable_mutex); } } pthread_mutex_unlock(dv_mutex); } else{ // forward to MRT if(pkt.header.dest_nodeID == myID){ printf("forwardsegToMRT\n"); struct segment seg; seg = *(struct segment *)&pkt.data; forwardsegToMRT(transport_connection, pkt.header.src_nodeID, &seg); } // forward to next node else{ routingtable_entry_t *head; head = routing_table->hash[makehash(pkt.header.dest_nodeID)]; while(head->next != NULL){ head = head->next; if(head->destNodeID == pkt.header.dest_nodeID){ nextNodeID = head->nextNodeID; break; } } nextNodeID = head->nextNodeID; printf("foward to %i\n", nextNodeID); overlay_sendpkt(nextNodeID, &pkt, overlay_connection); } } } close(overlay_connection); overlay_connection = -1; pthread_exit(NULL); } // TODO: This thread sends out route update packets every // ROUTEUPDATE_INTERVAL. The route update packet contains this // node's distance vector. // Broadcasting is done by set the dest_nodeID in packet header as // BROADCAST_NODEID and use overlay_sendpkt() to send it out. // Pseudocode // 1) get my node ID and number of neighbors // 2) while(1) // Fill in mnp_pkt header with myNodeID, BROADCAST_NODEID and // ROUTE_UPDATE // Cast the MNP packet data as pkt_routeupdate_t type, set the // entryNum as the number of neighbors // Lock the dv table, put distance vector into the packet data // Unlock the dv table // Set the length in packet header: sizeof(entryNum) + entryNum* // sizeof(routeupdate_entry_t) // if(overlay_sendpkt(BROADCAST_NODEID,&ru,overlay_conn < 0) // close(overlay_conn) // exit // Sleep ROUTEUPDATE_INTERVAL void *routeupdate_daemon(void *arg) { // initialize some variables int myID = topology_getMyNodeID(); int nbr_num = topology_getNbrNum(); int node_num = topology_getNodeNum(); struct packet pkt; // send broadcast every ROUTEUPDATE_INTERVAL while(1){ // initialize packet pkt.header.src_nodeID = myID; pkt.header.dest_nodeID = BROADCAST_NODEID; pkt.header.type = ROUTE_UPDATE; struct pktrt *ru; ru = (struct pktrt *)&pkt.data; ru->entryNum = node_num; // store dv_table into route update pthread_mutex_lock(dv_mutex); for(int i = 0; i <= node_num; i++){ struct routeupdate_entry ru_entry; ru_entry.nodeID = dv_table[nbr_num].dvEntry[i].nodeID; ru_entry.cost = dv_table[nbr_num].dvEntry[i].cost; ru->entry[i] = ru_entry; } pthread_mutex_unlock(dv_mutex); pkt.header.length = sizeof(ru->entryNum) + ru->entryNum*sizeof(routeupdate_entry_t); // send route update broadcast if(overlay_sendpkt(BROADCAST_NODEID, &pkt, overlay_connection) < 0){ close(overlay_connection); exit(9); } sleep(ROUTEUPDATE_INTERVAL); } } // TODO: this function opens a port on NETWORK_PORT and waits for // the TCP connection from local MRT process. // Pseudocode // 1) create a socket listening on NETWORK_PORT // 2) while (1) // 3) accept an connection from local MRT process // 4) while (getsegToSend()) keep receiving segment and // destination node ID from MRT // 5) encapsulate the segment into a MNP packet // 6) find the node ID of the next hop based on the routing table // 7) send the packet to next hop using overlay_sendpkt() // 8) close the connection to local MRT void waitTransport() { // some variables int dest_NodeID; int next_NodeID; int myID = topology_getMyNodeID(); struct segment seg; // socket stuff struct sockaddr_in server; int list_sock; list_sock = socket(AF_INET, SOCK_STREAM, 0); if (list_sock < 0){ perror("opening socket stream"); exit(1); } server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(NETWORK_PORT); if (bind(list_sock, (struct sockaddr *) &server, sizeof(server))) { perror("binding socket name"); exit(2); } listen(list_sock, 10); // mrt connection while(1){ struct sockaddr_in cli_addr; socklen_t cli_len; cli_len = sizeof cli_addr; transport_connection = accept(list_sock, (struct sockaddr *)&cli_addr,&cli_len); if (transport_connection == -1){ perror("accept"); continue; } else{ // continue sending segments from mrt to overlay while(getsegToSend(transport_connection, &dest_NodeID, &seg) == 1){ printf("getsegToSend\n"); // initialize new pkt struct packet pkt; memcpy(pkt.data, &seg, sizeof(seg)); pkt.header.src_nodeID = myID; pkt.header.dest_nodeID = dest_NodeID; pkt.header.type = MNP; pkt.header.length = sizeof(seg); // find next_node in routing table routingtable_entry_t *head; head = routing_table->hash[makehash(pkt.header.dest_nodeID)]; while(head->next != NULL){ if(head->destNodeID == pkt.header.dest_nodeID){ next_NodeID = head->nextNodeID; break; } head = head->next; } next_NodeID = head->nextNodeID; printf("overlay_sendpkt %i\n", pkt.header.dest_nodeID); overlay_sendpkt(next_NodeID, &pkt, overlay_connection); } } close(transport_connection); transport_connection = -1; } } // TODO: This function stops the MNP process. It closes all the // connections and frees all the dynamically allocated memory. // It is called when the MNP process receives a signal SIGINT. // 1) close overlay connection if it exists // 2) close the connection to MRT if it exists // 3) destroy tables, free mutex // 2) exit void network_stop() { // destroy and free everything nbrcosttable_destroy(nbr_cost_table); dvtable_destroy(dv_table); routingtable_destroy(routing_table); if(overlay_connection == 1) close(overlay_connection); if(transport_connection == 1) close(transport_connection); free(dv_mutex); free(routingtable_mutex); }
C
#include <stdio.h> #include <string.h> int main() { char a[25] = " this is a "; char b[25] = " this is b "; char c[25] = " we dont care about c "; int i; printf("\nThose 3 strings will get modified after using strcpy\n\n"); printf("%s\n%s\n%s\n", a, b, c); printf("\nNow using magic\n\n"); strcpy(c, a); printf("%s\n %s\n %s\n", a, b, c); printf("\nstrcpy did its job\n\n"); return 0; }
C
// input three angle of a triangle. Check it is valid or not #include <stdio.h> int main() { float a, b, c; printf("Enter three angles to check that it will form a valid traingle or not. \n"); scanf("%f %f %f", &a, &b, &c); if(a+b+c==180) printf("valid triangle \n"); else printf("invalid triangle \n"); return 0; }
C
#include "system.h" #include "FreeRTOS.h" void vApplicationTickHook( void ) { system_tick(); } void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ) { /* If the buffers to be provided to the Timer task are declared inside this function then they must be declared static - otherwise they will be allocated on the stack and so not exists after this function exits. */ static StaticTask_t xTimerTaskTCB; static StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ]; /* Pass out a pointer to the StaticTask_t structure in which the Timer task's state will be stored. */ *ppxTimerTaskTCBBuffer = &xTimerTaskTCB; /* Pass out the array that will be used as the Timer task's stack. */ *ppxTimerTaskStackBuffer = uxTimerTaskStack; /* Pass out the size of the array pointed to by *ppxTimerTaskStackBuffer. Note that, as the array is necessarily of type StackType_t, configTIMER_TASK_STACK_DEPTH is specified in words, not bytes. */ *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH; }
C
#include "stringobj.h" StringObj *f77xml_StringObj_new(unsigned int maxlen) { StringObj *str; str = (struct StringObj *)malloc(sizeof(struct StringObj)); str->str = (char *)malloc((maxlen+1)*sizeof(char)); bzero(str->str, maxlen+1); str->maxlen = maxlen; return str; } void f77xml_StringObj_delete(StringObj *self) { free (self->str); free (self); } void f77xml_StringObj_set(StringObj *self, const char *s) { bzero(self->str, self->maxlen+1); strncpy(self->str, s, self->maxlen); self->str[self->maxlen]=0; } void f77xml_StringObj_trim(StringObj *self) { char *ptr; ptr = self->str; ptr += (self->maxlen-1); while (*ptr == ' ') { *ptr = 0; ptr--; } } void f77xml_StringObj_untrim(StringObj *self) { char *ptr = self->str; while (*ptr) ptr++; while (ptr != self->str+self->maxlen) { *ptr=' '; ptr++; } } void f77xml_StringObj_clear(StringObj *self) { bzero(self->str, self->maxlen+1); } unsigned int f77xml_StringObj_size(StringObj *self) { return self->maxlen; }
C
#include "apue.h" #include <sys/wait.h> static void sig_int(int); int main(int argc, char *argv[]) { char buf[MAXLINE]; pid_t pid; int status; int len; if (signal(SIGINT, sig_int) == SIG_ERR) err_sys("signal error"); printf("%% "); while (fgets(buf, MAXLINE, stdin) != NULL) { len = strlen(buf); if (buf[len - 1] == '\n') buf[len - 1] = 0; if ((pid = fork()) < 0) { err_sys("fork error"); } else if (pid == 0) { /* child */ execl("/bin/sh", "sh", "-c", buf, (char*)0); err_ret("couldn't execute: %s", buf); exit(127); } else { /* parent */ if ((pid = waitpid(pid, &status, 0)) < 0) err_sys("waitpid error"); printf("%% "); } } return 0; } void sig_int(int signo) { printf("interrupt %d\n", signo); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* correct_cast_flags.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: epham <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/08 19:21:02 by epham #+# #+# */ /* Updated: 2019/04/16 15:06:02 by epham ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" int correct_flags(long double ival, t_printf *env) { env->preflen = 0; if (env->flags & PLUS) env->flags &= ~SPACE; if ((env->type != 'f' && env->type != 'F') && env->flags & (MINUS | PREC)) env->flags &= ~ZERO; if (ival < 0 && (env->flags & (PLUS | SPACE))) env->flags &= ~(PLUS | SPACE); if (((env->flags & HASH) && (env->type == 'x' || env->type == 'X')) || env->type == 'p') env->flags |= PREF; if (env->flags & PREF) env->preflen = 2; if ((env->flags & HASH) && (env->type == 'o' || env->type == 'O')) env->preflen = 1; if ((env->flags & HASH || env->flags & PLUS) && (env->type == 'u' || env->type == 'U')) { env->flags &= ~PLUS; env->flags &= ~HASH; } return (env->flags); } void correct_modif(t_printf *env, long long *val) { if (env->flags & HH) *val = (char)*val; else if (env->flags & H) *val = (short)*val; else if (env->flags & LL) *val = (long long)*val; else if (env->flags & L) *val = (long)*val; else if (env->flags & J) *val = (long long)*val; else if (env->flags & Z) *val = (size_t)*val; else *val = (int)*val; env->flags = correct_flags(*val, env); } void correct_fmodif(t_printf *env, long double *val) { if (env->flags & LL) *val = (long long)*val; if (env->flags & L) *val = (long)*val; else if (env->flags & BIGL) *val = (long double)*val; else if (env->flags & J) *val = (long long)*val; else if (env->flags & Z) *val = (size_t)*val; else *val = (double)*val; env->flags = correct_flags(*val, env); } void correct_umodif(t_printf *env, unsigned long long *val) { if (env->type == 'U') *val = (unsigned long)*val; else if (env->type == 'p') *val = (unsigned long long)*val; else if (env->flags & HH) *val = (unsigned char)*val; else if (env->flags & H) *val = (unsigned short int)*val; else if (env->flags & LL) *val = (unsigned long long int)*val; else if (env->flags & L) *val = (unsigned long int)*val; else if (env->flags & J) *val = (unsigned long long)*val; else if (env->flags & Z) *val = (size_t)*val; else *val = (unsigned int)*val; env->flags = correct_flags(*val, env); } void zero(t_printf *env) { if (env->type != 'p') { if ((env->prec == 0 || env->prec == 1) && env->flags & PREC) env->flags |= NULPREC; if ((env->prec == 0 || env->prec == 1) && (env->flags & HASH) && (env->width == 0 || env->width == 1)) env->flags |= NULHASH; if (env->flags & PREF) { env->preflen = 0; env->flags &= ~PREF; } } }
C
#include <stdio.h> #include <stdlib.h> #include "Beer.h" static int g_nNumberOfBeers=0; /* Made static so it only can be accessed here */ /* g_ is for "global" */ struct Beer *addBeer(struct Beer *beer) { struct Beer *new_beer; /* Allocate space for new element/node: */ new_beer=(struct Beer *)malloc(sizeof(struct Beer)); /* Insert new element/beer before any other element: */ new_beer->next=beer; printf("Type: "); scanf("%s",new_beer->type); printf("Price: "); scanf("%f",&new_beer->price); printf("Percentage: "); scanf("%f",&new_beer->alc); printf("Amount [ml]: "); scanf("%f",&new_beer->ml); g_nNumberOfBeers++; /* We increment since we just added a beer */ return new_beer; } void seeBeers(struct Beer *beer) { struct Beer *tmp; int i; for (i=0; i<g_nNumberOfBeers; i++) { tmp=beer->next; printf("Type: %s\n",beer->type); printf("Price: %f\n",beer->price); printf("Percentage: %f\n",beer->alc); printf("Amount [ml]: %f\n",beer->ml); beer=tmp; } }
C
#include <func.h> #define n 10000000 int main(){ int shmid=shmget(1000,4096,0600|IPC_CREAT); ERROR_CHECK(shmid,-1,"shmget"); int *p=(int *)shmat(shmid,NULL,0); *p=0; if(!fork()){ printf("this is child process!\n"); for(int idx=0;idx<n;++idx){ *p=*p+1; } return 0; } else{ printf("this is parent process!\n"); for(int idx=0;idx<n;++idx){ *p=*p+1; } wait(NULL); printf("res = %d\n",*p); int ret; ret=shmctl(shmid,IPC_RMID,NULL); ERROR_CHECK(ret,-1,"shmctl"); return 0; } }
C
#include "Rasteron.h" #include "OS_Util.h" // Global Definitions GradientLattice lattice1 = { 3, 3, 0xFF0000FF, 0xFF00FF00 }; GradientLattice lattice2 = { 12, 12, 0xFFFF00FF, 0xFF00FFFF }; GradientLattice lattice3 = { 64, 64, 0xFF000000, 0xFFFFFFFF }; Rasteron_Image* solidImg; Rasteron_Image* randNoiseImg; Rasteron_Image* randNoiseImg2; void genImages() { solidImg = createSolidImg((ImageSize){ 1100, 1200 }, 0xFF73e5ff); randNoiseImg = createNoiseImg_white((ImageSize) { 1100, 1200 }, 0xFFFF0000, 0xFF0000FF); randNoiseImg2 = createNoiseImg_gradient((ImageSize) { 1100, 1200 }, lattice1); } void cleanup(){ deleteImg(solidImg); deleteImg(randNoiseImg); deleteImg(randNoiseImg2); } BITMAP bmap1, bmap2, bmap3; LRESULT CALLBACK wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hDC = GetDC(hwnd); RECT rect; switch (message) { case (WM_CREATE): { bmap1 = createWinBmap(randNoiseImg); bmap2 = createWinBmap(randNoiseImg2); } case (WM_PAINT): { drawWinBmap(hwnd, &bmap2); } case (WM_CLOSE): {} default: return DefWindowProc(hwnd, message, wParam, lParam); } return 0; } int main(int argc, char** argv) { // Genertation Step seedRandGen(); genImages(); // Event Loop createWindow(wndProc, "Noise"); eventLoop(); // Cleanup Step cleanup(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> /* A Handler for a temporary file created with write_temp_file. In this implementation it's just a file descripter */ typedef int temp_file_handle; /* Writes length bytes from BUFFER into a temporary file. The temporary file is immediately unlinked. Returns a handle to the temporary file */ temp_file_handle write_temp_file (char* buffer, size_t length) { /* Create the filename and file. The XXXXXX will be replaced with characters that make the filename unique*/ char temp_filename[] = "/tmp/temp_file.XXXXXX"; int fd = mkstemp (temp_filename); /* Unlink the file immediately, so that it will be removed when the file descriptor is closed. */ //unlink (temp_filename); /* Writes the number of bytes first. */ write (fd, &length, sizeof(length)); /* Now writing the data itself. */ write (fd, buffer, length); return fd; } /* Reads the content of file a temporary file*/ char* read_temp_file (temp_file_handle temp_file, size_t* length) { char* buffer; /* The TEMP_FILE handle is a file descriptor to the temporary file. */ int fd = temp_file; /* Rewind to the beginning of the file. */ lseek (fd, 0, SEEK_SET); /* Read the size of the data in the temporary file. */ read (fd, length, sizeof (*length)); /* Allocate a buffer and read the data. */ buffer = (char*) malloc (*length); read (fd, buffer, *length); /* Close the file descriptor, which will cause the temporary file to go away. */ close (fd); return buffer; } int main () { char* buffer = "#include <stdlib.h>/* Write the number of bytes to the file"; size_t len = 100000000; int i = write_temp_file (buffer, strlen(buffer)); printf ("Contents are :\n %s", read_temp_file (i, &len)); }
C
#include<stdio.h> void swap(int *p, int *q) { int tmp = *p; *p = *q; *q = tmp; } int main() { int a[] = {3, 0, 5, 1, 4, 6, 2, 9, 8, 7}; int i ,j; for(i = 0; i < 10; i++) { for(j = i + 1; j < 10;j++) { if(a[i] > a[j]){ swap(&a[i], &a[j]); } } } int k; for(k = 0; k < 10; k++) { printf("%d\n", a[k]); } return 0; }
C
#include<stdio.h> int main(){ int a[3][4]={{10,9,2,1},{12,1,11,3},{4,13,21,14}};//ʼά int min=a[0][0],row=1,column=1;//ʼҪõı for(int i=0;i<=2;i++){//ÿԪؽб for(int j=0;j<=3;j++){ if(a[i][j]<min){//ָСԪ min=a[i][j],row=i,column=j;//¼Ԫؼбꡢб } } } printf("min=%d, row=%d, column=%d.",min,row+1,column+1);// return 0; }
C
#include<stdio.h> int s[100],n,top=-1; void push() { int item; if(top<n-1) { printf("Enter the item to push to stack:-"); scanf("%d",&item); top++; s[top]=item; } else printf("STACK OVERFLOW"); } void pop() { int item; if(top<0) printf("STACK EMPTY"); else { item=s[top]; top--; printf("%d popped from stack",item); } } void peep() { int item; if(top<0) printf("STACK EMPTY"); else { item=s[top]; printf("%d is at the top of the stack",item); } } void status() { if(top<0) printf("\nSTACK EMPTY"); else if(top==n-1) printf("\nSTACK FULL"); else { printf("\nThere are %d element(s) in the stack\n",top+1); float p=(top+1)*100/n; printf("\nThe stack is %f per cent filled",p); printf("\n\nYou can add %d elements more\n\n",n-top-1); } } void display() { if(top<0) printf("\nSTACK EMPTY"); else { printf("Contents of the Stack are:-"); for(int i=0;i<=top;i++) printf("%d ",s[i]); } } void main() { printf("\n0.Set size of Stack\n1.Push\n2.Pop\n3.Peep\n4.Status\n5.Display\n6.Exit"); int o; printf("\nEnter the option:-"); scanf("%d",&o); switch(o) { case 0: printf("Enter the size of stack "); scanf("%d",&n); main(); break; case 1: push(); main(); break; case 2: pop(); main(); break; case 3: peep(); main(); break; case 4: status(); main(); break; case 5: display(); main(); break; case 6: printf("Exiting"); break; default: printf("INVLAID OPTION"); main(); break; } }
C
#include <setjmp.h> #include <stdio.h> static int i = 0; static jmp_buf buf; #define ASM {\ asm ("movl %%esp, %0" "\n\t" "movl %%ebp, %1"\ : "=r"(x), "=r"(y));\ }; static int x,y; int foo(){ ASM printf("x=%d || y=%d \n",x,y); int j; if (setjmp(buf)){ for (j=0; j<5; j++){ i++; } } else { for (j=0; j<5; j++){ i--; } printf("j=%d\n", &j); longjmp(buf,~0); } } int main(void){ ASM printf("x=%d || y=%d \n",x,y); foo(); ASM printf("x=%d || y=%d \n",x,y); }
C
// // strp.c // hls-lesson8 // // Created by liusong huang on 2019/5/7. // Copyright © 2019 liusong huang. All rights reserved. // #include "strp.h" void T1(){ void test1(); test1(); void test2(); test2(); int a=10; printf("\n"); // void test3(); // test3(); void test4(); test4(); void test5(); test5(); void test6(); test6(); void test7(); test7(); void test8(); test8(); void test9(); test9(); void test10(); test10(); } void test1(){ printf("输出二维数组的有关数据\n"); int a[3][4]={1,3,5,7,9,11,13,15,17,19,21,23}; printf("%d,%d\n",a,*a);//首行地址和0行0列地址 printf("%d,%d\n",a[0],*(a+0));//0行0列地址 printf("%d,%d",&a[0],&a[0][0]); printf("\n##################\n"); } void test2(){ int a[3][4]={1,3,5,7,9,11,13,15,17,19,21,23}; int *p; for (p=a[0]; p<a[0]+12; p++) { if ((p-a[0])%4==0) { //printf("\n"); //printf("%2d",p); //printf("%2d",a[0]); //printf("%2d",p-a[0]); //printf("%2d",(p-a[0])%4); printf("\n"); } printf("%4d",*p); } printf("\n"); } void test3(){ int a[3][4]={1,3,5,7,9,11,13,15,17,19,21,23}; int (*p)[4],i,j; p=a; printf("please enter row and colum:\n"); scanf("%d,%d",&i,&j); printf("a[%d,%d]=%d\n",i,j,(*(p+i)+j)); } void test4(){ printf("\n"); int a[4]={1,3,5,7};//定义一个一位数组a,包含4个元素 int (*p)[4];//定义指向包含4个元素的一位数组的指针变量 p=&a;//p指向一位数组 printf("%d\n",(*p)[3]);//输出a[3] 输出证书7 } void test5(){ void average(float *p,int n); void search(float (*p)[4],int n); float score[3][4]={ {65,67,70,60}, {80,87,90,81}, {90,99,100,98} }; average(*score, 12); search(score, 2); search(score,1); search(score,0); } void average(float *p,int n){ float *p_end; float sum=0,aver; p_end=p+n-1; for (; p<=p_end; p++) { sum=sum+(*p); } aver=sum/n; printf("average=%5.2f\n",aver); } void search(float (*p)[4],int n){ int i; printf("the score of No.%d are:\n",n); for (i=0; i<4; i++) { printf("%7.2f",*(*(p+n)+i)); } printf("\n"); } void test6(){ char string[]="I love China!"; printf("%s\n",string); printf("%c\n",string[7]); //定义一个字符指针变量输出该字符 printf("定义一个字符指针变量\n"); char *string1="I love China!"; printf("%s\n",string1); printf("定义一个字符指针变量\n"); char *string3; string3="I love China!"; string3="I am a student."; printf("%s\n",string3); printf("定义字符数组\n"); char a[]="I am student.",b[20]; int i; for (i=0; *(a+i)!='\0'; i++) { *(b+i)=*(a+i); } *(b+i)='\0';printf("string a is:%s\n",a); printf("string b is :%s"); for (i=0; b[i]!='\0'; i++) { printf("%c",b[i]); } printf("\n"); } void test7(){ printf("\n\n用指针处理\n"); char a[]="I am a boy.",b[20],*p1,*p2; p1=a;p2=b; for (; *p1!='\0'; p1++,p2++) { *p2=*p1; } *p2='\0'; printf("string a is:%s\n",a); printf("string b is:%s\n",b); } //字符数组作为函数参数 void test8(){ void copy_string1(char from[],char to[]); char a[]="I am teacher."; char b[]="You are a student."; printf("string a=%s\nString b=%s\n",a,b); printf("copy string a to string b:\n"); copy_string1(a,b); printf("\nstring a=%s\nstring b=%s\n",a,b); } void copy_string1(char from[],char to[]){ int i=0; while (from[i]!='\0') { to[i]=from[i]; i++; } to[i]='\0'; } //用字符型指针变量作为实参 void test9(){ printf("\n用字符型指针变量作为实参\n"); void copy_string2(char from[],char to[]); char a[]="I am a teacher."; char b[]="You are a student."; char * from=a,* to =b; printf("stringa=%s\nstringb=%s\n",a,b); printf("\ncopy string a to string b:\n"); copy_string2(from, to); printf("string a=%s\nstring b=%s\n",a,b); } void copy_string2(char from[],char to[]){ int i=0; while (from[i]!='\0') { to[i]=from[i]; i++; } to[i]='\0'; } //用字符指针变量作行参和实参数 void test10(){ void copy_string3(char *from,char *to); char *a="I am a teacher."; char b[]="You are a student."; char *p=b; printf("string a=%s\nstring b=%s\n",a,b); printf("\ncopy string a to string b:\n"); copy_string3(a, p); printf("string a=%s\nstring b=%s\n",a,b); } void copy_string3(char *from,char *to){ for (; *from!='\0'; from++,to++) { *to=*from; } *to='\0'; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_matrices.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmbatha <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/06 13:42:17 by mmbatha #+# #+# */ /* Updated: 2018/07/21 14:29:20 by mmbatha ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" static void ft_calc_matrix(t_point *point1, t_matrix *m, t_scope *scope) { double temp_x; double temp_y; double temp_z; point1->x_axis -= scope->centre.x_axis; point1->y_axis -= scope->centre.y_axis; temp_x = point1->x_axis * m->a1 + point1->y_axis * m->a2 + \ point1->z_axis * m->a3 + point1->size * m->a4; temp_y = point1->x_axis * m->b1 + point1->y_axis * m->b2 + \ point1->z_axis * m->b3 + point1->size * m->b4; temp_z = point1->x_axis * m->c1 + point1->y_axis * m->c2 + \ point1->z_axis * m->c3 + point1->size * m->c4; point1->x_axis = temp_x; point1->y_axis = temp_y; point1->z_axis = temp_z; point1->x_axis += scope->centre.x_axis; point1->y_axis += scope->centre.y_axis; } static void ft_calc_matrices(t_matrix *m, t_scope *scope) { int x; int y; y = 0; while (y < scope->map->length) { x = 0; while (x < (scope->map->lines[y]->length)) { ft_calc_matrix(scope->map->lines[y]->points[x], m, scope); x++; } y++; } } void ft_calc_rotation(t_scope *scope, double rotation, char axis) { t_matrix *m_rotation; if (axis == 'x') m_rotation = ft_matrix_rotation_x(rotation); else if (axis == 'y') m_rotation = ft_matrix_rotation_y(rotation); else m_rotation = ft_matrix_rotation_z(rotation); ft_calc_matrices(m_rotation, scope); free(m_rotation); } void ft_calc_translation(t_scope *scope, double x, double y, \ double z) { t_matrix *m_translation; m_translation = ft_matrix_translation(x, y, z); ft_calc_matrices(m_translation, scope); ft_get_centre(scope); free(m_translation); } void ft_calc_scale(t_scope *scope, double size) { t_matrix *m_transform; m_transform = ft_matrix_scale(size); ft_calc_matrices(m_transform, scope); free(m_transform); }
C
/* c4下,g++编译通过。如果没有通过,请在c4设置中,g++参数 -lm前添加-std=c++11 (注,前后有空格) */ /* 使用sdl自带方向键控制,有点不好控制,自己慢慢来 */ /* 这里仅提供模板,更多功能,自己添加,去下载我制作的apk吧! */ /* c4droid吧,TTHHR制作,改写时请保留原注释! */ #include<SDL/SDL_image.h> #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> #include<time.h> // 头文件 #define SCREEN_WIDTH 480 // 所使用的图片的宽,自己修改 #define SCREEN_HEIGHT 800 // 使用图片的高,自己修改 SDL_Rect clip[9]; // 用来存各个小图 SDL_Surface *s = NULL; // 加载的图片 int map[3][3]; // 和小图对应的二维数组,用来方便移动和判断 int a, b; // 空图的坐标 int i, j; // 用于循环的变量 bool quit = false; // 控制程序退出的变量 SDL_Surface *screen = NULL; // 屏幕指针 void picrand(); // 用来初始化小图数组,随机 bool judge(); // 判断是否赢了 void init() // 启动和初始化 { SDL_Init(SDL_INIT_EVERYTHING); // 启动sdl screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE); // 设置屏幕 clip[1] = { 0, 0, SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3}; clip[2] = { SCREEN_WIDTH / 3, 0, SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3}; clip[3] = { 2 *SCREEN_WIDTH / 3, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3}; clip[4] = { 0, SCREEN_HEIGHT / 3, SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3}; clip[5] = { SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3, SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3}; clip[6] = { 2 *SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3, SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3}; clip[7] = { 0, 2 * SCREEN_HEIGHT / 3, SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3}; clip[8] = { SCREEN_WIDTH / 3, 2 * SCREEN_HEIGHT / 3, SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3}; // 各小图的具体位置 clip[0] = { NULL, NULL, NULL, NULL}; // 留空的小图 picrand(); // 随机 } SDL_Surface *loadimg(char *str) // 加载优化图片 { SDL_Surface *loadimg = NULL; SDL_Surface *opti = NULL; loadimg = IMG_Load(str); if (loadimg != NULL) { opti = SDL_DisplayFormat(loadimg); SDL_FreeSurface(loadimg); } return opti; } void apply_surface(int x, int y, SDL_Surface * source, SDL_Surface * destination, SDL_Rect * clip = NULL) // 将小图粘贴到屏幕 { // Holds offsets SDL_Rect offset; // Get offsets offset.x = x; offset.y = y; // Blit SDL_BlitSurface(source, clip, destination, &offset); } void draw() { SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0x00, 0x00, 0x00)); // 将窗口填充黑色 for (i = 0; i <= 8; i++) { switch (i) { case 0: apply_surface(2 * SCREEN_WIDTH / 3, 2 * SCREEN_HEIGHT / 3, s, screen, &clip[map[2][2]]); break; case 1: apply_surface(0, 0, s, screen, &clip[map[0][0]]); break; case 2: apply_surface(SCREEN_WIDTH / 3, 0, s, screen, &clip[map[0][1]]); break; case 3: apply_surface(2 * SCREEN_WIDTH / 3, 0, s, screen, &clip[map[0][2]]); break; case 4: apply_surface(0, SCREEN_HEIGHT / 3, s, screen, &clip[map[1][0]]); break; case 5: apply_surface(SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3, s, screen, &clip[map[1][1]]); break; case 6: apply_surface(2 * SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3, s, screen, &clip[map[1][2]]); break; case 7: apply_surface(0, 2 * SCREEN_HEIGHT / 3, s, screen, &clip[map[2][0]]); break; case 8: apply_surface(SCREEN_WIDTH / 3, 2 * SCREEN_HEIGHT / 3, s, screen, &clip[map[2][1]]); break; default:; } // 安小图数组顺序来粘贴小图 } SDL_Flip(screen); // 更新屏幕 } int main(int argc, char *args[]) { SDL_Event event; // 定义一个事件变量 init(); // 启动,初始化 s = loadimg("background.jpg"); // 加载自己使用的图片 draw(); // 画出初始的图 while (quit == false) { if (SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) // 判断按键是什么 { case SDLK_UP: if (b + 1 != 3) // 把这个判断去掉会有大bug { map[b][a] = map[b + 1][a]; // 空图变目标图片 map[b + 1][a] = 0; // 目标图片变空 b++; // 完成小图位置互换 } break; case SDLK_DOWN: if (b - 1 != -1) { map[b][a] = map[b - 1][a]; map[b - 1][a] = 0; b--; } break; case SDLK_LEFT: if (a + 1 != 3) { map[b][a] = map[b][a + 1]; map[b][a + 1] = 0; a++; } break; case SDLK_RIGHT: if (a - 1 != -1) { map[b][a] = map[b][a - 1]; map[b][a - 1] = 0; a--; } break; default:; } draw(); // 移动完成后,重新画图 } else if (event.type == SDL_QUIT) { // Quit the program quit = true; } } quit = judge(); // 对移动后的数组进行判断 } SDL_FreeSurface(s); SDL_Quit(); // 退出sdl return 0; } void picrand() // 随机 { srand((int)time(NULL)); b = rand() % 3; a = b; map[b][2] = 0; for (i = 0; i != 3; i++) { for (j = 0; j != 3; j++) { if ((b == i) && (j == 2)) ; else { if (a >= 8) a = 0; a++; map[i][j] = a; } } } a = 2; // 因为要确定0代表的空图在哪,所以把a重新赋值2 } bool judge() { // 这是判断,我觉得一点点一点点的判断,程序运行比较快 if (map[0][0] == 1 && map[2][2] == 0) { if (map[0][1] == 2 && map[0][2] == 3) { if (map[1][0] == 4 && map[1][1] == 5) { if (map[1][2] == 6 && map[2][0] == 7) { if (map[2][1] == 8) { return true; } } } } } return false; }
C
/* threshcrypt ui.c * Copyright 2012 Ryan Castellucci <[email protected]> * This software is published under the terms of the Simplified BSD License. * Please see the 'COPYING' file for details. */ #include <termios.h> #include <unistd.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> /* for mlock */ #include <sys/mman.h> #include "common.h" #include "util.h" #include "ui.h" int load_term(struct termios *termios_p) { if (tcsetattr(fileno(stdin), TCSANOW, termios_p) != 0) { fprintf(stderr, "Failed to load terminal settings"); return -1; } return 0; } int save_term(struct termios *termios_p) { if (tcgetattr(fileno(stdin), termios_p) != 0) { fprintf(stderr, "Failed to save terminal settings"); return -1; } return 0; } #define get_pass_return(ret) i = ret; goto get_pass_return; int get_pass(char *pass, uint8_t pass_size, const char *prompt, const char *vprompt, const char *rprompt, int verify) { struct termios old_term, new_term; uint8_t i, j; int chr; char *vpass = sec_malloc(pass_size + sizeof(char)); assert(pass_size > 1); do { if (save_term(&old_term) != 0) { get_pass_return(-1); } new_term = old_term; fprintf(stderr, "%s", prompt); /* Turn off echo */ new_term.c_lflag &= ~ECHO; if (load_term(&new_term) != 0) { get_pass_return(-1); } i = 0; while (i < pass_size - 1) { chr = getchar(); if (chr >= 32 && chr <= 126) { pass[i] = chr; i++; } else if (chr == '\b' && i > 0) { /* backspace */ pass[i] = '\0'; i--; } else if (chr == '\n') { pass[i] = '\0'; break; } } /* restore echo */ if (load_term(&old_term) != 0) { get_pass_return(-1); } if (vprompt != NULL) { fprintf(stderr, "\033[0G\033[2K"); j = get_pass(vpass, pass_size, vprompt, NULL, NULL, 0); if (j != i || memcmp(pass, vpass, i) != 0) { MEMWIPE(vpass, pass_size); MEMWIPE(pass, pass_size); if (verify > 1) { fprintf(stderr, "%s\n", rprompt); verify--; } else { get_pass_return(-1); } } else { MEMWIPE(vpass, pass_size); assert(i == j); assert(i == strlen(pass)); get_pass_return(i); } } else { break; } } while (verify > 0); fprintf(stderr, "\n"); get_pass_return: sec_free(vpass); return i; } /* vim: set ts=2 sw=2 et ai si: */
C
#include <stdio.h> #include <stdlib.h> typedef struct fila{ int *queue; int size; int first; int last; } fila; int push(fila*damae, int value){ //printf("Value: %d\n",value); (damae)->last++; if(((damae)->last - (damae)->first)==((damae)->size)){ (damae)->size *= 2; int * newArray=(int *) malloc(sizeof(int)*(damae)->size); int i; for(i = damae->first;i < damae->last;i++){ newArray[i] = damae->queue[i]; } damae->queue = newArray; } (damae)->queue[(damae)->last] = value; //(damae)->queue[] return 1; } int pop(fila*damae){ if((damae)->last < (damae)->first){ return -1; }else{ int value = (damae)->queue[(damae)->first]; (damae)->first++; return value; } } void printList(fila*damae){ int i; for(i = (damae)->first;i<=(damae)->last;i++){ printf("%d ",(damae)->queue[i]); } } int main (void){ fila daputa; daputa.size=5; daputa.first=0; daputa.last=-1; daputa.queue = (int *) malloc(sizeof(int)*daputa.size); int i; for(i=0;i<50;i++){ push(&daputa,i); } printList(&daputa); }
C
#include <stdio.h> #include <string.h> int main (void) { char buff[256]; //car printf ("Do you have at least one car?\n"); fgets (buff, sizeof(buff), stdin); char answerCar; sscanf (buff, "%c", &answerCar); //hourse short hourse; printf ("How many hourses do you have?\n"); scanf ("%hd", &hourse); //parents printf ("Do your parents still alive?\n"); fgets (buff, sizeof(buff), stdin); char answerParents; sscanf (buff, "%c", &answerParents); //deposit long deposit; printf ("How many deposit do you have?\n"); scanf ("%ld", &deposit); //logical if ((answerCar == 'y') && (answerParents == 'y') && (hourse > 0) || (deposit >= 5000000)) { printf ("I will marry you!\n"); } else { printf ("please go away secantly!\n"); } return 0; }
C
#include<stdio.h> main() { int a=10,b=20,c=0,i; c=a^b; for(i=0;c;i++) c=c&c-1; printf("%d",i); }
C
// // Created by wahba on 12/05/2016. // #include "helper/readFile.h"//FULLY DOCUMENTED #include "helper/basic.h" #include "helper/dependant.h" #include "helper/common.h" //pre Define void enclosed (char img_in[50][50]); void outline (char img_in[50][50]); int main() { //--------the essential part!!------------- char img[50][50]; //create place holder //readFile(img); //put image in place holder //----------------------------------------- printf("Image processing program by M W."); menu(img); //system("pause"); //left over from development return 0; //done }; int menu_Loop(){ int choice_sel; //place holder for the selection printf( //print the menu text "\n\n" "1) Loadfile\n" "2) Display Image\n" "3) Calculate Area\n" "4) Calculate Perimeter\n" "5) Calculate Shape Factor\n" "6) find minimum enclosing rectangle\n" "7) find centroid\n" "8) Display Outline\n" "9) Exit\n\n\n\n\n"//multiple new lines for looks "Please make a selection: " ); scanf("%d",&choice_sel); //scanf returns user input to choice_sel return choice_sel; //choice_sel is then returned from the function } void menu(char img[50][50]){ int menu_on; //this is used as a program on off switch int selection; //place holder for the selection int file_read = 0; //image loaded token while(menu_on) { //program is a loop where the condition is the presence of menu_on selection = menu_Loop(); //call function menu_Loop which returns an int from choice_sel system("cls"); //clean terminal if ( selection > 9 ||selection == 0) { printf("-----invalid selection-----\n"); } //check for valid selection if (selection == 1) { if (readFile(img)==1){ file_read=1; //change the status of image read token }else { printf("-----input valid image-----\n"); // else say no valid image } } if (file_read!=1){ printf("-----no image selected-----\n"); } //check token and display warning if no image if (file_read == 1) { //check if there is an image loaded through token to allow extended functions if (selection == 2) { // rest of menu select display(img); } if (selection == 3) { printf("Area is:%i \n", calc_area(img)); } if (selection == 4) { printf("perimeter is:%i \n", calc_perimeter(img)); } if (selection == 5) { printf("SF is:%i \n", calc_SF(img)); } if (selection == 6) { enclosed(img); } if (selection == 7) { centroid(img); } if (selection == 8) { outline(img); } //this will continue on to the main where the program returns zero and exits } if (selection == 9) { //exit function is eperate from the extended function because we can exit in all circumstances menu_on = 0; //menu_on is zero no longer just menu_on // this results in the while loop stopping } } }
C
#define _CRTDBG_MAP_ALLOC #include <stdlib.h> //NULL strtod() #include <crtdbg.h> #include "leptjson.h" #include <assert.h> //assert() #include <errno.h> //errno, ERANGE, malloc(), realloc(), free() #include <ctype.h> //isdigit() #include <math.h> //HUGE_VAL #include <string.h> //memcpy() //ṩ14API,staticʵֿķװ //-----------------궨岿---------------- #ifndef LEPT_PARSE_STACK_INIT_SIZE #define LEPT_PARSE_STACK_INIT_SIZE 256 #endif //ַcַchַƶһλ #define EXPECT(c, ch)\ do {\ assert(*c->json==(ch));\ ++c->json;\ }while(0) //жchǷ1-9֮ #define ISDIGIT1TO9(ch) ((ch) <= '9' && '1' <= (ch)) #define ISHEX(ch) ( ((ch) <= '9' && '0' <= (ch)) || \ ((toupper(ch) <= 'F' && 'A' <= toupper(ch) ))) //JSONcջַch #define PUTC(c, ch) \ do {\ char* tem = (char*) lept_context_push(c, sizeof(char));\ *tem = (ch);\ }while(0) //Ҫı //Ϊ˴洢ַһstack, //topָջԪصһλãsizeʾջĿռС sizetopĵλֽ //ջΪtop==0, ջΪtop == size typedef struct { const char* json; char* stack; size_t size, top; }lept_context; //˿հ׷ ws = *(%x20 / %x09 / %x0A / %x0D) static void lept_filter_whitespace(lept_context* c) { const char* p = c->json; //òҪ<ctype.h>isspace() while(' ' == *p || '\t' == *p || '\n' == *p || '\r' == *p) { ++p; } c->json = p; } //null, true, false cΪjsonıvΪ֮jsonԪأ //literalΪԤڽַ typeΪɹ֮Ԫ static int lept_parse_literal(lept_context* c, lept_value* v, const char* literal, lept_type type) { size_t i; //ڴliteral[0]ͬʱ++c->json EXPECT(c, literal[0]); //УϷַLEPT_PARSE_INVALID_VALUE for(i = 0; literal[i + 1]; ++i) { if(c->json[i] != literal[i + 1]) { return LEPT_PARSE_INVALID_VALUE; } } c->json += i; v->type = type; return LEPT_PARSE_OK; } //number static int lept_parse_number(lept_context* c, lept_value* v) { const char* p = c->json; //----'-' if('-' == *p) { ++p; } //---- //ֻ0 if('0' == *p) { ++p; } else { //0ֵĵһֱΪ1-9 if(!ISDIGIT1TO9(*p)) { return LEPT_PARSE_INVALID_VALUE; } // for(++p; isdigit(*p); ++p); } //----С if('.' == *p) { ++p; //С֮󣬱һ if(!isdigit(*p)) { return LEPT_PARSE_INVALID_VALUE; } // for(++p; isdigit(*p); ++p); } //----ָ if('e' == *p || 'E' == *p) { ++p; if('+' == *p || '-' == *p) { ++p; } //e/E'+','-'֮Ҫһ if(!isdigit(*p)) { return LEPT_PARSE_INVALID_VALUE; } // for(++p; isdigit(*p); ++p); } v->type = LEPT_NUMBER; errno = 0; //-----------------------עֱstrtod()Ὣ಻ϷֵͶȷת ////endstrtod()Ƿɹ,Գɹȥ /*char* end; v->num = strtod(c->json, &end); if(c->json == end) { return LEPT_PARSE_INVALID_VALUE; } c->json = end;*/ //------------------------- v->uni.num = strtod(c->json, NULL); //errnoΪERANGEdzΧǣ //HUGE_VAL == v->num || -HUGE_VAL == v->numȷinf //Ǹ -inf if(errno == ERANGE && (HUGE_VAL == v->uni.num || -HUGE_VAL == v->uni.num)) { return LEPT_PARSE_NUMBER_TOO_BIG; } c->json = p; return LEPT_PARSE_OK; } //cջszջÿ1.5ռ䣬ֱҪ //ֵ֮ǰջջһԪ //c->stackָû䣬 //c->szջʱ򣬻ӣʱ򣬲䡣 //c->topı䡣 static void* lept_context_push(lept_context* c, size_t sz) { void* ret; assert(0 < sz); if(c->size <= c->top + sz) { if(0 == c->size) { c->size = LEPT_PARSE_STACK_INIT_SIZE; } while(c->size <= c->top + sz) { //ȼc->size*=1.5; c->size += c->size >> 1; } c->stack = (char*)realloc(c->stack, c->size); } ret = c->stack + c->top; c->top += sz; return ret; } //ܣɾszջԪ //ջԪظڴɾĸ //ɾ֮ջԪصһλ static void* lept_context_pop(lept_context* c, size_t sz) { assert(sz <= c->top); c->top -= sz; return c->stack + c->top; } ///uXXXXġXXXXֵ֣浽*u static const char* lept_parse_hex4(const char* p, unsigned int* u) { unsigned int sum = 0; int i = 0; for(; i < 4 && ISHEX(p[i]); ++i) { sum <<= 4; if(isdigit(p[i])) { sum += p[i] - '0'; } else { sum += toupper(p[i]) - 'A' + 10; } } *u = sum; return (i < 4) ? NULL : p + i; } //UnicodeַUTF8ı뷽б static void lept_encode_utf8(lept_context* c, unsigned int uInt) { if(uInt < 0x0080) { PUTC(c, uInt & 0xFF); } else if(uInt < 0x0800) { PUTC(c, 0xC0 | ((uInt >> 6) & 0xFF)); PUTC(c, 0x80 | (uInt & 0x3F)); } else if(uInt < 0x10000) { PUTC(c, 0xE0 | ((uInt >> 12) & 0xFF)); PUTC(c, 0x80 | ((uInt >> 6) & 0x3F)); PUTC(c, 0x80 | (uInt & 0x3F)); } else { assert(uInt <= 0x10FFFF); PUTC(c, 0xF0 | ((uInt >> 18) & 0xFF)); PUTC(c, 0x80 | ((uInt >> 12) & 0x3F)); PUTC(c, 0x80 | ((uInt >> 6) & 0x3F)); PUTC(c, 0x80 | (uInt & 0x3F)); } } #define STRING_ERROR(ret) \ do{\ c->top = head;\ return ret;\ }while(0) //عstringԪ //ԭstringַJSONstringһ֣漰lept_value* vĸֵ static int lept_parse_string_raw(lept_context* c, char** s, size_t* l) { //ע˴headΪheadܲΪ0ʱcջѾԪأheadܲΪ0 size_t head = c->top, len; unsigned int uInt = 0, uInt2 = 0; const char* p; EXPECT(c, '\"'); p = c->json; while(1) { char ch = *p++; switch(ch) { case '\"': //սβַ len = c->top - head; const char* topLink = (const char*)lept_context_pop(c, len); *l = len; *s = (char*)malloc(len + 1); memcpy((void*)*s, topLink, len); (*s)[len] = '\0'; c->json = p; return LEPT_PARSE_OK; case '\\': //תַ switch(*p++) { case '\"': PUTC(c, '\"'); break; case '\\': PUTC(c, '\\'); break; case '/': PUTC(c, '/'); break; case 'b': PUTC(c, '\b'); break; case 'f': PUTC(c, '\f'); break; case 'n': PUTC(c, '\n'); break; case 'r': PUTC(c, '\r'); break; case 't': PUTC(c, '\t'); break; case 'u': //'\u'׼Unicodeַ p = lept_parse_hex4(p, &uInt); if(NULL == p) { STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_HEX); } //uInt[0xD800, 0xDBFF]ΧַΪǸߴдԵĽ //ߴΧ[0xD800, 0xDBFF]ʹΧ[0xDC00, 0xDFFF] if(uInt <= 0xDBFF && 0xD800 <= uInt) { if(*p != '\\' || *(p + 1) != 'u') { STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_SURROGATE); } p += 2; p = lept_parse_hex4(p, &uInt2); if(NULL == p) { STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_HEX); } if(uInt2 < 0xDC00 || 0xDFFF < uInt2) { STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_SURROGATE); } uInt = (((uInt - 0xD800) << 10) | (uInt2 - 0xDC00)) + 0x10000; } lept_encode_utf8(c, uInt); break; //Ƿתַ default: STRING_ERROR(LEPT_PARSE_INVALID_STRING_ESCAPE); } break; case '\0': //ȱٽβ STRING_ERROR(LEPT_PARSE_MISS_QUOTATION_MARK); default: //ASCIIֵС0x20ΪǷǷַ if((unsigned char)ch < 0x20) { STRING_ERROR(LEPT_PARSE_INVALID_STRING_CHAR); } //Question:޼ַ PUTC(c, ch); } } } //stringԪ static int lept_parse_string(lept_context* c, lept_value* v) { int ret; char* s; size_t len; ret = lept_parse_string_raw(c, &s, &len); if(LEPT_PARSE_OK == ret) { lept_set_string(v, s, len); //NOTE:ͷsڴй© free(s); } return ret; } //ǰΪlept_parse_arrayǰlept_parse_value static int lept_parse_value(lept_context* c, lept_value* v); //arrayԪ //array = %x5B ws [ value *( ws %x2C ws value ) ] ws %x5D static int lept_parse_array(lept_context* c, lept_value* v) { size_t size = 0; size_t i; int ret; EXPECT(c, '['); //˿հ׷ lept_filter_whitespace(c); if(']' == *c->json) { ++c->json; v->type = LEPT_ARRAY; v->uni.arr.size = 0; v->uni.arr.e = NULL; return LEPT_PARSE_OK; } while(1) { lept_value val; lept_init(&val); ret = lept_parse_value(c, &val); if(LEPT_PARSE_OK != ret) { ////Question : sz0ᱨ //lept_context_pop(c, size * sizeof(lept_value)); //return ret; break; } //sizeof(lept_value)СĿռѾarrеԪ memcpy(lept_context_push(c, sizeof(lept_value)), &val, sizeof(lept_value)); //һԪ ++size; lept_filter_whitespace(c); if(',' == *c->json) { ++c->json; lept_filter_whitespace(c); } else if(']' == *c->json) { ++c->json; v->type = LEPT_ARRAY; v->uni.arr.size = size; //sizeʾԪصĸ szʾԪռռĴС int sz = size * sizeof(lept_value); //JSONԪvָszСռ䣬sizelept_valueԪأʱδֵ v->uni.arr.e = (lept_value*)malloc(sz); //JSONĵcջtopsz,ͬʱcջֵv->uni.arr.eָĿռ memcpy((void*)v->uni.arr.e, lept_context_pop(c, sz), sz); return LEPT_PARSE_OK; } else { //ȱٶԼҷ //磺'\0', '{' ret = LEPT_PARSE_MISS_COMMA_OR_SQUARE_BRACKET; break; } } //NOTE:sizeΪ0 for(i = 0; i < size; ++i) { lept_free((lept_value*)lept_context_pop(c, sizeof(lept_value))); } return ret; } //ͷųԱ static void lept_free_member(lept_member* m); //objectԪ static int lept_parse_object(lept_context* c, lept_value* v) { size_t i, size = 0; size_t sz; lept_member member; int ret; EXPECT(c, '{'); lept_filter_whitespace(c); //1'}', Ϊնֱӷ, size=0 if('}' == *c->json) { ++c->json; v->type = LEPT_OBJECT; v->uni.obj.m = NULL; v->uni.obj.size = 0; return LEPT_PARSE_OK; } member.key = NULL; while(1) { lept_init(&member.val); //2Ƚؼ֣ڴ'"'ûг'"',ret = LEPT_PARSE_MISS_KEY; if('\"' != *c->json) { ret = LEPT_PARSE_MISS_KEY; break; } ret = lept_parse_string_raw(c, &member.key, &member.keyLen); if(LEPT_PARSE_OK != ret) { break; } lept_filter_whitespace(c); if(':' != *c->json) { ret = LEPT_PARSE_MISS_COLON; break; } ++c->json; lept_filter_whitespace(c); ret = lept_parse_value(c, &member.val); if(LEPT_PARSE_OK != ret) { break; } memcpy(lept_context_push(c, sizeof(lept_member)), &member, sizeof(lept_member)); //ˣһĽɹsize+1 ++size; //member.keyʼ member.key = NULL; lept_filter_whitespace(c); if(',' == *c->json) { ++c->json; lept_filter_whitespace(c); } else if('}' == *c->json) { ++c->json; v->type = LEPT_OBJECT; v->uni.obj.size = size; sz = size * sizeof(lept_member); v->uni.obj.m = (lept_member*)malloc(sz); memcpy((void *)v->uni.obj.m, lept_context_pop(c, sz), sz); return LEPT_PARSE_OK; } else { ret = LEPT_PARSE_MISS_COMMA_OR_CURLY_BRACKET; break; } } //NOTE:,ͷkey free(member.key); for(i = 0; i < size; ++i) { lept_free_member((lept_member*)lept_context_pop(c, sizeof(lept_member))); } return ret; } //json ---ַȷjsonͷ static int lept_parse_value(lept_context* c, lept_value* v) { switch(*c->json) { case 'n': //Խnull return lept_parse_literal(c, v, "null", LEPT_NULL); case 't': //Խtrue return lept_parse_literal(c, v, "true", LEPT_TRUE); case 'f': //Խfalse return lept_parse_literal(c, v, "false", LEPT_FALSE); case '\0': //JSONַΪΪ return LEPT_PARSE_EXPECT_VALUE; case '\"': //Խstring return lept_parse_string(c, v); case '[': //Խarray return lept_parse_array(c, v); case '{': //Խobject return lept_parse_object(c, v); default: //Ϸַ---ʱΪnumberͣȻе⣩ return lept_parse_number(c, v); } } //jsonı int lept_parse(lept_value* v, const char* json) { lept_context cntxt; int ret; //vΪ assert(NULL != v); //ʼcеjsonıָ룬ջָ룬ջռСѶ cntxt.json = json; cntxt.stack = NULL; cntxt.size = cntxt.top = 0; //ǰĿհ׷ lept_filter_whitespace(&cntxt); //cntxtϢret ret = lept_parse_value(&cntxt, v); if(LEPT_PARSE_OK == ret) { //˿հ׷ lept_filter_whitespace(&cntxt); //cntxtıȻڴı if(*cntxt.json) { ret = LEPT_PARSE_ROOT_NOT_SINGULAR; } } if(LEPT_PARSE_OK != ret) { v->type = LEPT_ERROR; } //ֹڴй© assert(0 == cntxt.top); free(cntxt.stack); return ret; } //JSON lept_type lept_get_type(const lept_value* v) { assert(NULL != v); return v->type; } //ͷųԱ static void lept_free_member(lept_member* m) { assert(NULL != m); free(m->key); lept_free(&m->val); } //ͷJSONԪռõĿռ䣬ԪΪLEPT_ERROR void lept_free(lept_value* v) { assert(NULL != v); size_t i; switch(v->type) { //vstringֱͷſռ case LEPT_STRING: free(v->uni.str.s); break; //varrayݹͷԪصĿռ case LEPT_ARRAY: for(i = 0; i < v->uni.arr.size; ++i) { lept_free(v->uni.arr.e + i); } free(v->uni.arr.e); break; case LEPT_OBJECT: for(i = 0; i < v->uni.obj.size; ++i) { lept_free_member(v->uni.obj.m + i); } free(v->uni.arr.e); default: break; } v->type = LEPT_ERROR; } //----------------ȡJSONԪֵJSONԪֵĽӿ--------- int lept_get_null(const lept_value* v) { assert(NULL != v && (LEPT_NULL == v->type)); return v->type; } void lept_set_null(lept_value* v) { lept_free(v); v->type = LEPT_NULL; } int lept_get_boolean(const lept_value* v) { assert(NULL != v && (LEPT_TRUE == v->type || LEPT_FALSE == v->type)); return v->type; } void lept_set_boolean(lept_value* v, int b) { lept_free(v); v->type = b ? LEPT_TRUE : LEPT_FALSE; } double lept_get_number(const lept_value* v) { assert(NULL != v&&LEPT_NUMBER == v->type); return v->uni.num; } void lept_set_number(lept_value* v, double num) { //˴vΪǿագlept_free(v)ᱨ lept_free(v); v->uni.num = num; v->type = LEPT_NUMBER; } const char* lept_get_string(const lept_value* v) { assert(NULL != v&& LEPT_STRING == v->type); return v->uni.str.s; } size_t lept_get_string_length(const lept_value* v) { assert(NULL != v && LEPT_STRING == v->type); return v->uni.str.len; } void lept_set_string(lept_value* v, const char* s, size_t len) { assert(s != NULL || 0 == len); lept_free(v); v->uni.str.s = (char*)malloc(len + 1); memcpy(v->uni.str.s, s, len); v->uni.str.s[len] = '\0'; v->uni.str.len = len; v->type = LEPT_STRING; } lept_value* lept_get_array_element(const lept_value* v, size_t index) { assert(NULL != v&&LEPT_ARRAY == v->type&&index < v->uni.arr.size); return &v->uni.arr.e[index]; } size_t lept_get_array_size(const lept_value* v) { assert(NULL != v &&LEPT_ARRAY == v->type); return v->uni.arr.size; } const char* lept_get_object_key(const lept_value* v, size_t index) { assert(NULL != v&&LEPT_OBJECT == v->type); assert(index < v->uni.obj.size); return v->uni.obj.m[index].key; } size_t lept_get_object_key_length(const lept_value* v, size_t index) { assert(NULL != v&&LEPT_OBJECT == v->type); assert(index < v->uni.obj.size); return v->uni.obj.m[index].keyLen; } lept_value* lept_get_object_value(const lept_value* v, size_t index) { assert(NULL != v&&LEPT_OBJECT == v->type); assert(index < v->uni.obj.size); return &v->uni.obj.m[index].val; } size_t lept_get_object_size(const lept_value* v) { assert(NULL != v&&LEPT_OBJECT == v->type); return v->uni.obj.size; }
C
#include<stdio.h> #include<stdlib.h> #include "hdr/107_sorting.h" int a[7][7] = { {0,16,12,21,0,0,0}, {16,0,0,17,20,0,0}, {12,0,0,28,0,31,0}, {21,17,28,0,18,19,23}, {0,20,0,18,0,0,11}, {0,0,31,19,0,0,27}, {0,0,0,23,11,27,0} }; int main() { int i,j; int** p; struct ans b; p = malloc(7*sizeof(int *)); for(i=0;i<7;i++) { p[i] = malloc(7*sizeof(int)); for(j=0;j<7;j++) p[i][j] = a[i][j]; } b = get_edges(p, 7); sort_edges_by_weight(b.e, b.size); for(i=0;i<b.size;i++) printf("%d ", b.e[i].w); printf("\n"); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <signal.h> #include <unistd.h> #include "window.h" #include "io_functions.h" #include "db.h" /* Struct encapsulating information about a client */ typedef struct Client { Window *window; // The client window pthread_t thread; } Client; // Global variables Database *db; char *scriptname; typedef struct node { pthread_t thread; struct node *next; } node; node *root; void LLadd(pthread_t new); int LLrem(Client *client); // Forward declarations Client *client_new(int id); void client_delete(Client *client); void *run_client(void *client); void process_command(char *command, char *response); int threadcount; int stopped; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mute = PTHREAD_MUTEX_INITIALIZER; /*********************************** * Main function ***********************************/ int main(int argc, char **argv) { if(argc == 1) { scriptname = NULL; } else if(argc == 2) { int len = strlen(argv[1]); scriptname = malloc(len+1); strncpy(scriptname, argv[1], len+1); } else { fprintf(stderr, "Usage: %s [scriptname]\n", argv[0]); exit(1); } threadcount = 0; stopped = 0; // Ignore SIGPIPE struct sigaction ign; ign.sa_handler = SIG_IGN; sigemptyset(&ign.sa_mask); ign.sa_flags = SA_RESTART; sigaction(SIGPIPE, &ign, NULL); db = db_new(); char test[1024]; int i = 0; for(i = 0; i < 1024; i++) { test[i] = '\0'; } int reset = 0; Client *client; int counter = 0; while(reset==0) { int check = read(STDIN_FILENO, test, 1024); if(check==0) { break; } if(test[0]=='\n') { if(!(client = client_new(counter))) { fprintf(stderr, "Could not create client\n"); exit(1); } counter++; } else { if(strlen(test)==2) { if(test[0]=='s') { if(stopped==1) { puts("already stopped"); } else { pthread_mutex_lock(&mute); stopped = 1; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mute); puts("stop"); } } else if(test[0]=='g') { if(stopped==1) { pthread_mutex_lock(&mute); stopped = 0; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mute); puts("go"); } else { puts("not stopped"); } } else { puts("not a commmand"); } } else { puts("not a commmand"); } } } while(threadcount > 0) { //do nothing; } db_delete(db); free(scriptname); pthread_exit(0); } void LLadd(pthread_t new) { node *newnode = malloc(sizeof(node)); newnode->thread = new; newnode->next = NULL; if(root) { node *iter; iter = root; while(iter->next) { iter = iter->next; } iter->next = newnode; } else { root = newnode; } } int LLrem(Client *client) { pthread_t del = client->thread; node *iter = root->next; node *prev = root; if(root->thread==del) { root = iter; free(prev); return 0; } else { while(iter) { if(iter->thread==del) { prev->next = iter->next; free(iter); return 0; } else { iter = iter->next; prev = prev->next; } } puts("Thread not found in Linked List, SHOULD NEVER HAPPEN!"); return 1; } } /*********************************** * Client handling functions ***********************************/ /* Create a new client */ Client *client_new(int id) { Client *client = (Client *)malloc(sizeof(Client)); if(!client) { perror("malloc"); return NULL; } pthread_t test; // Create a window and set up a communication channel with it char title[20]; sprintf(title, "Client %d", id); if(!(client->window = window_new(title, scriptname))) { free(client); return NULL; } pthread_create(&test, 0, run_client, client); client->thread = test; LLadd(test); pthread_detach(test); threadcount++; return client; } /* Delete a client and all associated resources */ void client_delete(Client *client) { window_delete(client->window); LLrem(client); free(client); } /* Function executed for a given client */ void *run_client(void *client) { char command[BUF_LEN]; char response[BUF_LEN]; // Main loop of the client: fetch commands from window, interpret // and handle them, and send results to window. while(get_command(((Client *)client)->window, command)) { pthread_mutex_lock(&mute); while(stopped!=0) pthread_cond_wait(&cond, &mute); pthread_mutex_unlock(&mute); process_command(command, response); if(!send_response(((Client *)client)->window, response)) break; } fprintf(stderr, "Quitting Client\n"); client_delete(((Client *)client)); threadcount--; return NULL; } /*********************************** * Command processing functions ***********************************/ char *skip_ws(char *str); char *skip_nonws(char *str); void next_word(char **curr, char **next); /* Process the given command and produce an appropriate response */ void process_command(char *command, char *response) { char *curr; char *next = command; next_word(&curr, &next); if(!*curr) { strcpy(response, "no command"); } else if(!strcmp(curr, "a")) { next_word(&curr, &next); char *name = curr; next_word(&curr, &next); if(!*curr || *(skip_ws(next))) { strcpy(response, "ill-formed command"); } else if(db_add(db, name, curr)) { strcpy(response, "added"); } else { strcpy(response, "already in database"); } } else if(!strcmp(curr, "q")) { next_word(&curr, &next); if(!*curr || *(skip_ws(next))) { strcpy(response, "ill-formed command"); } else if(!db_query(db, curr, response, BUF_LEN)) { strcpy(response, "not in database"); } } else if(!strcmp(curr, "d")) { next_word(&curr, &next); if(!*curr || *(skip_ws(next))) { strcpy(response, "ill-formed command"); } else if(db_remove(db, curr)) { strcpy(response, "deleted"); } else { strcpy(response, "not in database"); } } else if(!strcmp(curr, "p")) { next_word(&curr, &next); if(!*curr || *(skip_ws(next))) { strcpy(response, "ill-formed command"); } else { FILE *foutput = fopen(curr, "w"); if (foutput) { db_print(db, foutput); fclose(foutput); strcpy(response, "done"); } else { strcpy(response, "could not open file"); } } } else if(!strcmp(curr, "f")) { next_word(&curr, &next); if(!*curr || *(skip_ws(next))) { strcpy(response, "ill-formed command"); } else { FILE *finput = fopen(curr, "r"); if(finput) { while(fgets(command, BUF_LEN, finput) != 0) process_command(command, response); fclose(finput); strcpy(response, "file processed"); } else { strcpy(response, "could not open file"); } } } else { strcpy(response, "invalid command"); } } /* Advance pointer until first non-whitespace character */ char *skip_ws(char *str) { while(isspace(*str)) str++; return str; } /* Advance pointer until first whitespace or null character */ char *skip_nonws(char *str) { while(*str && !(isspace(*str))) str++; return str; } /* Advance to the next word and null-terminate */ void next_word(char **curr, char **next) { *curr = skip_ws(*next); *next = skip_nonws(*curr); if(**next) { **next = 0; (*next)++; } }
C
#define TAB_SIZE 4 extern char filename[50]; extern int NOL; extern char** CODE; extern int CURSOR[2]; void replaceTabWithSpaces(); void preprocessing(); void replaceTabWithSpaces(){ int i; for(i=0; i<NOL; i++){ int index = strpos(CODE[i],"\t",0); if(index == -1) continue; substrDelete(CODE[i],index,index+1); int j; for(j=0; j<TAB_SIZE; j++) substrInsert(CODE[i]," ",index); } } void preprocessing(){ saveDefaultAttributes(); selectCompiler(); if(!isFileExists(filename)) writeString(" ",filename);//Creates an empty file CODE = readArrayOfStrings(filename); replaceTabWithSpaces(); CURSOR[0] = 0; editFile(); }
C
/* * Morris preorder traversal */ #include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct bstnode { struct bstnode *left; struct bstnode *right; int val; } bstnode_t; bstnode_t * make_bstnode(int val) { bstnode_t *node = calloc(1, sizeof(bstnode_t)); node->val = val; return node; } bstnode_t * insert_bst(bstnode_t *root, int val) { bstnode_t *node = make_bstnode(val); bstnode_t *current, *prev = NULL; if(root == NULL) { return node; } current = root; while(current) { if(current->val <= val) { prev = current; current = current->right; continue; } prev = current; current = current->left; } if(prev->val <= val) { prev->right = node; } else { prev->left = node; } return root; } void morris_preorder(bstnode_t *root) { bstnode_t *current, *pred; current = root; while(current) { /* * If there is no left sub-tree for this node, print the * value at this node and then go its right sub-tree. */ if(current->left == NULL) { printf(" %d ", current->val); current = current->right; } else { /* * There is a left sub-tree for 'current'. We can find * inorder predecessor for 'current' in its left * sub-tree. */ pred = current->left; while(pred->right != NULL && pred->right != current) { pred = pred->right; } /* * Now 'pred' is the inorder predecessor of 'current'. * After pre-order traversing current's left sub-tree, * we need to come to 'current' to continue, so link * up pred and current, make pred's right to point * to current. We knew that pred's right will be NULL. * Unless, we already did this link-up in the previous * iteration, now it's time to destroy that fake link. */ if(pred->right == NULL) { //printf("Temp link established between %d and %d\n", // pred->val, current->val); pred->right = current; /* * Since this is pre-order, print current's value * before venturing further into its left sub-tree. */ printf(" %d ", current->val); current = current->left; } else { //printf("Temp link destroyed between %d and %d\n", // pred->val, current->val); /* * Destroy the fake link between this node and its * successor. */ pred->right = NULL; /* * We pre-order traversed 'current' and its * left-subtree, time to move onto its right * sub-tree. */ current = current->right; } } } return; } void destroy_tree(bstnode_t *root) { if(root == NULL) return; destroy_tree(root->left); destroy_tree(root->right); free(root); return; } #define MIN(A, B) ((A) < (B) ? (A) : (B)) int main(int argc, char *argv[]) { bstnode_t *root = NULL; int i, *resultp = NULL, resultsz; int low, high; int arr[] = {4, 2, 1, 3, 6, 5, 7}; srand(time(NULL)); for(i = 0; i < 7; i++) { root = insert_bst(root, arr[i]);//rand() % 77); } morris_preorder(root); printf("\n"); #if 0 low = rand() % 100; high = low + rand() % 100; printf("Range query results for range: [%d %d]:\n", low, high); range_query(root, low, high); printf("\n"); /*for(i = 0; i < resultsz; i++) { printf(" %d ", result[i]); } printf("\n"); if(result) { free(result); } */ #endif destroy_tree(root); return 0; }
C
#include <stdio.h> int main(void) { int a[] = {5, 15, 34, 54, 14, 2, 52, 72}; int *p; p = a; /* printf("%d\n", p == a[0]); illegal: mismatched types */ printf("%d\n", p == &a[0]); /* true */ printf("%d\n", *p == a[0]); /* true */ printf("%d\n", p[0] == a[0]); /* true */ }
C
#include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <semaphore.h> #include <sys/types.h> #include <unistd.h> #define check_error(expr, msg) \ do { \ if(!(expr)){ \ fprintf(stderr, "%s\n", msg); \ exit(EXIT_FAILURE); \ } \ } while(0) #define ARRAY_MAX (256) typedef struct { sem_t inDataReady; int array[ARRAY_MAX]; unsigned arrayLen; } osData; void *getMemBlock(const char *path, unsigned *size); int main(int argc, char **argv) { check_error(argc == 3, "argc"); unsigned sizeIn = 0; unsigned sizeOut = 0; osData *inData = getMemBlock(argv[1], &sizeIn); osData *outData = getMemBlock(argv[2], &sizeOut); check_error(sem_wait(&(inData->inDataReady)) != -1, "sem_wait"); int *out = outData->array; int *in = inData->array; int n = (int)inData->arrayLen; int j = 0; for(int i = 0; i < n; i++) { int current = in[i]; int original = current; int ones = 0; do { if(current % 2 == 1) ones++; current /= 2; }while(current != 0); if(ones >= 4) { out[j] = original; j++; } } outData->arrayLen = j; /*printf("%d\n", j); for(int i = 0; i < j; i++) { printf("%d ", out[i]); }*/ check_error(sem_post(&(outData->inDataReady)) != -1, "sem_post"); check_error(munmap(inData, sizeIn) != -1, "munmap"); check_error(munmap(outData, sizeOut) != -1, "munmap"); //check_error(shm_unlink(argv[1]) != -1, "shm_unkink"); return 0; } void *getMemBlock(const char *path, unsigned *size) { int memFd = shm_open(path, O_RDWR, 0600); check_error(memFd != -1, "shm_open"); struct stat fInfo; check_error(fstat(memFd, &fInfo) != -1, "fstat"); *size = fInfo.st_size; void *addr; check_error((addr = mmap(0, *size, PROT_READ | PROT_WRITE, MAP_SHARED, memFd, 0)) != MAP_FAILED, "mmap"); close(memFd); return addr; }
C
/* 把字符串看做指针 */ #include <stdio.h> int main(int argc, char const *argv[]) { printf("%s, %p, %c\n", "We", "are", *("space faters" + 1)); getchar(); return 0; }
C
/* * $XConsortium: XTextExt.c,v 11.24 89/12/11 19:10:40 rws Exp $ * * Copyright 1989 Massachusetts Institute of Technology */ #include "Xlibint.h" #define min_byte2 min_char_or_byte2 #define max_byte2 max_char_or_byte2 /* * CI_GET_ROWZERO_CHAR_INFO_2D - do the same thing as CI_GET_CHAR_INFO_1D, * except that the font has more than one row. This is special case of more * general version used in XTextExt16.c since row == 0. This is used when * max_byte2 is not zero. A further optimization would do the check for * min_byte1 being zero ahead of time. */ #define CI_GET_ROWZERO_CHAR_INFO_2D(fs,col,def,cs) \ { \ cs = def; \ if (fs->min_byte1 == 0 && \ col >= fs->min_byte2 && col <= fs->max_byte2) { \ if (fs->per_char == NULL) { \ cs = &fs->min_bounds; \ } else { \ cs = &fs->per_char[(col - fs->min_byte2)]; \ if (CI_NONEXISTCHAR(cs)) cs = def; \ } \ } \ } /* * XTextExtents - compute the extents of string given as a sequences of eight * bit bytes. Since we know that the input characters will always be from the * first row of the font (i.e. byte1 == 0), we can do some optimizations beyond * what is done in XTextExtents16. */ #if NeedFunctionPrototypes XTextExtents ( XFontStruct *fs, const char *string, int nchars, int *dir, /* RETURN font information */ int *font_ascent, /* RETURN font information */ int *font_descent, /* RETURN font information */ register XCharStruct *overall) /* RETURN character information */ #else XTextExtents (fs, string, nchars, dir, font_ascent, font_descent, overall) XFontStruct *fs; char *string; int nchars; int *dir, *font_ascent, *font_descent; /* RETURN font information */ register XCharStruct *overall; /* RETURN character information */ #endif { int i; /* iterator */ Bool singlerow = (fs->max_byte1 == 0); /* optimization */ int nfound = 0; /* number of characters found */ XCharStruct *def; /* info about default char */ unsigned char *us; /* be 8bit clean */ if (singlerow) { /* optimization */ CI_GET_DEFAULT_INFO_1D (fs, def); } else { CI_GET_DEFAULT_INFO_2D (fs, def); } *dir = fs->direction; *font_ascent = fs->ascent; *font_descent = fs->descent; /* * Iterate over the input string getting the appropriate * char struct. * The default (which may be null if there is no def_char) will be returned * if the character doesn't exist. On the first time * through the loop, * assign the values to overall; otherwise, compute * the new values. */ for (i = 0, us = (unsigned char *) string; i < nchars; i++, us++) { register unsigned uc = (unsigned) *us; /* since about to do macro */ register XCharStruct *cs; if (singlerow) { /* optimization */ CI_GET_CHAR_INFO_1D (fs, uc, def, cs); } else { CI_GET_ROWZERO_CHAR_INFO_2D (fs, uc, def, cs); } if (cs) { if (nfound++ == 0) { *overall = *cs; } else { overall->ascent = max (overall->ascent, cs->ascent); overall->descent = max (overall->descent, cs->descent); overall->lbearing = min (overall->lbearing, overall->width + cs->lbearing); overall->rbearing = max (overall->rbearing, overall->width + cs->rbearing); overall->width += cs->width; } } } /* * if there were no characters, then set everything to 0 */ if (nfound == 0) { overall->width = overall->ascent = overall->descent = overall->lbearing = overall->rbearing = 0; } return; } /* * XTextWidth - compute the width of a string of eightbit bytes. This is a * subset of XTextExtents. */ #if NeedFunctionPrototypes int XTextWidth ( XFontStruct *fs, const char *string, int count) #else int XTextWidth (fs, string, count) XFontStruct *fs; char *string; int count; #endif { int i; /* iterator */ Bool singlerow = (fs->max_byte1 == 0); /* optimization */ XCharStruct *def; /* info about default char */ unsigned char *us; /* be 8bit clean */ int width = 0; /* RETURN value */ if (singlerow) { /* optimization */ CI_GET_DEFAULT_INFO_1D (fs, def); } else { CI_GET_DEFAULT_INFO_2D (fs, def); } /* * Iterate over all character in the input string; only consider characters * that exist. */ for (i = 0, us = (unsigned char *) string; i < count; i++, us++) { register unsigned uc = (unsigned) *us; /* since about to do macro */ register XCharStruct *cs; if (singlerow) { /* optimization */ CI_GET_CHAR_INFO_1D (fs, uc, def, cs); } else { CI_GET_ROWZERO_CHAR_INFO_2D (fs, uc, def, cs); } if (cs) width += cs->width; } return width; }
C
#include <stdio.h> #include <string.h> void permute(char *ptr,int len,int c){ int i; char temp; if (c == len -1){ printf("%s\n",ptr); } else { for(i=c; i < len ; i++){ temp = ptr[c]; ptr[c] = ptr[i]; ptr[i] = temp; permute(ptr,len,c+1); temp = ptr[c]; ptr[c] = ptr[i]; ptr[i] = temp; } } } void main (){ char str[100]; int len =0 , c=0; gets(str); len = strlen(str); permute(str,len,c); }
C
/* * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <semaphore.h> #include <signal.h> #include "ring_buffer.h" #define ALEXA_RECON_PART_END ("\r\n--this-is-a-boundary--\r\n") #define RING_BUFFER_LEN (512 * 1024) struct _ring_buffer_s { unsigned char *buf; size_t buf_len; volatile size_t write_pos; volatile size_t read_pos; volatile size_t readable_len; pthread_mutex_t lock; int fin_flags; }; ring_buffer_t *RingBufferCreate(size_t len) { printf("[%s:%d] ring_buffer_create start\n", __FUNCTION__, __LINE__); if (len <= 0) { len = RING_BUFFER_LEN; } ring_buffer_t *ring_buffer = (ring_buffer_t *)calloc(1, sizeof(ring_buffer_t)); if (ring_buffer) { ring_buffer->buf = (char *)calloc(1, len); if (!ring_buffer->buf) { goto EXIT; } ring_buffer->buf_len = len; ring_buffer->write_pos = 0; ring_buffer->read_pos = 0; ring_buffer->readable_len = 0; ring_buffer->fin_flags = 0; pthread_mutex_init(&ring_buffer->lock, NULL); return ring_buffer; } EXIT: if (ring_buffer) { free(ring_buffer); } printf("[%s:%d] ring_buffer_create error cause by calloc failed\n", __FUNCTION__, __LINE__); return NULL; } void RingBufferDestroy(ring_buffer_t **_this) { printf("[%s:%d] ring_buffer_destroy start\n", __FUNCTION__, __LINE__); if (_this) { ring_buffer_t *ring_buffer = *_this; if (ring_buffer) { if (ring_buffer->buf) { free(ring_buffer->buf); } pthread_mutex_destroy(&ring_buffer->lock); free(ring_buffer); } } else { printf("[%s:%d] input error\n", __FUNCTION__, __LINE__); } } void RingBufferReset(ring_buffer_t *_this) { printf("[%s:%d] circle_buffer_reset start\n", __FUNCTION__, __LINE__); if (_this) { pthread_mutex_lock(&_this->lock); _this->write_pos = 0; _this->read_pos = 0; _this->readable_len = 0; _this->fin_flags = 0; pthread_mutex_unlock(&_this->lock); } else { printf("[%s:%d] error: input error exit\n", __FUNCTION__, __LINE__); } } size_t RingBufferWrite(ring_buffer_t *_this, char *data, size_t len) { size_t write_len = 0; if (_this) { pthread_mutex_lock(&_this->lock); write_len = _this->buf_len - _this->readable_len; write_len = write_len > len ? len : write_len; if (write_len && _this->fin_flags != 1) { write_len = (_this->buf_len - _this->write_pos) > write_len ? write_len : (_this->buf_len - _this->write_pos); memcpy(_this->buf + _this->write_pos, data, write_len); _this->write_pos = (_this->write_pos + write_len) % _this->buf_len; _this->readable_len += write_len; pthread_mutex_unlock(&_this->lock); return write_len; } else { printf("[%s:%d] ring buffer is full\n", __FUNCTION__, __LINE__); pthread_mutex_unlock(&_this->lock); return 0; } } printf("[%s:%d] error: input error exit\n", __FUNCTION__, __LINE__); return -1; } size_t RingBufferRead(ring_buffer_t *_this, char *data, size_t len) { size_t read_len = 0; if (_this) { pthread_mutex_lock(&_this->lock); read_len = (_this->buf_len - _this->read_pos) > _this->readable_len ? _this->readable_len : (_this->buf_len - _this->read_pos); read_len = read_len > len ? len : read_len; if (read_len > 0) { memcpy(data, _this->buf + _this->read_pos, read_len); _this->readable_len = _this->readable_len - read_len; _this->read_pos = (_this->read_pos + read_len) % _this->buf_len; pthread_mutex_unlock(&_this->lock); // printf("[--------%s:%d] read size is %d read_pos is %d\n", __FUNCTION__, __LINE__, // read_len, _this->read_pos); return read_len; } else { pthread_mutex_unlock(&_this->lock); printf("[%s:%d] ring buffer is empty\n", __FUNCTION__, __LINE__); return 0; } } printf("[%s:%d] error: input error exit\n", __FUNCTION__, __LINE__); return -1; } size_t RingBufferReadableLen(ring_buffer_t *_this) { if (_this) { size_t readable_len = 0; pthread_mutex_lock(&_this->lock); readable_len = _this->readable_len; pthread_mutex_unlock(&_this->lock); return readable_len; } printf("[%s:%d] error: input error exit\n", __FUNCTION__, __LINE__); return -1; } size_t RingBufferLen(ring_buffer_t *_this) { if (_this) { size_t buf_len = 0; pthread_mutex_lock(&_this->lock); buf_len = _this->buf_len; pthread_mutex_unlock(&_this->lock); return buf_len; } printf("[%s:%d] error: input error exit\n", __FUNCTION__, __LINE__); return -1; } int RingBufferSetFinished(ring_buffer_t *_this, int finished) { size_t write_len = 0; size_t len = 0; char *data = NULL; if (_this) { data = ALEXA_RECON_PART_END; len = strlen(ALEXA_RECON_PART_END); pthread_mutex_lock(&_this->lock); write_len = _this->buf_len - _this->readable_len; write_len = write_len > len ? len : write_len; if (write_len > 0) { write_len = (_this->buf_len - _this->write_pos) > write_len ? write_len : (_this->buf_len - _this->write_pos); memcpy(_this->buf + _this->write_pos, data, write_len); _this->write_pos = (_this->write_pos + write_len) % _this->buf_len; _this->readable_len += write_len; //printf("[%s:%d] end boundary write_len(%d) len(%d)\n", \ // __FUNCTION__, __LINE__, write_len, len); } _this->fin_flags = 1; pthread_mutex_unlock(&_this->lock); return 0; } printf("[%s:%d] error: input error exit\n", __FUNCTION__, __LINE__); return -1; } int RingBufferSetStop(ring_buffer_t *_this, int stop) { size_t write_len = 0; size_t len = 0; char *data = NULL; if (_this) { data = ALEXA_RECON_PART_END; len = strlen(ALEXA_RECON_PART_END); pthread_mutex_lock(&_this->lock); _this->write_pos = 0; _this->read_pos = 0; _this->readable_len = 0; write_len = _this->buf_len - _this->readable_len; write_len = write_len > len ? len : write_len; if (write_len > 0) { write_len = (_this->buf_len - _this->write_pos) > write_len ? write_len : (_this->buf_len - _this->write_pos); memcpy(_this->buf + _this->write_pos, data, write_len); _this->write_pos = (_this->write_pos + write_len) % _this->buf_len; _this->readable_len += write_len; //printf("[%s:%d] end boundary write_len(%d) len(%d)\n", \ // __FUNCTION__, __LINE__, write_len, len); } _this->fin_flags = 1; pthread_mutex_unlock(&_this->lock); return 0; } printf("[%s:%d] error: input error exit\n", __FUNCTION__, __LINE__); return -1; } int RingBufferGetFinished(ring_buffer_t *_this) { if (_this) { int finished = 0; pthread_mutex_lock(&_this->lock); finished = _this->fin_flags; pthread_mutex_unlock(&_this->lock); return finished; } printf("[%s:%d] error: input error exit\n", __FUNCTION__, __LINE__); return -1; }
C
/* roman_numeral_calc.c Andrew Howard - 2016 This file defines library functions that allow the user to add and subtract Roman numeral numbers. Other functions facilitate the conversion between Roman numerals and decimal numbers. The largest Roman numeral supported is 3999 (MMMCMXCIX) and the smallest is 1 (I). */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <stdbool.h> #include "roman_numeral_calc.h" //Roman numeral symbols and associated decimal values. These are used //in the conversion between decimal numbers and Roman numerals. static const char roman_symbol[] = {'M','D','C','L','X','V','I'}; static const int decimal_symbol[] = {1000, 500, 100, 50, 10, 5, 1}; static const int num_symbol = 7; /* Convert decimal numbers (1-3999) to Roman numerals. The function writes to a C string provided by the caller. The array must be large enough to store the characters of the numerals and the null- terminating character. A '0' value is returned if the conversion was successful. A '1' value is returned if the conversion fails due to invalid input. */ int decimal_to_roman(const int decimal, char * numeral) { //First check if number is within the accepted range. if(decimal < MIN_DECIMAL || decimal > MAX_DECIMAL) { //Failed, return. return 1; } //Check for a null pointer. if(numeral == NULL) { //Failed, return. return 1; } //Ensure the string is clean before writing over it. memset(numeral, 0, strlen(numeral)); //Generate buffer string used when generating Roman numerals. char * buffer = (char*)malloc(sizeof(char) + (strlen(MAX_LENGTH_ROMAN)+1)); memset(buffer, 0, (strlen(MAX_LENGTH_ROMAN)+1)); //Temporary integer to store value of remaining decimal number //as Roman numerals are added to the string. int dtemp = decimal; /* When converting from decimal to Roman numerals, there are four sections within each decimal place (powers of 10) that are represented different by numerals. i) Immediately less the higher power of 10 (i.e. 9 -> IX) ii) Less than the highest number but not less than the middle value. (i.e. 8 -> VIII) iii) Immediately less than the middle value. (i.e. 4 -> IV) iv) Lowest values (i.e. 2 -> II) The rules for converting decimal numbers to Roman numerals can be applied systematically to each decimal place, so long as these four regions are processed accordingly for the respective Roman numeral values. */ //As the largest decimal number allowed is 3999, only the lowest //region of the 1000's place is checked. This is a special case. if(dtemp >= 1000) { //Count the 1000's in the decimal number. Rounds down. int n = floor(((float)dtemp)/1000.0); //Add 1000's by appending "M" several times. Maximum of 3. for(int i=0; i<n; i++) { //Append "M" to end of numeral buffer string. strcat(buffer,"M"); //Subtract 1000 from decimal value. dtemp -= 1000; } } //For each decimal place from the 100's to the 1's, convert to //Roman numerals. "symbol_iter" starts at 2 because that is the //index for the 100s decimal value and Roman numeral symbol C. for(int symbol_iter=2; symbol_iter < num_symbol; symbol_iter+=2) { //decimal value that represents the decimal place int dplace = decimal_symbol[symbol_iter]; //Decimal number values representing the four cases of values //within the current decimal place. int val9 = 9 * dplace; int val5 = 5 * dplace; int val4 = 4 * dplace; int val1 = dplace; if(dtemp >= val9) { //Append the Roman numeral for the value immediately //before the next highest decimal place. That is, "CM", //"XC", or "IX". buffer[strlen(buffer)] = roman_symbol[symbol_iter]; buffer[strlen(buffer)] = roman_symbol[symbol_iter-2]; //Subtract the value from dtemp dtemp -= val9; } //Check if dtemp contains the middle value for the current //decimal place. if(dtemp >= val5) { //Append Roman numeral for middle value to buffer. buffer[strlen(buffer)] = roman_symbol[symbol_iter-1]; //Subtract middle value from dtemp. dtemp -= val5; } //Check if dtemp is immediately less than the middle value. if(dtemp >= val4) { //Append Roman numerals for the value immediately less //than the middle value. (i.e. IV) buffer[strlen(buffer)] = roman_symbol[symbol_iter]; buffer[strlen(buffer)] = roman_symbol[symbol_iter-1]; //Subract from dtemp. dtemp -= val4; } //Check dtemp for value in the lowest portion of the current //decimal place. if(dtemp >= val1) { //Count the multiples of val1 in dtemp. Round down. int n = floor(((float)dtemp)/((float)val1)); //Add numeral for current decimal place. Maximum of 3. for(int i=0; i<n; i++) { //Append numeral for current decimal place to end of //numeral buffer string. buffer[strlen(buffer)] = roman_symbol[symbol_iter]; //Subtract val1 from remaining decimal value. dtemp -= val1; } } } //Copy contents of buffer to "numeral". strncpy(numeral, buffer, strlen(buffer)+1); //dtemp should equal zero now, with all value extracted and //converted to Roman numerals. If not, something went wrong. if(dtemp != 0) { //Failed, return. return 1; } //Free buffer memory free(buffer); //Successful conversion, return. return 0; } /* Convert Roman numerals to decimal numbers in the range 1-3999. The function is passed a C string containing the Roman numerals to convert and a pointer to the integer variable that will receive the converted decimal value. A '0' value is returned if the conversion was successful. A '1' value is returned if the conversion fails due to invalid input. */ int roman_to_decimal(const char * numeral, int * decimal) { //Ensure that numeral string is not null. if(numeral == NULL) { //Invalid input, conversion fails. return 1; } //Ensure that decimal integer is not null. if(decimal == NULL) { //Invalid input, conversion fails. return 1; } //temporary variable to store decimal number as it is built int dtemp = 0; //Copy the original numeral to another c string that can be //manipulated as need. char * ntemp = (char*)malloc(sizeof(char) * (strlen(numeral)+1)); memcpy(ntemp, numeral, strlen(numeral)+1); //Ensure that the characters of the input string are valid. //Lowercase correct letters are accepted and converted to //uppercase. for(int i=0; i<strlen(ntemp); i++) { //Force conversion to uppercase. ntemp[i] = toupper(ntemp[i]); //Checks if the letter is one of the accepted Roman symbols. if(ntemp[i] < 'C' || ntemp[i] > 'X') { //Invalid Roman numeral, exit. free(ntemp); return 1; } else { //Check character against list of Roman symbols. While //this is a double-nested loop, both loops are small. bool validChar = false; for(int j=0; j<num_symbol; j++) { if(ntemp[i] == roman_symbol[j]) { //Found valid character, exit loop. validChar = true; break; } } //Current character in string is not a valid Roman numeral //symbol. Return a "1" for conversion failure. if(!validChar) { free(ntemp); return 1; } } } //If the numeral string is preceeded by M's, these represent //values of 1000. There should be 3 maximum. int count=0; while(strchr(ntemp,'M') == ntemp) { //Add 1000 to decimal value. dtemp += 1000; //Shift the characters of the string so the first is //dropped off. The null terminating character is copied //over as well, so the string's length is correctly //shortened. memmove(ntemp, ntemp+1, strlen(ntemp)); count++; //Check for more than 3 M's in a row. if(count > 3) { //Incorrectly formated Roman numeral, return. free(ntemp); return 1; } } /* Converting from Roman numerals to decimal numbers follows a similar approach as the reverse conversion that is described in "decimal_to_roman()" above. Within each decimal place, strings representing 9, 5, 4, and 1 are searched for within "ntemp". As they are identified in leading positions in the numeral string, they are removed from the front of the string and their equivalent value is added to the growing decimal value, stored in "dtemp". */ //For each decimal place from the 100's to the 1's, search for the //Roman numerals that represent the respective values of 9, 5, 4, //and 1. "symbol_iter" starts at 2 because that is the //index for the 100s decimal value and Roman numeral symbol C. for(int symbol_iter=2; symbol_iter < num_symbol; symbol_iter+=2) { //decimal value that represents the decimal place int dplace = decimal_symbol[symbol_iter]; //Decimal number values representing the four cases of values //within the current decimal place. int val9 = 9 * dplace; int val5 = 5 * dplace; int val4 = 4 * dplace; int val1 = dplace; //Roman numeral strings that correspond to the above decimal //values. All are null-terimated c strings. char numstr9[] = {'\0', '\0', '\0'}; numstr9[0] = roman_symbol[symbol_iter]; numstr9[1] = roman_symbol[symbol_iter-2]; char numstr5[] = {'\0', '\0'}; numstr5[0] = roman_symbol[symbol_iter-1]; char numstr4[] = {'\0', '\0', '\0'}; numstr4[0] = roman_symbol[symbol_iter]; numstr4[1] = roman_symbol[symbol_iter-1]; char numstr1[] = {'\0', '\0'}; numstr1[0] = roman_symbol[symbol_iter]; //Check for numeral string that represents the 9 value. if(strstr(ntemp, numstr9)) { //Check if the string is at beginning. if(strstr(ntemp, numstr9) == ntemp) { //Add the corresponding 9 value to the decimal. dtemp += val9; //Remove beginning two characters of string. memmove(ntemp, ntemp+1, strlen(ntemp)); memmove(ntemp, ntemp+1, strlen(ntemp)); } else { //Incorrectly formated Roman numeral, return. free(ntemp); return 1; } } //Check for numeral for 5, not necessarily at the beginning. if(strstr(ntemp, numstr5)) { //Check for leading 5 numeral. if(strstr(ntemp, numstr5) == ntemp) { //Add the corresponding 5 value to the decimal. dtemp += val5; //Shift the characters of the string so the first is //dropped off. The null terminating character is //copied over as well, so the string's length is //correctly shortened. memmove(ntemp, ntemp+1, strlen(ntemp)); } else if(strstr(ntemp, numstr4) == ntemp) { //Check for leading numeral for 4 value. //Add corresponding 4 value to the decimal. dtemp += val4; //Shift the characters of the string so the first two //are dropped off. The null terminating character is //copied twice over as well, so the string's length is //correctly shortened. memmove(ntemp, ntemp+1, strlen(ntemp)); memmove(ntemp, ntemp+1, strlen(ntemp)); //With leading numeral for 4 value, there should be no //following numerals for the 1 value. if(strstr(ntemp,"numstr1")) { //Incorrectly formated Roman numeral, return. free(ntemp); return 1; } } else { //Incorrectly formated Roman numeral, return. free(ntemp); return 1; } } //If the string starts with numerals for the 1 value, here //should be 3 maximum. int count=0; while(strstr(ntemp, numstr1) == ntemp) { //Add corresponding 1 value to the decimal. dtemp += val1; //Shift the characters of the string so the first is //dropped off. The null terminating character is copied //over as well, so the string's length is correctly //shortened. memmove(ntemp, ntemp+1, strlen(ntemp)); count++; //Check for more than 3 numerals for 1 values in a row. if(count > 3) { //Incorrectly formated Roman numeral, return. free(ntemp); return 1; } } } //Free the temporary Roman numeral string. free(ntemp); //Store the final converted decimal number. *decimal = dtemp; return 0; } /* Add two Roman numerals. The addition is performed by converting both Roman numeral operands to decimal, adding the decimal numbers, and then converting the result to Roman numerals. All strings should be pre-allocated. The sum must be less than or equal to 3999 for the addition to succeed. A '0' value is returned if the addition succeeds. A '1' value is returned if the addition fails, either due to a failed conversion or the sum is too large. */ int roman_addition(const char * numeral_a, const char * numeral_b, char * numeral_sum) { //Check for null strings if(numeral_a == NULL || numeral_b == NULL || numeral_sum == NULL) { //Addition failed. return 1; } //Integers used for conversion and addition. int decimal_a; int decimal_b; int decimal_sum; //Convert the operands to decimal, checking for flags from //conversion functions. if(roman_to_decimal(numeral_a, &decimal_a) || roman_to_decimal(numeral_b, &decimal_b)) { //Addition failed. return 1; } //Add the decimal values. decimal_sum = decimal_a + decimal_b; //Check if sum is within maximum value supported. if(decimal_sum > MAX_DECIMAL) { //Addition failed. return 1; } //Convert decimal sum to Roman numeral sum, check for flag. if(decimal_to_roman(decimal_sum, numeral_sum)) { //Addition failed. return 1; } return 0; } /* Subtract two Roman numerals. The subtraction is performed by converting both Roman numeral operands to decimal, subtracting the decimal numbers, and then converting the result to Roman numerals. All strings should be pre-allocated. The difference must be greater than or equal to 1 for the subtraction to succeed. A '0' value is returned if the subtraction succeeds. A '1' value is returned if the subtraction fails, either due to a failed conversion or the difference is too small. */ int roman_subtraction(const char * numeral_a, const char * numeral_b, char * numeral_diff) { //Check for null strings if(numeral_a == NULL || numeral_b == NULL || numeral_diff == NULL) { //Subtraction failed. return 1; } //Integers used for conversion and subtraction. int decimal_a; int decimal_b; int decimal_diff; //Convert the operands to decimal, checking for flags from //conversion functions. if(roman_to_decimal(numeral_a, &decimal_a) || roman_to_decimal(numeral_b, &decimal_b)) { //Subtraction failed. return 1; } //Subtract the decimal values. decimal_diff = decimal_a - decimal_b; //Check if difference is a valid decimal number. if(decimal_diff < 1) { //Subtraction failed. return 1; } //Convert decimal difference to Roman numeral difference, check //for flag. if(decimal_to_roman(decimal_diff, numeral_diff)) { //Subtraction failed. return 1; } return 0; }
C
#define PI (4.*atan(1.)) #include <math.h> double f(double x) { return 2 * pow(sin(3 * PI - 2 * x), 2) * pow(cos(5 * PI + 2 * x), 2); }
C
/* * GccApplication1.c * Created: 2/27/2019 6:54:28 PM * Author: cuicas */ //RUNNING OFF 1MHZ #include <avr/io.h> int main () { DDRB = 0xff; //set all of portB to output TCCR1B = (1<<CS12) | (1<<CS10);//setting these bits specifically 5 so that pre-scaler is 1024 int count = 0; //this is how I will control the sequence of events so LED is on first. while (1) { if (count %2 == 0) //this is how I will control the sequence of events so LED is on first. { PORTB = 0x02; // turn on LED TCNT1 = 0x00; // restart clock while (TCNT1<=0x01A8) //the amount of time in hex = 0.435s LED is on { } count+=1; // increase count so that next event turns off LED } else { PORTB = 0x00; // turn off LED TCNT1 = 0x00; // restart clock while (TCNT1<=0x011A) // desired off time in hex = 0.29 { } count+=1; // increase count so that next event turns on LED } } return 0;} // on time 0x1A8 = 0.435 s // off time 0x11A = 0.29 s, but after simulating closer to 0x11C
C
/* ** EPITECH PROJECT, 2018 ** socket.c ** File description: ** socket */ #include <sys/socket.h> #include <netdb.h> #include <ifaddrs.h> #include <unistd.h> #include <stdio.h> int memsetzero(void *ptr, size_t size) { char *tmp = ptr; if (tmp == NULL) return (-1); for (size_t i = 0; i < size; i++) tmp[i] = 0; return (0); } int create_server(uint16_t port) { struct sockaddr_in server; int fd; fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) return (-1); memsetzero(&server, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(port); if (bind(fd, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) < 0) { close(fd); return (-1); } return (fd); } int accept_client(int sockfd, int backlog) { struct sockaddr_in client; socklen_t clilen = sizeof(client); int fd; if (listen(sockfd, backlog) < 0) return (-1); fd = accept(sockfd, (struct sockaddr *)&client, &clilen); if (fd < 0) return (-1); return (fd); } int connect_to_server(uint16_t port, const char *ip) { struct hostent *info; struct sockaddr_in serv_addr; int fd; info = gethostbyname(ip); if (info == NULL) return (-1); fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) return (-1); memsetzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr = *(struct in_addr *)info->h_addr; serv_addr.sin_port = htons(port); if (connect(fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) < 0) { close(fd); return (-1); } return (fd); }
C
#pragma once typedef struct vector_implementation { int size; int capacity; int *data; } vector; // return pointer to new vector vector* vector_create(); // returns vector size int vector_size(vector* v); // returns capacity int vector_capacity(vector* v); //return true if size is 0 int vector_is_empty(vector* v); // return value form index i int vector_at(vector* v, int i); // push at the end void vector_push(vector* v, int val); // insert at any index in bounds void vector_insert(vector* v, int i, int val); // insert at the beginning void vector_prepend(vector* v, int val); // delete last element and return it's value int vector_pop(vector* v); // delete element at index void vector_delete(vector* v, int i); // remove first element with matching value void vector_remove(vector* v, int val); // return index of first element with value int vector_find(vector* v, int val);
C
#include"delay.h" __IO uint32_t TimingDelay; /*延时1us函数*/ void delay_us(__IO uint32_t usnTime) { TimingDelay = usnTime; while(TimingDelay != 0); } void delay_ms(__IO uint32_t msnTime) { TimingDelay = msnTime * 1000; while(TimingDelay != 0); } static volatile uint32_t usTicks = 0; // cycles per microsecond volatile uint32_t sysTickUptime = 0; // unit is us,so it will rollover after 71mins. but maybe we won't care. void cycleCounterInit(void) { RCC_ClocksTypeDef clocks; RCC_GetClocksFreq(&clocks); usTicks = clocks.SYSCLK_Frequency / 1000000; } void SysTick_Handler(void) { sysTickUptime ++; if (TimingDelay != 0x00) { TimingDelay--; } } uint32_t currentTime(void) { register uint32_t us, cycle_cnt; do { us = sysTickUptime; cycle_cnt = SysTick->VAL; } while (us != sysTickUptime); return (us) + (usTicks - cycle_cnt) / usTicks; } // Return us void delay_current_us(uint32_t nus) { uint32_t t0=currentTime(); while(currentTime() - t0 < nus); } void delay_current_ms(uint32_t nms) { uint32_t t0=currentTime(); while(currentTime() - t0 < nms * 1000); } void delay_noInt_ms(uint32_t time) { time *= 1429;//50000 -> 35.006ms while(time --); }
C
#include<stdio.h> #include <math.h> void main() { int i,n,v,v1,number=0; printf("Enter a value:"); scanf("%d",&n); v=n; v1=ceil(sqrt(n)); for(i=2;i<=v1;i++) { if(v%1==0) number=1; } if ((number==0&& v!=1)||v==2||v==3) printf("%d is a prime number",v); else printf("%d is not a prime number",v); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> void clearstdin(void) { char temp; while((temp=getchar())!='\n'); } int main() { int num; srand(time(NULL)); num = rand() % 100 + 1; char input[3]; int guess = 101; int correct = 0; printf("Press Enter to continue"); while (correct == 0) { clearstdin(); printf("Enter a number between 0 and 100: \n"); fgets(input, 3, stdin); guess = atoi(input); if (guess < num) { printf("You guessed %d! The correct number is higher\n", guess); } else if (guess > num) { printf("You guessed %d! The correct number is lower\n", guess); } else if (guess == num) { correct = 1; } } printf("You guessed correctly. The number was %d\n", guess); return 0; }
C
#pragma once // CX basic low-level file i/o // This acts as a bridge to the operating system. It does synchronous I/O with // only the OS-provided buffering. Unlike the C standard library, I/O is not // line-oriented in any way. #include <cx/cx.h> CX_C_BEGIN typedef struct FSFile FSFile; enum FSOpenFlags { FS_Read = 1, FS_Write = 2, FS_Create = 4, FS_Truncate = 8, FS_Lock = 16, FS_Overwrite = (FS_Write | FS_Create | FS_Truncate), }; enum FSSeekType { FS_Set = 0x00010000, FS_Cur = 0x00020000, FS_End = 0x00030000, }; FSFile *fsOpen(strref path, flags_t flags); bool fsClose(FSFile *file); bool fsRead(FSFile *file, void *buf, size_t sz, size_t *bytesread); bool fsWrite(FSFile *file, void *buf, size_t sz, size_t *byteswritten); int64 fsTell(FSFile *file); int64 fsSeek(FSFile *file, int64 off, int seektype); bool fsFlush(FSFile *file); CX_C_END
C
#include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdio.h> int main(void){ int fd = open("a.txt",O_CREAT|O_WRONLY|O_TRUNC,0644); int i= 0; while(1){ int fd1 = dup2(fd,i); printf("%d\n",fd1); i++; if(fd1<0) printf("over\n"); } }
C
#include <stdio.h> int main() { int number; printf("Enter a digit: "); /* * Store value of the number the user entered into the command line * in number. */ scanf("%d", &number); printf("You entered: %d", number); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <pthread.h> struct Customer { int id; /* round */ int arrive; int cont; // continuously play round int rest; int total; int start; // should start int accum; int explored; int prewait; struct Customer *next; }; static struct Customer *head = NULL; static pthread_t threads[2]; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cv = PTHREAD_COND_INITIALIZER; static int G = 0, gcount = 0; static int it = 1, threadnum, existcus = 0; /* <the guarantee number G> <total number of customers> <customer1 arrive time><continuously play round><rest time><total play round number N> <customer2 arrive time><continuously play round><rest time><total play round number N> */ struct Customer *create_customer(int id, char *arrive, char *cont, char *rest, char *total) { struct Customer *cus; cus = malloc(sizeof(struct Customer)); cus->id = id; cus->arrive = atoi(arrive); cus->cont = atoi(cont); cus->rest = atoi(rest); cus->total = atoi(total); cus->start = cus->arrive; cus->accum = 0; cus->prewait = 0; cus->explored = 0; return cus; } void save_file_content(char *filename) { char *line = NULL; size_t capacity = 0; ssize_t byte; FILE *fp = fopen(filename, "r"); if (fp == NULL) { printf("file does not exist\n"); exit(1); } byte = getline(&line, &capacity, fp); if (byte <= 0) { printf("error read file\n"); exit(1); } // guarantee rounds G = atoi(line); byte = getline(&line, &capacity, fp); if (byte <= 0) { printf("error read file\n"); exit(1); } int C = atoi(line); struct Customer *cus; char *str[4]; for (int i = 0; i < C; i++) { byte = getline(&line, &capacity, fp); if (byte <= 0) { printf("error read file\n"); exit(1); } str[0] = strtok(line, " "); for (int j = 0; j < 3; j++) { str[j + 1] = strtok(NULL, " "); } cus = create_customer(i + 1, str[0], str[1], str[2], str[3]); cus->next = head; head = cus; } free(line); fclose(fp); } void eject(struct Customer *this) { struct Customer *prev, *cus = head; while (cus && cus != this) { prev = cus; cus = cus->next; } if (head == this) { head = this->next; } else { prev->next = this->next; } } void inject(struct Customer *this) { this->next = head; head = this; } void check_finish(int time, int id, struct Customer **customer) { (*customer)->accum++; gcount++; if (time >= (*customer)->start + (*customer)->cont || (*customer)->accum >= (*customer)->total || gcount >= G) { printf("%d %d finish playing", time, (*customer)->id); if ((*customer)->accum >= (*customer)->total || gcount >= G) { printf(" YES #%d\n", id); gcount = 0; free(*customer); } else { printf(" NO #%d\n", id); (*customer)->prewait = 0; (*customer)->explored = 0; (*customer)->start = time + (*customer)->rest; inject(*customer); } *customer = NULL; existcus--; } } struct Customer *get_customer(int time, int id) { struct Customer *cus = head, *result = NULL; int minstart = INT_MAX; while (cus) { if (cus->start <= time && cus->start < minstart) { result = cus; minstart = cus->start; } cus = cus->next; } if (result) { eject(result); printf("%d %d start playing #%d\n", time, result->id, id); result->start = time; existcus++; return result; } else { // both of machine are released if (existcus == 0) { gcount = 0; } } return NULL; } void check_waiting(int time, int id) { struct Customer *cus; cus = head; while (cus) { if (cus->start <= time) { // explored by other thread if (cus->explored >= 1 && cus->prewait == 0) { printf("%d %d wait in line\n", time, cus->id); cus->prewait = 1; } else { cus->explored++; } } cus = cus->next; } } int handle_customer(int time, int id, struct Customer **customer) { pthread_mutex_lock(&m); //printf("gcount=%d, G=%d\n", gcount, G); while(it != id){ pthread_cond_wait(&cv, &m); } // handle existing customer if (*customer) { check_finish(time, id, customer); } // no existing customer if (*customer == NULL) { // no more customer if (head == NULL) { threadnum--; // change to other thread it = it % 2 + 1; pthread_mutex_unlock(&m); pthread_cond_signal(&cv); return 0; } *customer = get_customer(time, id); } check_waiting(time, id); if (threadnum == 2) { // change to other thread it = it % 2 + 1; } pthread_mutex_unlock(&m); pthread_cond_signal(&cv); return 1; } void *claw_machine(void *arg) { int id = *(int *)arg; int time = 0; struct Customer* cus = NULL; while (handle_customer(time, id, &cus)) { time++; } return NULL; } int main(int argc, char **argv) { if (argc != 2) { printf("usage: ./<exec file> <input file>\n"); exit(1); } save_file_content(argv[1]); int t0 = 1, t1 = 2; threadnum = 2; pthread_create(&threads[0], NULL, claw_machine, &t0); pthread_create(&threads[1], NULL, claw_machine, &t1); for (int i = 0; i < 2 ; i++) { pthread_join(threads[i], NULL); } }
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 cmd {scalar_t__ c_iscloneop; int /*<<< orphan*/ c_name; struct cmd* c_next; } ; /* Variables and functions */ struct cmd* cmds ; scalar_t__ strcmp (char const*,int /*<<< orphan*/ ) ; __attribute__((used)) static const struct cmd * cmd_lookup(const char *name, int iscreate) { const struct cmd *p; for (p = cmds; p != NULL; p = p->c_next) if (strcmp(name, p->c_name) == 0) { if (iscreate) { if (p->c_iscloneop) return p; } else { if (!p->c_iscloneop) return p; } } return NULL; }
C
#include <stdio.h> int main() { char x1,x2,result; // Beispiel 1: x1 = 35; x2 = 85; result = x1 + x2; printf("Beispiel 1: %hi + %hi = %hi\n",x1 ,x2, result); // Beispiel 2: x1 = 85; x2 = 85; result = x1 + x2; printf("Beispiel 2: %hi + %hi = %hi\n", x1, x2, result); return 0; // Beispiel 1: # + U = x // Beispiel 2: U + U = � // Beispiel 1: 35 + 85 = 120 // Beispiel 2: 85 + 85 = -86 }
C
#include <stdio.h> int main() { int n = 0; int num; printf("Ҫλ"); scanf("%d",&num); n++; num /= 10; while ( num > 0 ) { n++; num /= 10; } printf("λ%d",n); system("pause"); return 0; }
C
void ft_putchar(char ch); void ft_putstr(char *str) { while (*str) { ft_putchar(*str); str += 1; } } int ft_strcmp(char *s1, char *s2) { int i; i = 0; while (s1[i] && s2[i]) { if (s1[i] != s2[i]) return (s1[i] - s2[i]); i += 1; } return (s1[i] - s2[i]); } void ft_sort(char **argv) { int i; int sorted; char *tmp; sorted = 0; while (!sorted) { sorted = 1; i = 1; while (argv[i + 1]) { if (ft_strcmp(argv[i], argv[i + 1]) > 0) { sorted = 0; tmp = argv[i]; argv[i] = argv[i + 1]; argv[i + 1] = tmp; } i += 1; } } } void ft_display(int argc, char **argv) { int i; i = 1; while (i < argc) { ft_putstr(argv[i]); ft_putchar('\n'); i += 1; } } int main(int argc, char **argv) { if (argc > 1) { ft_sort(argv); ft_display(argc, argv); } return (0); }
C
#include <stdio.h> #include<math.h> int f(int x,int y) { float result=pow(x,2)+y; double sr=sqrt(result); return ((sr - floor(sr)) == 0); } int main() { long x,y; long result=0,flag=0; long i; long j; scanf("%ld %ld",&x,&y); for(i=1;i<=x;i++) { for(j=1;j<=y;j++) {result=f(i,j); if(result==1) flag++; } // printf("%d ",flag); } printf("%ld",flag); return 0; }
C
#include "AEEDebugger.h" static uint32 OEMDEBUGGER_AddRef(IDEBUGGER* po); static uint32 OEMDEBUGGER_Release(IDEBUGGER* po); static int OEMDEBUGGER_QueryInterface (IDEBUGGER *pMe, AEECLSID id, void **ppo); static void OEMDEBUGGER_SetCtx(IDEBUGGER* po, void* pbCtx); static void* OEMDEBUGGER_GetCtx(IDEBUGGER* po); static int OEMDEBUGGER_RegCallback(IDEBUGGER* po, void* callbackFn); static uint32 OEMDEBUGGER_GetHeapRange(IDEBUGGER* po); static uint32 OEMDEBUGGER_GetHeapSize(IDEBUGGER* po); static uint32 OEMDEBUGGER_GetStackRange(IDEBUGGER* po); static uint32 OEMDEBUGGER_GetStackSize(IDEBUGGER* po); void OEMDEBUGGER_DogKick(IDEBUGGER* po); /*=========================================================================== OEMDEBUGGER_AddRef() Description: This function increments the reference count of the IDEBUGGER Interface object. This allows the object to be shared by multiple callers. The object is freed when the reference count reaches 0 (zero). Prototype: static uint32 OEMDEBUGGER_AddRef(IDEBUGGER* po) Parameters: Pointer to the IDebugger interface Returns: The updated reference count. Comments Ideally there will be one interface active at a given time Side Effects: None See Also: None =========================================================================== ======================================================================= OEMDEBUGGER_Release() Description: This function increments the reference count of the IDEBUGGER Interface object. This allows the object to be shared by multiple callers. The object is freed when the reference count reaches 0 (zero). Prototype: static uint32 OEMDEBUGGER_Release(IDEBUGGER* po) Parameters: Pointer to the IDebugger interface Returns: The update reference count. Comments None Side Effects: None See Also: None =========================================================================== OEMDEBUGGER_QueryInterface() Description: This is the QueryInterface function of the IDebugger Extension. Prototype: static uint32 OEMDEBUGGER_QueryInterface(IDEBUGGER *pMe, AEECLSID id, void **ppo) Parameters: Pointer to the IDebugger interface Class Id. Returned object. Returns: Comments None Side Effects: None See Also: None ============================================================================== =========================================================================== OEMDEBUGGER_SetCtx() Description: This function is used to set the address of the brew debugger context and used to store the address of the debugger context inside BREW and when the app returns from the undef exception, the IDEBUGGER_GetCtx() is used to retrieve the address. Prototype: static void OEMDEBUGGER_SetCtx(IDEBUGGER* po, void* pbCtx) Parameters: po - Pointer to the IDebugger interface pbCtx - Pointer to the brew debugger context (used for storing the address) Returns: void Comments None Side Effects: None See Also: None ======================================================================= ======================================================================= OEMDEBUGGER_GetCtx() Description: When the control is returned to the stub, the stub needs to know the address at which the debugging context was stored. This is done by making a call to the IDebugger interface which returns the address of the pointer pointing to the context. Prototype: static void* OEMDEBUGGER_GetCtx(IDEBUGGER* po) Parameters: po = Pointer to the IDEBUGGER interface Returns: A void pointer to the address where the context is stored. The app then typecasts the pointer to the debug context structure. Comments None Side Effects: None See Also: None ======================================================================= ======================================================================= OEMDEBUGGER_RegCallback() Description: This function is used by the app to register a callback function when a breakpoint is hit.The IDegubber interface then stores the pointer to this function in the debugger lib and when the bkpt is hit and the function brew_dbg_undef_return is invoked after returning from the exception, it in turn calls this function in the stub and the control is now with the stub. Prototype: static int OEMDEBUGGER_RegCallback(IDEBUGGER* po, void* callbackFn) Parameters: po - pointer to the IDEBUGGER interface callbackFn - pointer to a callback function from the stub Returns: EFAILED/SUCCESS Comments None Side Effects: None See Also: None ======================================================================= ======================================================================= OEMDEBUGGER_GetHeapRange Description: This function gets the starting address of the heap. Prototype: uint32 OEMDEBUGGER_GetHeapRange(IDEBUGGER* po); Parameters: po - pointer to the IDEBUGGER interface Returns: starting address of the heap allocation Comments None Side Effects: None See Also: None ======================================================================= ======================================================================= OEMDEBUGGER_GetHeapSize Description: It gets the size of the heap Prototype: uint32 OEMDEBUGGER_GetHeapSize(IDEBUGGER* po) Parameters: po - pointer to the IDEBUGGER interface Returns: size of the heap allocation Comments None Side Effects: None See Also: None ======================================================================= ======================================================================= OEMDEBUGGER_GetStackRange Description: It gets the starting address of the stack allocation Prototype: uint32 OEMDEBUGGER_GetStackRange(IDEBUGGER* po) Parameters: po - pointer to the IDEBUGGER interface Returns: size of the heap allocation Comments: None Side Effects: None See Also: None ======================================================================= ======================================================================= OEMDEBUGGER_GetStackSize Description: It gets the size of the stack allocation Prototype: uint32 OEMDEBUGGER_GetStackSize(IDEBUGGER* po) Parameters: po - pointer to the IDEBUGGER interface Returns: size of the stack Comments: None Side Effects: None See Also: None ======================================================================= ======================================================================= OEMDEBUGGER_DogKick Description: This procedure resets the watchdog timer circuit. Resets the circuit so that we have another N milliseconds before the circuit will reset the system. Arms auto-kick. Prototype: void OEMDEBUGGER_DogKick(IDEBUGGER* po) Parameters: po - pointer to the IDEBUGGER interface Returns: size of the stack Comments: None Side Effects: None See Also: None ===========================================================================*/
C
#include "holberton.h" #include <stdio.h> /** *main - accepts void prints 1 to 100 * but if something is divisable by 3 * print fizz and buzz if 5 both * if devisable by both *Return: 0 */ int main(void) { int i; for (i = 1 ; i <= 99 ; i++) { if ((i % 3) == 0 && (i % 5) == 0) printf("FizzBuzz "); else if ((i % 3) == 0) printf("Fizz "); else if ((i % 5) == 0) printf("Buzz "); else { printf("%d ", i); } } printf("Buzz"); putchar('\n'); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <wave.h> #include <snddevice.h> int main(int argc, char *argv[]) { WaveDecoder decoder; SndPlayer player; int i, ret; if(argc < 2) { fprintf(stderr, "用法:%s WAVE音频列表\n", argv[0]); return EXIT_FAILURE; } bzero(&decoder, sizeof(decoder)); ret = openSndDevice(NULL, &player); if(0 != ret) goto Error; for(i = 1; i < argc; i++) { fprintf(stdout, "play file: %s\n", argv[i]); ret = initWaveDecoder(argv[i], &decoder); if(0 != ret) continue; player.args.rate = decoder.args.rate; player.args.bits = decoder.args.bits; player.args.channels = decoder.args.channels; player.buffer = decoder.buffer; ret = setSndDevice(&player); if(0 != ret) { player.error = SNDERR_INVAARG; goto Error; } while(1) { ret = getWaveData(&decoder); if(0 != ret) break;//读取音频失败 /* 音频播放完成 */ if(0 == decoder.dataLength) break; /* 用实际读取数据长度,设置本次播放长度 */ player.length = decoder.dataLength; /* 播放音频数据 */ ret = writeSndDevice(&player); /* 写数据到音频设备失败 */ if(0 != ret) goto Error; } destroyWaveDecoder(&decoder); } closeSndDevice(&player); return EXIT_SUCCESS; Error: if(player.error != 0) fprintf(stderr, sndErrorString(&player)); perror(": Waveplay"); destroyWaveDecoder(&decoder); closeSndDevice(&player); return ret; }
C
int main() { int a; a = 1+1-(1+1)*2/2; // = 0 printi(a); //0 printf("\n"); int b = 5; int c = a * (b + 1 + 1) + 1; // = 1 //int e = -d //erreur de syntaxe ';' /* test commentaire sur plusieurs lignes */ //int e = -d; //erreur sémantique sur d //int f = 0 / 0; //division par 0 c++; printi(c); // 2 c--; c += 1; c-=1; printf("\nHello world !\n"); printi(42); printf("\n"); //caractère spéciaux à ne pas effacer printi(c); // 1 return 0; }
C
// Prim Wandeevong // CS 135 // Lab 10 // 4-15-19 // #include <stdio.h> int main() { char str[21], vowels[21], consonants[21]; char *strPointer, *vowelPointer, *consonantPointer; printf("Enter a string (20 characters maximum): "); scanf("%s", str); strPointer = &str[0]; vowelPointer = &vowels[0]; consonantPointer = &consonants[0]; while (*strPointer != '\0') { if(*strPointer == 'a' || *strPointer == 'e' || *strPointer == 'i' || *strPointer == 'o' || *strPointer== 'u' || *strPointer == 'A' || *strPointer == 'E' || *strPointer == 'I' || *strPointer == 'O' || *strPointer == 'U' ) { *vowelPointer = *strPointer; vowelPointer++; } else { *consonantPointer = *strPointer; consonantPointer++; } strPointer++; } *vowelPointer = '\0'; *consonantPointer = '\0'; vowelPointer = &vowels[0]; consonantPointer = &consonants[0]; printf("Original string: %s\n", str); printf("All the vowels: %s\n", vowelPointer); printf("All the consonants: %s\n", consonantPointer); return 0; }
C
#include <stdio.h> #include <io.h> #include <stdint.h> #define BASE_ADDR ((volatile char*) 0x00011000) #define MSG00_TEST 0b0101010101010101010101010 0000000 #define MSG01_TEST 0b0110010011101000111100010 0000000 #define MSG02_TEST 0b01001110010111101110001110000000 #define MSG03_TEST 0b0001100110011001100110011 0000000 const uint8_t gen = 0b10011001; const uint32_t msg = MSG02_TEST; void print_bits_impl(unsigned int num) { if (num > 1) { print_bits_impl(num / 2); } printf("%d", num % 2); } void print_bits(unsigned int num) { print_bits_impl(num); printf("\n"); } int main() { printf("Hello from Nios II!\n"); uint32_t gen_shifted = (gen << 24) + 1; printf("Inputs: \n"); print_bits(msg); print_bits(gen_shifted); printf("Inputs end \n\n"); IOWR(BASE_ADDR, 0, msg); print_bits(IORD(BASE_ADDR, 0)); IOWR(BASE_ADDR, 4, gen_shifted); print_bits(IORD(BASE_ADDR, 4)); uint32_t read; while ((read=IORD(BASE_ADDR, 4))) { printf("Waiting for CRC to finish\n"); print_bits(read); } uint32_t ret = IORD(BASE_ADDR, 0); printf("Result"); print_bits(ret); printf("Goodbye from NIOS II\n"); return 0; }
C
#include "holberton.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> /** * write_error - prints out error for write * @file: input file * Return: void */ void write_error(const char *file) { dprintf(STDERR_FILENO, "Error: Can't write to %s\n", file); exit(99); } /** * read_error - prints out read error * @file: input file * Return: void */ void read_error(const char *file) { dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", file); exit(98); } /** * main - copy contents of file to another * @argc: number of inputs * @argv: file names * Return: integer */ int main(int argc, char *argv[]) { char buf[1024]; int f_from, f_to, file1, file2, close_to, close_from; if (argc != 3) dprintf(STDERR_FILENO, "Usage: cp file_from file_to\n"), exit(97); file1 = open(argv[1], O_RDONLY); if (file1 == -1) { read_error(argv[1]); } file2 = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0664); if (file2 == -1) write_error(argv[2]); f_from = read(file1, buf, sizeof(buf)); if (f_from == -1) read_error(argv[1]); while (f_from > 0) { f_to = write(file2, buf, f_from); if (f_to == -1) { write_error(argv[2]); } f_from = read(file1, buf, sizeof(buf)); if (f_from == -1) { read_error(argv[1]); } } close_from = close(file1); if (close_from == -1) dprintf(STDERR_FILENO, "Error: Can't close fd %d\n", f_from), exit(100); close_to = close(file2); if (close_to == -1) dprintf(STDERR_FILENO, "Error: Can't close fd %d\n", f_to), exit(100); return (0); }
C
#include<stdio.h> #include "Util.h" void InsertNth(struct node** head, int ndx, int data) { if(ndx == 0) { Push(head, data); } else { int i = 0; struct node* cur = *head; for(i = 0; i < ndx -1; i++) { cur = cur->next; } if(cur != NULL) { Push(&(cur->next), data); } } } void main() { struct node* head = NULL; InsertNth(&head, 0, 13); InsertNth(&head, 1, 42); InsertNth(&head, 1, 5); PrintList(head); }
C
/* Name: Paul Talaga Date: Jan 26, 2018 Desc: Does the power function. Compile this with the -lm flag at the end like: $ gcc pow.c -lm This includes the math library during the linking phase. */ #include <stdio.h> #include <math.h> int main(){ float base = 0.0; float exponent = 0.0; printf("Enter a base:\n"); scanf("%f", &base); printf("Enter an exponent:\n"); scanf("%f", &exponent); printf("%f to the %f power is %f\n", base, exponent, pow( base,exponent) ); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> int main(int argc, char const *argv[]) { FILE* fid; fid=fopen("/proc/device-tree/compatible","r"); if (fid==NULL) { printf("Problema al leer device-tree\n"); exit(-1); } printf("\nLeyendo el device-tree...\n\n"); printf("\nFin de la lectura del device-tree...\n\n"); fclose(fid); return 0; }
C
#include "head.h" int CheckMessage(user_t *usert) { FILE* cm; int nowmon = 0, nowday = 0; time_t t; struct tm *pt; lr_t lr; int subday = 0, retmon = 0, retday = 0; if ((cm = fopen(usert->name, "rb")) == NULL) { perror("fopen error"); Press getchar(); return -1; } time(&t); pt = localtime(&t); nowmon = pt->tm_mon; nowday = pt->tm_mday; //ǰ¼ʱʱ䣻 rewind(cm); while (1) { memset(&lr, 0, sizeof(lr_t)); fread(&lr, sizeof(lr_t), 1, cm); if (feof(cm))break; if (lr.lr == 'L' && lr.useful == 1) //˸ÿ°30; { if (lr.lrt.year == (pt->tm_year +1900)) { subday = (pt->tm_mon - lr.lrt.month) * 30 + (pt->tm_mday - lr.lrt.day); retmon = lr.lrt.month + 1; retday = lr.lrt.day + 7; if (retday > 30) { retday -= 30; retmon += 1; if (retmon > 12)retmon -= 12; } if (subday >Borrowtime)printf("δ鼮NO.%d\tʱΪ%d\n", lr.bnum, subday-Borrowtime); if ((Borrowtime-subday ) <= 7)printf("ΪNO.%d鼮7ڵ,뼰ʱ飡\nΪ%d/%d/%d\n", lr.bnum,lr.lrt.year,retmon,retday); //⣡ } else printf("̫಻㣡\n"); } } fclose(cm); return 0; }