language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
// // main.c // challenge_2 // // Created by Alessandro Narciso on 2019-03-16. // Copyright © 2019 Alessandro Narciso. All rights reserved. // //Harder challenge: only if one or more of the numbers are prime, swap the places //{100,17,25,3,1,80,50,2,79,62} //{comp, prime, comp, prime, comp, comp, comp, prime, prime, comp} //{1, 2, 3, 4, 5, 5, 4, 3, 2, 1} 5 pairs //pair 1, both comp, no swap //pair 2, both prime, swap //pair 3, one prime, swap //pair 4, one prime, swap //pair 5, both comp, no swap //finished array should be: //{100,79,2,50,1,80,3,25,17,62} #include <stdio.h> //Function for printing arrays //If prime, will return 1; else, will return 0; int isprime(int num) { //Variables: j to iterate through natural numbers, flag to signal if num is prime int j, flag; //Check edge cases if(num <= 1) return 0; //0 and 1 are not prime //Set flag flag = 1; //Iterate through loop until num/2; start at 2 and increment through all natural numbers until limit for (j = 2; j <= num/2; j++) { //If num is divisible by a natural number j, it is not prime if ((num % j) == 0) { flag = 0; //flag signal not prime if divisible by a natural number break; //break loop to stop iterating and return value } } if (flag == 0) return 0; //number is not prime else return 1; //number is prime } //Function to reverse the array void rvereseArray(int arr[], int start, int end) { //Use temp to hold values from one array when swapping placement int temp; //Loop for reversing while (start < end) { if(isprime(arr[start]) == 1 || isprime(arr[end]) == 1){ temp = arr[start]; //Temp holds value at index start arr[start] = arr[end]; //Value at index start takes the value at index end arr[end] = temp; //Value at index end takes the value temp is holding (original value at index start) } //Moving indices to reverse next values start++; end--; } } void printArray(int arr[], int size) { //Variable for array for loop counter int i; //For loop to print array, iterating through index values i for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } //Main function that calls to other functions int main(void) { //Array we will be reversing int arr[] = {100,17,25,3,1,80,50,2,79,62}; //Print original array printf("Original array is: \n");//Output for user feedback printArray(arr, 10);//Call to function to print array //Reverse array and check if prime rvereseArray(arr, 0, 9); //Call to function to reverse array (index value of edges as parameters) printf("Reversed array is: \n"); //Output for user feedback printArray(arr, 10); //Call to function to print array return 0; }
C
#ifndef READ_FROM_CONFIG_H #define READ_FROM_CONFIG_H #define MAXSTR 500 /** * Structure defining configuration variables. * * */ typedef struct { unsigned int xdim; unsigned int ydim; unsigned int nzombies; unsigned int nhumans; unsigned int nzplayers; unsigned int nhplayers; unsigned int turns; } CONFIG; /** * Read from config file. * * @param argc Number of arguments passed through command line. * @param argv Array of strings that contain the arguments passed. * @return A new `CONFIG` object. * */ CONFIG read_config(int argc, char *argv[]); /** * Set config values * * @param config Pointer to `CONFIG` object. * @param key Constant string. * @param val Integer value. * */ void set_config_val(CONFIG *config, const char *key, int val); #endif
C
#include<stdio.h> #include<conio.h> void main() { int i,size,a[50],num,pos; clrscr(); printf("Enter the size"); scanf("%d",&size); printf("enter element of array"); for(i=0;i<size;i++) scanf("%d",&a[i]); printf("enetr the position"); scanf("%d",&pos); printf("enter the number"); scanf("%d",&num); if(pos<=0||pos>size+1) printf("invalid position"); else { for(i=size-1;i>=pos-1;i--) { a[i+1]=a[i]; } a[pos-1]=num; size++; } for(i=0;i<size;i++) printf("%d ",a[i]); getch(); }
C
//ģƥ㷨 #define N 10; //Ʒ #define K 25; //ά double LeastDistance() { double min=10000000000; number_no number_no; for(int n=0;n<N;n++) { for(int i=0;i<pattern[n].number;i++) { if(match(pattern[n].feature[i],testsample)<min) { //ƥСֵ min=match(pattern[n].feature[i],testsample); number_no.number=n;//ģ number_no.no=i;//ģ } } } return number_no;// } double match(double a[], double b[]) { double count=0.0; for(int i=0;i<K;i++) { count+=(a[i]-b[i])*(a[i]-b[i]); } return count; }
C
#include <stdio.h> #include <stdlib.h> typedef int T; int cmpInt(T a, T b) { return a < b; } int cmp(const void *a,const void *b){ return *(int*)a - *(int*)b; } void quickSort(T *array, int (*compare)(T a, T b), int l, int r) { int i, j; T mid; if (r - l < 2) return; for (i = l, j = r - 1, mid = array[l]; i < j;) { while (compare(mid, array[j]) && i < j) j--; if (i < j) array[i++] = array[j]; while (compare(array[i], mid) && i < j) i++; if (i < j) array[j--] = array[i]; } array[i] = mid; quickSort(array, compare, l, i); quickSort(array, compare, i + 1, r); } int n, num[(int)1e6 + 5]; int i, gap; int main() { scanf("%d", &n); if (n == 1 || n == 2) { printf("Yes"); return 0; } for (i = 0; i < n; i++) scanf("%d", num + i); //quickSort(num, cmpInt, 0, n); qsort(num,n,sizeof(int),cmp); gap = num[1] - num[0]; for (i = 2; i < n; i++) if (num[i] - num[i - 1] != gap) { printf("NO"); return 0; } printf("Yes"); return 0; }
C
#include <stdio.h> #include <math.h> int main() { int N, K; double ans = 0.0; scanf("%d%d", &N, &K); // 確率計算 for (int i = 1; i <= N; i++) { double tmp = 1/N; // その目が出る確率 int num = i; // 勝つまでのループ while (num<K) { num *= 2; tmp /= 2; } ans += tmp; } printf("%lf", ans); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* Exercise 1-8 Write a program to count blanks, tabs, and new lines. */ int main() { int c, nl, space, tab; nl = 0; space = 0; tab = 0; while ((c = getchar()) != EOF){ if(c == '\n'){ ++nl; } if(c == ' '){ ++space; } if(c == '\t'){ ++tab; } } printf("New lines: %d\nspaces: %d\ntabs: %d", nl, space, tab); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]) { char command[1024]; if (argc != 2) { fprintf(stderr, "Usage: %s <filename>\n", argv[0]); exit(0); } sprintf(command,"stat %s",argv[1]); system(command); return 0; }
C
#include <stdio.h> int sum(int n) { int s = 0; if (n == 0) return 0; else { s = n % 10; n = n / 10; return s + sum(n); } } int main() { int n, y; printf("enter the number\n"); scanf("%d", &n); y = sum(n); printf("sum of digit is %d", y); }
C
#include <stdio.h> int main(){ int x; while(1){ scanf("%d",&x); if(x==0) break; printf("Number %d in hexadecimal is %X.\n",x,x); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<pthread.h> void *threadFn(void* arg) { pthread_detach(pthread_self()); sleep(1); printf("Thread Fn\n"); pthread_exit(NULL); } int main(int argc, char** argv) { pthread_t tid; int ret = pthread_create(&tid, NULL, threadFn, NULL); if (ret != 0) { perror("Thread Creation Error\n"); exit(1); } printf("After thread created in Main\n"); pthread_exit(NULL); }
C
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include "error_handling.h" #include "shared_memory.h" #define PERMS 0666 static inline int shm_get(key_t key, size_t size) { assert(size > 0); int shm_id; shm_id = shmget(key, size, IPC_CREAT | PERMS); if (shm_id == -1) { handle_error("Error: shmget"); } return shm_id; } static inline void *shm_attach(int shm_id) { return shmat(shm_id, NULL, 0); } static inline int shm_dettach(const void *memory) { assert(memory != NULL); int shm_id; if ((shm_id = shmdt(memory)) == -1) { handle_error("Error: shmdt"); } return shm_id; } static inline int shm_control(int shm_id) { return shmctl(shm_id, IPC_RMID, 0); } shm_t *shared_memory_create(key_t key) { int shm_id; shm_t *shared_memory; shm_id = shm_get(key, sizeof(shm_t)); shared_memory = shm_attach(shm_id); shared_memory->number = 0; return shared_memory; } int shared_memory_dettach(shm_t *shared_memory) { int shm_id; if ((shm_id = shm_dettach(shared_memory)) == -1) handle_error("Error: shmdt"); return shm_id; } int shared_memory_deallocate(int shm_id) { return shm_control(shm_id); }
C
// Do not remove #ifdef ... #endif before and after each function. // // They are used to test different functions in your program and give // partial credits, in case your program does not work completely. #include "student.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "msort.h" void StudentPrint(Student * stu, int num) { printf("There are %d students\n", num); for (int ind = 0; ind < num; ind ++) { printf("ID = %d, First Name = %s, Last Name = %s\n", stu[ind].ID, stu[ind].firstname, stu[ind].lastname); } } #ifdef TEST_READ // return false if anything is wrong // return true if reading the file successfully and the data is save in // the allocated memory // input: filename, the name of the input file // output: address of the allocated memory // output: number of students bool StudentRead(char * filename, Student * * stu, int * numelem) { // open the file to read FILE * inf; inf = fopen(filename, "r"); // if fopen fails, return false // do not use fclose since fopen already fails if (inf == NULL) { return false; } // count the number of lines to determine the number of students char character; //stores the character obtained using fscanf int length = 0; //stores the length int current = fscanf(inf, "%c", &character); while(current != EOF) { if(character == '\n') { (length++); } current = fscanf(inf, "%c", &character); } (*numelem) = length; //assigns the obtained length value to the data at numelem // return to the beginning of the file // you can use fseek or // fclose followed by fopen // You need to check whether fseek or fopen fails // Do not use rewind because it does not report whether it fails int status = 0; //stores the status returned by fseek status = fseek(inf,0,SEEK_SET); if(status) { return false; } // allocate memory for the data Student * stuptr; stuptr = malloc(sizeof(*stuptr) * (length)); *stu = stuptr; // check whether memory allocation fails if((stuptr) == NULL) { return false; } // read the data from the file and store the data in the allocated memory int counter1 = 0; //Counter variable for the for-loop for(counter1 = 0; counter1 < length; counter1++) { fscanf(inf, "%d %s %s\n", &(stuptr[counter1]).ID, stuptr[counter1].firstname, stuptr[counter1].lastname); } // close the file fclose(inf); return true; } #endif #ifdef TEST_WRITE // return false if anything is wrong // return true if writing the file successfully // input: filename, the name of the output file // input: address of the student array // input: number of students bool StudentWrite(char * filename, Student * stu, int numelem) { FILE * ouf; ouf = fopen(filename,"w"); // if fopen fails, return false // do not use fclose since fopen already fails if(ouf == NULL) { return false; } // write the students to the output file int counter2 = 0; for(counter2 = 0; counter2 < numelem; counter2++) { fprintf(ouf, "%d %s %s\n", stu[counter2].ID, stu[counter2].firstname, stu[counter2].lastname); } fclose(ouf); return true; } #endif #ifdef TEST_SORTID int comparefuncID(const void * arg1, const void * arg2) { const Student * ptr1 = (const Student *) arg1; const Student * ptr2 = (const Student *) arg2; return ((ptr1->ID) - (ptr2->ID)); } void StudentSortbyID(Student * stu, int numelem) { msort(stu,numelem,comparefuncID); } #endif #ifdef TEST_SORTFIRSTNAME int cmpstringpfirstname(const void *arg1, const void *arg2) { const Student * ptr1 = (const Student *) arg1; const Student * ptr2 = (const Student *) arg2; return strcmp(ptr1->firstname, ptr2->firstname); } void StudentSortbyFirstName(Student * stu, int numelem) { msort(stu,numelem,cmpstringpfirstname); } #endif #ifdef TEST_SORTLASTNAME int cmpstringplastname(const void *arg1, const void *arg2) { const Student * ptr1 = (const Student *) arg1; const Student * ptr2 = (const Student *) arg2; return strcmp(ptr1->lastname, ptr2->lastname); } void StudentSortbyLastName(Student * stu, int numelem) { msort(stu,numelem,cmpstringplastname); } #endif
C
#include <stdlib.h> #include <stdio.h> #include <string.h> //todo delete fun //todo opt the insert index, because it is now sorted-index ,result in that it is just like link list static int cas_int_inc(int *addr,int delta){ int ret =0; __asm__ __volatile__( "lock;xaddl %2,%1;" :"=a"(ret) :"m"(*addr),"0"(delta) :"memory","cc" ); return ret; } struct TreeNode_; typedef struct TreeNode_ TreeNode; typedef TreeNode * TreeRoot; typedef int IndexData; struct TreeNode_{ TreeNode *right,*left; IndexData indx; void *data; }; struct Tree_; typedef struct Tree_ Tree; struct Tree_{ TreeNode *root; int size; }; /************** struct Data_; typedef struct Data_ Data; typedef struct Data_{ //index -d int index; //udata -d int dataUid; int topic; //pdata -d int partition ; }; *****/ TreeNode* createNode(void* data); void append(TreeRoot root,TreeNode *node); TreeNode* findNodeByIndex(TreeRoot root,IndexData indx); Tree* createTree(){ Tree * tree = malloc(sizeof(Tree)); memset(tree,0,sizeof(Tree)); tree->size =0; return tree; } void destoryTree(Tree *tree){ if (tree!=NULL){ free(tree); printf("release Tree complete ...\n"); } } int TreeInsert(Tree * tree,void* data){ int id = tree->size; TreeNode *n = (TreeNode*)createNode(data); n->indx = id; cas_int_inc(&tree->size,1); if (tree->root==NULL){ tree->root = n; }else{ append(tree->root,n); } return id; } void* TreeFind(Tree * tree,int idx){ TreeNode * n =findNodeByIndex(tree->root,idx); if (n!=NULL){ return n->data; } return NULL; } TreeNode* createNode(void* data){ TreeNode* node =0; do{ node=(TreeNode*) malloc(sizeof(TreeNode)); }while(node==0); memset(node,0,sizeof(TreeNode)); node->data=data; return node; } void append(TreeRoot root,TreeNode *node){ if (root==NULL || node==NULL)return; if (node->indx<=root->indx){ if (root->left!=NULL){ append(root->left,node); }else{ root->left = node; printf("inserted node idx:%d \n",node->indx); } }else{ if (root->right!=NULL){ append(root->right,node); }else{ root->right = node; printf("inserted node idx:%d \n",node->indx); } } } void forEachInOrder(TreeRoot root){ if (root==NULL){ return ; } forEachInOrder(root->left); printf("%d\n",root->indx); forEachInOrder(root->right); } typedef void (*ForeachCallback)(TreeNode* node); void forEachPostOrderByCallack(TreeRoot root,ForeachCallback callbackFn){ if (root==NULL || callbackFn==NULL){ return ; } forEachPostOrderByCallack(root->left,callbackFn); forEachPostOrderByCallack(root->right,callbackFn); //printf("%d\n",root->indx); callbackFn(root); } TreeNode* findNodeByIndex(TreeRoot root,int indx){ if (root==NULL)return NULL; // printf(" right -> currIndx=%d, target=%d\n",root->indx,indx); if (root->indx==indx){ printf("find finished\n"); return root; } if (indx<root->indx){ if (root->left!=NULL){ printf(" left <- \n"); return findNodeByIndex(root->left,indx); }else{ return NULL;//已经是nil 往下没有节点了,就是没找到了 } }else{ if (root->right!=NULL){ return findNodeByIndex(root->right,indx); }else{ return NULL;//已经是nil 往下没有节点了,就是没找到了 } } return NULL; } void foreachDestroyInner(TreeNode* node){ if (node!=NULL){ free(node); printf("release element idx:%d \n",node->indx); } } //数的作用就是导航检索,适合猜数据的左右方向导航的 struct File_; typedef struct File_ File; struct File_{ int fd; char name[30]; }; int main(int argc,const char *argvs[]){ File f1={1,"helloworld"}; File f8={8,"helloworld8"}; File f6={6,"helloworld6"}; File f5={5,"helloworld5"}; File f3={3,"helloworld3"}; Tree *tree = createTree(); int indx_1= TreeInsert(tree,&f1); int indx_8= TreeInsert(tree,&f8); int indx_6= TreeInsert(tree,&f6); int indx_5= TreeInsert(tree,&f5); int indx_3= TreeInsert(tree,&f3); printf("indx_1=%d,indx_8=%d,indx_6=%d,indx_5=%d,indx_3=%d \n", indx_1,indx_8,indx_6,indx_5,indx_3 ); forEachInOrder(tree->root); printf("==========================\n"); File * target= TreeFind(tree, indx_6); if (target!=0){ printf("result: fd=%d name=%s \n",target->fd,target->name); }else{ printf("find nil\n"); } forEachPostOrderByCallack(tree->root,foreachDestroyInner); destoryTree(tree); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <wiringPi.h> #include <wiringPiI2C.h> #include <pthread.h> #include <unistd.h> #include "Accelerometer.h" struct Accelerometer { void* userData; void (*callback)(void*); /*private*/ pthread_t thread; /*private*/ int fd; }; typedef struct Accelerometer Accelerometer; void *pingThread(void* userData) { Accelerometer* self = (Accelerometer*) userData; int prevRead = wiringPiI2CReadReg16(self->fd, 0x36); while (1) { int read = wiringPiI2CReadReg16(self->fd, 0x36); int diff = abs(read - prevRead); //printf("diff: %i\n", diff); if (diff >= threshold && diff < wrap && read > prevRead) { //printf("Threshold exceeded\n"); self->callback(self->userData); } prevRead = read; usleep(10); } } void Accelerometer__init(Accelerometer* self, void (*callback)(void*), void* userData) { self->userData = userData; self->callback = callback; pinModeAlt( 8, 0b100 ); //"alt0" pinModeAlt( 9, 0b100 ); //"alt0" self->fd = wiringPiI2CSetup(0x53); wiringPiI2CWriteReg8(self->fd, 0x2D, 0b00101000); pthread_create(&self->thread, NULL, &pingThread, (void*) self); } Accelerometer* Accelerometer__create(void (*callback)(void*), void* userData) { Accelerometer* result = (Accelerometer*) malloc(sizeof(Accelerometer)); Accelerometer__init(result, callback, userData); return result; }
C
#include "common.h" struct spng_decomp { unsigned char *buf; /* input buffer */ size_t size; /* input buffer size */ char *out; /* output buffer */ size_t decomp_size; /* decompressed data size */ size_t decomp_alloc_size; /* actual buffer size */ size_t initial_size; /* initial value for decomp_size */ }; static inline uint16_t read_u16(const void *_data) { const unsigned char *data = _data; return (data[0] & 0xffU) << 8 | (data[1] & 0xffU); } static inline uint32_t read_u32(const void *_data) { const unsigned char *data = _data; return (data[0] & 0xffUL) << 24 | (data[1] & 0xffUL) << 16 | (data[2] & 0xffUL) << 8 | (data[3] & 0xffUL); } static inline int32_t read_s32(const void *_data) { const unsigned char *data = _data; int32_t ret; uint32_t val = (data[0] & 0xffUL) << 24 | (data[1] & 0xffUL) << 16 | (data[2] & 0xffUL) << 8 | (data[3] & 0xffUL); memcpy(&ret, &val, 4); return ret; } int is_critical_chunk(struct spng_chunk *chunk) { if(chunk == NULL) return 0; if((chunk->type[0] & (1 << 5)) == 0) return 1; return 0; } static inline int read_data(spng_ctx *ctx, size_t bytes) { if(ctx == NULL) return 1; if(!bytes) return 0; if(ctx->streaming && (bytes > ctx->data_size)) { void *buf = spng__realloc(ctx, ctx->data, bytes); if(buf == NULL) return SPNG_EMEM; ctx->data = buf; ctx->data_size = bytes; } int ret; ret = ctx->read_fn(ctx, ctx->read_user_ptr, ctx->data, bytes); if(ret) return ret; ctx->bytes_read += bytes; if(ctx->bytes_read < bytes) return SPNG_EOVERFLOW; return 0; } static inline int read_and_check_crc(spng_ctx *ctx) { if(ctx == NULL) return 1; int ret; ret = read_data(ctx, 4); if(ret) return ret; ctx->current_chunk.crc = read_u32(ctx->data); if(is_critical_chunk(&ctx->current_chunk) && ctx->crc_action_critical == SPNG_CRC_USE) goto skip_crc; else if(ctx->crc_action_ancillary == SPNG_CRC_USE) goto skip_crc; if(ctx->cur_actual_crc != ctx->current_chunk.crc) return SPNG_ECHUNK_CRC; skip_crc: return 0; } /* Read and validate the current chunk's crc and the next chunk header */ static inline int read_header(spng_ctx *ctx) { if(ctx == NULL) return 1; int ret; struct spng_chunk chunk = { 0 }; ret = read_and_check_crc(ctx); if(ret) return ret; ret = read_data(ctx, 8); if(ret) return ret; chunk.offset = ctx->bytes_read - 8; chunk.length = read_u32(ctx->data); memcpy(&chunk.type, ctx->data + 4, 4); if(chunk.length > png_u32max) return SPNG_ECHUNK_SIZE; ctx->cur_chunk_bytes_left = chunk.length; ctx->cur_actual_crc = crc32(0, NULL, 0); ctx->cur_actual_crc = crc32(ctx->cur_actual_crc, chunk.type, 4); memcpy(&ctx->current_chunk, &chunk, sizeof(struct spng_chunk)); return 0; } /* Read chunk bytes and update crc */ static int read_chunk_bytes(spng_ctx *ctx, uint32_t bytes) { if(ctx == NULL) return 1; if(!bytes) return 0; if(bytes > ctx->cur_chunk_bytes_left) return 1; /* XXX: more specific error? */ int ret; ret = read_data(ctx, bytes); if(ret) return ret; if(is_critical_chunk(&ctx->current_chunk) && ctx->crc_action_critical == SPNG_CRC_USE) goto skip_crc; else if(ctx->crc_action_ancillary == SPNG_CRC_USE) goto skip_crc; ctx->cur_actual_crc = crc32(ctx->cur_actual_crc, ctx->data, bytes); skip_crc: ctx->cur_chunk_bytes_left -= bytes; return ret; } static int discard_chunk_bytes(spng_ctx *ctx, uint32_t bytes) { if(ctx == NULL) return 1; int ret; if(ctx->streaming) /* Do small, consecutive reads */ { while(bytes) { uint32_t len = 8192; if(len > bytes) len = bytes; ret = read_chunk_bytes(ctx, len); if(ret) return ret; bytes -= len; } } else { ret = read_chunk_bytes(ctx, bytes); if(ret) return ret; } return 0; } /* Read at least one byte from the IDAT stream */ static int get_idat_bytes(spng_ctx *ctx, uint32_t *bytes_read) { if(ctx == NULL || bytes_read == NULL) return 1; if(memcmp(ctx->current_chunk.type, type_idat, 4)) return 1; int ret; uint32_t len; while(!ctx->cur_chunk_bytes_left) { ret = read_header(ctx); if(ret) return ret; if(memcmp(ctx->current_chunk.type, type_idat, 4)) return SPNG_EIDAT_TOO_SHORT; } if(ctx->streaming) {/* TODO: calculate bytes to read for progressive reads */ len = 8192; if(len > ctx->current_chunk.length) len = ctx->current_chunk.length; } else len = ctx->current_chunk.length; ret = read_chunk_bytes(ctx, len); *bytes_read = len; return ret; } static uint8_t paeth(uint8_t a, uint8_t b, uint8_t c) { int16_t p = (int16_t)a + (int16_t)b - (int16_t)c; int16_t pa = abs(p - (int16_t)a); int16_t pb = abs(p - (int16_t)b); int16_t pc = abs(p - (int16_t)c); if(pa <= pb && pa <= pc) return a; else if(pb <= pc) return b; return c; } static int defilter_scanline(const unsigned char *prev_scanline, unsigned char *scanline, size_t scanline_width, uint8_t bytes_per_pixel) { if(prev_scanline == NULL || scanline == NULL || scanline_width <= 1) return 1; size_t i; uint8_t filter = 0; memcpy(&filter, scanline, 1); if(filter > 4) return SPNG_EFILTER; if(filter == 0) return 0; #if defined(SPNG_OPTIMIZE_FILTER) if(filter == SPNG_FILTER_TYPE_UP) goto no_opt; if(bytes_per_pixel == 4) { if(filter == SPNG_FILTER_TYPE_SUB) png_read_filter_row_sub4(scanline_width - 1, scanline + 1); else if(filter == SPNG_FILTER_TYPE_AVERAGE) png_read_filter_row_avg4(scanline_width - 1, scanline + 1, prev_scanline + 1); else if(filter == SPNG_FILTER_TYPE_PAETH) png_read_filter_row_paeth4(scanline_width - 1, scanline + 1, prev_scanline + 1); return 0; } else if(bytes_per_pixel == 3) { if(filter == SPNG_FILTER_TYPE_SUB) png_read_filter_row_sub3(scanline_width - 1, scanline + 1); else if(filter == SPNG_FILTER_TYPE_AVERAGE) png_read_filter_row_avg3(scanline_width - 1, scanline + 1, prev_scanline + 1); else if(filter == SPNG_FILTER_TYPE_PAETH) png_read_filter_row_paeth3(scanline_width - 1, scanline + 1, prev_scanline + 1); return 0; } no_opt: #endif for(i=1; i < scanline_width; i++) { uint8_t x, a, b, c; if(i > bytes_per_pixel) { memcpy(&a, scanline + i - bytes_per_pixel, 1); memcpy(&b, prev_scanline + i, 1); memcpy(&c, prev_scanline + i - bytes_per_pixel, 1); } else /* first pixel in row */ { a = 0; memcpy(&b, prev_scanline + i, 1); c = 0; } memcpy(&x, scanline + i, 1); switch(filter) { case SPNG_FILTER_TYPE_SUB: { x = x + a; break; } case SPNG_FILTER_TYPE_UP: { x = x + b; break; } case SPNG_FILTER_TYPE_AVERAGE: { uint16_t avg = (a + b) / 2; x = x + avg; break; } case SPNG_FILTER_TYPE_PAETH: { x = x + paeth(a,b,c); break; } } memcpy(scanline + i, &x, 1); } return 0; } /* Read and validate all critical and relevant ancillary chunks up to the first IDAT Returns zero and sets ctx->first_idat on success */ static int get_ancillary_data_first_idat(spng_ctx *ctx) { if(ctx == NULL) return 1; if(ctx->data == NULL) return 1; if(!ctx->valid_state) return SPNG_EBADSTATE; int ret; unsigned char *data; struct spng_chunk chunk; chunk.offset = 8; chunk.length = 13; size_t sizeof_sig_ihdr = 29; ret = read_data(ctx, sizeof_sig_ihdr); if(ret) return ret; data = ctx->data; uint8_t signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 }; if(memcmp(data, signature, sizeof(signature))) return SPNG_ESIGNATURE; chunk.length = read_u32(data + 8); memcpy(&chunk.type, data + 12, 4); if(chunk.length != 13) return SPNG_EIHDR_SIZE; if(memcmp(chunk.type, type_ihdr, 4)) return SPNG_ENOIHDR; ctx->cur_actual_crc = crc32(0, NULL, 0); ctx->cur_actual_crc = crc32(ctx->cur_actual_crc, data + 12, 17); ctx->ihdr.width = read_u32(data + 16); ctx->ihdr.height = read_u32(data + 20); memcpy(&ctx->ihdr.bit_depth, data + 24, 1); memcpy(&ctx->ihdr.color_type, data + 25, 1); memcpy(&ctx->ihdr.compression_method, data + 26, 1); memcpy(&ctx->ihdr.filter_method, data + 27, 1); memcpy(&ctx->ihdr.interlace_method, data + 28, 1); if(!ctx->max_width) ctx->max_width = png_u32max; if(!ctx->max_height) ctx->max_height = png_u32max; ret = check_ihdr(&ctx->ihdr, ctx->max_width, ctx->max_height); if(ret) return ret; ctx->file_ihdr = 1; ctx->stored_ihdr = 1; while( !(ret = read_header(ctx))) { memcpy(&chunk, &ctx->current_chunk, sizeof(struct spng_chunk)); if(!memcmp(chunk.type, type_idat, 4)) { memcpy(&ctx->first_idat, &chunk, sizeof(struct spng_chunk)); return 0; } ret = read_chunk_bytes(ctx, chunk.length); if(ret) return ret; data = ctx->data; /* Reserved bit must be zero */ if( (chunk.type[2] & (1 << 5)) != 0) return SPNG_ECHUNK_TYPE; /* Ignore private chunks */ if( (chunk.type[1] & (1 << 5)) != 0) continue; if(is_critical_chunk(&chunk)) /* Critical chunk */ { if(!memcmp(chunk.type, type_plte, 4)) { if(chunk.length == 0) return SPNG_ECHUNK_SIZE; if(chunk.length % 3 != 0) return SPNG_ECHUNK_SIZE; if( (chunk.length / 3) > 256 ) return SPNG_ECHUNK_SIZE; if(ctx->ihdr.color_type == 3) { if(chunk.length / 3 > (1 << ctx->ihdr.bit_depth) ) return SPNG_ECHUNK_SIZE; } ctx->plte.n_entries = chunk.length / 3; size_t i; for(i=0; i < ctx->plte.n_entries; i++) { memcpy(&ctx->plte.entries[i].red, data + i * 3, 1); memcpy(&ctx->plte.entries[i].green, data + i * 3 + 1, 1); memcpy(&ctx->plte.entries[i].blue, data + i * 3 + 2, 1); } ctx->plte_offset = chunk.offset; ctx->file_plte = 1; } else if(!memcmp(chunk.type, type_iend, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_ihdr, 4)) return SPNG_ECHUNK_POS; else return SPNG_ECHUNK_UNKNOWN_CRITICAL; } else if(!memcmp(chunk.type, type_chrm, 4)) /* Ancillary chunks */ { if(ctx->file_plte && chunk.offset > ctx->plte_offset) return SPNG_ECHUNK_POS; if(ctx->file_chrm) return SPNG_EDUP_CHRM; if(chunk.length != 32) return SPNG_ECHUNK_SIZE; ctx->chrm_int.white_point_x = read_u32(data); ctx->chrm_int.white_point_y = read_u32(data + 4); ctx->chrm_int.red_x = read_u32(data + 8); ctx->chrm_int.red_y = read_u32(data + 12); ctx->chrm_int.green_x = read_u32(data + 16); ctx->chrm_int.green_y = read_u32(data + 20); ctx->chrm_int.blue_x = read_u32(data + 24); ctx->chrm_int.blue_y = read_u32(data + 28); if(check_chrm_int(&ctx->chrm_int)) return SPNG_ECHRM; ctx->file_chrm = 1; ctx->stored_chrm = 1; } else if(!memcmp(chunk.type, type_gama, 4)) { if(ctx->file_plte && chunk.offset > ctx->plte_offset) return SPNG_ECHUNK_POS; if(ctx->file_gama) return SPNG_EDUP_GAMA; if(chunk.length != 4) return SPNG_ECHUNK_SIZE; ctx->gama = read_u32(data); if(!ctx->gama) return SPNG_EGAMA; if(ctx->gama > png_u32max) return SPNG_EGAMA; ctx->file_gama = 1; ctx->stored_gama = 1; } else if(!memcmp(chunk.type, type_iccp, 4)) { if(ctx->file_plte && chunk.offset > ctx->plte_offset) return SPNG_ECHUNK_POS; if(ctx->file_iccp) return SPNG_EDUP_ICCP; if(!chunk.length) return SPNG_ECHUNK_SIZE; continue; /* XXX: https://gitlab.com/randy408/libspng/issues/31 */ } else if(!memcmp(chunk.type, type_sbit, 4)) { if(ctx->file_plte && chunk.offset > ctx->plte_offset) return SPNG_ECHUNK_POS; if(ctx->file_sbit) return SPNG_EDUP_SBIT; if(ctx->ihdr.color_type == 0) { if(chunk.length != 1) return SPNG_ECHUNK_SIZE; memcpy(&ctx->sbit.grayscale_bits, data, 1); } else if(ctx->ihdr.color_type == 2 || ctx->ihdr.color_type == 3) { if(chunk.length != 3) return SPNG_ECHUNK_SIZE; memcpy(&ctx->sbit.red_bits, data, 1); memcpy(&ctx->sbit.green_bits, data + 1 , 1); memcpy(&ctx->sbit.blue_bits, data + 2, 1); } else if(ctx->ihdr.color_type == 4) { if(chunk.length != 2) return SPNG_ECHUNK_SIZE; memcpy(&ctx->sbit.grayscale_bits, data, 1); memcpy(&ctx->sbit.alpha_bits, data + 1, 1); } else if(ctx->ihdr.color_type == 6) { if(chunk.length != 4) return SPNG_ECHUNK_SIZE; memcpy(&ctx->sbit.red_bits, data, 1); memcpy(&ctx->sbit.green_bits, data + 1, 1); memcpy(&ctx->sbit.blue_bits, data + 2, 1); memcpy(&ctx->sbit.alpha_bits, data + 3, 1); } if(check_sbit(&ctx->sbit, &ctx->ihdr)) return SPNG_ESBIT; ctx->file_sbit = 1; ctx->stored_sbit = 1; } else if(!memcmp(chunk.type, type_srgb, 4)) { if(ctx->file_plte && chunk.offset > ctx->plte_offset) return SPNG_ECHUNK_POS; if(ctx->file_srgb) return SPNG_EDUP_SRGB; if(chunk.length != 1) return SPNG_ECHUNK_SIZE; memcpy(&ctx->srgb_rendering_intent, data, 1); if(ctx->srgb_rendering_intent > 3) return SPNG_ESRGB; ctx->file_srgb = 1; ctx->stored_srgb = 1; } else if(!memcmp(chunk.type, type_bkgd, 4)) { if(ctx->file_plte && chunk.offset < ctx->plte_offset) return SPNG_ECHUNK_POS; if(ctx->file_bkgd) return SPNG_EDUP_BKGD; uint16_t mask = ~0; if(ctx->ihdr.bit_depth < 16) mask = (1 << ctx->ihdr.bit_depth) - 1; if(ctx->ihdr.color_type == 0 || ctx->ihdr.color_type == 4) { if(chunk.length != 2) return SPNG_ECHUNK_SIZE; ctx->bkgd.gray = read_u16(data) & mask; } else if(ctx->ihdr.color_type == 2 || ctx->ihdr.color_type == 6) { if(chunk.length != 6) return SPNG_ECHUNK_SIZE; ctx->bkgd.red = read_u16(data) & mask; ctx->bkgd.green = read_u16(data + 2) & mask; ctx->bkgd.blue = read_u16(data + 4) & mask; } else if(ctx->ihdr.color_type == 3) { if(chunk.length != 1) return SPNG_ECHUNK_SIZE; if(!ctx->file_plte) return SPNG_EBKGD_NO_PLTE; memcpy(&ctx->bkgd.plte_index, data, 1); if(ctx->bkgd.plte_index >= ctx->plte.n_entries) return SPNG_EBKGD_PLTE_IDX; } ctx->file_bkgd = 1; ctx->stored_bkgd = 1; } else if(!memcmp(chunk.type, type_trns, 4)) { if(ctx->file_plte && chunk.offset < ctx->plte_offset) return SPNG_ECHUNK_POS; if(ctx->file_trns) return SPNG_EDUP_TRNS; if(!chunk.length) return SPNG_ECHUNK_SIZE; uint16_t mask = ~0; if(ctx->ihdr.bit_depth < 16) mask = (1 << ctx->ihdr.bit_depth) - 1; if(ctx->ihdr.color_type == 0) { if(chunk.length != 2) return SPNG_ECHUNK_SIZE; ctx->trns.gray = read_u16(data) & mask; } else if(ctx->ihdr.color_type == 2) { if(chunk.length != 6) return SPNG_ECHUNK_SIZE; ctx->trns.red = read_u16(data) & mask; ctx->trns.green = read_u16(data + 2) & mask; ctx->trns.blue = read_u16(data + 4) & mask; } else if(ctx->ihdr.color_type == 3) { if(chunk.length > ctx->plte.n_entries) return SPNG_ECHUNK_SIZE; if(!ctx->file_plte) return SPNG_ETRNS_NO_PLTE; size_t k; for(k=0; k < chunk.length; k++) { memcpy(&ctx->trns.type3_alpha[k], data + k, 1); } ctx->trns.n_type3_entries = chunk.length; } else return SPNG_ETRNS_COLOR_TYPE; ctx->file_trns = 1; ctx->stored_trns = 1; } else if(!memcmp(chunk.type, type_hist, 4)) { if(!ctx->file_plte) return SPNG_EHIST_NO_PLTE; if(chunk.offset < ctx->plte_offset) return SPNG_ECHUNK_POS; if(ctx->file_hist) return SPNG_EDUP_HIST; if( (chunk.length / 2) != (ctx->plte.n_entries) ) return SPNG_ECHUNK_SIZE; size_t k; for(k=0; k < (chunk.length / 2); k++) { ctx->hist.frequency[k] = read_u16(data + k*2); } ctx->file_hist = 1; ctx->stored_hist = 1; } else if(!memcmp(chunk.type, type_phys, 4)) { if(ctx->file_phys) return SPNG_EDUP_PHYS; if(chunk.length != 9) return SPNG_ECHUNK_SIZE; ctx->phys.ppu_x = read_u32(data); ctx->phys.ppu_y = read_u32(data + 4); memcpy(&ctx->phys.unit_specifier, data + 8, 1); if(check_phys(&ctx->phys)) return SPNG_EPHYS; ctx->file_phys = 1; ctx->stored_phys = 1; } else if(!memcmp(chunk.type, type_splt, 4)) { if(ctx->user_splt) continue; /* XXX: should check profile names for uniqueness */ if(!chunk.length) return SPNG_ECHUNK_SIZE; ctx->file_splt = 1; if(!ctx->stored_splt) { ctx->n_splt = 1; ctx->splt_list = spng__calloc(ctx, 1, sizeof(struct spng_splt)); if(ctx->splt_list == NULL) return SPNG_EMEM; } else { ctx->n_splt++; if(ctx->n_splt < 1) return SPNG_EOVERFLOW; if(sizeof(struct spng_splt) > SIZE_MAX / ctx->n_splt) return SPNG_EOVERFLOW; void *buf = spng__realloc(ctx, ctx->splt_list, ctx->n_splt * sizeof(struct spng_splt)); if(buf == NULL) return SPNG_EMEM; ctx->splt_list = buf; memset(&ctx->splt_list[ctx->n_splt - 1], 0, sizeof(struct spng_splt)); } uint32_t i = ctx->n_splt - 1; size_t keyword_len = chunk.length > 80 ? 80 : chunk.length; char *keyword_nul = memchr(data, '\0', keyword_len); if(keyword_nul == NULL) return SPNG_ESPLT_NAME; memcpy(&ctx->splt_list[i].name, data, keyword_len); if(check_png_keyword(ctx->splt_list[i].name)) return SPNG_ESPLT_NAME; keyword_len = strlen(ctx->splt_list[i].name); if( (chunk.length - keyword_len - 1) == 0) return SPNG_ECHUNK_SIZE; memcpy(&ctx->splt_list[i].sample_depth, data + keyword_len + 1, 1); if(ctx->n_splt > 1) { uint32_t j; for(j=0; j < i; j++) { if(!strcmp(ctx->splt_list[j].name, ctx->splt_list[i].name)) return SPNG_ESPLT_DUP_NAME; } } if(ctx->splt_list[i].sample_depth == 16) { if( (chunk.length - keyword_len - 2) % 10 != 0) return SPNG_ECHUNK_SIZE; ctx->splt_list[i].n_entries = (chunk.length - keyword_len - 2) / 10; } else if(ctx->splt_list[i].sample_depth == 8) { if( (chunk.length - keyword_len - 2) % 6 != 0) return SPNG_ECHUNK_SIZE; ctx->splt_list[i].n_entries = (chunk.length - keyword_len - 2) / 6; } else return SPNG_ESPLT_DEPTH; if(ctx->splt_list[i].n_entries == 0) return SPNG_ECHUNK_SIZE; if(sizeof(struct spng_splt_entry) > SIZE_MAX / ctx->splt_list[i].n_entries) return SPNG_EOVERFLOW; ctx->splt_list[i].entries = spng__malloc(ctx, sizeof(struct spng_splt_entry) * ctx->splt_list[i].n_entries); if(ctx->splt_list[i].entries == NULL) return SPNG_EMEM; const unsigned char *splt = data + keyword_len + 2; size_t k; if(ctx->splt_list[i].sample_depth == 16) { for(k=0; k < ctx->splt_list[i].n_entries; k++) { ctx->splt_list[i].entries[k].red = read_u16(splt + k * 10); ctx->splt_list[i].entries[k].green = read_u16(splt + k * 10 + 2); ctx->splt_list[i].entries[k].blue = read_u16(splt + k * 10 + 4); ctx->splt_list[i].entries[k].alpha = read_u16(splt + k * 10 + 6); ctx->splt_list[i].entries[k].frequency = read_u16(splt + k * 10 + 8); } } else if(ctx->splt_list[i].sample_depth == 8) { for(k=0; k < ctx->splt_list[i].n_entries; k++) { uint8_t red, green, blue, alpha; memcpy(&red, splt + k * 6, 1); memcpy(&green, splt + k * 6 + 1, 1); memcpy(&blue, splt + k * 6 + 2, 1); memcpy(&alpha, splt + k * 6 + 3, 1); ctx->splt_list[i].entries[k].frequency = read_u16(splt + k * 6 + 4); ctx->splt_list[i].entries[k].red = red; ctx->splt_list[i].entries[k].green = green; ctx->splt_list[i].entries[k].blue = blue; ctx->splt_list[i].entries[k].alpha = alpha; } } ctx->stored_splt = 1; } else if(!memcmp(chunk.type, type_time, 4)) { if(ctx->file_time) return SPNG_EDUP_TIME; if(chunk.length != 7) return SPNG_ECHUNK_SIZE; struct spng_time time; time.year = read_u16(data); memcpy(&time.month, data + 2, 1); memcpy(&time.day, data + 3, 1); memcpy(&time.hour, data + 4, 1); memcpy(&time.minute, data + 5, 1); memcpy(&time.second, data + 6, 1); if(check_time(&time)) return SPNG_ETIME; ctx->file_time = 1; if(!ctx->user_time) memcpy(&ctx->time, &time, sizeof(struct spng_time)); ctx->stored_time = 1; } else if(!memcmp(chunk.type, type_text, 4) || !memcmp(chunk.type, type_ztxt, 4) || !memcmp(chunk.type, type_itxt, 4)) { ctx->file_text = 1; continue; /* XXX: https://gitlab.com/randy408/libspng/issues/31 */ } else if(!memcmp(chunk.type, type_offs, 4)) { if(ctx->file_offs) return SPNG_EDUP_OFFS; if(chunk.length != 9) return SPNG_ECHUNK_SIZE; ctx->offs.x = read_s32(data); ctx->offs.y = read_s32(data + 4); memcpy(&ctx->offs.unit_specifier, data + 8, 1); if(check_offs(&ctx->offs)) return SPNG_EOFFS; ctx->file_offs = 1; ctx->stored_offs = 1; } else if(!memcmp(chunk.type, type_exif, 4)) { if(ctx->file_exif) return SPNG_EDUP_EXIF; ctx->file_exif = 1; struct spng_exif exif; exif.data = spng__malloc(ctx, chunk.length); if(exif.data == NULL) return SPNG_EMEM; memcpy(exif.data, data, chunk.length); exif.length = chunk.length; if(check_exif(&exif)) { spng__free(ctx, exif.data); return SPNG_EEXIF; } if(!ctx->user_exif) memcpy(&ctx->exif, &exif, sizeof(struct spng_exif)); else spng__free(ctx, exif.data); ctx->stored_exif = 1; } } return ret; } static int validate_past_idat(spng_ctx *ctx) { if(ctx == NULL) return 1; int ret; int prev_was_idat = 1; struct spng_chunk chunk; unsigned char *data; memcpy(&chunk, &ctx->last_idat, sizeof(struct spng_chunk)); while( !(ret = read_header(ctx))) { memcpy(&chunk, &ctx->current_chunk, sizeof(struct spng_chunk)); ret = read_chunk_bytes(ctx, chunk.length); if(ret) return ret; data = ctx->data; /* Reserved bit must be zero */ if( (chunk.type[2] & (1 << 5)) != 0) return SPNG_ECHUNK_TYPE; /* Ignore private chunks */ if( (chunk.type[1] & (1 << 5)) != 0) continue; /* Critical chunk */ if(is_critical_chunk(&chunk)) { if(!memcmp(chunk.type, type_iend, 4)) return 0; else if(!memcmp(chunk.type, type_idat, 4) && prev_was_idat) continue; /* ignore extra IDATs */ else return SPNG_ECHUNK_POS; /* critical chunk after last IDAT that isn't IEND */ } prev_was_idat = 0; if(!memcmp(chunk.type, type_chrm, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_gama, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_iccp, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_sbit, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_srgb, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_bkgd, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_hist, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_trns, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_phys, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_splt, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_offs, 4)) return SPNG_ECHUNK_POS; else if(!memcmp(chunk.type, type_time, 4)) { if(ctx->file_time) return SPNG_EDUP_TIME; if(chunk.length != 7) return SPNG_ECHUNK_SIZE; struct spng_time time; time.year = read_u16(data); memcpy(&time.month, data + 2, 1); memcpy(&time.day, data + 3, 1); memcpy(&time.hour, data + 4, 1); memcpy(&time.minute, data + 5, 1); memcpy(&time.second, data + 6, 1); if(check_time(&time)) return SPNG_ETIME; ctx->file_time = 1; if(!ctx->user_time) memcpy(&ctx->time, &time, sizeof(struct spng_time)); ctx->stored_time = 1; } else if(!memcmp(chunk.type, type_exif, 4)) { if(ctx->file_exif) return SPNG_EDUP_EXIF; ctx->file_exif = 1; struct spng_exif exif; exif.data = spng__malloc(ctx, chunk.length); if(exif.data == NULL) return SPNG_EMEM; memcpy(exif.data, data, chunk.length); exif.length = chunk.length; if(check_exif(&exif)) { spng__free(ctx, exif.data); return SPNG_EEXIF; } if(!ctx->user_exif) memcpy(&ctx->exif, &exif, sizeof(struct spng_exif)); else spng__free(ctx, exif.data); ctx->stored_exif = 1; } else if(!memcmp(chunk.type, type_text, 4) || !memcmp(chunk.type, type_ztxt, 4) || !memcmp(chunk.type, type_itxt, 4)) { ctx->file_text = 1; continue; /* XXX: https://gitlab.com/randy408/libspng/issues/31 */ } } return ret; } /* Scale "sbits" significant bits in "sample" from "bit_depth" to "target" "bit_depth" must be a valid PNG depth "sbits" must be less than or equal to "bit_depth" "target" must be between 1 and 16 */ static uint16_t sample_to_target(uint16_t sample, uint8_t bit_depth, uint8_t sbits, uint8_t target) { uint16_t sample_bits; int8_t shift_amount; if(bit_depth == sbits) { if(target == sbits) return sample; /* no scaling */ }/* bit_depth > sbits */ else sample = sample >> (bit_depth - sbits); /* shift significant bits to bottom */ /* downscale */ if(target < sbits) return sample >> (sbits - target); /* upscale using left bit replication */ shift_amount = target - sbits; sample_bits = sample; sample = 0; while(shift_amount >= 0) { sample = sample | (sample_bits << shift_amount); shift_amount -= sbits; } int8_t partial = shift_amount + (int8_t)sbits; if(partial != 0) sample = sample | (sample_bits >> abs(shift_amount)); return sample; } int get_ancillary(spng_ctx *ctx) { if(ctx == NULL) return 1; if(ctx->data == NULL) return 1; if(!ctx->valid_state) return SPNG_EBADSTATE; int ret; if(!ctx->first_idat.offset) { ret = get_ancillary_data_first_idat(ctx); if(ret) { ctx->valid_state = 0; return ret; } } return 0; } /* Same as above except it returns 0 if no buffer is set */ int get_ancillary2(spng_ctx *ctx) { if(ctx == NULL) return 1; if(!ctx->valid_state) return SPNG_EBADSTATE; if(ctx->data == NULL) return 0; int ret; if(!ctx->first_idat.offset) { ret = get_ancillary_data_first_idat(ctx); if(ret) { ctx->valid_state = 0; return ret; } } return 0; } int spng_decode_image(spng_ctx *ctx, void *out, size_t out_size, int fmt, int flags) { if(ctx == NULL) return 1; if(out == NULL) return 1; if(!ctx->valid_state) return SPNG_EBADSTATE; if(ctx->encode_only) return SPNG_ENCODE_ONLY; int ret; size_t out_size_required; ret = spng_decoded_image_size(ctx, fmt, &out_size_required); if(ret) return ret; if(out_size < out_size_required) return SPNG_EBUFSIZ; ret = get_ancillary(ctx); if(ret) return ret; uint8_t channels = 1; /* grayscale or indexed_color */ if(ctx->ihdr.color_type == SPNG_COLOR_TYPE_TRUECOLOR) channels = 3; else if(ctx->ihdr.color_type == SPNG_COLOR_TYPE_GRAYSCALE_ALPHA) channels = 2; else if(ctx->ihdr.color_type == SPNG_COLOR_TYPE_TRUECOLOR_ALPHA) channels = 4; uint8_t bytes_per_pixel; if(ctx->ihdr.bit_depth < 8) bytes_per_pixel = 1; else bytes_per_pixel = channels * (ctx->ihdr.bit_depth / 8); z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; if(inflateInit(&stream) != Z_OK) return SPNG_EZLIB; struct spng_subimage sub[7]; memset(sub, 0, sizeof(struct spng_subimage) * 7); size_t scanline_width; ret = calculate_subimages(sub, &scanline_width, &ctx->ihdr, channels); if(ret) return ret; unsigned char *scanline_orig = NULL, *scanline = NULL, *prev_scanline = NULL; scanline_orig = spng__malloc(ctx, scanline_width); prev_scanline = spng__malloc(ctx, scanline_width); if(scanline_orig == NULL || prev_scanline == NULL) { ret = SPNG_EMEM; goto decode_err; } /* Some of the error-handling goto's might leave scanline incremented, leading to a failed free(), this prevents that. */ scanline = scanline_orig; int i; for(i=0; i < 7; i++) { /* Skip empty passes */ if(sub[i].width != 0 && sub[i].height != 0) { scanline_width = sub[i].scanline_width; break; } } uint16_t *gamma_lut = NULL; uint16_t gamma_lut8[256]; if(flags & SPNG_DECODE_USE_GAMA && ctx->stored_gama) { float file_gamma = (float)ctx->gama / 100000.0f; float max; uint32_t i, lut_entries; if(fmt == SPNG_FMT_RGBA8) { lut_entries = 256; max = 255.0f; gamma_lut = gamma_lut8; } else /* SPNG_FMT_RGBA16 */ { lut_entries = 65536; max = 65535.0f; ctx->gamma_lut = spng__malloc(ctx, lut_entries * sizeof(uint16_t)); if(ctx->gamma_lut == NULL) { ret = SPNG_EMEM; goto decode_err; } gamma_lut = ctx->gamma_lut; } float screen_gamma = 2.2f; float exponent = file_gamma * screen_gamma; if(FP_ZERO == fpclassify(exponent)) { ret = SPNG_EGAMA; goto decode_err; } exponent = 1.0f / exponent; for(i=0; i < lut_entries; i++) { float c = pow((float)i / max, exponent) * max; c = fmin(c, max); gamma_lut[i] = c; } } uint8_t red_sbits, green_sbits, blue_sbits, alpha_sbits, grayscale_sbits; red_sbits = ctx->ihdr.bit_depth; green_sbits = ctx->ihdr.bit_depth; blue_sbits = ctx->ihdr.bit_depth; alpha_sbits = ctx->ihdr.bit_depth; grayscale_sbits = ctx->ihdr.bit_depth; if(ctx->ihdr.color_type == SPNG_COLOR_TYPE_INDEXED) { red_sbits = 8; green_sbits = 8; blue_sbits = 8; alpha_sbits = 8; } if(ctx->stored_sbit) { if(flags & SPNG_DECODE_USE_SBIT) { if(ctx->ihdr.color_type == 0) { grayscale_sbits = ctx->sbit.grayscale_bits; alpha_sbits = ctx->ihdr.bit_depth; } else if(ctx->ihdr.color_type == 2 || ctx->ihdr.color_type == 3) { red_sbits = ctx->sbit.red_bits; green_sbits = ctx->sbit.green_bits; blue_sbits = ctx->sbit.blue_bits; alpha_sbits = ctx->ihdr.bit_depth; } else if(ctx->ihdr.color_type == 4) { grayscale_sbits = ctx->sbit.grayscale_bits; alpha_sbits = ctx->sbit.alpha_bits; } else /* == 6 */ { red_sbits = ctx->sbit.red_bits; green_sbits = ctx->sbit.green_bits; blue_sbits = ctx->sbit.blue_bits; alpha_sbits = ctx->sbit.alpha_bits; } } } uint8_t depth_target = 8; /* FMT_RGBA8 */ if(fmt == SPNG_FMT_RGBA16) depth_target = 16; uint32_t bytes_read; ret = get_idat_bytes(ctx, &bytes_read); if(ret) goto decode_err; stream.avail_in = bytes_read; stream.next_in = ctx->data; int pass; uint32_t scanline_idx; uint32_t k; uint8_t r_8, g_8, b_8, a_8, gray_8; uint16_t r_16, g_16, b_16, a_16, gray_16; uint16_t r, g, b, a, gray; unsigned char pixel[8] = {0}; size_t pixel_offset = 0; size_t pixel_size = 4; /* SPNG_FMT_RGBA8 */ if(fmt == SPNG_FMT_RGBA16) pixel_size = 8; for(pass=0; pass < 7; pass++) { /* Skip empty passes */ if(sub[pass].width == 0 || sub[pass].height == 0) continue; scanline_width = sub[pass].scanline_width; /* prev_scanline is all zeros for the first scanline */ memset(prev_scanline, 0, scanline_width); /* Decompress one scanline at a time for each subimage */ for(scanline_idx=0; scanline_idx < sub[pass].height; scanline_idx++) { stream.avail_out = scanline_width; stream.next_out = scanline; do { ret = inflate(&stream, Z_SYNC_FLUSH); if(ret != Z_OK) { if(ret == Z_STREAM_END) /* zlib reached an end-marker */ {/* we don't have a full scanline or there are more scanlines left */ if(stream.avail_out != 0 || scanline_idx != (sub[pass].height - 1)) { ret = SPNG_EIDAT_TOO_SHORT; goto decode_err; } } else if(ret != Z_BUF_ERROR) { ret = SPNG_EIDAT_STREAM; goto decode_err; } } /* We don't have scanline_width of data and we ran out of IDAT bytes */ if(stream.avail_out != 0 && stream.avail_in == 0) { ret = get_idat_bytes(ctx, &bytes_read); if(ret) goto decode_err; stream.avail_in = bytes_read; stream.next_in = ctx->data; } }while(stream.avail_out != 0); ret = defilter_scanline(prev_scanline, scanline, scanline_width, bytes_per_pixel); if(ret) goto decode_err; r=0; g=0; b=0; a=0; gray=0; r_8=0; g_8=0; b_8=0; a_8=0; gray_8=0; r_16=0; g_16=0; b_16=0; a_16=0; gray_16=0; scanline++; /* increment past filter byte, keep indexing 0-based */ /* Process a scanline per-pixel and write to *out */ for(k=0; k < sub[pass].width; k++) { /* Extract a pixel from the scanline, *_16/8 variables are used for memcpy'ing depending on bit_depth, r, g, b, a, gray (all 16bits) are used for processing */ switch(ctx->ihdr.color_type) { case SPNG_COLOR_TYPE_GRAYSCALE: { if(ctx->ihdr.bit_depth == 16) { gray_16 = read_u16(scanline + (k * 2)); if(flags & SPNG_DECODE_USE_TRNS && ctx->stored_trns && ctx->trns.gray == gray_16) a_16 = 0; else a_16 = 65535; } else /* <= 8 */ { memcpy(&gray_8, scanline + k / (8 / ctx->ihdr.bit_depth), 1); uint16_t mask16 = (1 << ctx->ihdr.bit_depth) - 1; uint8_t mask = mask16; /* avoid shift by width */ uint8_t samples_per_byte = 8 / ctx->ihdr.bit_depth; uint8_t max_shift_amount = 8 - ctx->ihdr.bit_depth; uint8_t shift_amount = max_shift_amount - ((k % samples_per_byte) * ctx->ihdr.bit_depth); gray_8 = gray_8 & (mask << shift_amount); gray_8 = gray_8 >> shift_amount; if(flags & SPNG_DECODE_USE_TRNS && ctx->stored_trns && ctx->trns.gray == gray_8) a_8 = 0; else a_8 = 255; } break; } case SPNG_COLOR_TYPE_TRUECOLOR: { if(ctx->ihdr.bit_depth == 16) { r_16 = read_u16(scanline + (k * 6)); g_16 = read_u16(scanline + (k * 6) + 2); b_16 = read_u16(scanline + (k * 6) + 4); if(flags & SPNG_DECODE_USE_TRNS && ctx->stored_trns && ctx->trns.red == r_16 && ctx->trns.green == g_16 && ctx->trns.blue == b_16) a_16 = 0; else a_16 = 65535; } else /* == 8 */ { memcpy(&r_8, scanline + (k * 3), 1); memcpy(&g_8, scanline + (k * 3) + 1, 1); memcpy(&b_8, scanline + (k * 3) + 2, 1); if(flags & SPNG_DECODE_USE_TRNS && ctx->stored_trns && ctx->trns.red == r_8 && ctx->trns.green == g_8 && ctx->trns.blue == b_8) a_8 = 0; else a_8 = 255; } break; } case SPNG_COLOR_TYPE_INDEXED: { uint8_t entry = 0; memcpy(&entry, scanline + k / (8 / ctx->ihdr.bit_depth), 1); uint16_t mask16 = (1 << ctx->ihdr.bit_depth) - 1; uint8_t mask = mask16; /* avoid shift by width */ uint8_t samples_per_byte = 8 / ctx->ihdr.bit_depth; uint8_t max_shift_amount = 8 - ctx->ihdr.bit_depth; uint8_t shift_amount = max_shift_amount - ((k % samples_per_byte) * ctx->ihdr.bit_depth); entry = entry & (mask << shift_amount); entry = entry >> shift_amount; if(entry < ctx->plte.n_entries) { r_8 = ctx->plte.entries[entry].red; g_8 = ctx->plte.entries[entry].green; b_8 = ctx->plte.entries[entry].blue; } else { ret = SPNG_EPLTE_IDX; goto decode_err; } if(flags & SPNG_DECODE_USE_TRNS && ctx->stored_trns && (entry < ctx->trns.n_type3_entries)) a_8 = ctx->trns.type3_alpha[entry]; else a_8 = 255; break; } case SPNG_COLOR_TYPE_GRAYSCALE_ALPHA: { if(ctx->ihdr.bit_depth == 16) { gray_16 = read_u16(scanline + (k * 4)); a_16 = read_u16(scanline + (k * 4) + 2); } else /* == 8 */ { memcpy(&gray_8, scanline + (k * 2), 1); memcpy(&a_8, scanline + (k * 2) + 1, 1); } break; } case SPNG_COLOR_TYPE_TRUECOLOR_ALPHA: { if(ctx->ihdr.bit_depth == 16) { r_16 = read_u16(scanline + (k * 8)); g_16 = read_u16(scanline + (k * 8) + 2); b_16 = read_u16(scanline + (k * 8) + 4); a_16 = read_u16(scanline + (k * 8) + 6); } else /* == 8 */ { memcpy(&r_8, scanline + (k * 4), 1); memcpy(&g_8, scanline + (k * 4) + 1, 1); memcpy(&b_8, scanline + (k * 4) + 2, 1); memcpy(&a_8, scanline + (k * 4) + 3, 1); } break; } }/* switch(ctx->ihdr.color_type) */ if(ctx->ihdr.bit_depth == 16) { r = r_16; g = g_16; b = b_16; a = a_16; gray = gray_16; } else { r = r_8; g = g_8; b = b_8; a = a_8; gray = gray_8; } if(ctx->ihdr.color_type == SPNG_COLOR_TYPE_GRAYSCALE || ctx->ihdr.color_type == SPNG_COLOR_TYPE_GRAYSCALE_ALPHA) { gray = sample_to_target(gray, ctx->ihdr.bit_depth, grayscale_sbits, depth_target); a = sample_to_target(a, ctx->ihdr.bit_depth, alpha_sbits, depth_target); } else { uint8_t processing_depth = ctx->ihdr.bit_depth; if(ctx->ihdr.color_type == SPNG_COLOR_TYPE_INDEXED) processing_depth = 8; r = sample_to_target(r, processing_depth, red_sbits, depth_target); g = sample_to_target(g, processing_depth, green_sbits, depth_target); b = sample_to_target(b, processing_depth, blue_sbits, depth_target); a = sample_to_target(a, processing_depth, alpha_sbits, depth_target); } if(ctx->ihdr.color_type == SPNG_COLOR_TYPE_GRAYSCALE || ctx->ihdr.color_type == SPNG_COLOR_TYPE_GRAYSCALE_ALPHA) { r = gray; g = gray; b = gray; } if(flags & SPNG_DECODE_USE_GAMA && ctx->stored_gama) { r = gamma_lut[r]; g = gamma_lut[g]; b = gamma_lut[b]; } /* only use *_8/16 for memcpy */ r_8 = r; g_8 = g; b_8 = b; a_8 = a; r_16 = r; g_16 = g; b_16 = b; a_16 = a; gray_8 = gray; gray_16 = gray; if(fmt == SPNG_FMT_RGBA8) { memcpy(pixel, &r_8, 1); memcpy(pixel + 1, &g_8, 1); memcpy(pixel + 2, &b_8, 1); memcpy(pixel + 3, &a_8, 1); } else if(fmt == SPNG_FMT_RGBA16) { memcpy(pixel, &r_16, 2); memcpy(pixel + 2, &g_16, 2); memcpy(pixel + 4, &b_16, 2); memcpy(pixel + 6, &a_16, 2); } if(!ctx->ihdr.interlace_method) { memcpy((char*)out + pixel_offset, pixel, pixel_size); pixel_offset = pixel_offset + pixel_size; } else { const unsigned int adam7_x_start[7] = { 0, 4, 0, 2, 0, 1, 0 }; const unsigned int adam7_y_start[7] = { 0, 0, 4, 0, 2, 0, 1 }; const unsigned int adam7_x_delta[7] = { 8, 8, 4, 4, 2, 2, 1 }; const unsigned int adam7_y_delta[7] = { 8, 8, 8, 4, 4, 2, 2 }; pixel_offset = ((adam7_y_start[pass] + scanline_idx * adam7_y_delta[pass]) * ctx->ihdr.width + adam7_x_start[pass] + k * adam7_x_delta[pass]) * pixel_size; memcpy((char*)out + pixel_offset, pixel, pixel_size); } }/* for(k=0; k < sub[pass].width; k++) */ scanline--; /* point to filter byte */ /* NOTE: prev_scanline is always defiltered */ memcpy(prev_scanline, scanline, scanline_width); }/* for(scanline_idx=0; scanline_idx < sub[pass].height; scanline_idx++) */ }/* for(pass=0; pass < 7; pass++) */ if(ctx->cur_chunk_bytes_left) /* zlib stream ended before an IDAT chunk boundary */ {/* discard the rest of the chunk */ ret = discard_chunk_bytes(ctx, ctx->cur_chunk_bytes_left); } decode_err: inflateEnd(&stream); spng__free(ctx, scanline_orig); spng__free(ctx, prev_scanline); if(ret) { ctx->valid_state = 0; return ret; } memcpy(&ctx->last_idat, &ctx->current_chunk, sizeof(struct spng_chunk)); ret = validate_past_idat(ctx); if(ret) ctx->valid_state = 0; return ret; }
C
#include "MenuLCD.h" void InitMenu() { m[0].down = &m[1]; m[0].right = &m1[0]; // 2 m[1].up = &m[0]; m[1].right = &m2[0]; m[1].down = &m[2]; // 3 m[2].up = &m[1]; m[2].right = &m3[0]; m[2].down = &m[3]; // 4 m[3].up = &m[2]; m[3].right = &m4[0]; m[3].down = &m[4]; // 5 m[4].up = &m[3]; m[4].right = &m5[0]; m[4].down = &m[5]; // 6 m[5].up = &m[4]; m[5].right = &m6[0]; // M1 // 11 m1[0].left = &m[0]; m1[0].down = &m1[1]; // 12 m1[1].up = &m1[0]; m1[1].down = &m1[2]; m1[1].left = &m[0]; // 13 m1[2].up = &m1[1]; m1[2].left = &m[0]; // M2 // 21 m2[0].left = &m[0]; m2[0].down = &m2[1]; // 22 m2[1].up = &m2[0]; m2[1].down = &m2[2]; m2[1].left = &m[0]; // 23 m2[2].up = &m2[1]; m2[2].left = &m[0]; // M3 // 31 m3[0].left = &m[0]; m3[0].down = &m3[1]; // 32 m3[1].up = &m3[0]; m3[1].down = &m3[2]; m3[1].left = &m[0]; // 33 m3[2].up = &m3[1]; m3[2].left = &m[0]; // M4 // 41 m4[0].left = &m[0]; m4[0].down = &m4[1]; // 42 m4[1].up = &m4[0]; m4[1].down = &m4[2]; m4[1].left = &m[0]; // 43 m4[2].up = &m4[1]; m4[2].left = &m[0]; // M5 // 51 m5[0].left = &m[0]; m5[0].down = &m5[1]; // 52 m5[1].up = &m5[0]; m5[1].down = &m5[2]; m5[1].left = &m[0]; // 53 m5[2].up = &m5[1]; m5[2].left = &m[0]; // M6 // 61 m6[0].left = &m[0]; m6[0].down = &m6[1]; // 62 m6[1].up = &m6[0]; m6[1].down = &m6[2]; m6[1].left = &m[0]; // 63 m6[2].up = &m6[1]; m6[2].left = &m[0]; }
C
#include<stdio.h> int main() { int a[3][4]={1,2,3,4,5,6,7,8,9,0,1,2}; display(a,3,4); } void display(int (*q)[4],int r,int c) { int i,j,*p; for(i=0;i<r;i++) { p=(q+i); for(j=0;j<c;j++) { printf("%d ", *(p+j)); } printf("\n"); } }
C
#include<stdio.h> struct nikhil { int i; } fuck; int main() { int j; printf("%d\n",fuck.i); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> typedef struct data_{ int dia, mes, ano; } data; typedef struct hora_{ int hora, min; } hora; typedef struct compromisso_{ data d; hora h; char desc[50]; } compromisso; int main() { setlocale(LC_ALL, "Portuguese"); int x, y, i=0, j; compromisso add[50]; printf("Bem-vindo agenda, o que deseja fazer?\n1. Registrar compromisso\n2. Listar todos os compromissos\n3. Listar compromissos de um ms\n4. Sair\n\n"); while(x != 4) { fflush(stdin); scanf("%d", &x); if(x == 1) { printf("Insira a data desejada:\n"); printf("Dia: "); fflush(stdin); scanf("%d/%d/%d", &add[i].d.dia, &add[i].d.mes, &add[i].d.ano); printf("Horrio: "); fflush(stdin); scanf("%d:%d", &add[i].h.hora, &add[i].h.min); printf("Nome do compromisso: "); fflush(stdin); gets(add[i].desc); i++; } else if(x == 2) { for(j=0; j<i; j++) { printf("%s %d/%d/%d %d:%d \n", add[j].desc, add[j].d.dia, add[j].d.mes, add[j].d.ano, add[j].h.hora, add[j].h.min); } } else if(x == 3) { printf("Voc deseja ver seus compromissos de qual ms?: "); scanf("%d", &y); for(j=0; j<i; j++) { if(y == add[j].d.mes) { printf("%s %d/%d/%d %d:%d \n", add[j].desc, add[j].d.dia, add[j].d.mes, add[j].d.ano, add[j].h.hora, add[j].h.min); } } if(i == 0) { printf("Sem compromissos pendentes nesse ms!\n"); } } else if(x == 4) { printf("\nAte mais !!!"); break; } printf("\n"); } return 0; }
C
/* ** EPITECH PROJECT, 2020 ** NWP_myteams_2019 ** File description: ** tools */ #include "command.h" int isquoted(lklist_char_t *ll) { int q = 0; if (ll->size(ll) >= 2) { for (size_t i = 0; i != ll->size(ll); i += 1) { if (ll->at(ll, i) == '"') q++; } if (q == 2 && ll->at(ll, 0) == '"' && ll->at(ll, ll->size(ll) - 1) == '"') return 1; } return 0; }
C
/* $OpenBSD: line.c,v 1.63 2021/03/01 10:51:14 lum Exp $ */ /* This file is in the public domain. */ /* * Text line handling. * * The functions in this file are a general set of line management * utilities. They are the only routines that touch the text. They * also touch the buffer and window structures to make sure that the * necessary updating gets done. * * Note that this code only updates the dot and mark values in the window * list. Since all the code acts on the current window, the buffer that * we are editing must be displayed, which means that "b_nwnd" is non-zero, * which means that the dot and mark values in the buffer headers are * nonsense. */ #include <ctype.h> #include <limits.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "def.h" int casereplace = TRUE; /* * Preserve the case of the replaced string. */ int setcasereplace(int f, int n) { if (f & FFARG) casereplace = n > 0; else casereplace = !casereplace; ewprintf("Case-replace is %sabled", casereplace ? "en" : "dis"); return (TRUE); } /* * Allocate a new line of size `used'. lrealloc() can be called if the line * ever needs to grow beyond that. */ struct line * lalloc(int used) { struct line *lp; if ((lp = malloc(sizeof(*lp))) == NULL) return (NULL); lp->l_text = NULL; lp->l_size = 0; lp->l_used = used; /* XXX */ if (lrealloc(lp, used) == FALSE) { free(lp); return (NULL); } return (lp); } int lrealloc(struct line *lp, int newsize) { char *tmp; if (lp->l_size < newsize) { if ((tmp = realloc(lp->l_text, newsize)) == NULL) return (FALSE); lp->l_text = tmp; lp->l_size = newsize; } return (TRUE); } /* * Delete line "lp". Fix all of the links that might point to it (they are * moved to offset 0 of the next line. Unlink the line from whatever buffer * it might be in, and release the memory. The buffers are updated too; the * magic conditions described in the above comments don't hold here. */ void lfree(struct line *lp) { struct buffer *bp; struct mgwin *wp; for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_linep == lp) wp->w_linep = lp->l_fp; if (wp->w_dotp == lp) { wp->w_dotp = lp->l_fp; wp->w_doto = 0; } if (wp->w_markp == lp) { wp->w_markp = lp->l_fp; wp->w_marko = 0; } } for (bp = bheadp; bp != NULL; bp = bp->b_bufp) { if (bp->b_nwnd == 0) { if (bp->b_dotp == lp) { bp->b_dotp = lp->l_fp; bp->b_doto = 0; } if (bp->b_markp == lp) { bp->b_markp = lp->l_fp; bp->b_marko = 0; } } } lp->l_bp->l_fp = lp->l_fp; lp->l_fp->l_bp = lp->l_bp; free(lp->l_text); free(lp); } /* * This routine is called when a character changes in place in the current * buffer. It updates all of the required flags in the buffer and window * system. The flag used is passed as an argument; if the buffer is being * displayed in more than 1 window we change EDIT to HARD. Set MODE if the * mode line needs to be updated (the "*" has to be set). */ void lchange(int flag) { struct mgwin *wp; /* update mode lines if this is the first change. */ if ((curbp->b_flag & BFCHG) == 0) { flag |= WFMODE; curbp->b_flag |= BFCHG; } for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_bufp == curbp) { wp->w_rflag |= flag; if (wp != curwp) wp->w_rflag |= WFFULL; } } } /* * Insert "n" copies of the character "c" at the current location of dot. * In the easy case all that happens is the text is stored in the line. * In the hard case, the line has to be reallocated. When the window list * is updated, take special care; I screwed it up once. You always update * dot in the current window. You update mark and a dot in another window * if it is greater than the place where you did the insert. Return TRUE * if all is well, and FALSE on errors. */ int linsert(int n, int c) { struct line *lp1; struct mgwin *wp; RSIZE i; int doto; int s; if (!n) return (TRUE); if ((s = checkdirty(curbp)) != TRUE) return (s); if (curbp->b_flag & BFREADONLY) { dobeep(); ewprintf("Buffer is read only"); return (FALSE); } lchange(WFEDIT); /* current line */ lp1 = curwp->w_dotp; /* special case for the end */ if (lp1 == curbp->b_headp) { struct line *lp2, *lp3; /* now should only happen in empty buffer */ if (curwp->w_doto != 0) { dobeep(); ewprintf("bug: linsert"); return (FALSE); } /* allocate a new line */ if ((lp2 = lalloc(n)) == NULL) return (FALSE); /* previous line */ lp3 = lp1->l_bp; /* link in */ lp3->l_fp = lp2; lp2->l_fp = lp1; lp1->l_bp = lp2; lp2->l_bp = lp3; for (i = 0; i < n; ++i) lp2->l_text[i] = c; for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_linep == lp1) wp->w_linep = lp2; if (wp->w_dotp == lp1) wp->w_dotp = lp2; if (wp->w_markp == lp1) wp->w_markp = lp2; } undo_add_insert(lp2, 0, n); curwp->w_doto = n; return (TRUE); } /* save for later */ doto = curwp->w_doto; if ((lp1->l_used + n) > lp1->l_size) { if (lrealloc(lp1, lp1->l_used + n) == FALSE) return (FALSE); } lp1->l_used += n; if (lp1->l_used != n) memmove(&lp1->l_text[doto + n], &lp1->l_text[doto], lp1->l_used - n - doto); /* Add the characters */ for (i = 0; i < n; ++i) lp1->l_text[doto + i] = c; for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_dotp == lp1) { if (wp == curwp || wp->w_doto > doto) wp->w_doto += n; } if (wp->w_markp == lp1) { if (wp->w_marko > doto) wp->w_marko += n; } } undo_add_insert(curwp->w_dotp, doto, n); return (TRUE); } /* * Do the work of inserting a newline at the given line/offset. * If mark is on the current line, we may have to move the markline * to keep line numbers in sync. * lnewline_at assumes the current buffer is writable. Checking for * this fact should be done by the caller. */ int lnewline_at(struct line *lp1, int doto) { struct line *lp2; struct mgwin *wp; int nlen, tcurwpdotline; lchange(WFFULL); curwp->w_bufp->b_lines++; /* Check if mark is past dot (even on current line) */ if (curwp->w_markline > curwp->w_dotline || (curwp->w_dotline == curwp->w_markline && curwp->w_marko >= doto)) curwp->w_markline++; tcurwpdotline = curwp->w_dotline; /* If start of line, allocate a new line instead of copying */ if (doto == 0) { /* new first part */ if ((lp2 = lalloc(0)) == NULL) return (FALSE); lp2->l_bp = lp1->l_bp; lp1->l_bp->l_fp = lp2; lp2->l_fp = lp1; lp1->l_bp = lp2; for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_linep == lp1) wp->w_linep = lp2; if (wp->w_dotline >= tcurwpdotline && wp->w_bufp == curwp->w_bufp) wp->w_dotline++; } undo_add_boundary(FFRAND, 1); undo_add_insert(lp2, 0, 1); undo_add_boundary(FFRAND, 1); return (TRUE); } /* length of new part */ nlen = llength(lp1) - doto; /* new second half line */ if ((lp2 = lalloc(nlen)) == NULL) return (FALSE); if (nlen != 0) bcopy(&lp1->l_text[doto], &lp2->l_text[0], nlen); lp1->l_used = doto; lp2->l_bp = lp1; lp2->l_fp = lp1->l_fp; lp1->l_fp = lp2; lp2->l_fp->l_bp = lp2; /* Windows */ for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_dotp == lp1 && wp->w_doto >= doto) { wp->w_dotp = lp2; wp->w_doto -= doto; wp->w_dotline++; } else if (wp->w_dotline > tcurwpdotline && wp->w_bufp == curwp->w_bufp) wp->w_dotline++; if (wp->w_markp == lp1 && wp->w_marko >= doto) { wp->w_markp = lp2; wp->w_marko -= doto; } } undo_add_boundary(FFRAND, 1); undo_add_insert(lp1, llength(lp1), 1); undo_add_boundary(FFRAND, 1); return (TRUE); } /* * Insert a newline into the buffer at the current location of dot in the * current window. */ int lnewline(void) { int s; if ((s = checkdirty(curbp)) != TRUE) return (s); if (curbp->b_flag & BFREADONLY) { dobeep(); ewprintf("Buffer is read only"); return (FALSE); } return (lnewline_at(curwp->w_dotp, curwp->w_doto)); } /* * This function deletes "n" bytes, starting at dot. (actually, n+1, as the * newline is included) It understands how to deal with end of lines, etc. * It returns TRUE if all of the characters were deleted, and FALSE if * they were not (because dot ran into the end of the buffer). * The "kflag" indicates either no insertion, or direction of insertion * into the kill buffer. */ int ldelete(RSIZE n, int kflag) { struct line *dotp; RSIZE chunk; struct mgwin *wp; int doto; char *cp1, *cp2; size_t len; char *sv = NULL; int end; int s; int rval = FALSE; if ((s = checkdirty(curbp)) != TRUE) return (s); if (curbp->b_flag & BFREADONLY) { dobeep(); ewprintf("Buffer is read only"); goto out; } len = n; if ((sv = calloc(1, len + 1)) == NULL) goto out; end = 0; undo_add_delete(curwp->w_dotp, curwp->w_doto, n, (kflag & KREG)); while (n != 0) { dotp = curwp->w_dotp; doto = curwp->w_doto; /* Hit the end of the buffer */ if (dotp == curbp->b_headp) goto out; /* Size of the chunk */ chunk = dotp->l_used - doto; if (chunk > n) chunk = n; /* End of line, merge */ if (chunk == 0) { if (dotp == blastlp(curbp)) goto out; lchange(WFFULL); if (ldelnewline() == FALSE) goto out; end = strlcat(sv, curbp->b_nlchr, len + 1); --n; continue; } lchange(WFEDIT); /* Scrunch text */ cp1 = &dotp->l_text[doto]; memcpy(&sv[end], cp1, chunk); end += chunk; sv[end] = '\0'; for (cp2 = cp1 + chunk; cp2 < &dotp->l_text[dotp->l_used]; cp2++) *cp1++ = *cp2; dotp->l_used -= (int)chunk; for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_dotp == dotp && wp->w_doto >= doto) { wp->w_doto -= chunk; if (wp->w_doto < doto) wp->w_doto = doto; } if (wp->w_markp == dotp && wp->w_marko >= doto) { wp->w_marko -= chunk; if (wp->w_marko < doto) wp->w_marko = doto; } } n -= chunk; } if (kchunk(sv, (RSIZE)len, kflag) != TRUE) goto out; rval = TRUE; out: free(sv); return (rval); } /* * Delete a newline and join the current line with the next line. If the next * line is the magic header line always return TRUE; merging the last line * with the header line can be thought of as always being a successful * operation. Even if nothing is done, this makes the kill buffer work * "right". If the mark is past the dot (actually, markline > dotline), * decrease the markline accordingly to keep line numbers in sync. * Easy cases can be done by shuffling data around. Hard cases * require that lines be moved about in memory. Return FALSE on error and * TRUE if all looks ok. We do not update w_dotline here, as deletes are done * after moves. */ int ldelnewline(void) { struct line *lp1, *lp2, *lp3; struct mgwin *wp; int s; if ((s = checkdirty(curbp)) != TRUE) return (s); if (curbp->b_flag & BFREADONLY) { dobeep(); ewprintf("Buffer is read only"); return (FALSE); } lp1 = curwp->w_dotp; lp2 = lp1->l_fp; /* at the end of the buffer */ if (lp2 == curbp->b_headp) return (TRUE); /* Keep line counts in sync */ curwp->w_bufp->b_lines--; if (curwp->w_markline > curwp->w_dotline) curwp->w_markline--; if (lp2->l_used <= lp1->l_size - lp1->l_used) { bcopy(&lp2->l_text[0], &lp1->l_text[lp1->l_used], lp2->l_used); for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_linep == lp2) wp->w_linep = lp1; if (wp->w_dotp == lp2) { wp->w_dotp = lp1; wp->w_doto += lp1->l_used; } if (wp->w_markp == lp2) { wp->w_markp = lp1; wp->w_marko += lp1->l_used; } } lp1->l_used += lp2->l_used; lp1->l_fp = lp2->l_fp; lp2->l_fp->l_bp = lp1; free(lp2); return (TRUE); } if ((lp3 = lalloc(lp1->l_used + lp2->l_used)) == NULL) return (FALSE); bcopy(&lp1->l_text[0], &lp3->l_text[0], lp1->l_used); bcopy(&lp2->l_text[0], &lp3->l_text[lp1->l_used], lp2->l_used); lp1->l_bp->l_fp = lp3; lp3->l_fp = lp2->l_fp; lp2->l_fp->l_bp = lp3; lp3->l_bp = lp1->l_bp; for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_linep == lp1 || wp->w_linep == lp2) wp->w_linep = lp3; if (wp->w_dotp == lp1) wp->w_dotp = lp3; else if (wp->w_dotp == lp2) { wp->w_dotp = lp3; wp->w_doto += lp1->l_used; } if (wp->w_markp == lp1) wp->w_markp = lp3; else if (wp->w_markp == lp2) { wp->w_markp = lp3; wp->w_marko += lp1->l_used; } } free(lp1); free(lp2); return (TRUE); } /* * Replace plen characters before dot with argument string. Control-J * characters in st are interpreted as newlines. There is a casehack * disable flag (normally it likes to match case of replacement to what * was there). */ int lreplace(RSIZE plen, char *st) { RSIZE rlen; /* replacement length */ struct line *lp; RSIZE n; int s, doto, is_query_capitalised = 0, is_query_allcaps = 0; int is_replace_alllower = 0; char *repl = NULL; if ((s = checkdirty(curbp)) != TRUE) return (s); if (curbp->b_flag & BFREADONLY) { dobeep(); ewprintf("Buffer is read only"); return (FALSE); } if ((repl = strdup(st)) == NULL) { dobeep(); ewprintf("out of memory"); return (FALSE); } rlen = strlen(repl); undo_boundary_enable(FFRAND, 0); (void)backchar(FFARG | FFRAND, (int)plen); if (casereplace != TRUE) goto done; lp = curwp->w_dotp; if (ltext(lp) == NULL) goto done; doto = curwp->w_doto; n = plen; is_query_capitalised = isupper((unsigned char)lgetc(lp, doto)); if (is_query_capitalised) { for (n = 0, is_query_allcaps = 1; n < plen && is_query_allcaps; n++) { is_query_allcaps = !isalpha((unsigned char)lgetc(lp, doto)) || isupper((unsigned char)lgetc(lp, doto)); doto++; if (doto == llength(lp)) { doto = 0; lp = lforw(lp); n++; /* \n is implicit in the buffer */ } } } for (n = 0, is_replace_alllower = 1; n < rlen && is_replace_alllower; n++) is_replace_alllower = !isupper((unsigned char)repl[n]); if (is_replace_alllower) { if (is_query_allcaps) { for (n = 0; n < rlen; n++) repl[n] = toupper((unsigned char)repl[n]); } else if (is_query_capitalised) { repl[0] = toupper((unsigned char)repl[0]); } } done: (void)ldelete(plen, KNONE); region_put_data(repl, rlen); lchange(WFFULL); undo_boundary_enable(FFRAND, 1); free(repl); return (TRUE); } /* * Allocate and return the supplied line as a C string */ char * linetostr(const struct line *ln) { int len; char *line; len = llength(ln); if (len == INT_MAX) /* (len + 1) overflow */ return (NULL); if ((line = malloc(len + 1)) == NULL) return (NULL); (void)memcpy(line, ltext(ln), len); line[len] = '\0'; return (line); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rfontain <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/08 03:11:22 by rfontain #+# #+# */ /* Updated: 2018/10/09 19:44:43 by rfontain ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_countw(const char *str, char c) { int i; int count; i = 0; count = 0; while (str[i]) { while (str[i] == c && str[i]) i++; if (str[i] != c && str[i] != '\0') { count++; while (str[i] != c && str[i]) i++; } } return (count); } static int ft_strlensp(const char *str, char c) { int i; int j; i = 0; j = 0; while (str[j] && str[j] == c) j++; while (str[j + i] && str[j + i] != c) i++; return (i); } char **ft_strsplit(char const *s, char c) { char **split; int k; int nbword; int i; if (s == NULL) return (NULL); if ((split = (char**)malloc(sizeof(char*) * (ft_countw(s, c) + 1))) == NULL) return (NULL); nbword = ft_countw(s, c); k = 0; while (nbword--) { if (!(split[k] = malloc(sizeof(char) * (ft_strlensp(s, c) + 1)))) return (NULL); while (*s && *s == c) s++; i = 0; while (*s != c && *s != '\0') split[k][i++] = *s++; split[k][i] = '\0'; k++; } split[k] = NULL; return (split); }
C
#include <stdio.h> #include "myMath.h" int main(){ double var; printf("please enter a number\n"); scanf("%lf",&var ); double eToThex = Exponent(var); double xToThe3 = Power(var, 3); float fx1Add = add(eToThex, xToThe3); float fx1 = sub(fx1Add, 2); double x3 = mul(3, var); double x2ToThe2 = mul(2, (int)(Power(var, 2))); float fx2 = add(x3, x2ToThe2); double tmp = (Power(var, 3)); double x4ToThe3 = mul(4, tmp); double mulDiv5 = div(x4ToThe3, 5); double x2 = mul(2, var); float fx3 = sub(mulDiv5, x2); printf("The value of f(x) = e^x + x^3 − 2 at x = %f is %0.4f\n", var, fx1); printf("The value of f(x) = 3x + 2X^2 at x = %f is %0.4f\n", var, fx2); printf("The value of f(x) = (4x^3)/5 -2x at x = %f is %0.4f\n", var, fx3); return 0; }
C
//Definition for singly-linked list. struct ListNode { int val; struct ListNode *next; }; struct ListNode *reverseList(struct ListNode *head) { if (!head || !head->next) return head; struct ListNode *res = reverseList(head->next); head->next->next = head; head->next = 0; return res; } void reorderList(struct ListNode *head) { if (!head) return; struct ListNode *middle = head, *tail = head->next; while (tail && tail->next) { middle = middle->next; tail = tail->next->next; } tail = reverseList(middle->next); middle->next = 0; for (struct ListNode *p = head; tail; p = p->next->next) { struct ListNode *node = tail; tail = tail->next; node->next = p->next; p->next = node; } }
C
#include <stdio.h> #include <cs50.h> #include <math.h> int main(void){ float change; int coins = 0; do { printf("How much change do I owe you?\n"); change = GetFloat(); } while(change < 0); float c = change * 100; c = round(c); float cents = (float) c; while(cents >= 25){ coins = coins + 1; cents = cents - 25; } while(cents >= 10){ coins = coins + 1; cents = cents - 10; } while(cents >= 5){ coins = coins + 1; cents = cents - 5; } while(cents >= 1){ coins = coins + 1; cents = cents - 1; } printf("%d", coins); printf("\n"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pipe.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tvanelst <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/06 13:48:39 by tvanelst #+# #+# */ /* Updated: 2021/08/06 13:48:40 by tvanelst ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" static char **create_empty_tab(t_ms *ms, char c, char *line) { int counter; char quoteflag; char **tab; counter = 1; while (*line) { quoteflag = ms_quoteflag(ms, *line); if (*line++ == c && !(S_Q & quoteflag) && !(D_Q & quoteflag)) counter++; } ms->tab_size = counter; tab = ft_calloc(sizeof(char *), (counter + 1)); if (!tab) error_msg(-1, strerror(errno), ms); return (tab); } static int ms_fill_tab(t_ms *ms, t_pipe *pipe, char *line, int *i) { int k; if (!*(line + 1) || (*line == '|' && !(S_Q & ms->quoteflag) && !(D_Q & ms->quoteflag))) { k = 1; if (*line == '|') { pipe->split_flag = 1; k = 0; } ms->tab[*i] = ft_substr(line - pipe->index, 0, pipe->index + k); if (!ms->tab[*i]) { error_msg(-1, strerror(errno), ms); ms_free_and_init_dtab(ms->tab); return (0); } (*i)++; } return (1); } char **ms_pipe_split(t_ms *ms, char *line) { t_pipe pipe; int i; i = 0; pipe = (t_pipe){}; ms->quoteflag = 0; ms->tab = create_empty_tab(ms, '|', line); if (!ms->tab) return (NULL); while (*line) { if (pipe.split_flag) { pipe.index = 0; ms->quoteflag = 0; } pipe.split_flag = 0; ms_quoteflag(ms, *line); if (!ms_fill_tab(ms, &pipe, line++, &i)) return (NULL); pipe.index++; } return (ms->tab); }
C
// C program to demonstrate the use of calloc() // and malloc() #include <stdio.h> #include <stdlib.h> int main() { int* arr; // malloc() allocate the memory for 5 integers // containing garbage values // void* malloc(size_t size); arr = (int*)malloc(5 * sizeof(int)); // 5*4bytes = 20 bytes // Deallocates memory previously allocated by malloc() function free(arr); // calloc() allocate the memory for 5 integers and // set 0 to all of them // void* calloc(size_t num, size_t size); arr = (int*)calloc(5, sizeof(int)); // Deallocates memory previously allocated by calloc() function free(arr); return (0); } /** * same as calloc * * ptr = malloc(size); * memset(ptr, 0, size); */
C
#include <poll.h> #include "event.h" // select specific int maxfd = FD_SETSIZE; typedef struct select_fds { struct pollfd *fdarray; } select_fds; static void select_free_event(select_fds *api_state); int select_create_event(eventloop *ep) { struct select_fds *main_fds = malloc(sizeof(select_fds)); if (main_fds == NULL) goto err; ep->api_state = main_fds; main_fds->fdarray = 0; main_fds->fdarray = malloc(ep->fd_size * sizeof(struct pollfd)); return 0; err: if (main_fds) select_free_event(main_fds); return -1; } static void select_free_event(select_fds *api_state) { free(api_state->fdarray); free(api_state); } static int select_poll(eventloop *ep, struct timeval *tvp) { int numevents = 0; select_fds *api_state = ep->api_state; // set the pollfd array int count = 0; for (int fd = 0; fd < ep->max_fd + 1; fd++) { event *e = &ep->events[fd]; short poll_event = 0; if (e->flag & YEVENT_READ) poll_event |= POLL_IN; if (e->flag & YEVENT_WRITE) poll_event |= POLL_OUT; // fd got thing to write if (poll_event) { struct pollfd *pf = &api_state->fdarray[count]; pf->fd = fd; pf->events = poll_event; pf->revents = 0; count++; // printf("count %d %d %x\n", count, pf->events, pf->fd); } } int millseconds = tvp->tv_sec * 1000 + tvp->tv_usec/1000; int ret = poll(api_state->fdarray, count, millseconds); if (ret == 0) { /* nothing happen */ goto end_err; } else if (ret < 0) { /* ret = -1,some error happen */ numevents = -1; goto end_err; } else { int fired = 0; for (int i = 0; i < count; i++) { int flag = YEVENT_NONE; if (fired > ret) break; // can read struct pollfd *pf = &api_state->fdarray[i]; if (pf->revents & POLL_IN) { flag |= YEVENT_READ; } // can write if (pf->revents & POLL_OUT) { flag |= YEVENT_WRITE; } // something happen with this fd if (flag != YEVENT_NONE) { ep->changed_events[fired].flag = flag; ep->changed_events[fired].fd = pf->fd; fired ++; } } numevents = fired; } end_err: return numevents; } static int select_add(eventloop *ep, int fd, int flag) { return 0; } void select_del(eventloop *ep, int fd, int flag) { }
C
/* host_1 */ /****************************************************************** * Remote Shell - Server Program * * ******************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define BUFFER_SIZE 256 #define QUEUE_LENGTH 5 #define DEFAULT_SERVER_PORT 5000 #define LOGIN_CMD "login" #define FALSE 0 #define TRUE 1 void error(const char* msg) { perror(msg); exit(1); /* Abort */ } void input(const char* arg) { printf("usage: %s -p <port> -c </full/path/to/commands_file> ", arg); exit(0); } void instruction(int p) { printf("| Server listening on port %d |\n", p); } int main(int argc, char* argv[]) { int sockfd, newsockfd, serverLen, clientLen; int port = DEFAULT_SERVER_PORT; /* port number */ char buffer[BUFFER_SIZE], temp_buf[BUFFER_SIZE]; /* Buffers */ char* cmd_file_pathname = NULL; /* Commands filename */ struct sockaddr_in serverINETAddress; /* Server Internet address */ struct sockaddr* serverSockAddrPtr; /* Ptr to server address */ struct sockaddr_in clientINETAddress; /* Client Internet address */ struct sockaddr* clientSockAddrPtr; /* Ptr to client address */ /* Ignore death-of-child signals to prevent zombies */ signal (SIGCHLD, SIG_IGN); /* Create the server Internet socket */ sockfd = socket(AF_INET, SOCK_STREAM, /* DEFAULT_PROTOCOL */ 0); if(sockfd < 0) error("ERROR opening socket"); /* Fill in server socket address fields */ serverLen = sizeof(serverINETAddress); bzero((char*)&serverINETAddress, serverLen); /* Clear structure */ serverINETAddress.sin_family = AF_INET; /* Internet domain */ serverINETAddress.sin_addr.s_addr = htonl(INADDR_ANY); /* Accept all */ serverINETAddress.sin_port = htons(port); /* Server port number */ serverSockAddrPtr = (struct sockaddr*) &serverINETAddress; /* Bind to socket address */ if(bind(sockfd, serverSockAddrPtr, serverLen) < 0) error("ERROR on binding"); /* Set max pending connection queue length */ if(listen(sockfd, QUEUE_LENGTH) < 0) error("ERROR on listening"); clientSockAddrPtr = (struct sockaddr*) &clientINETAddress; clientLen = sizeof(clientINETAddress); instruction(port); /* Display instructions */ while(1) { /* Loop forever */ /* Accept a client connection */ newsockfd = accept(sockfd,/*NULL*/clientSockAddrPtr,/*NULL */&clientLen); if(newsockfd < 0) error("ERROR on accept"); printf("Server %d: connection %d accepted\n", getpid(), newsockfd); int logged = FALSE; /* not logged in */ if(fork() == 0) { /* Create a child to serve client */ /* Perform redirection */ int a = dup2(newsockfd, STDOUT_FILENO); int b = dup2(newsockfd, STDERR_FILENO); if(a < 0 || b < 0) error("ERROR on dup2"); while(1) { bzero(buffer, sizeof(buffer)); /* Receive */ if(recv(newsockfd, buffer, sizeof(buffer), 0) < 0) error("ERROR on receiving"); if (strcmp(buffer, "exit\n") == 0) { /* Exit */ close(newsockfd); exit(0); } /* Tokenize command */ bzero(temp_buf, sizeof(temp_buf)); strcpy(temp_buf, buffer); char* p = strtok(temp_buf, " "); /* token (cmd) */ if(strcmp(p, LOGIN_CMD)==0) continue; /* Ignore LOGIN_CMD */ /* Manage 'cd' */ if(strcmp(p, "cd")== 0 ) { p = strtok(NULL, " "); /* This is the new path */ p[strlen(p)-1] = '\0'; /* replace newline termination char */ /* Change current working directory */ if(chdir(p) < 0) perror("error"); } else system(buffer); /* Issue a command */ } } else close (newsockfd); /* Close newsocket descriptor */ } close(sockfd); return 0; /* Terminate */ }
C
#include "stdio.h" #include "stdlib.h" int main(int argc, char const *argv[]) { FILE *fd = fopen(argv[1], "rb"); if(fd) { fseek(fd, 0, SEEK_END); size_t len = ftell(fd); fseek(fd, 0, SEEK_SET); char *data = malloc(len * sizeof(char)); if(fread(data, sizeof(char), len, fd)) { unsigned int *dataInt = data; unsigned int key = strtoul(argv[2], NULL, 16); unsigned int maybePrime = (key & 0xFE) + 1; if(maybePrime % 3 == 0) maybePrime += 2; if(maybePrime < 3)maybePrime *= 241; for(int i = 0; i < len/sizeof(int); i++) { printf("%08x,", dataInt[i]); dataInt[i] ^= key; printf("%08x, %08x\n", dataInt[i], key); key = (key * key % maybePrime); if(key < 3) key+=3; } }else{ return -1; } fclose(fd); fd = fopen(argv[3], "wb"); if(fd) { fwrite(data, sizeof(char), len, fd); fclose(fd); }else{ return -1; } free(data); }else{ return -1; } return 0; }
C
/* ** EPITECH PROJECT, 2019 ** 106bombyx_2018 ** File description: ** display the usage */ #include "./../include/bombyx.h" void disp_usage(void) { my_putstr("USAGE\n"); my_putstr(" ./106bombyx n [k | i0 i1]\n\n"); my_putstr("DESCRIPTION\n"); my_putstr(" n number of first generation individuals\n"); my_putstr(" k growth rate from 1 to 4\n"); my_putstr(" i0 initial generation (included)\n"); my_putstr(" i1 final generation (included)\n"); }
C
#include <ansi.h> /****************************************************************************** * Program: vitality.c * Path: /players/dragnar/SevenSpires/scrolls * Type: Object * Created: June 30th, 2015 by Dragnar * * Purpose: One of the scrolls in the Seven Spires area that give temporary * powers to a player. This one enhances a players max HP for a short * amount of time, depending on level / prestige. * * History: * 06/30/2015 - Dragnar * Created * 02/22/2017 - Dragnar * Updated so it can't be dropped when active. ******************************************************************************/ int active, amount; id(string str) { return str == "scroll" || str == "vitality" || str == "scroll of vitality" || str == (active ? "generic_hp_bonus" : "scroll") || str == (active ? "active_vitality" : "scroll"); } short() { return "A Scroll of "+(active ? HIG : NORM)+"Vitality"+NORM; } long() { write(YEL+ " _________________________________\n\ / _\\ \\\n\ \\ (_/_____________________________/\n\ \\ \\\n\ \\ \\\n\ \\ "+HIG+"\\ / o _)_ _ ) o _)_"+NORM+YEL+" \\ \n\ \\ "+HIG+"\\/ ( (_ (_( ( ( (_ (_("+NORM+YEL+" \\\n\ \\ "+HIG+" _)"+NORM+YEL+" \\\n\ \\ \\\n\ \\ \\\n\ __\\ "+NORM+"Reading of this scroll will"+YEL+" \\\n\ / )_\\ "+NORM+"invoke the power within"+YEL+" \\\n\ \\___/_____________________________/\n"+NORM); if( this_player() && this_player()->query_level() > 50 ) write("\tActive : "+active+"\n\ \tAmount : "+amount+"\n"); } reset(arg){ if(arg) return; } init() { add_action("read_scroll","read"); if( !environment() || !environment()->is_player() ) return; amount = environment()->query_level() + environment()->query_extra_level() + environment()->query_prestige_level(); } int read_scroll(string str) { if( !str || !id(str) ) return 0; if( active ) { write("The scroll's power has already been released.\n"); return 1; } /** Prevent stacking **/ if( present("active_vitality", this_player() )) { write("Your enhanced vitality prevents you from using the scroll.\n"); return 1; } write("You read the ancient words on the scroll and feel strength rush into you!\n"); say(this_player()->query_name()+" says some ancient words and strength rushes into them.\n"); call_out("time_out", (int) this_player()->query_level() * 35 + (int) this_player()->query_extra_level() * 10 ); active = 1; return 1; } int gen_hp_bonus() { return active ? amount : 0; } time_out() { if(environment() && environment()->is_player() ) tell_object( environment(), HIG+"The scroll bursts into flames and you feel weakened.\n"+NORM); destruct(this_object()); } get() { return 1; } drop() { if( active ) { write("You are too bonded to the scroll to part with it.\n"); return 1; } else { return 0; } } query_weight() { return 0; } query_value() { return 0; } query_save_flag() { return (active ? 1 : 0); }
C
#include<stdio.h> #define X 4 int main(void) { int i,j; double mx1[X][X],mx2[X][X],mx3[X][X]; printf("Please input first matrix.\n"); for(j=0;j<X;j++) { for(i=0;i<X;i++) { printf("Please input component[ %d %d ].\n",j+1,i+1); scanf("%lf",&mx1[j][i]); } } printf("Please input second matrix.\n"); for(j=0;j<X;j++) { for(i=0;i<X;i++) { printf("Please input component[ %d %d ].\n",j+1,i+1); scanf("%lf",&mx2[j][i]); } } printf("\n"); printf("First matrix is\n"); for(j=0;j<X;j++) { for(i=0;i<X;i++) { printf("%f ",mx1[j][i]); } printf("\n"); } printf("\n"); printf("Second matrix is\n"); for(j=0;j<X;j++) { for(i=0;i<X;i++) { printf("%f ",mx2[j][i]); } printf("\n"); } printf("\n"); printf("First mat+Second mat\n"); for(j=0;j<X;j++) { for(i=0;i<X;i++) { mx3[j][i]=mx1[j][i]+mx2[j][i]; printf("%f ",mx3[j][i]); } printf("\n"); } printf("\n"); printf("First mat-Second mat\n"); for(j=0;j<X;j++) { for(i=0;i<X;i++) { mx3[j][i]=mx1[j][i]-mx2[j][i]; printf("%f ",mx3[j][i]); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <locale.h> #include "MyLib.h" #include <Windows.h> #include <math.h> #include <stdlib.h> #include <time.h> void First(){ fflush(stdin); int *Matrix; int n,m; printf(" - - \n"); scanf("%d%d",&n,&m); Matrix = (int*)malloc(n*m * sizeof(int)); printf(" (1) (2)?\n"); char c; fflush(stdin); scanf("%c",&c); if(c=='1'){ printf(" -100 100"); RandMatrix(n, m, Matrix); } else if(c=='2') { printf(" \n"); ScanMatrix(n, m, Matrix); } PrintMatrix(n, m, Matrix); } void Second(){ fflush(stdin); int *Matrix; int n; printf(" - \n"); scanf("%d",&n); Matrix = (int*)malloc(n*n * sizeof(int)); printf(" (1) (2)?\n"); char c; fflush(stdin); scanf("%c",&c); if(c=='1'){ printf(" -100 100"); RandMatrix(n, n, Matrix); PrintMatrix(n,n,Matrix); } else if(c=='2') { printf(" \n"); ScanMatrix(n, n, Matrix); } printf(" :\n"); TrMat(n,Matrix); PrintMatrix(n,n,Matrix); } void Third(){ fflush(stdin); int *Matrix1,*Matrix2; int n1,m1,n2,m2; printf(" - - \n"); scanf("%d%d",&n1,&m1); Matrix1 = (int*)malloc(n1*m2 * sizeof(int)); printf(" - - \n"); scanf("%d%d",&n2,&m2); Matrix2 = (int*)malloc(n2*m2 * sizeof(int)); printf(" (1) (2)?\n"); char c; fflush(stdin); scanf("%c",&c); if(c=='1'){ printf(" -100 100"); RandMatrix(n1, m1, Matrix1); PrintMatrix(n1,m1,Matrix1); RandMatrix(n2, m2, Matrix2); PrintMatrix(n2,m2,Matrix2); printf("\n"); } else if(c=='2') { printf(" \n"); ScanMatrix(n1, m1, Matrix1); printf(" \n"); ScanMatrix(n2, m2, Matrix2); } int *Matrix; int n,m; n=n1; m=m2; Matrix = (int*)malloc(n*m * sizeof(int)); MulMat(Matrix1,n1,m1,Matrix2,n2,m2,Matrix); PrintMatrix(n,m,Matrix); } void Four(){ fflush(stdin); char *str; int n; printf(" - \n"); scanf("%d",&n); str = (char*)malloc(n * sizeof(char)); printf(" (1) (2)?\n"); char c; fflush(stdin); scanf("%c",&c); if(c=='1'){ printf(" 32-126\n"); RandStr(n,str); PrintStr(n,str); } else if(c=='2') { printf(" \n"); ScanStr(n,str); } printf("\n ?\n"); fflush(stdin); int l=0,k=0; char *substr; scanf("%d",&l); printf("C ?\n"); scanf("%d",&k); substr = (char*)malloc(n * sizeof(char)); CopyArrFT(k,l,str,substr); PrintStr(l,substr); printf("\n"); } void Five(){ // , - fflush(stdin); int *Arr; int n; printf(" - \n"); scanf("%d",&n); Arr = (int*)malloc(n * sizeof(int)); printf(" (1) (2)?\n"); char c; fflush(stdin); scanf("%c",&c); if(c=='1'){ printf(" -100 100\n"); RandArr(n, Arr); } else if(c=='2') { printf(" \n"); ScanArr(n, Arr); } SortArrBub(n,Arr); // - - . , PrintArr(n, Arr); L705(n,Arr); } void Six(){ fflush(stdin); int *Arr; int n; printf(" - \n"); scanf("%d",&n); Arr = (int*)malloc(n * sizeof(int)); printf(" (1) (2)?\n"); char c; fflush(stdin); scanf("%c",&c); if(c=='1'){ printf(" -100 100\n"); RandArr(n, Arr); for(int i = 0; i<n; i++){ Arr[i]%=2; } } else if(c=='2') { printf(" \n"); ScanArr(n, Arr); } PrintArr(n,Arr); FZ(n,Arr); } void Seven(){ fflush(stdin); printf(" \n"); int n; printf(" - \n"); scanf("%d",&n); float **Mat; Mat = (float**)malloc(n * sizeof(float*)); for (int i = 0; i<n; i++) Mat[i] = (float*)malloc(n * sizeof(float*)); printf(" (1) (2)?\n"); char c; fflush(stdin); scanf("%c",&c); if(c=='1'){ printf(" -100 100"); RandMatrixF(n, n, Mat); PrintMatrixF(n,n,Mat); } else if(c=='2') { printf(" \n"); ScanMatrixF(n, n, Mat); } printf(" :\n"); DiagMat(n,Mat); PrintMatrixF(n,n,Mat); } void Eight(){ fflush(stdin); int *Matrix; int n; printf(" - \n"); scanf("%d",&n); Matrix = (int*)malloc(n*n * sizeof(int)); printf(" (1) (2)?\n"); char c; fflush(stdin); scanf("%c",&c); if(c=='1'){ printf(" -100 100"); RandMatrix(n, n, Matrix); PrintMatrix(n,n,Matrix); } else if(c=='2') { printf(" \n"); ScanMatrix(n, n, Matrix); } int **Mat; Mat = (int**)malloc(n * sizeof(int*)); for (int i = 0; i<n; i++) Mat[i] = (int*)malloc(n * sizeof(int*)); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ Mat[i][j]=*(Matrix+i*n+j); } } free(Matrix); printf(" : %d\n",DetMat(n,Mat)); } void Nine(){ fflush(stdin); char *str; int n; printf(" - \n"); scanf("%d",&n); str = (char*)malloc(n * sizeof(char)); printf(" \n"); fflush(stdin); ScanStr(n,str); PrintStr(n,str); int p; printf(" ?\t"); fflush(stdin); scanf("%d",&p); Cstr(n,str,p); PrintStr(n,str); Dstr(n,str,p); PrintStr(n,str); } void Zero(){ char a = ' '; do{ printf(" ?\n 1) \n 2) \n 3) \n"); printf(" 4) \n 5) \n 6) \n"); printf(" 7*) \n 8*) \n 9*) \n"); printf(" \n"); fflush(stdin); scanf("%c",&a); switch(a){ case '1': printf(" - \n"); First(); break; case '2': printf(" - \n"); Second(); break; case '3': printf(" - \n"); Third(); break; case '4': printf(" - \n"); Four(); break; case '5': printf(" - \n"); Five(); break; case '6': printf(" - \n"); Six(); break; case '7': printf(" * - \n"); Seven(); break; case '8': printf(" * - \n"); Eight(); break; case '9': printf(" * - \n"); Nine(); break; } printf(" - \n"); fflush(stdin); scanf("%c",&a); }while(a==' '); }
C
#include <stdio.h> #include <stdlib.h> /* QUESTAO Implemente um algoritmo RECURSIVO que LEIA um vetor de inteiros com n posições (n definido pelo usuário). Após o usuário inserir elementos no vetor, o algoritmo deve imprimir os números armazenados na última até a primeira posição do vetor. */ /* PROTOTYPES */ int Imprimir_Vetor_Ultima_Primeira ( int tam, int v[tam] ); int Ler_vetor ( int tam, int v[tam], int i ); int main() { int tam; int iterator = 0; scanf("%i",&tam); int vetor[tam]; Ler_vetor(tam,vetor,iterator); Imprimir_Vetor_Ultima_Primeira(tam,vetor); return 0; } int Imprimir_Vetor_Ultima_Primeira ( int tam, int v[tam] ) { for ( int i = tam - 1; i >= 0; i-- ) { printf("%i ",v[i]); } printf("\n"); return 0; } int Ler_vetor ( int tam, int v[tam], int i ) { if ( i == tam ) { return 0; } else { scanf("%i",&v[i]); return Ler_vetor(tam,v,++i); } }
C
#include <stdio.h> #include <time.h> #include <stdlib.h> int main(void){ int n; srand((unsigned)time(NULL)); n = rand() % 100 + 1; printf("数値:%d\n", n); if(n >= 20 && n < 80){ printf("20以上80未満です\n"); }else{ printf("20未満か、80以上です\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> int main(int argc, char* argv[]) { int sockfd; char buffer[1024]; char *hello = "Hello message from server."; struct sockaddr_in server_addr, client_addr; /* Creating socket file descriptor */ if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket creation failed."); exit(EXIT_FAILURE); } memset(&server_addr, 0, sizeof(server_addr)); memset(&client_addr, 0, sizeof(client_addr)); /* Filling server information */ server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(8080); if ( (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) ) { perror("bind failed."); exit(EXIT_FAILURE); } int len, n; n = recvfrom(sockfd, (char *)buffer, 1024, MSG_WAITALL, (struct sockaddr *) &client_addr, &len); buffer[n] = '\0'; printf("Client: %s\n", buffer); sendto(sockfd, (const char *)hello, strlen(hello), 0, (const struct sockaddr *) &client_addr, len); printf("Hello message sent.\n"); return 0; }
C
#include <stdio.h> int main(){ int ec[3][2], pendiente = 0; for(int i = 0; i<2; i++){ for(int j = 0; j<2; j++){ if(j==0){ printf("\nIntroduzca el valor de X%d: ", (i+1)); }else{ printf("\nIntroduzca el valor de Y%d: ", (i+1)); } scanf("%d", &ec[i][j]); } } //printf("X1: %d, Y1: %d\n", ec[0][0], ec[0][1]); //printf("X2: %d, Y2: %d\n", ec[1][0], ec[1][1]); ec[0][2] = (ec[1][1] - ec[1][0])/(ec[0][1] - ec[0][0]); //printf("Pendiente: %d\n", ec[0][2]); printf("La ecuacion de la recta en su forma y=mx + b es:\n"); printf("\t y = %d*%d + %d\n", ec[0][2], ec[0][0], ec[0][1]); return 0; }
C
#include "holberton.h" /** * print_binary - prints binary representation of num * @n: value to print * * Return: void */ void print_binary(unsigned long int n) { unsigned long int x; unsigned long int r; unsigned long int l; short int switch_on = 0; unsigned long int size; size = sizeof(unsigned long int) * 8; if (n == 0) { _putchar('0'); } else { for (x = 0; x < size; x++) { l = n << 1; r = l >> 1; if (n != r) { switch_on = 1; _putchar('1'); } else if (switch_on == 1) { _putchar('0'); } n = n << 1; } } }
C
#include "key.h" #include "delay.h" #include "pin_def.h" #include "stm32f10x.h" #include <string.h> void key_init(void) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | (GPIO_Pin_8 - GPIO_Pin_3); GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 - GPIO_Pin_0; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(GPIOA, &GPIO_InitStructure); } void key_scan(u8 KeyDown[]) { u8 i, j; //memset(KeyDown, 0, 480); for (i = 0; i < 60; ++i) KeyDown[i] = 0; GPIOB->ODR &= 0xff05; // pb1,3,4,5,6,7=0 delay_us(1); if ((GPIOA->IDR & 0x03ff) != 0x03ff) { delay_ms(6); GPIOB->ODR |= 0x00f8; delay_us(1); for (i = 1; i < 9; ++i) KeyDown[i] = !PAin(i); for (j = 3; j < 8; ++j) { GPIOB->ODR &= 0xff05; GPIOB->ODR |= ~(0x01 << j) & 0xfa; delay_us(1); for (i = 0; i < 10; ++i) KeyDown[(j - 2)*10 + i] = !PAin(i); } } }
C
class Base { public: Base() : i_() {} virtual void increment(long v) { i_ += v; } private: long i_; }; template <typename T> class Derived : public Base { public: Derived() : Base(), j_() {} void increment(long v) { j_ += v; Base::increment(v); } // This does not compile even though multiply() is not used: // Base does not depend on the template parameter T void multiply(long v) { j_ *= v; Base::multiply(v); } private: T j_; }; int main() { Derived<long> d; d.increment(5); }
C
/** * @file Element.h * @brief Fichier d'entête du module \em Element. * * @author Alexis BRENON */ #ifndef __ELEMENT_H__ #define __ELEMENT_H__ /** * @typedef Key * @brief Une clé est un pointeur sur n'importe quel type. * Seule la fonction de hachage devra savoir de quel type elle est. */ typedef void* Key; /** * @struct sElement * @brief Structure représentant les éléments à stocker dans la table. * Cette structure doit absolument contenir un champ de type Key nommé key. */ struct sElement { Key key; /**< Clé de l'élément (pointera sur le nom */ char* name; /**< Nom du contact */ char num[5]; /**< Numéro du contact */ }; /** * @typedef Element * @brief Redéfinition de type. */ typedef struct sElement Element; /* ** *************************************************************** ** */ /* ** ** */ /* ** INTERFACE ** */ /* ** ** */ /* ** *************************************************************** ** */ /* ** *************************************************************** ** */ /* ** Fonctions de création/initialisation. ** */ /* ** *************************************************************** ** */ /** * @fn Element* elementCreate ( const char* name, const char num[5] ); * @brief Crée et initialise un élément. * * @param[in] name Nom du contact * @param[in] num Numéro du contact * @return L'élément créé. */ Element* elementCreate ( const char* name, const char num[5] ); /** * @fn void elementDestroy ( Element** ppElem ); * @brief Libère et détruit un élément. * * @param[in,out] ppElem POinteur sur pointeur sur l'élément à détruire. */ void elementDestroy ( Element** ppElem ); /** * @fn void elementInit ( Element* pElem, const char* name, const char num[5] ); * @brief Initialise un élément. * * @param[in,out] pElem Pointeur sur l'élément à initialiser. * @param[in] name Nom du contact * @param[in] num Numéro du contact */ void elementInit ( Element* pElem, const char* name, const char num[5] ); /** * @fn void elementRelease ( Element* pElem ); * @brief Libère l'espace alloué par un élément. * * @param[in,out] pElem Pointeur sur l'élément à libérer. */ void elementRelease ( Element* pElem ); /** * @fn void elementCopy ( Element* pElemDest, const Element* pElemSourc ); * @brief Constructeur de copie. * * @param[out] pElemDest Pointeur sur Element près à être initialisé. * @param[in] pElemSourc Element copié. */ void elementCopy ( Element* pElemDest, const Element* pElemSourc ); /* ** *************************************************************** ** */ /* ** Accesseurs/Mutateurs ** */ /* ** *************************************************************** ** */ /** * @fn void elementSetName ( Element* pElem, const char* name ); * @brief Mutateur sur le nom. * * @param[in,out] pElem Elément * @param[in] name Nom du contact. */ void elementSetName ( Element* pElem, const char* name ); /** * @fn const char* elementGetName ( Element* pElem, ); * @brief Accesseur sur le nom. * * @param[in,out] pElem Elément * @return Nom du contact. */ const char* elementGetName ( Element* pElem ); /** * @fn void elementSetNum ( Element* pElem, const char num[5] ); * @brief Mutateur sur le numéro. * * @param[in,out] pElem Elément * @param[in] num Numero du contact. */ void elementSetNum ( Element* pElem, const char num[5] ); /** * @fn const char* elementGetNum ( Element* pElem, ); * @brief Accesseur sur le numéro. * * @param[in,out] pElem Elément * @return Numero du contact. */ const char* elementGetNum ( Element* pElem ); /* ** *************************************************************** ** */ /* ** Fonctions relative à la table de hachage ** */ /* ** *************************************************************** ** */ /** * @fn int elementKeyCmp ( const Key key1, const Key key2 ); * @brief Fonction de comparaison de deux clés. * * @param[in] key1 Première clé * @param[in] key2 Deuxieme clé * @return 0 si les deux clés sont idéntiques. */ int elementKeyCmp ( const Key key1, const Key key2 ); /** * @fn int elementHashExtraction ( const Key key, int iMax ); * @brief Fonction de hachage par extraction. * * @param[in] key Clé à hacher * @param[in] iMax Valeur maximale de la caleur de hachage * @return La valeur de hachage correspondant à la clé */ int elementHashExtraction ( const Key key, int iMax ); /** * @fn int elementHashCompression ( const Key key, int iMax ); * @brief Fonction de hachage par compression. * * @param[in] key Clé à hacher * @param[in] iMax Valeur maximale de la caleur de hachage * @return La valeur de hachage correspondant à la clé */ int elementHashCompression ( const Key key, int iMax ); /** * @fn int elementHashModulo ( const Key key, int iMax ); * @brief Fonction de hachage par modulo. * * @param[in] key Clé à hacher * @param[in] iMax Valeur maximale de la caleur de hachage * @return La valeur de hachage correspondant à la clé */ int elementHashModulo ( const Key key, int iMax ); /** * @fn int elementHashMultiplication ( const Key key, int iMax ); * @brief Fonction de hachage par multiplication. * * @param[in] key Clé à hacher * @param[in] iMax Valeur maximale de la caleur de hachage * @return La valeur de hachage correspondant à la clé */ int elementHashMultiplication ( const Key key, int iMax ); #endif /* __ELEMENT_H__ */
C
#include <stdlib.h> #include <stdio.h> struct produto { int codP; float valor; struct produto *proxP; }; typedef struct produto *structP; struct cliente { int codC; struct produto *prod; struct cliente *proxC; }; typedef struct cliente *structC; void chegada(); void listarProd(); void consumo(); float saida(); void fechar(); void listarCli(); int menu(); structC inicio=NULL; float totDin; int main(){ totDin=0.0f; int acao; do { acao=menu(); switch(acao){ case 1: chegada(); break; case 2: consumo(); break; case 3: totDin+=saida(); break; case 4: listarProd(); break; case 5: listarCli(); break; } } while (acao!=0); fechar(); } int menu(){ int opcao; printf("\nDinheiro de Hoje: %.2f",totDin); printf("\n1: Chegada do cliente"); printf("\n2: Consumo de produto"); printf("\n3: Saida do cliente"); printf("\n4: Listagem de produtos"); printf("\n5: Listagem de Clientes"); printf("\n0: Fechar o restaurante"); printf("\nDigite a opcao (0 - 4): "); scanf("%d",&opcao); return opcao; } void chegada(){ structC p; int n; p=(structC) malloc(sizeof(struct cliente)); printf("\nDigite o codigo do cliente:\t"); scanf("%d",&n); p->prod=NULL; p->codC=n; p->proxC=inicio; inicio=p; } void consumo(){ structP z; structC p; int X; int n; printf("\nDigite o codigo do cliente:\t"); scanf("%d",&X); p=inicio; while(p->codC!=X){ p=p->proxC; } z=(structP) malloc(sizeof(struct produto)); printf("\nDigite o codigo do produto:\t"); scanf("%d",&n); printf("\nDigite o valor do produto:\t"); scanf("%f.2",&(z->valor)); z->codP=n; z->proxP=p->prod; p->prod=z; } /* void saida() { float somacliente; structP z; structP s; structC p = inicio; int X; printf("\nDigite o codigo do cliente:\t"); scanf("%d",&X); while(p->codC==!X){ p=p->proxC; } z=p->prod; if(p->prod!=NULL){ while(z!=NULL){ s=s->proxP; somacliente+=z->valor; z=z->proxP; free(s); s=p; //transferir o auxiliar que deleta para o presente elemento da lista } } else { printf("Nenhum produto foi pedido"); } } */ float saida(){ int X; structP z; structP x; structC p = inicio; structC q = NULL; float soma; printf("\nDigite o codigo do cliente:\t"); scanf("%d",&X); while(p->codC!=X){ q=p; p=p->proxC; } z=p->prod; while(z!=NULL){ printf("\nCOD: %d PRECO: %.2f",z->codP,z->valor); soma+= z->valor; x=z->proxP; free(z); z=x; } printf("\nTotal: %.2f\n",soma); if (q) { q->proxC=p->proxC; } else { inicio=p->proxC; } free(p); return soma; } void listarCli(){ structC p =inicio; printf("\n"); while (p!=NULL){ printf("\n%d",p->codC); p=p->proxC; } printf("\n"); } void listarProd(){ structP z; structC p = inicio; int X; printf("\n\nDigite o codigo do cliente: "); scanf("%d",&X); while(p->codC!=X){ p=p->proxC; } z=p->prod; while(z!=NULL){ printf("\nCOD: %d PRECO: %f",z->codP,z->valor); z=z->proxP; } printf("\nNão há mais produtos\n"); } void fechar(){ structP z; structP x; structC p = inicio; structC q = NULL; float soma; while(p){ printf("\nCliente %d", p->codC); z=p->prod; while(z!=NULL){ printf("\nCOD: %d PRECO: %.2f",z->codP,z->valor); soma+= z->valor; x=z->proxP; free(z); z=x; } printf("\nTotal: %.2f\n",soma); totDin+=soma; soma =0; q=p->proxC; free(p); p=q; } printf("\nTOTAL DO DIA: %.2f\n",totDin); }
C
#include"jitendra.h" #include"prototype.h" int bsort() { printf("In %s\n",__func__); int i,a[100],n,temp,j; printf("enter the number of aray\n"); scanf("%d",&n); printf("ente the aray\n"); for(i = 0;i<n;i++) { scanf("%d",&a[i]); } for(i =0;i<n-1;i++) { for(j=0;j<n-1;j++) { if (a[j]> a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] =temp; } } } printf("sortedaray\n"); for(i = 0;i<n;i++) { printf("%d",a[i]); } return 0; }
C
#include "queue_circular_headers.h" static struct node *getnode() { struct node *ptr = calloc(1, sizeof(struct node)); printf("enter node data:"); scanf("%d", &ptr->data); return ptr; } /* int createQueue(struct queue **q, unsigned int len) { struct node *last = NULL; struct node *p; int i; if (q == NULL || *q == NULL) return -1; for(i=0; i<len; i++) { if(last == NULL) { (*q)->last = getnode(); last = (*q)->last; last->link = last; } else { p = getnode(); p->link = last->link; last->link = p; last = last->link; } } // The below approach is not correct. The one should be done as seen beneath of it // Remember ETH_HDR() MACRO. // *q->head = *q->tail = *q->last = last; (*q)->head = (*q)->tail = (*q)->last = last; return 0; } */ int createQueue(struct queue *q, unsigned int len) { struct node *last = NULL; struct node *p; int i; if (q == NULL) return -1; for(i=0; i<len; i++) { if(last == NULL) { q->last = getnode(); last = q->last; last->link = last; } else { p = getnode(); p->link = last->link; last->link = p; last = last->link; } } // The below approach is not correct. The one should be done as seen beneath of it //*q->head = *q->tail = *q->last = last; q->head = q->tail = q->last = last; return 0; } void display(struct queue *q) { struct node *last = q->last; struct node *p = last; if (last == NULL) { printf("Empty List\n"); return; } p = last->link; do { printf("%d ", p->data); p = p->link; } while(p != last->link); printf("\n"); } /* static void addatbegin(struct queue *q) { struct node *last = q->last; struct node *tmp = getnode(); if (last == NULL) { last = tmp; last->link = last; } else { tmp->link = last->link; //tmp->link = last->link; If HEAD NODE USED. last->link = tmp; } tmp = NULL; return; } static void addatend(void) { struct node *tmp, *p; tmp = getnode(); if (last == NULL) { last = tmp; last->link = last; } else { tmp->link = last->link; last->link = tmp; last = last->link; } tmp = NULL; return; } static void reverse(void) { struct node *p,*q,*r; if(last) { p = last->link; q = p->link; } else { return; } if (q == NULL) return; p->link = last; last = p; //while (q != last) { do { r = q->link; q->link = p; p = q; q = r; } while(q != last); return; } static void deletenode(void) { struct node *tmp, *p; int n; if (last == NULL) { printf("List is empty\n"); return; } printf("enter node to delete:"); scanf("%d",&n); tmp = NULL; p = last->link; do { if (last->link->data == n) { tmp = last->link; last->link = last->link->link; p = last->link; } else if (p->link->data == n) { tmp = p->link; if (p->link == last) last = p; p->link = p->link->link; } else { p = p->link; } if (tmp) { // If we are deleting the only node if (tmp == last && tmp == last->link) { last = NULL; return; } free(tmp); tmp = NULL; } } while (p != last); return; } static void deletelist(void) { struct node *tmp, *p; p = last->link; last->link = NULL; while (p) { tmp = p; p = p->link; free(tmp); } last = NULL; return; } */
C
#include "main.h" /** * _isupper - Check if a letter is upper * @i: The number to be checked * * Return: 1 for upper letter or 0 for any else */ int _isupper(int i) { if (i >= 65 && i <= 90) { return (1); } return (0); }
C
#include<stdio.h> void main() { int n; printf("Enter the number :"); scanf("%d",&n); for(int i=1; i<n;i++) { for (int j=1; j<=n; j++) { printf("*"); } printf("\n"); } }
C
#include <string.h> #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include "misc.h" typedef struct { int start; int end; } interval; // make the last pair sorted first, and recur ahead and left pairs static int partitionSort(interval * nums, int low, int high) { interval temp; int j = low; // max high - 1 for (int i = low; i < high - 1; i++) { // compare with the last node if (nums[i].start < nums[high].start || (nums[i].start == nums[high].start && nums[i].end < nums[high].end)) { memcpy(&temp, &nums[i], sizeof(interval)); memcpy(&nums[i], &nums[j], sizeof(interval)); memcpy(&nums[j], &temp, sizeof(interval)); j++; } } memcpy(&temp, &nums[j+1], sizeof(interval)); memcpy(&nums[high], &nums[j+1], sizeof(interval)); memcpy(&nums[j+1], &temp, sizeof(interval)); return j+1; } static void quickSort(interval * nums, int low, int high) { if (high <= low) return; int p = partitionSort(nums, low, high); // smaller than P quickSort(nums, low, p-1); // bigger than P quickSort(nums, p+1, high); } static interval * mergeIntervals(interval *nums, int n, int *ret_num) { interval *ret = malloc(sizeof(interval) * n); int i; int count = 0; if (n == 0) { return NULL; } // sort the intervals quickSort(nums, 0, n-1); memcpy(&ret[count++], &nums[0], sizeof(interval)); for (i = 1; i < n; i++) { if (nums[i].start <= ret[count - 1].end) { // merge, end is the maximal of two ends, [1, 8] and [2, 6] ret[count - 1].end == MAX(nums[i].end, ret[count-1].end); } else { memcpy(&ret[count++], &nums[i], sizeof(interval)); } } *ret_num = count; return ret; } /* 可以分 3 段处理, 先添加原来的区间,即在给的 newInterval 之前的区间。 然后添加 newInterval ,注意这里可能需要合并多个区间。 最后把原来剩下的部分添加到最终结果中即可。 */ static interval * insertIntervals(interval *nums, int n, int *ret_num, interval * insert) { interval *ret = malloc(sizeof(interval) * n + 1); int i; int count = 0; if (n == 0) { memcpy(&ret[count++], insert, sizeof(interval)); return NULL; } // first step for (i = 0; i < n; i++) { if (nums[i].end < insert->start) { memcpy(&ret[count++], &nums[i], sizeof(interval)); } else { break; } } // second step for (; i < n; i++) { if (nums[i].start <= insert->end) { insert->end = MAX(insert->end, nums[i].end); insert->start = MIN(insert->start, nums[i].start); } else { break; } } memcpy(&ret[count++], insert, sizeof(interval)); // third step for (; i < n; i++) { memcpy(&ret[count++], &nums[i], sizeof(interval)); } *ret_num = count; return ret; } int main(int argc, char **argv) { interval array[] = {{1,3},{2,6},{8,10},{15,18}}; interval array2[] = {{1,3},{2,6},{8,10},{15,18}}; interval insert = {12, 23}; interval *ret; int ret_num = 0; ret = mergeIntervals(array, 4, &ret_num); if (ret_num) { for (int i = 0; i < ret_num; i++) { printf("[%d,%d]\t", ret[i].start, ret[i].end); } printf("\n"); free(ret); } ret = insertIntervals(array2, 4, &ret_num, &insert); if (ret_num) { for (int i = 0; i < ret_num; i++) { printf("[%d,%d]\t", ret[i].start, ret[i].end); } printf("\n"); free(ret); } }
C
/************************************************************************/ /* */ /* Interface file for a BINARY_TREE ADT */ /* */ /* Refer to lecture notes for details. */ /* */ /* David Vernon */ /* 5/3/2017 Added function to initialize the tree */ /* /* Wuyeh Jobe (03/18/2020) added functions to calculate height of tree,*/ /* assign element, print in order to file, calculate number of probes */ /* for a word, find if a word exist. */ /************************************************************************/ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #define FALSE 0 #define TRUE 1 typedef struct { char *word; int frequency; int wordLevel; int n_probes; } ELEMENT_TYPE; typedef struct node *NODE_TYPE; typedef struct node { ELEMENT_TYPE element; NODE_TYPE left, right; } NODE; typedef NODE_TYPE BINARY_TREE_TYPE; typedef BINARY_TREE_TYPE WINDOW_TYPE; /*** function prototypes ***/ /*** initialize a tree ***/ void initialize(BINARY_TREE_TYPE *tree, static bool first_call); /*** insert an element in a tree ***/ BINARY_TREE_TYPE *insert(ELEMENT_TYPE e, BINARY_TREE_TYPE *tree ); /*** returns & deletes the smallest node in a tree (i.e. the left-most node) */ ELEMENT_TYPE delete_min(BINARY_TREE_TYPE *tree); /*** delete an element in a tree ***/ BINARY_TREE_TYPE *delete_element(ELEMENT_TYPE e, BINARY_TREE_TYPE *tree); /*** inorder traversal of a tree, printing node elements **/ int inorder(BINARY_TREE_TYPE tree, int n); /*** print all elements in a tree by traversing inorder ***/ int print(BINARY_TREE_TYPE tree); /*** error handler: print message passed as argument and take appropriate action ***/ int error(char *s); /*** assign values to an element ***/ int assign_element_value(ELEMENT_TYPE *e, /*int frequency,*/ char w[]); /*** delete all nodes ***/ int postorder_delete_nodes(BINARY_TREE_TYPE tree); /** Check if a word is in a tree **/ int find(ELEMENT_TYPE e, BINARY_TREE_TYPE tree ); /** Calculate the height of the tree **/ int treeHeight(BINARY_TREE_TYPE tree); /** Calculate the the number of probes required for a word int numberOfProbes(ELEMENT_TYPE e, BINARY_TREE_TYPE tree);**/ /*** inorder traversal of a tree, printing words to the file with their freqeuncy **/ int print_inorder_to_file(BINARY_TREE_TYPE tree, FILE *fp_out, int n); /** Calculate the level at which a word is **/ /*int level(ELEMENT_TYPE e, BINARY_TREE_TYPE tree);*/ /** Calculate the total probes and the total number of words **/ void totalProbes(BINARY_TREE_TYPE tree); /** return the total probes for the tree **/ double getAverageProbes();
C
// Linked List : insert_at_begin: returning single pointer #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; }node_t; void display(node_t *head) { } //void insert_at_begin(node_t **p_head, int value) node_t *insert_at_begin(node_t *head, int value) { node_t *p_newnode; p_newnode = (node_t *) malloc(sizeof(node_t)); p_newnode->data = value; // setting next of newnode to current linked list p_newnode->next = head; // head points to new node head = p_newnode; return head; } int main() { // declare head pointer node_t *head = NULL; node_t *ptr; head = insert_at_begin(head, 10); head = insert_at_begin(head, 20); head = insert_at_begin(head, 30); head = insert_at_begin(head, 40); // Call display() : // expect 40 30 20 10 #if 0 node_t *ptr = NULL; // create node1 node_t *p_node1; p_node1 = (node_t*) malloc(sizeof(node_t)); p_node1->data = 10; p_node1->next = NULL; // point head to node1 head = p_node1; // create node2, node_t *p_node2; p_node2 = (node_t*) malloc(sizeof(node_t)); p_node2->data = 20; p_node2->next = NULL; // connect node2 after node1 p_node1->next = p_node2; #endif // print the linked list printf("Contents of Linked Lists : "); ptr = head; while (ptr != NULL) { printf("%d ", ptr->data);//data in struct pointed at by ptr ptr = ptr->next; //next in struct pointed at by ptr } printf("\n"); //TBD : add loop to free the memory }
C
/* * File: sjf.c * Author: Stephen Sampson * Purpose: This file contains the shortest job first module to serve HTTP * requests. */ #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/sendfile.h> #include <sys/stat.h> #include <string.h> #include <unistd.h> #include "network.h" #include "universal_functions.h" /* * linked list implementation adapted from: http://tutorialspoint.com/ * data_structures_algorithms/linked_list_program_in_c.html */ /* LINKED LIST STRUCTS */ struct node{ int sequence; // sequence number of the job coming in int socket; // socket number to send the file on int fd; // file descriptor of the file requested float bytes_left; // remaining bytes left to transfer to client int quantum; // how many bytes will be sent at a time struct node *next; // pointer to the next node in linked list }; struct node *head = NULL; // pointer to the head of the linked list struct node *current = NULL; // last entry in linked list points to NULL /* LINKED LIST FUNCTION PROTOTYPES */ bool isEmpty(void); // determines whether linked list has any entries int inQueue(void); // determines how many jobs are in the queue void printList(void); // debugging only - prints all jobs in queue /* adds new node at the beginning of the linked list */ void push_front(int sequence, int socket, int fd, float bytes_left, int quantum); struct node *pop_front(void); // removes job at front of linked list void sort(void); // sorts linked list by job size /* SJF SCHEDULING ALGORITHM EXECUTION */ void sjf(int port_number, int debug) { int client_socket = -1; // socket the client connected on int sequence = 0; // global sequence counter - how many jobs int quantum = 2147479552; // maximum size to be sent at once char **request_elements = calloc(3, sizeof(char**)); char *to_parse = calloc(256, sizeof(char)); // function to parse request char *location = calloc(256, sizeof(char)); // location of requested file FILE *requested_file; // the requested file struct node *processing; // job currently being processed int seqip; // sequence number of job in progress int sockip; // socket number of job in progress int fdip; // file descriptor of job in progress float blip; // bytes left of job in progress int quantip; // quantum for job in progress network_init(port_number); // initialize network on specified port while(1){ if (inQueue()==0){ // check if queue is empty network_wait(); // if queue is empty, put program to sleep } /* The code within the following while loop is used to interpret and queue * any valid waiting requests. */ while((client_socket = network_open()) != -1){ /* if network_open() returns a positive integer, parse the request * on this socket */ if(client_socket>0){ read(client_socket, to_parse, 256); // read request into buffer parse(request_elements, to_parse); // parse request from buffer /* if any of the three required HTTP request elements are missing, * send error 400 malformed request on client socket */ if((request_elements[0]==NULL)|(request_elements[1]==NULL)| (request_elements[2]==NULL)){ msg400(client_socket); // malformed request. Error 400 close(client_socket); // close socket connection }else { /* if the request is valid, look for the requested file */ if((strcmp(request_elements[0],"GET")==0)&& (strcmp(request_elements[2],"HTTP/1.1")==0)){ location = request_elements[1]; location++; /* if requested file is where it should be, open it and get * required information on the file then add the job to the * queue */ if(fopen( location, "r" ) != NULL){ requested_file = fopen( location, "r"); int fd = -1; // var to store file descriptor fd = fileno(requested_file); // store file descriptor struct stat buf; // create a buffer fstat(fd, &buf); // retrieve file statistics float filesize = buf.st_size; // find file size sequence++; // increment glkobal seq counter /* push job to queue with all required info */ push_front(sequence, client_socket, fd, filesize, quantum); sort(); // sort queue by job size msg200(client_socket); // request ok! } else { msg404(client_socket); // fopen() returned NULL. Error404 close(client_socket); // close client connection } } else { msg400(client_socket); // malformed request. Error 400 close(client_socket); // close client connection } } /* ensure request array is cleaned up */ int i=0; for(i=0;i<3;i++){ if(request_elements[i]!=NULL) memset(request_elements[i], '\0', strlen(request_elements[i])); } } } /* If request queue is not empty, process first request in queue */ if(!isEmpty()){ // check if queue empty processing = pop_front(); // pop first entry store in node seqip = processing->sequence; // store sequence of popped job sockip = processing->socket; // store socket of popped job fdip = processing->fd; // store fd of popped job blip = processing->bytes_left;// store bytes left of popped job quantip = processing->quantum;// store quantum of popped job if(blip<=quantip){ // this will always be true in sjf lseek(fdip, (off_t)-blip, SEEK_END);// set location in file sendfile(sockip, fdip, NULL, blip); // send entire file fflush(stdout); // flush stdout buffer printf("Request %d Completed\n", seqip); // print to console close(fdip); // close file descriptor in progress close(sockip); // close socket in progress } else { /* this section is just to handle files that exceed the filesize * limit of sendfile by sending it in multiple pieces... It is * not enabled currently as the loop above will not add a job * to the queue if its filesize exceeds sendfile() capabilities */ sendfile(sockip,fdip,NULL,quantip); blip=blip-quantip; push_front(seqip, sockip, fdip, blip, quantip); } } } } /****************************************************************************** * LINKED LIST FUNCTIONS * ADAPTED FROM TUTORIALSPOINT.COM. FULL LINK ABOVE *****************************************************************************/ /* CHECK IF LIST IS EMPTY */ bool isEmpty(void){ return head == NULL; } /* DETERMINE NUMBER OF ELEMENTS IN LIST */ int inQueue(void) { int length = 0; struct node *current; for(current = head; current != NULL; current = current->next){ length++; } return length; } /* PRINT THE LINKED LIST TO CONSOLE */ void printList(void){ struct node *ptr = head; printf("\n["); while(ptr != NULL){ printf("(%d,%d,%d,%f,%d)",ptr->sequence, ptr->socket, ptr->fd, ptr->bytes_left, ptr->quantum); ptr = ptr->next; } printf("]\n\n"); } /* ADD ENTRY TO FRONT OF LINKED LIST */ void push_front(int sequence, int socket, int fd, float bytes_left, int quantum){ struct node *link = (struct node*) malloc(sizeof(struct node)); link->sequence = sequence; link->socket = socket; link->fd = fd; link->bytes_left = bytes_left; link->quantum = quantum; link->next = head; head = link; } /* REMOVE ENTRY FROM FRONT OF LINKED LIST */ struct node *pop_front(void){ struct node *tempLink = head; head = head->next; return tempLink; } /* SORT LINKED LIST BY INCREASING VALUE OF 'BYTES_LEFT' */ void sort(void){ int i, j, k, tempseq, tempsock, tempfd, tempquant; float tempbl; struct node *current; struct node *next; int size = inQueue(); k = size; for(i=0;i<size-1;i++,k--){ current = head; next = head->next; for(j=1;j<k;j++){ /* CHECK IF NEXT ENTRY HAS MORE BYTES LEFT THAN CURRENT ENTRY. * IF SO, SWAP THEM */ if(current->bytes_left > next->bytes_left) { tempseq = current->sequence; current->sequence = next->sequence; next->sequence = tempseq; tempsock=current->socket; current->socket = next->socket; next->socket = tempsock; tempfd = current->fd; current->fd = next->fd; next->fd = tempfd; tempbl = current->bytes_left; current->bytes_left = next->bytes_left; next->bytes_left = tempbl; tempquant = current->quantum; current->quantum = next->quantum; next->quantum = tempquant; /* IF CURRENT ENTRY AND NEXT ENTRY HAVE THE SAME AMOUNT OF BYTES * REMAINING TO TRANSFER, SORT THEM IN ORDER OF SEQUENCE NUMBER */ } else if((current->bytes_left==next->bytes_left)&& (current->sequence>next->sequence)){ tempseq = current->sequence; current->sequence = next->sequence; next->sequence = tempseq; tempsock=current->socket; current->socket = next->socket; next->socket = tempsock; tempfd = current->fd; current->fd = next->fd; next->fd = tempfd; tempbl = current->bytes_left; current->bytes_left = next->bytes_left; next->bytes_left = tempbl; tempquant = current->quantum; current->quantum = next->quantum; next->quantum = tempquant; } current = current->next; next = next->next; } } } /****************************************************************************** * END OF FILE *****************************************************************************/
C
/* * Copyright (c) 2017, Jack Lange <[email protected]> * All rights reserved. * * This is free software. You are permitted to use, * redistribute, and modify it as specified in the file "PETLAB_LICENSE". */ #include <limits.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include "pet_json.h" #include "pet_util.h" #include "pet_log.h" /* Internalize nxjson functions */ #include "nxjson.h" #include "nxjson.c" pet_json_obj_t pet_json_new_obj(char * key) { return create_json(NX_JSON_OBJECT, key, NULL); } pet_json_obj_t pet_json_new_arr(char * key) { return create_json(NX_JSON_ARRAY, key, NULL); } pet_json_obj_t pet_json_parse_str(char * str) { pet_json_obj_t new_obj = PET_JSON_INVALID_OBJ; new_obj = nx_json_parse(str); if (new_obj == NULL) { log_error("Could not parse JSON string (%s)\n", str); return PET_JSON_INVALID_OBJ; } return new_obj; } char * pet_json_serialize(pet_json_obj_t obj) { return nx_json_serialize(obj); } void pet_json_free(pet_json_obj_t object) { assert(object != NULL); assert(((struct nx_json *)object)->root == 1); nx_json_free(object); return; } pet_json_obj_t pet_json_get_object(pet_json_obj_t obj, char * key) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return PET_JSON_INVALID_OBJ; } if (tgt_obj->type != NX_JSON_OBJECT) { return PET_JSON_INVALID_OBJ; } return tgt_obj; } int pet_json_add_object(pet_json_obj_t root_obj, pet_json_obj_t new_obj) { return nx_json_splice(root_obj, new_obj); } int pet_json_splice(pet_json_obj_t obj, pet_json_obj_t new_obj) { return nx_json_splice(obj, new_obj); } int pet_json_split(pet_json_obj_t obj) { return nx_json_split(obj); } int pet_json_del_object(pet_json_obj_t obj) { nx_json_free(obj); return 0; } int pet_json_del_by_key(pet_json_obj_t obj, char * key) { nx_json_del(obj, key); return 0; } int pet_json_get_string(pet_json_obj_t obj, char * key, char ** val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_STRING) { return -1; } *val = tgt_obj->text_value; return 0; } int pet_json_get_bool(pet_json_obj_t obj, char * key, int * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_BOOL) { return -1; } if ((tgt_obj->int_value != 0) && (tgt_obj->int_value != 1)) { return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_int(pet_json_obj_t obj, char * key, int * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if ((tgt_obj->int_value > INT_MAX) || (tgt_obj->int_value < INT_MIN)) { log_error("PET_JSON_INT: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_double(pet_json_obj_t obj, char * key, double * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_DOUBLE) { return -1; } *val = tgt_obj->dbl_value; return 0; } int pet_json_get_s8(pet_json_obj_t obj, char * key, int8_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if ((tgt_obj->int_value > SCHAR_MAX) || (tgt_obj->int_value < SCHAR_MIN)) { log_error("PET_JSON_S8: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_s16(pet_json_obj_t obj, char * key, int16_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if ((tgt_obj->int_value > SHRT_MAX) || (tgt_obj->int_value < SHRT_MIN)) { log_error("PET_JSON_S16: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_s32(pet_json_obj_t obj, char * key, int32_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if ((tgt_obj->int_value > INT_MAX) || (tgt_obj->int_value < INT_MIN)) { log_error("PET_JSON_S32: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_s64(pet_json_obj_t obj, char * key, int64_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_u8(pet_json_obj_t obj, char * key, uint8_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if (tgt_obj->int_value > UCHAR_MAX) { log_error("PET_JSON_U8: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_u16(pet_json_obj_t obj, char * key, uint16_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if (tgt_obj->int_value > USHRT_MAX) { log_error("PET_JSON_U16: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_u32(pet_json_obj_t obj, char * key, uint32_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if (tgt_obj->int_value > UINT_MAX) { log_error("PET_JSON_U32: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_get_u64(pet_json_obj_t obj, char * key, uint64_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_add_string(pet_json_obj_t obj, char * key, char * str) { struct nx_json new_json; new_json.type = NX_JSON_STRING; new_json.text_value = str; // pet_strndup(str, MAX_JSON_LEN); return ((nx_json_add(obj, key, &new_json) == NULL) ? -1 : 0); } int pet_json_add_bool(pet_json_obj_t obj, char * key, int val) { struct nx_json new_json; new_json.type = NX_JSON_BOOL; new_json.int_value = val; return ((nx_json_add(obj, key, &new_json) == NULL) ? -1 : 0); } int pet_json_add_int(pet_json_obj_t obj, char * key, int val) { struct nx_json new_json; new_json.type = NX_JSON_INTEGER; new_json.int_value = val; return ((nx_json_add(obj, key, &new_json) == NULL) ? -1 : 0); } int pet_json_add_double(pet_json_obj_t obj, char * key, double val) { struct nx_json new_json; new_json.type = NX_JSON_DOUBLE; new_json.dbl_value = val; return ((nx_json_add(obj, key, &new_json) == NULL) ? -1 : 0); } int pet_json_add_s64(pet_json_obj_t obj, char * key, int64_t val) { struct nx_json new_json; new_json.type = NX_JSON_INTEGER; new_json.int_value = val; return ((nx_json_add(obj, key, &new_json) == NULL) ? -1 : 0); } int pet_json_add_u64(pet_json_obj_t obj, char * key, uint64_t val) { return pet_json_add_s64(obj, key, val); } int pet_json_add_s8(pet_json_obj_t obj, char * key, int8_t val) { return pet_json_add_s64(obj, key, val); } int pet_json_add_s16(pet_json_obj_t obj, char * key, int16_t val) { return pet_json_add_s64(obj, key, val); } int pet_json_add_s32(pet_json_obj_t obj, char * key, int32_t val) { return pet_json_add_s64(obj, key, val); } int pet_json_add_u8(pet_json_obj_t obj, char * key, uint8_t val) { return pet_json_add_s64(obj, key, val); } int pet_json_add_u16(pet_json_obj_t obj, char * key, uint16_t val) { return pet_json_add_s64(obj, key, val); } int pet_json_add_u32(pet_json_obj_t obj, char * key, uint32_t val) { return pet_json_add_s64(obj, key, val); } int pet_json_set_string(pet_json_obj_t obj, char * key, char * str) { struct nx_json new_val; new_val.type = NX_JSON_STRING; new_val.text_value = str; // pet_strndup(str, MAX_JSON_LEN); return nx_json_set(obj, key, &new_val); } int pet_json_set_bool(pet_json_obj_t obj, char * key, int val) { struct nx_json new_val; new_val.type = NX_JSON_BOOL; new_val.int_value = val; return nx_json_set(obj, key, &new_val); } int pet_json_set_int(pet_json_obj_t obj, char * key, int val) { struct nx_json new_val; new_val.type = NX_JSON_INTEGER; new_val.int_value = val; return nx_json_set(obj, key, &new_val); } int pet_json_set_double(pet_json_obj_t obj, char * key, double val) { struct nx_json new_val; new_val.type = NX_JSON_DOUBLE; new_val.dbl_value = val; return nx_json_set(obj, key, &new_val); } int pet_json_set_s64(pet_json_obj_t obj, char * key, int64_t val) { struct nx_json new_val; new_val.type = NX_JSON_INTEGER; new_val.int_value = val; return nx_json_set(obj, key, &new_val); } int pet_json_set_u64(pet_json_obj_t obj, char * key, uint64_t val) { return pet_json_set_s64(obj, key, val); } int pet_json_set_s8(pet_json_obj_t obj, char * key, int8_t val) { return pet_json_set_s64(obj, key, val); } int pet_json_set_s16(pet_json_obj_t obj, char * key, int16_t val) { return pet_json_set_s64(obj, key, val); } int pet_json_set_s32(pet_json_obj_t obj, char * key, int32_t val) { return pet_json_set_s64(obj, key, val); } int pet_json_set_u8(pet_json_obj_t obj, char * key, uint8_t val) { return pet_json_set_s64(obj, key, val); } int pet_json_set_u16(pet_json_obj_t obj, char * key, uint16_t val) { return pet_json_set_s64(obj, key, val); } int pet_json_set_u32(pet_json_obj_t obj, char * key, uint32_t val) { return pet_json_set_s64(obj, key, val); } pet_json_obj_t pet_json_get_array(pet_json_obj_t obj, char * key) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get(obj, key); if (tgt_obj == NULL) { return PET_JSON_INVALID_OBJ; } if (tgt_obj->type != NX_JSON_ARRAY) { return PET_JSON_INVALID_OBJ; } return tgt_obj; } int pet_json_get_array_len(pet_json_obj_t arr) { return ((struct nx_json *)arr)->length; } pet_json_obj_t pet_json_add_array(pet_json_obj_t obj, char * key) { struct nx_json new_json; new_json.type = NX_JSON_ARRAY; return nx_json_add(obj, key, &new_json); } int pet_json_del_array(pet_json_obj_t obj) { nx_json_free(obj); return 0; } pet_json_obj_t pet_json_array_get_object(pet_json_obj_t arr, int idx) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return PET_JSON_INVALID_OBJ; } if (tgt_obj->type != NX_JSON_OBJECT) { return PET_JSON_INVALID_OBJ; } return tgt_obj; } int pet_json_array_get_string(pet_json_obj_t arr, int idx, char ** val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_STRING) { return -1; } *val = tgt_obj->text_value; return 0; } int pet_json_array_get_bool(pet_json_obj_t arr, int idx, int * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_BOOL) { return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_int(pet_json_obj_t arr, int idx, int * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if ((tgt_obj->int_value > INT_MAX) || (tgt_obj->int_value < INT_MIN)) { log_error("PET_JSON_INT: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_double(pet_json_obj_t arr, int idx, double * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_DOUBLE) { return -1; } *val = tgt_obj->dbl_value; return 0; } int pet_json_array_get_s8(pet_json_obj_t arr, int idx, int8_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if ((tgt_obj->int_value > SCHAR_MAX) || (tgt_obj->int_value < SCHAR_MIN)) { log_error("PET_JSON_S8: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_s16(pet_json_obj_t arr, int idx, int16_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if ((tgt_obj->int_value > SHRT_MAX) || (tgt_obj->int_value < SHRT_MIN)) { log_error("PET_JSON_S16: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_s32(pet_json_obj_t arr, int idx, int32_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if ((tgt_obj->int_value > INT_MAX) || (tgt_obj->int_value < INT_MIN)) { log_error("PET_JSON_S32: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_s64(pet_json_obj_t arr, int idx, int64_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_u8(pet_json_obj_t arr, int idx, uint8_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if (tgt_obj->int_value > UCHAR_MAX) { log_error("PET_JSON_U8: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_u16(pet_json_obj_t arr, int idx, uint16_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if (tgt_obj->int_value > USHRT_MAX) { log_error("PET_JSON_U16: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_u32(pet_json_obj_t arr, int idx, uint32_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } if (tgt_obj->int_value > UINT_MAX) { log_error("PET_JSON_U32: Bounds Error\n"); return -1; } *val = tgt_obj->int_value; return 0; } int pet_json_array_get_u64(pet_json_obj_t arr, int idx, uint64_t * val) { struct nx_json * tgt_obj = NULL; tgt_obj = nx_json_get_item(arr, idx); if (tgt_obj == NULL) { return -1; } if (tgt_obj->type != NX_JSON_INTEGER) { return -1; } *val = tgt_obj->int_value; return 0; } /* * Set the value of an existing array item */ int pet_json_array_set_string(pet_json_obj_t arr, int idx, char * str) { struct nx_json new_val; new_val.type = NX_JSON_STRING; new_val.text_value = str; return nx_json_set_item(arr, idx, &new_val); } int pet_json_array_set_bool(pet_json_obj_t arr, int idx, int val) { struct nx_json new_val; new_val.type = NX_JSON_BOOL; new_val.int_value = val; return nx_json_set_item(arr, idx, &new_val); } int pet_json_array_set_int(pet_json_obj_t arr, int idx, int val) { struct nx_json new_val; new_val.type = NX_JSON_INTEGER; new_val.int_value = val; return nx_json_set_item(arr, idx, &new_val); } int pet_json_array_set_double(pet_json_obj_t arr, int idx, double val) { struct nx_json new_val; new_val.type = NX_JSON_DOUBLE; new_val.dbl_value = val; return nx_json_set_item(arr, idx, &new_val); } int pet_json_array_set_s64(pet_json_obj_t arr, int idx, int64_t val) { struct nx_json new_val; new_val.type = NX_JSON_INTEGER; new_val.int_value = val; return nx_json_set_item(arr, idx, &new_val); } int pet_json_array_set_u64(pet_json_obj_t arr, int idx, uint64_t val) { return pet_json_array_set_s64(arr, idx, val); } int pet_json_array_set_s8(pet_json_obj_t arr, int idx, int8_t val) { return pet_json_array_set_s64(arr, idx, val); } int pet_json_array_set_s16(pet_json_obj_t arr, int idx, int16_t val) { return pet_json_array_set_s64(arr, idx, val); } int pet_json_array_set_s32(pet_json_obj_t arr, int idx, int32_t val) { return pet_json_array_set_s64(arr, idx, val); } int pet_json_array_set_u8(pet_json_obj_t arr, int idx, uint8_t val) { return pet_json_array_set_s64(arr, idx, val); } int pet_json_array_set_u16(pet_json_obj_t arr, int idx, uint16_t val) { return pet_json_array_set_s64(arr, idx, val); } int pet_json_array_set_u32(pet_json_obj_t arr, int idx, uint32_t val) { return pet_json_array_set_s64(arr, idx, val); } /* * Add a new item to an existing array */ int pet_json_array_add_object(pet_json_obj_t arr, int * idx, pet_json_obj_t obj) { int tmp_idx = 0; tmp_idx = nx_json_array_splice(arr, obj); if (idx) *idx = tmp_idx; return 0; } int pet_json_array_add_string(pet_json_obj_t arr, int * idx, char * val) { struct nx_json new_val; int tmp_idx = 0; new_val.type = NX_JSON_STRING; new_val.text_value = val; //pet_strndup(val, MAX_JSON_LEN); tmp_idx = nx_json_add_item(arr, &new_val); if (idx) *idx = tmp_idx; return 0; } int pet_json_array_add_bool(pet_json_obj_t arr, int * idx, int val) { struct nx_json new_val; int tmp_idx = 0; new_val.type = NX_JSON_BOOL; new_val.int_value = val; tmp_idx = nx_json_add_item(arr, &new_val); if (idx) *idx = tmp_idx; return 0; } int pet_json_array_add_int(pet_json_obj_t arr, int * idx, int val) { struct nx_json new_val; int tmp_idx = 0; new_val.type = NX_JSON_INTEGER; new_val.int_value = val; tmp_idx = nx_json_add_item(arr, &new_val); if (idx) *idx = tmp_idx; return 0; } int pet_json_array_add_double(pet_json_obj_t arr, int * idx, double val) { struct nx_json new_val; int tmp_idx = 0; new_val.type = NX_JSON_DOUBLE; new_val.dbl_value = val; tmp_idx = nx_json_add_item(arr, &new_val); if (idx) *idx = tmp_idx; return 0; } int pet_json_array_add_s64(pet_json_obj_t arr, int * idx, int64_t val) { struct nx_json new_val; int tmp_idx = 0; new_val.type = NX_JSON_INTEGER; new_val.int_value = val; tmp_idx = nx_json_add_item(arr, &new_val); if (idx) *idx = tmp_idx; return 0; } int pet_json_array_add_u64(pet_json_obj_t arr, int * idx, uint64_t val) { return pet_json_array_add_s64(arr, idx, val); } int pet_json_array_add_s8(pet_json_obj_t arr, int * idx, int8_t val) { return pet_json_array_add_s64(arr, idx, val); } int pet_json_array_add_s16(pet_json_obj_t arr, int * idx, int16_t val) { return pet_json_array_add_s64(arr, idx, val); } int pet_json_array_add_s32(pet_json_obj_t arr, int * idx, int32_t val) { return pet_json_array_add_s64(arr, idx, val); } int pet_json_array_add_u8(pet_json_obj_t arr, int * idx, uint8_t val) { return pet_json_array_add_s64(arr, idx, val); } int pet_json_array_add_u16(pet_json_obj_t arr, int * idx, uint16_t val) { return pet_json_array_add_s64(arr, idx, val); } int pet_json_array_add_u32(pet_json_obj_t arr, int * idx, uint32_t val) { return pet_json_array_add_s64(arr, idx, val); } /* Delete an array item at index idx */ int pet_json_array_del_idx(pet_json_obj_t arr, int idx) { nx_json_del_item(arr, idx); return 0; } int pet_json_array_del_item(pet_json_obj_t arr, pet_json_obj_t item) { nx_json_free(item); return 0; } /* Fills in parameter structure with results from a parsed JSON string * Return Value: * 0 = Success * 1 = More tokens than params * -1 = Parse Error */ int pet_json_get_params(pet_json_obj_t obj, struct pet_json_param * params, uint32_t num_params) { uint32_t i = 0; int ret = 0; /* Check Params and grab values */ for (i = 0; i < num_params; i++) { switch (params[i].type) { case PET_JSON_U8: ret = pet_json_get_u8 (obj, params[i].name, (uint8_t *)&params[i].val); break; case PET_JSON_S8: ret = pet_json_get_s8 (obj, params[i].name, (int8_t *)&params[i].val); break; case PET_JSON_U16: ret = pet_json_get_u16(obj, params[i].name, (uint16_t *)&params[i].val); break; case PET_JSON_S16: ret = pet_json_get_s16(obj, params[i].name, (int16_t *)&params[i].val); break; case PET_JSON_U32: ret = pet_json_get_u32(obj, params[i].name, (uint32_t *)&params[i].val); break; case PET_JSON_S32: ret = pet_json_get_s32(obj, params[i].name, (int32_t *)&params[i].val); break; case PET_JSON_U64: ret = pet_json_get_u64(obj, params[i].name, (uint64_t *)&params[i].val); break; case PET_JSON_S64: ret = pet_json_get_s64(obj, params[i].name, (int64_t *)&params[i].val); break; case PET_JSON_STRING: { ret = pet_json_get_string(obj, params[i].name, (char **)&params[i].ptr); break; } case PET_JSON_OBJECT: log_error("PET_JSON_OBJECT not currently supported\n"); goto out; default: log_error("Error Invalid Parameter Type (%d)\n", params[i].type); goto out; } } out: if (ret < 0) { log_error("Error Parsing JSON value\n"); } return ret; }
C
/*************************************** * EECS2031ON – Lab3 * * Author: Chung, Chun-Kit * * Email: [email protected] * * eecs_username: chunkit* * York Student #: 217125329 ****************************************/ #include <stdio.h> #define MAX_SIZE 21 int length(char[]); int indexOf(char[], char); int occurrence(char[], char); int isQuit(char[]); int i = 0; main() { char word[MAX_SIZE]; char c; char helloArr[] = "helloWorld"; printf("\"%s\" contains %d characters, but the size is %d (bytes)\n", helloArr, length(helloArr), sizeof(helloArr)); helloArr[5] = '\0'; helloArr[3] = 'X'; helloArr[7] = 'Y'; printf("\"%s\" contains %d characters, but the size is %d (bytes)\n\n", helloArr, length(helloArr), sizeof(helloArr)); /********** Fill in your code here. **********/ printf("Enter a word and a character separated by blank: "); scanf("%s %c", word, &c); while (1) { if (isQuit(word)) { break; } printf("\nInput word is \"%s\". Contains %d characters", word, length(word)); printf("\n\'%c\' appears %d times in the word\n", c, occurrence(word, c)); printf("Index of \'%c\' in the word is %d\n\n", c, indexOf(word, c)); printf("Enter a word and a character separated by blank: "); scanf("%s %c", word, &c); } return 0; } int length(char arr[]) { int charCount = 0; for (i = 0; arr[i] != '\0'; i++) { charCount++; } return charCount; } int indexOf(char arr[], char c) { int index = 0; for (i = 0; arr[i] != '\0'; i++) { if (arr[i] == c) { index = i; return index; } } return -1; } int occurrence(char arr[], char c) { int counter = 0; for (i = 0; i < sizeof(arr); i++) { if (arr[i] == c) { counter++; } } if (counter > 0) { return counter; } return counter; } int isQuit(char arr[]) { if (arr[0] == 'q' && arr[1] == 'u' && arr[2] == 'i' && arr[3] == 't') return 1; else return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* export_build_in.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fignigno <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/27 21:42:25 by fignigno #+# #+# */ /* Updated: 2021/04/16 17:49:16 by fignigno ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/build_in.h" static int check_key(char *key, t_envp *envp) { int i; if (!key) return (0); i = -1; while (key[++i]) if (!ft_isalpha(key[i]) && key[i] != '_') return (0); while (envp) { if (!ft_strcmp(envp->key, key)) return (-1); envp = envp->next; } return (1); } static int add_exist(char **key_val, t_envp *envp, int res) { if (!res) { write(2, "beautiful shell: `", 18); write(2, key_val[0], ft_strlen(key_val[0])); write(2, "\': not a valid identifier\n", 26); errno = 2; free(key_val[0]); if (key_val[1]) free(key_val[1]); return (1); } free(envp->value); free(key_val[0]); envp->value = key_val[1]; return (0); } static int add_to_envp(char *str, t_envp *envp) { char **key_val; int res; int status; key_val = ft_split_envp(str, '='); res = check_key(key_val[0], envp); status = 0; while (envp->next) envp = envp->next; if (res > 0) { envp->next = (t_envp *)malloc(sizeof(t_envp)); alloc_check(envp->next); envp = envp->next; envp->key = key_val[0]; envp->value = key_val[1]; envp->next = NULL; } else status = add_exist(key_val, envp, res); free(key_val); return (status); } static int export_add(t_com *com, t_envp *envp) { int i; int res; i = 1; res = 0; while (com->args[i]) { res += add_to_envp(com->args[i], envp); ++i; } return (res); } int export_com(t_com *com, t_envp *env) { int res; if (count_args(com) == 1) { export_out(env); return (0); } else { res = export_add(com, env); } return (res != 0); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <errno.h> #include <signal.h> #include <stdarg.h> #include <sys/socket.h> #include <netinet/in.h> // sockaddr_in #include <arpa/inet.h> // htons #define TOTALCLIENTS 10 #define MESSAGESSIZE 100 #define SMALLMESSAGESSIZE 50 #define LOGINSIZE 20 #define TOKENSIZE 32 #define CMDSIZE 6 char TOKEN[TOKENSIZE] = "LOGIN::"; void printub(const char *); int getsize(const char *); void remove_nl(char *); void multistrcat(char *, ...); void sig_alarm(int); void sig_int(int); void sig_stub(int); int sys_error(char *); enum Family { FAM = AF_INET, SOCK = SOCK_DGRAM }; struct Connection { char *host; int port; int socket; // сокет struct sockaddr_in addr; } conn = { "127.0.0.1", 7654 }; struct Clients { struct sockaddr_in addr[TOTALCLIENTS]; char login[TOTALCLIENTS]; } clnt; struct SystemHandlers { void (*sig_alarm) (); void (*sig_int) (); void (*sig_stub) (); int (*sys_error) (char *); } hdl = { &sig_alarm, &sig_int, &sig_stub, &sys_error, }; void sigaction_init(int sig, void handler()); // ------------------------- // ------------------------- // ------------------------- // ------------------------- // ------------------------- // ------------------------- int add_client(struct Clients, struct sockaddr_in); void send_to_clients(struct Connection, struct Clients, struct sockaddr_in, socklen_t); int main() { sigaction_init(SIGALRM, hdl.sig_alarm); conn.addr.sin_family = FAM; conn.addr.sin_port = htons(conn.port); if(!inet_aton(conn.host, &conn.addr.sin_addr)) { hdl.sys_error("Invalid address"); } conn.socket = socket(FAM, SOCK, 0); if(conn.socket == -1) { hdl.sys_error("Socket connection"); } int bnd = bind(conn.socket, (struct sockaddr*)&conn.addr, sizeof(conn.addr)); if(bnd == -1) { hdl.sys_error("Bind connection"); } else { printub("Server is working...\n----------------------\n\n"); } char incoming[MESSAGESSIZE]; do { bzero(incoming, MESSAGESSIZE); struct sockaddr_in from_addr; socklen_t addrlen = sizeof(from_addr); alarm(120); recvfrom(conn.socket, incoming, sizeof(incoming), 0, (struct sockaddr*)&from_addr, &addrlen); #ifdef DEBUG // [-DDEBUG=1 cmd] printf("%s\n", incoming); #endif if(!strncmp(incoming, TOKEN, 7)) { // Уязвимость -> LOGIN:: может быть введено пользователем вручную // Как вариант можно отправлять хешируемое значение для логирования static int count = 0; if((count = add_client(clnt, from_addr)) <= TOTALCLIENTS) { // Клиента добавляем в массив clnt.addr[count] = from_addr; // Отправляем контрольный бит sendto(conn.socket, "1", 1, 0, (struct sockaddr*)&from_addr, addrlen); count++; } continue; } char * istr; if((istr = strstr(incoming, ": ::name"))) { int ind = (int)(istr - incoming); char log[ind]; strncpy(log, incoming, ind); printf("%s\n", log); continue; } if(strstr(incoming, ": ::exit")) { printf("%s\n", incoming); continue; } send_to_clients(conn, clnt, from_addr, addrlen); } while(1); close(conn.socket); return 0; } // Низкоуровневая ф-ция вывода, нужна для вывода без буферизации void printub(const char *str) { write(1, str, getsize(str)); } // Чтоб не передавать параметр размера в функцию; // у указателя размер всегда равен 4 / 8 байтам, // а нужен реальный размер массива int getsize(const char *str) { int len = 0; while(str[len]) len++; return len; } void remove_nl(char *str) { str[getsize(str) - 1] = '\0'; } void multistrcat(char *str, ...) { va_list args; va_start(args, str); bzero(str, getsize(str)); char *s_arg; while (strcmp(s_arg = va_arg(args, char *), "\0")) { strcat(str, s_arg); } va_end(args); } // Изменить на sigaction void sig_alarm(int sig) { printub("Alarm::socket didn\'t get any response\n"); exit(1); } void sig_int(int sig) { char notify[SMALLMESSAGESSIZE]; // multistrcat(notify, "\t\t", user.login, " leave this chat\n", "\0"); // send_message_to(conn, notify); exit(0); } void sig_stub(int sig) { exit(0); } void sigaction_init(int sig, void handler()) { struct sigaction act; memset(&act, 0, sizeof(act)); sigset_t set; sigemptyset(&set); sigaddset(&set, sig); act.sa_mask = set; act.sa_handler = handler; sigaction(sig, &act, 0); } int sys_error(char * msg) { perror(msg); return(1); } int add_client(struct Clients clnt, struct sockaddr_in from_addr) { int k = 0; for(;k <= 10; k++) { if(clnt.addr[k].sin_port == from_addr.sin_port) { return 11; } else if (!clnt.addr[k].sin_port) { return k; } } return 11; // Массив полон, клиентов добавлять нельзя } void send_to_clients(struct Connection conn, struct Clients clnt, struct sockaddr_in from_addr, socklen_t addrlen) { int j = 0; int total_message_size = 30; for(;j <= TOTALCLIENTS && (clnt.addr[j].sin_port); j++) { if(clnt.addr[j].sin_port == from_addr.sin_port) continue; char message[total_message_size]; bzero(message, total_message_size); // strcat(message, income); if(sendto(conn.socket, message, sizeof(message), 0, (struct sockaddr*)&clnt.addr[j], addrlen) == -1) { perror("not sent"); } } }
C
#include <stdio.h> #include <stdlib.h> /* Function to sort elements */ int cmpint(const void *a, const void *b) { /* explicit type cast to pointers to integers */ return ( *(int*)a - *(int*)b ); } int main() { int values[] = { 88, 56, 100, 2, 25 }; printf("De array voor sorteren: \n"); for (int n = 0; n < 5; n++) { printf("%d ", values[n]); } qsort(values, 5, sizeof(int), cmpint); printf("\nDe array na sorteren: \n"); for (int n = 0; n < 5; n++) { printf("%d ", values[n]); } return(0); }
C
#include "../library/commonUtils/arrayOperations.h" #include "../library/stack.h" #include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> double convertStringToNumber(char* string, int* firstDigitIndex) { int i = *firstDigitIndex; double number = 0; for (; isdigit(string[i]); ++i) { number *= 10; number += string[i] - '0'; } *firstDigitIndex = i; return number; } bool isOperation(char c) { return '*' <= c && c <= '/'; } void performNumericOperation(Stack* numbers, char operation) { StackElement* number2 = pop(numbers); StackElement* number1 = pop(numbers); switch (operation) { case '+': push(numbers, createStackElement(getValue(number1) + getValue(number2))); break; case '-': push(numbers, createStackElement(getValue(number1) - getValue(number2))); break; case '*': push(numbers, createStackElement(getValue(number1) * getValue(number2))); break; case '/': push(numbers, createStackElement(getValue(number1) / getValue(number2))); } deleteStackElement(number1); deleteStackElement(number2); } double calculateExpressionValue(char* expression) { Stack* numbers = createStack(); for (int i = 0; i < strlen(expression); ++i) { if (isdigit(expression[i])) push(numbers, createStackElement(convertStringToNumber(expression, &i))); if (isOperation(expression[i])) performNumericOperation(numbers, expression[i]); } StackElement* element = pop(numbers); double expressionValue = getValue(element); deleteStackElement(element); deleteStack(numbers); return expressionValue; } int main() { printf("Enter expression in postfix notation:\n"); char* expression = readString(); printf("Here is the value of your expression: %lf", calculateExpressionValue(expression)); free(expression); return 0; }
C
#include "template.h" uint8_t newTxDataAvaliable = 0; // flag to DLL interface, set buy USER to '1' when has some data to send (after newTxData has been set), set automaticly by Interface to '0' after sent. uint8_t newTxData = 0; // hold data to send to Phy, (relevant only when "newTxDataAvaliable" == 1), set by USER. uint8_t newRxDataAvaliable = 0; // flag from DLL interface, set buy Interface to '1' when recieve somting in Rx from phy, as to be reset by USER after read the "newRxData" content uint8_t newRxData = 0;// hold data received from Phy, (relevant only when "newRxDataAvaliable" == 1), set by Interface. uint8_t DllAlive = 0; //req from uppre layer struct Ethernet_req* req_desc = NULL; uint8_t printer_flag = NO_PRINT; uint8_t recieved_value = 0; int fputc(int ch, FILE *f) // over-run pritf { /* Place your implementation of fputc here */ HAL_UART_Transmit(&huart2,(uint8_t*)&ch,1,1); // 1 tick waiting (1ms) enough for 87us/byte at 115200 return ch; } int fgetc(FILE *f) // over-run scanf { uint8_t ch=0,status = 0; do { status = HAL_UART_Receive(&huart2,&ch,1,10); }while(status == HAL_ERROR || status == HAL_TIMEOUT); // wait until the user will put the carecters. if(ch == 0x7E) //"char of value ~ will reset the board" NVIC_SystemReset(); return (ch); } inline void printer() { switch(printer_flag) { case PRINT_REQ_MAC: // print "enter dest mac address: printf("Enter destination MAC address (FORMAT = XXXXXXXXXXXX):\r\n"); printer_flag = NO_PRINT; break; case PRINT_DEST_MAC: // print dest mac printf("\r\nDestination MAC address is: %02X:%02X:%02X:%02X:%02X:%02X\r\n", req_desc->destinationMac[0],req_desc->destinationMac[1],req_desc->destinationMac[2], req_desc->destinationMac[3],req_desc->destinationMac[4],req_desc->destinationMac[5]); printf("Enter payload and then press 'Enter' (max size is: 1500 bytes!)\r\n"); printer_flag = NO_PRINT; break; case PRINT_SIZE_ERROR: printf("\r\nError! packet overflow! - max size is %d bytes (press any key to restart)\r\n",TX_BUFFER_SIZE); printer_flag = NO_PRINT; break; case PRINT_DLL_GOT_REQUEST: printf("\r\nRequest sent to DLL (wait for transmission to complete).\r\n"); printer_flag = NO_PRINT; break; case PRINT_DLL_BUSY: printf("\rDll busy! wait for Dll to read the request!\r\n"); printer_flag = NO_PRINT; break; case PRINT_DLL_GOT_THE_REQUST: printf("\rDll got the request! (press any key to build a next request)\r\n"); printer_flag = NO_PRINT; break; } } /******************************************************************************/ /* STM32F3xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32f3xx.s). */ /******************************************************************************/ /** * @brief This function handles EXTI line[9:5] interrupts. */ void EXTI9_5_IRQHandler(void) { /* USER CODE BEGIN EXTI9_5_IRQn 0 */ static int8_t edge = EDGE_REST; static uint8_t FalseInterrupt_cut = RESET; static uint8_t DataBusToWrite; static GPIO_PinState setDataBusValidValue = GPIO_PIN_RESET; uint8_t PhyIsNotInReset = HAL_GPIO_ReadPin(Phy_reset_GPIO_Port, Phy_reset_Pin); uint8_t CurrentSampledEdge = HAL_GPIO_ReadPin(Phy_clock_GPIO_Port, Phy_clock_Pin); if (DllAlive) // wait for DLL init to finish. { if ((edge == EDGE_REST) && (PhyIsNotInReset)) { edge = CurrentSampledEdge; // INIT FalseInterrupt_cut = RESET; } else if (!PhyIsNotInReset) edge = EDGE_REST; //RESET else if (FalseInterrupt_cut == RESET) // wait for next trunsaction edge^=1; if ((edge != EDGE_REST) && (edge == CurrentSampledEdge)) // clear some false interrupt transaction hazarads { FalseInterrupt_cut = RESET; if (edge == EDGE_FALL) readBus(&DataBusToWrite,&setDataBusValidValue); else //if (edge == EDGE_RISE) write.. { HAL_GPIO_WritePin(Phy_tx_data_bus_pin0_GPIO_Port,(uint16_t)DataBusToWrite,GPIO_PIN_SET); HAL_GPIO_WritePin(Phy_tx_data_bus_pin0_GPIO_Port,(uint16_t)(~DataBusToWrite),GPIO_PIN_RESET); HAL_GPIO_WritePin(Phy_tx_valid_GPIO_Port,Phy_tx_valid_Pin,setDataBusValidValue); } } else if (edge != EDGE_REST) FalseInterrupt_cut = SET; } /* USER CODE END EXTI9_5_IRQn 0 */ HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_9); /* USER CODE BEGIN EXTI9_5_IRQn 1 */ /* USER CODE END EXTI9_5_IRQn 1 */ } /** * @brief This function handles USART2 global interrupt / USART2 wake-up interrupt through EXTI line 26. */ void USART2_IRQHandler(void) { /* USER CODE BEGIN USART2_IRQn 0 */ static uint8_t uartState = UART_STATE_IDLE; static uint16_t index = 0; static char macVal[3] = {0}; uint8_t data = huart2.Instance->RDR ; uint8_t* payload; uint8_t sendLoopBack = 1; switch (uartState) { case UART_STATE_IDLE: if (!req_desc) // only if req is free! then free for getting new req. { req_desc =(Ethernet_req*) malloc (sizeof(Ethernet_req)); payload = (uint8_t*) malloc (TX_BUFFER_SIZE); if (req_desc && payload) { req_desc->payload = payload; req_desc->vld = 0; uartState = UART_STATE_GETTING_MAC ; printer_flag = PRINT_REQ_MAC; index = 0; }else { if (req_desc) { free(req_desc); req_desc = NULL; } puts("Rx buffer calloc fail, wait for old requests to finish!"); } } else { sendLoopBack = 0; printer_flag = PRINT_DLL_BUSY; } break; case UART_STATE_GETTING_MAC: macVal[index & 0x1] = data; // odd => first byte, even = > second byte , therd byte is for string end "\0' if (index & 0x1) req_desc->destinationMac[index>>1] = strtol(macVal,NULL,16); //convert string to hex number. index++; if ((index>>1) == MAC_ADDRESS_LEN) // finished mac recieve. { uartState = UART_STATE_DATA_REACIVE; printer_flag = PRINT_DEST_MAC; SET_PAYLOAD_SIZE((req_desc),0); } break; case UART_STATE_DATA_REACIVE: if (GET_PAYLOAD_SIZE((req_desc)) > TX_BUFFER_SIZE) { uartState = UART_STATE_IDLE ; printer_flag = PRINT_SIZE_ERROR; }else if (data != '\r') // not finishd { req_desc->payload[GET_PAYLOAD_SIZE(req_desc)] = data; INC_PAYLOAD_SIZE(req_desc); }else { req_desc->payload[GET_PAYLOAD_SIZE(req_desc)] = '\0'; uartState = UART_STATE_IDLE ; req_desc->vld = SET; printer_flag = PRINT_DLL_GOT_REQUEST; } break; } if (sendLoopBack) HAL_UART_Transmit(&huart2,&data,1,10); /* USER CODE END USART2_IRQn 0 */ HAL_UART_IRQHandler(&huart2); /* USER CODE BEGIN USART2_IRQn 1 */ /* USER CODE END USART2_IRQn 1 */ } //DO not touch! void readBus(uint8_t *DataBusToWrite, GPIO_PinState *setDataBusValidValue) { uint8_t Phy_busy = HAL_GPIO_ReadPin(Phy_tx_busy_GPIO_Port, Phy_tx_busy_Pin); // check if Phy free for Tx request. uint8_t Rx_valid = HAL_GPIO_ReadPin(Phy_rx_valid_GPIO_Port, Phy_rx_valid_Pin); // check if Phy put some new Rx data on interface. //Rx if(Rx_valid) // new Rx data { newRxData = (uint8_t)((Phy_rx_data_bus_pin0_GPIO_Port->IDR) >> 8); newRxDataAvaliable = 1; } //Tx if (*setDataBusValidValue == GPIO_PIN_SET) // Tx valid stay for one cycle. *setDataBusValidValue = GPIO_PIN_RESET; else if (!Phy_busy && newTxDataAvaliable) // phy ready for new word && we have someting to send { // set values that will put to wire in next rising edge. *DataBusToWrite = newTxData; *setDataBusValidValue = GPIO_PIN_SET; newTxDataAvaliable = 0; // update data took by interface. } } uint8_t isRxByteReady(void) { // return the value of newRxDataAvaliable flag return newRxDataAvaliable; } uint8_t getByte(void) { // get byte from Interface and reset flag, IMPORTANT: read this funtion without check "isByteReady()" first will return false result. uint8_t newByte = newRxData; newRxDataAvaliable = 0; return newByte; } uint8_t isPhyTxReady(void) { // return '1' if last byte sent to phy ans '0' else return !newTxDataAvaliable; } uint8_t sendByte(uint8_t data) { // sent byte to interface, IMPORTANT: using this methode without use "isPhyTxReady()" mey reasult return '0' meen - fail (last byte didn't sent yet) , id success return '1' if (newTxDataAvaliable) return 0; // fail! last byte didn't sent yet. newTxData = data; newTxDataAvaliable = 1; return 1; } uint8_t isNewTxRequest(){ return req_desc && req_desc->vld; } Ethernet_req* getTxRequeset(){ // Important! - after finish using result need to free the Ethernet_req & Ethernet_req.payload. Ethernet_req* temp = req_desc; req_desc = NULL; if (temp) printer_flag = PRINT_DLL_GOT_THE_REQUST; return temp; }
C
/* author: Alice Francener problem: Extremely Basic url: https://www.urionlinejudge.com.br/judge/en/problems/view/1001 */ #include<stdio.h> int main(){ int a, b, x; scanf("%d %d",&a,&b); x=a+b; printf("X = %d\n",x); return 0; }
C
/**************************************************************************** ** FILE: assignment.c ** AUTHOR: Brendan Lally ** STUDENT ID: 18407220 ** UNIT: Computer Communication (CNCO2000) ** PURPOSE: Contains implementations of the Application, Network and Datalink layers for a simulated network in cnet. ** LAST MOD: 22/05/16 **************************************************************************** **/ #include <cnet.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "assignment.h" static int setup = TRUE; int* ackExpected; int* frameExpected; int* nextFrameToSend; CnetTimerID** lasttimer; LinkedList** frameQueue; LinkedList** overflowQueue; /*************************************************************************** application_downto_network() receives a message from cnet and stores it in a packet. network_upto_application() receives a packet and sends the message up to cnet. **************************************************************************** **/ EVENT_HANDLER(application_downto_network) { CnetAddr destaddr; MSG message; Packet packet; size_t length = sizeof(MSG); /* Obtains a new message to be delivered */ CHECK(CNET_read_application(&destaddr, (char*)&message.data, &length)); /* Construct packet using message and source/dest addresses */ memcpy(&packet.data, &message, length); packet.src_addr = nodeinfo.nodenumber; packet.dest_addr = destaddr; packet.msglen = length; network_downto_datalink(packet); } void network_upto_application(int link, Packet packet) { MSG message = packet.data; size_t length = packet.msglen; printf("\tApplication received %d bytes on link %d - from %s\n", length, link, destination[packet.src_addr]); CHECK(CNET_write_application((char*)&message.data, &length)); } /*************************************************************************** network_downto_datalink() receives a packet and encases it in a frame and finds the link required to send it to its destination. The frame is added to a queue and sent down. datalink_upto_network() receives a frame and then checks if the packet in the frame is at the correct address. If its not, it is forwarded. **************************************************************************** **/ void network_downto_datalink(Packet packet) { Frame frame; int i; size_t psize = sizeof(Packet); /*Determine which link to send the frame on */ int link = routing[nodeinfo.nodenumber][packet.dest_addr]; /* Initialise all the fields in frame */ frame.kind = DL_DATA; frame.seqno = nextFrameToSend[link]; memcpy(&frame.packet, &packet, psize); frame.length = packet.msglen; frame.checksum = 0; /* Calculates the checksum */ frame.checksum = CNET_ccitt((unsigned char *)&frame, sizeof(frame)); /* Increment the next frame to send */ nextFrameToSend[link] = ++nextFrameToSend[link] % MAX_SEQ_NUM; /* If Aus or Indo then use a larger window size */ if (nodeinfo.nodenumber == 0 || nodeinfo.nodenumber == 1) { if (frameQueue[link]->size >= SWITCHSIZE) { for (i = 0; i < NUMNODES; i++) { if (routing[nodeinfo.address][i] == link) { CNET_disable_application(i); } } /* Add the next frame to the overflow buffer */ addFrame(overflowQueue[link], frame); CNET_set_LED(link, "red"); } else { /*Add the newly created frame to the queue */ addFrame(frameQueue[link], frame); datalink_downto_physical(frame, link); CNET_set_LED(link, "green"); } } else { if(frameQueue[link]->size >= WINDOWSIZE) { /* Check each link from the current node and disable their message gen to current link */ for(i = 0; i < NUMNODES; i++) { if(routing[nodeinfo.address][i] == link) { CNET_disable_application(i); } } /* Add the next frame to the overflow buffer */ addFrame(overflowQueue[link], frame); CNET_set_LED(link, "red"); } else { /*Add the newly created frame to the queue */ addFrame(frameQueue[link], frame); datalink_downto_physical(frame, link); CNET_set_LED(link, "green"); } } } void datalink_upto_network(int link, Frame frame) { Packet packet = frame.packet; /* Check if packet is at the correct address */ if (nodeinfo.nodenumber == packet.dest_addr) { network_upto_application(link, packet); } else { /* Resend packet if it hasn't reached its final destination */ network_downto_datalink(packet); } } /*************************************************************************** datalink_downto_physical() receives a frame and a link to send it on. A timer is started for each data frame and the frame is written to the physical layer. physical_upto_datalink() receives a frame from the physical layer and depending on what type of frame it is, stops the timer (if ack) or creates an acknowledgment to send (if data). **************************************************************************** **/ static void datalink_downto_physical(Frame frame, int link) { size_t length = sizeof(frame); switch (frame.kind) { /* Acknowledgment frame */ case DL_ACK: { printf("ACK transmitted with seqno=%d, on link %d\n\n", frame.seqno, link); break; } /* Data frame */ case DL_DATA: { CnetTime timeout; printf("DATA transmitted with seqno=%d, on link %d\n", frame.seqno, link); printf("DEST: %s and SOURCE: %s\n\n", destination[frame.packet.dest_addr], destination[frame.packet.src_addr]); /* Calculates the time delivery time = Transmission Time + Propagation Delay */ timeout = length*((CnetTime)8000000 / linkinfo[link].bandwidth) + linkinfo[link].propagationdelay; /* Create a new timer based on the link the frame is traveling on */ lasttimer[link][frame.seqno] = CNET_start_timer(EV_TIMER1, 3 * timeout, (CnetData)link); break; } } /* Pass Frame to the CNET physical layer to send Frame along link. */ CHECK(CNET_write_physical(link, &frame, &length)); } EVENT_HANDLER(physical_upto_datalink) { Frame frame, frame1, ack; size_t length; int link, checksum, checksumExp, difference, i, j, k; length = sizeof(Frame); /* Read data frame from the physical layer*/ CHECK(CNET_read_physical(&link, &frame, &length)); checksum = frame.checksum; frame.checksum = 0; checksumExp = CNET_ccitt((unsigned char *)&frame, sizeof(frame)); /* Check if the checksum is correct. ie the same as expected */ if( checksumExp != checksum) { printf("\t\t\t\tBAD checksum - frame ignored\n"); return; } switch (frame.kind) { case DL_ACK: /* Check if the the ackowledement frame is the same or later than expected*/ if (frame.seqno >= ackExpected[link]) { difference = frame.seqno - ackExpected[link]; /* Stop the timer for all outstanding acknowledgments up to the received */ for (i = difference; i >= 0; i--) { CHECK(CNET_stop_timer(lasttimer[link][(ackExpected[link] + i) % MAX_SEQ_NUM])); } } else { difference = frame.seqno + (MAX_SEQ_NUM - ackExpected[link]); /* Stop the timer for all outstanding acknowledgments up to the received */ for (i = difference; i >= 0; i--) { int seq = frame.seqno - i; CHECK(CNET_stop_timer(lasttimer[link][(MAX_SEQ_NUM + seq) % MAX_SEQ_NUM])); } } printf("\t\t\t\tACK received with seqno=%d, from link %d\n\n", frame.seqno, link); ackExpected[link] = frame.seqno + 1; /* Add Frames from the overflow buffer to the queue and send them */ for (k = 0; k <= difference; k++) { CNET_set_LED(link, "green"); removeFrame(frameQueue[link]); /* Add a new frame to the frameQueue from the overflowQueue */ if (overflowQueue[link]->size != 0) { frame1 = peekFirst(overflowQueue[link]); addFrame(frameQueue[link], frame1); removeFrame(overflowQueue[link]); /* Send the newly added frame */ datalink_downto_physical(frame1, link); } /* Enables the generation of new messages for delivery to other nodes */ for (j = 0; j < NUMNODES; j++) { if (routing[nodeinfo.address][j] == link) { CNET_enable_application(j); } } } break; case DL_DATA: /* Check if the the data frame is the same as expected */ if (frame.seqno == frameExpected[link]) { printf("\t\t\t\tDATA received with seqno=%d, from link %d\n", frame.seqno, link); printf("\t\t\t\tDEST: %s and SOURCE: %s\n\n", destination[frame.packet.dest_addr], destination[frame.packet.src_addr]); frameExpected[link] = ++frameExpected[link] % MAX_SEQ_NUM; /* Create an acknowledgment frame for the data frame received */ ack.kind = DL_ACK; ack.seqno = frame.seqno; ack.length = 0; ack.checksum = 0; ack.checksum = CNET_ccitt((unsigned char *)&ack, sizeof(ack)); /* Send acknowledgment frame */ datalink_downto_physical(ack, link); /* Pass the received frame up */ datalink_upto_network(link, frame); } /* If the frames don't match then ignore the frame */ else printf("Frame out of order. Ignored\n"); break; } } /***************************Timeout Function******************************** PURPOSE: Function handles timeout events. The timed-out frame is resent along with all the frames that were sent after that frame. **************************************************************************** **/ EVENT_HANDLER(timeouts) { int link = (int)data; Frame frame; LinkedListNode* current = frameQueue[link]->head; /* Resend the frame that timed out */ frame = current->frame; printf("Timeout, of seqno=%d on link %d\n", frame.seqno, link); datalink_downto_physical(frame, link); current = current->next; /* Resend all the frames after the timed out frame */ while (current != NULL) { frame = current->frame; CHECK(CNET_stop_timer(lasttimer[link][frame.seqno])); datalink_downto_physical(frame, link); current = current->next; } } /***************************Showstate Function******************************** PURPOSE: Function prints out the current state of a particular node. Including the expected frame number (both data and acknowledgment) and the contents of the sliding window. ****************************************************************************** **/ EVENT_HANDLER(showstate) { int i; printf("\n\n########## STATE OF NODE %d###########\n\n", nodeinfo.nodenumber); for (i = 1; i <= nodeinfo.nlinks; i++) { printf("\nLINK %d", i); printf("\n\tackExpected\t= %d\n\tnextFrameToSend\t= %d\n\tframeExpected\t= %d\n", ackExpected[i], nextFrameToSend[i], frameExpected[i]); printQueue(frameQueue[i]); printf("\nOVERFLOW\n"); printQueue(overflowQueue[i]); } } /***************************Reboot Node Function******************************** PURPOSE: Sets up and initialises the queues and frame counters. Handles cnet events by calling the application layer and physical layer functions, and the timeouts and showstate functions. ****************************************************************************** **/ EVENT_HANDLER(reboot_node) { int i; /* The initalisation only occurs the very first time that reboot is called */ if (setup == TRUE) { ackExpected = (int*)calloc(nodeinfo.nlinks + 1, sizeof(int)); frameExpected = (int*)calloc(nodeinfo.nlinks + 1, sizeof(int)); nextFrameToSend = (int*)calloc(nodeinfo.nlinks + 1, sizeof(int)); lasttimer = (CnetTimerID**)calloc(nodeinfo.nlinks + 1, sizeof(CnetTimerID*)); frameQueue = (LinkedList**)calloc(nodeinfo.nlinks + 1, sizeof(LinkedList*)); overflowQueue = (LinkedList**)calloc(nodeinfo.nlinks + 1, sizeof(LinkedList*)); CNET_enable_application(ALLNODES); for (i = 0; i <= nodeinfo.nlinks; i++) { frameQueue[i] = createQueue(); overflowQueue[i] = createQueue(); lasttimer[i] = (CnetTimerID*)calloc(MAX_SEQ_NUM, sizeof(CnetTimerID)); } setup = FALSE; } /* Call application_downto_network function whenever the EV_APPLICATIONREADY1 event occurs*/ CHECK(CNET_set_handler( EV_APPLICATIONREADY, application_downto_network, 0)); /* Call physical_ready function whenever the EV_PHYSICALREADY event occurs*/ CHECK(CNET_set_handler( EV_PHYSICALREADY, physical_upto_datalink, 0)); /* Call timeouts function whenever the EV_TIMER1 event occurs*/ CHECK(CNET_set_handler( EV_TIMER1, timeouts, data)); /* Call showstate function whenever the EV_DEBUG1 event occurs*/ CHECK(CNET_set_handler( EV_DEBUG0, showstate, 0)); CHECK(CNET_set_debug_string( EV_DEBUG0, "State")); } /**************************QUEUE FUNCTIONS******************************** CONTAINS: Contains the necessary functions to create and manage a linked list implemented queue **************************************************************************** **/ LinkedList* createQueue() { LinkedList* list = (LinkedList*)malloc(sizeof(LinkedList)); list->head = NULL; list->tail = NULL; list->size = 0; return list; } void addFrame(LinkedList* list, Frame frame) { LinkedListNode* newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode)); newNode->frame = frame; newNode->next = NULL; ++list->size; /*If there are currently no nodes in the list.*/ if (list->head == NULL) { list->head = newNode; list->tail = newNode; } /*If there is one or more nodes in the list.*/ else { list->tail->next = newNode; list->tail = newNode; } } void removeFrame(LinkedList* list) { LinkedListNode* temp = list->head; list->size--; if (list->head != NULL) { list->head = (list->head)->next; } free(temp); } void printQueue(LinkedList* list) { /*current points to the first node in the list. */ LinkedListNode* current = list->head; /*Iterate through the linked list and print the data field. */ while (current != NULL) { printf("Seqno: %d\n", current->frame.seqno); current = current->next; } } Frame peekFirst(LinkedList* list) { return list->head->frame; }
C
/* ===================================================================================================================================== Name : MatrixMultiplication3S.c Author : Antonio Tino & Giacomo Astarita Version : 2.0 Description : Bisogna effettuare il calcolo del prodotto C = A x B con A[m][h], B[h][n] e C[m][n]. Le matrici A, B e C sono suddivise in blocchi di colonne e bisogna assegnare al processo Pi, con i = 0, ..., p-1, i blocchi Ai, Bi e Ci, rispettivamente di dimensione m x (h/p), h x (n/p) e m x (n/p). Strategia: ANELLO ===================================================================================================================================== */ #include <stdio.h> #include <stdlib.h> #include "mpi.h" #define STAMPA 0 /* Assegna lo spazio di memoria alla matrice */ int* inizializza_spazio_matrice(int rows, int cols){ int* Matrix = calloc(rows * cols, sizeof(int)); return Matrix; } /* Creazione della matrice contenente numeri casuali */ void create_matrix(int *matrix, int row, int col){ int i, j; for(i=0;i<row;i++){ for(j=0;j<col;j++) matrix[col*i+j] = rand() % 10; } } /* Stampa a video la matrice */ void stampa_matrice(int* matrice, int rows, int cols, char* nome){ if (STAMPA==0) return; printf("\nStampa matrice %s\n",nome); fflush(stdout); for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ printf("%d\t",matrice[i*cols+j]); fflush(stdout); } printf("\n"); fflush(stdout); } } /* Calcola il lavoro da assegnare ad ogni processore */ void calculateWork(int *work, int nproc, int colonne){ int w, i; if(colonne%nproc==0) for(i=0;i<nproc;i++) work[i]=colonne/nproc; else{ int resto=colonne-(colonne/nproc)*nproc; for(i=0;i<nproc;i++){ if (resto>0){ work[i]=colonne/nproc+1; resto--; }else work[i]=colonne/nproc; } } } /* Effettua il prodotto tra matrici */ void prodotto_matrici(int* A, int* B, int* C, int rowA, int colA, int rowB, int colB, int righeBfatte){ for(int i=0;i<rowA;i++){ for(int j=0;j<colB;j++){ for(int k=0;k<colA;k++){ //colA==rowB altrimenti non si può effettuare il prodotto C[i*colB+j]+=A[i*colA+k]*B[(righeBfatte+k)*colB+j]; } } } } /* Copia le varie sottomatrici da inviare */ void copia_sottomatrici(int* originale, int* copia, int row, int col, int *colW, int idproc){ int colonna_iniziale, colonna_finale, offset=0,i; int riga=0, colonna=0; for(i=0;i<idproc;i++) offset+=colW[i]; colonna_iniziale=offset; colonna_finale=colonna_iniziale+colW[idproc]; for(i=colonna_iniziale;i<colonna_finale;i++){ for(int j=0;j<row;j++){ copia[riga*colW[idproc]+colonna]=originale[j*col+i]; riga++; } colonna++; riga=0; } } /* Ripristina le varie sottomatrici */ void ripristina_sottomatrici(int* risultato, int* parziale, int rowR, int colR, int *colW, int idproc, int colP){ int i=0, j=0, offset=0; for(i=0;i<idproc;i++) offset+=colW[i]; for(i=0;i<rowR;i++) for(j=0;j<colP;j++) risultato[i*colR+j+offset]=parziale[i*colP+j]; } int main(int argc, char *argv[]){ /* Id del processo e numero di processi */ int nproc, myid; /* Puntatori alle matrici */ int *A, *B, *C; /* Puntatori */ int *Aloc, *Bloc, *Cloc, *Mtemp, *colAp, *colBp; /* Dimensioni delle matrici A e B */ int rowA, rowB, colA, colB; /* Id del processo a cui inviare e id del processo da cui ricevere*/ int idSend, idRecv; /* Variabili per il calcolo del tempo */ double start, finish; /* Indici */ int i, j, k; /* Restituisce lo status*/ MPI_Status status; /* Start MPI */ MPI_Init(&argc, &argv); /* Trova l'id del processo */ MPI_Comm_rank(MPI_COMM_WORLD, &myid); /* Trova il numero di processi */ MPI_Comm_size(MPI_COMM_WORLD, &nproc); /* Controllo che l'utente abbia inserito correttamente i dati, in caso negativo utilizzo quelli di default */ if(argc < 5){ rowA=5; colA=4; rowB=4; colB=3; if(myid==0){ printf("PARAMETRI DI DEFAULT\n"); printf("La matrice A è di dimensione %d x %d\n", rowA, colA); printf("La matrice B è di dimensione %d x %d\n", rowB, colB); fflush(stdout); } }else{ rowA=atoi(argv[1]); colA=atoi(argv[2]); rowB=atoi(argv[3]); colB=atoi(argv[4]); if(myid==0){ printf("PARAMETRI INSERITI DALL'UTENTE\n"); printf("La matrice A è di dimensione %d x %d\n", rowA, colA); printf("La matrice B è di dimensione %d x %d\n", rowB, colB); fflush(stdout); } } /* Controllo che il numero di colonne della matrice A siano uguali al numero di righe della matrice B */ if(colA!=rowB) { if(myid==0){ printf("Impossibile effettuare la moltiplicazione (colA != rowB)\n"); fflush(stdout); } exit(0); } /* Controllo che il numero di processori non sia maggiore del numero di colonne di A */ if(nproc>colA){ if(myid==0){ printf("Numero di processi %d è inferiore alle colonne di A %d. Impossibile distribuire il lavoro\n", nproc, colA); fflush(stdout); } exit(0); } /* Vettore in cui mi salvo il numero di colonne delle matrici per ogni processore*/ colAp=inizializza_spazio_matrice(1, nproc); colBp=inizializza_spazio_matrice(1, nproc); /* Calcola il lavoro da distribuire ad ogni processore */ calculateWork(colAp, nproc, colA); calculateWork(colBp, nproc, colB); /* Allocazione di memoria per le matrici A, B e C locali */ Aloc=inizializza_spazio_matrice(rowA, colAp[myid]); Bloc=inizializza_spazio_matrice(rowB, colBp[myid]); Cloc=inizializza_spazio_matrice(rowA, colBp[myid]); if(myid == 0){ /* Inizio tempo di calcolo */ printf("\nInizio tempo di calcolo...\n\n"); fflush(stdout); start = MPI_Wtime(); /* Allocazione di memoria per le matrici A e B*/ A=inizializza_spazio_matrice(rowA, colA); B=inizializza_spazio_matrice(rowB, colB); srand(13); /*Creazione delle matrici A e B*/ create_matrix(A, rowA, colA); create_matrix(B, rowB, colB); /*Se il flag STAMPA è settato ad 1, si effettua la stampa delle matrici A e B*/ stampa_matrice(A, rowA, colA, "A"); stampa_matrice(B, rowB, colB, "B"); /* Assegno i primi elementi delle matrici A e B al processo P0 */ copia_sottomatrici(A, Aloc, rowA, colA, colAp, myid); copia_sottomatrici(B, Bloc, rowB, colB, colBp, myid); /* Il processo P0 assegna il lavoro agli altri processori */ for(i=1;i<nproc;i++){ /* Allocazione di memoria per la matrice A temporanea*/ Mtemp=inizializza_spazio_matrice(rowA, colAp[i]); /* Copia le sottomatrici da inviare */ copia_sottomatrici(A, Mtemp, rowA, colA, colAp, i); MPI_Send(Mtemp, rowA*colAp[i], MPI_INT, i, 0, MPI_COMM_WORLD); /* Libera la memoria utilizzata per la matrice temporanea*/ free(Mtemp); /* Allocazione di memoria per la matrice B temporanea*/ Mtemp=inizializza_spazio_matrice(rowB, colBp[i]); /* Copia le sottomatrici da inviare */ copia_sottomatrici(B, Mtemp, rowB, colB, colBp, i); MPI_Send(Mtemp, rowB*colBp[i], MPI_INT, i, 0, MPI_COMM_WORLD); /* Libera la memoria utilizzata per la matrice temporanea*/ free(Mtemp); } /* Libera la memoria utilizzata per la matrice A e la matrice B*/ free(A); free(B); } else { MPI_Recv(Aloc, rowA*colAp[myid], MPI_INT, 0, 0, MPI_COMM_WORLD, &status); MPI_Recv(Bloc, rowB*colBp[myid], MPI_INT, 0, 0, MPI_COMM_WORLD, &status); } /* Computazione */ int passo=0, righeBfatte=0; /* Ogni processo calcola l'identificativo del processo a cui inviare */ idSend=(myid+1)%nproc; /* Ogni processo calcola l'identificativo del processo da cui ricevere */ if(myid-1<0) idRecv=nproc-1; else idRecv=myid-1; int realIdRecv=myid; int tempid; /* Fase di calcolo */ for(i=0;i<myid;i++) righeBfatte+=colAp[i]; prodotto_matrici(Aloc, Bloc, Cloc, rowA, colAp[realIdRecv], rowB, colBp[myid], righeBfatte); int *Aloctemp=inizializza_spazio_matrice(rowA, colAp[myid]); for(i=0;i<nproc-1;i++){ passo++; if(myid-passo<0) tempid=nproc-passo; else tempid=myid-passo; if(colAp[realIdRecv]!=colAp[tempid]){ Aloctemp=inizializza_spazio_matrice(rowA, colAp[tempid]); } /* Si utilizza la MPI_Sendrecv per effettuare le send e le recv in modo parallelo, quindi evitando problemi di buffer*/ MPI_Sendrecv(Aloc, rowA*colAp[realIdRecv], MPI_INT, idSend, 0, Aloctemp, rowA*colAp[tempid], MPI_INT, idRecv, 0 ,MPI_COMM_WORLD, &status); realIdRecv=tempid; Aloc=Aloctemp; if(righeBfatte-colAp[realIdRecv]<0) righeBfatte=rowB-righeBfatte-colAp[realIdRecv]; else righeBfatte=(righeBfatte-colAp[realIdRecv])%rowB; /* Fase di calcolo */ prodotto_matrici(Aloc, Bloc, Cloc, rowA, colAp[realIdRecv], rowB, colBp[myid], righeBfatte); } /* Ogni processo libera la memoria che ha utilizzato */ free(Aloc); free(Bloc); if(myid==0){ /* Allocazione di memoria per la matrice C */ C=inizializza_spazio_matrice(rowA, colB); /* Ripristina la propria sottomatrice */ ripristina_sottomatrici(C, Cloc, rowA, colB, colBp, myid, colBp[myid]); for(i=1;i<nproc;i++){ MPI_Recv(Cloc, rowA*colBp[i], MPI_INT, i, 0, MPI_COMM_WORLD, &status); /* Ripristina le sottomatrici degli altri processi*/ ripristina_sottomatrici(C, Cloc, rowA, colB, colBp, i, colBp[i]); } /* Fine tempo di calcolo */ printf("\n...Fine tempo di calcolo\n"); fflush(stdout); finish = MPI_Wtime(); stampa_matrice(C,rowA,colB,"C"); printf("\nTempo di computazione: %f\n", finish - start); fflush(stdout); free(C); }else{ /* Ogni processo invia a P0 la sua parte della matrice C e libera la memoria utilizzata*/ MPI_Send(Cloc, rowA*colBp[myid], MPI_INT, 0, 0, MPI_COMM_WORLD); free(Cloc); } /* Shut down MPI */ MPI_Finalize(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "process.h" /* A method that mix two sounds together with sound weights correspond to the sound array. Returns a single finished mixed sound structs. */ sound* mix(sound *s[],float w[], int c){ int longestLength = 0; float rate = 0; for(int i = 0; i < c; i++){ if(s[i]->length > longestLength) longestLength = s[i]->length; rate = s[i]->rate; } if(longestLength == 0){ return NULL; } sound *mix = (sound*)malloc(sizeof(sound)); mix->rate = rate; mix->length = longestLength; mix->samples = (float *)malloc(sizeof(float)*longestLength); for(int i = 0; i < longestLength; i++) { mix->samples[i] = 0; } for(int i = 0; i < c; i++) { for (int j = 0; j < s[i]->length; j++) { mix->samples[j] += s[i]->samples[j]*w[i]; } } return mix; } /* A method that just multiply point by point two sound signals together. Returns a single finished modulated sound. */ sound* modulate(sound *s1, sound *s2){ if(s1->length != s2->length){ return NULL; } sound *modulate = (sound*)malloc(sizeof(sound)); modulate->rate = s1->rate; modulate->length = s1->length; modulate->samples = (float *)malloc(sizeof(float)*s1->length); for(int i = 0; i < s1->length; i++) { modulate->samples[i] = s1->samples[i] * s2->samples[i]; } return modulate; } /* A method that does convolution by summing samples by real numbers. Returns a single filtered sound. */ sound* filter(sound *s, float fir[], int c){ if(s->length == 0){ return NULL; } sound *filter = (sound*)malloc(sizeof(sound)); filter->rate = s->rate; filter->length = s->length; filter->samples = (float *)malloc(sizeof(float)*s->length); for(int i = 0; i < s->length; i++) { filter->samples[i] = 0; } for(int i = 0; i < s->length; i++){ for (int j = 0; j < c; j++){ if(i-j >= 0){ filter->samples[i] += s->samples[i-j]*fir[j]; } } } return filter; } /* This function calculates the fir array that is to be pass to the filter method that is to be process. The delay and the attenuation are use for calculating the fir array. It returns a sound array that has been filtered. */ sound* reverb(sound *s, float delay, float attenuation){ if(attenuation >= 1 || attenuation <= 0){ return NULL; } if(delay <= 0 || delay >= 0.1){ return NULL; } if (s == NULL) { return NULL; } int firArraySize = s->rate * delay; float *fir = (float*)malloc(sizeof(float)*firArraySize); for(int i = 0; i < firArraySize; i++){ if (i == 0) { fir[i] = 1; } else if(i == firArraySize - 1){ fir[i] = attenuation; } else if(i != 0 || i != firArraySize - 1){ fir[i] = 0; } } sound *reverb = filter(s, fir, firArraySize); free(fir); return reverb; } /* This is somewhat a similar function to reverb but it is using O(n) by processing the the sound in the method directly. Returns a pointer sound that has been process. */ sound* echo(sound *s, float delay, float attenuation){ if(attenuation >= 1 || attenuation <= 0){ return NULL; } if(delay < 0.1 || delay > 1){ return NULL; } if (s == NULL) { return NULL; } int firArraySize = s->rate * delay; sound *echo = (sound*)malloc(sizeof(sound)); echo->rate = s->rate; echo->length = s->length; echo->samples = (float *)malloc(sizeof(float)*s->length); for(int i = 0; i < s->length; i++) { echo->samples[i] = 0; } for(int i = 0; i < s->length; i++){ if(i-(firArraySize - 1) >= 0){ echo->samples[i] = s->samples[i] + s->samples[i-(firArraySize - 1)] * attenuation; } else{ echo->samples[i] = s->samples[i]; } } return echo; }
C
#include "aircraft.h" int aircraft_get_size(aircraft_linked_list * head){ int size = 1; while(head->next != NULL){ head = head->next; size++; } return size; } void aircraft_add_new(aircraft_linked_list ** head, aircraft_template new_aircraft, int pos_x, int pos_y){ aircraft_linked_list * new, * head_temp = (*head); new = (aircraft_linked_list*)malloc(sizeof(aircraft_linked_list)); strcpy(new->name, new_aircraft.name); new->team = new_aircraft.team; new->health = new_aircraft.health; new->type = new_aircraft.type; new->direction = new_aircraft.direction; new->id = new_aircraft.id; new->cost = new_aircraft.cost; new->speed = new_aircraft.speed; new->missile_type = new_aircraft.missile_type; new->special_attack_missile_type = new_aircraft.special_attack_missile_type; new->is_follower = new_aircraft.is_follower; new->is_using_special_attack = new_aircraft.is_using_special_attack; new->special_attack_counter = new_aircraft.special_attack_counter; new->pos_x = pos_x; new->pos_y = pos_y; new->size_x = new_aircraft.size_x; new->size_y = new_aircraft.size_y; new->sprite = new_aircraft.sprite; new->next = NULL; if(head_temp != NULL){ while(head_temp->next != NULL){ head_temp = head_temp->next; } head_temp->next = new; } else (*head) = new; } void aircraft_remove_index(aircraft_linked_list ** head, int index){ int i, size = 1; aircraft_linked_list * sizeTemp, * headTemp, * tailTemp; tailTemp = (*head); headTemp = (*head); sizeTemp = (*head); while(sizeTemp->next!=NULL){ sizeTemp = sizeTemp->next; size++; } for(i=0; i<index-1; i++) tailTemp = tailTemp->next; for(i=0; i<index; i++) headTemp = headTemp->next; if(size > 2) tailTemp->next = headTemp->next; else tailTemp->next = NULL; free(headTemp); }
C
#include <stdio.h> int main(void) { int num1 = 1,num2 = 2,asd = 0; int sum = 2; printf("߂̓񍀂1,2ƂA\n"); for (int i = 1; ; i++) { asd += num1 + num2; if (asd%2 == 0) { sum += asd; } printf("%d %d %d\n",asd,num1,num2); num1 = num2; num2 = asd; if (asd > 4000000){ break; } asd = 0; } printf("tB{ib`400ȉ̋̍̒l%dłB\n",sum);//4613732 return 0; }
C
/**** globals defined in main.c file ****/ #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ext2fs/ext2_fs.h> #include "type.h" extern MINODE minode[NMINODE]; extern MINODE *root; extern PROC proc[NPROC], *running; extern char gpath[256]; extern char *name[64]; extern int n; extern int fd, dev; extern int nblocks, ninodes, bmap, imap, iblk; extern char line[256], cmd[32], pathname[256]; /*************************FUNCTIONS*******************************/ int tst_bit(char *buf, int bit) { int i, j; i = bit/8; j=bit%8; if (buf[i] & (1 << j)) return 1; return 0; } int set_bit(char *buf, int bit) { int i, j; i = bit/8; j=bit%8; buf[i] |= (1 << j); } int clr_bit(char *buf, int bit) { int i, j; i = bit/8; j=bit%8; buf[i] &= ~(1 << j); } int incFreeInodes(int dev) /*decrement number of free inodes*/ { char buf[BLKSIZE]; // dec free inodes count in SUPER and GD get_block(dev, 1, buf); sp = (SUPER *)buf; sp->s_free_inodes_count++; put_block(dev, 1, buf); get_block(dev, 2, buf); gp = (GD *)buf; gp->bg_free_inodes_count++; put_block(dev, 2, buf); } int decFreeInodes(int dev) /*decrement number of free inodes*/ { char buf[BLKSIZE]; // dec free inodes count in SUPER and GD get_block(dev, 1, buf); sp = (SUPER *)buf; sp->s_free_inodes_count--; put_block(dev, 1, buf); get_block(dev, 2, buf); gp = (GD *)buf; gp->bg_free_inodes_count--; put_block(dev, 2, buf); } int idealloc(int dev, int ino) { char buf[BLKSIZE]; get_block(dev, imap, buf); clr_bit(buf, ino-1); put_block(dev, imap, buf); incFreeInodes(dev); } int ialloc(int dev) { int i; char buf[BLKSIZE]; // read inode_bitmap block get_block(dev, imap, buf); for (i=0; i < ninodes; i++){ if (tst_bit(buf, i)==0){ set_bit(buf,i); decFreeInodes(dev); put_block(dev, imap, buf); return i+1; } } printf("ialloc(): no more free inodes\n"); return 0; } int pimap() { int i; char buf[BLKSIZE]; printf("imap = %d\n", imap); // read inode_bitmap block get_block(fd, imap, buf); for (i=0; i < ninodes; i++){ (tst_bit(buf, i)) ? putchar('1') : putchar('0'); if (i && (i % 8)==0) printf(" "); } printf("\n"); } int incFreeBlocks(int dev) /*decrement number of free blocks*/ { char buf[BLKSIZE]; // dec free inodes count in SUPER and GD get_block(dev, 1, buf); sp = (SUPER *)buf; sp->s_free_blocks_count++; put_block(dev, 1, buf); get_block(dev, 2, buf); gp = (GD *)buf; gp->bg_free_blocks_count++; put_block(dev, 2, buf); } int decFreeBlocks(int dev) /*decrement number of free blocks*/ { char buf[BLKSIZE]; // dec free inodes count in SUPER and GD get_block(dev, 1, buf); sp = (SUPER *)buf; sp->s_free_blocks_count--; put_block(dev, 1, buf); get_block(dev, 2, buf); gp = (GD *)buf; gp->bg_free_blocks_count--; put_block(dev, 2, buf); } int bdealloc(int dev, int bno) { char buf[BLKSIZE]; get_block(dev, bmap, buf); clr_bit(buf, bno-1); put_block(dev, bmap, buf); incFreeBlocks(dev); } int balloc(int dev) { int b; char buf[BLKSIZE]; // read inode_bitmap block get_block(dev, bmap, buf); for (b=0; b < nblocks; b++){ if (tst_bit(buf, b)==0){ set_bit(buf,b); decFreeBlocks(dev); put_block(dev, bmap, buf); return b+1; } } printf("balloc(): no more free blocks\n"); return 0; } int pbmap() { int i; char buf[BLKSIZE]; printf("bmap = %d\n", bmap); // read block_bitmap block get_block(fd, bmap, buf); for (i=0; i < nblocks; i++){ (tst_bit(buf, i)) ? putchar('1') : putchar('0'); if (i && (i % 8)==0) printf(" "); } printf("\n"); }
C
#include <stdio.h> void main10() { int i; for(i=10; i>=1; i--) printf("%d\n", i); getch(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "plateau.h" #include "coup.h" #include "caractereEnEntier.h" #include <stdio.h> void OTH_affichagePlateau(PL_Plateau plateau) { int x,y; printf(" abcdefgh "); printf("\n"); printf(" +--------+"); printf("\n"); for (y = 1; y <= 8; y++) /*On parcourt les lignes*/ { printf("%d|",y); for (x = 1; x <= 8; x++) /*Et les colonnes*/ { if (PI_ObtenirEtatPion(PL_ObtenirPion(PO_defPosition(y,x),plateau)) == 0) /*On vérifie l'état du pion pour chaque position*/ { printf(" "); /*Le caractère ' ' est utilisé pour une case vide*/ } else { if (PI_ObtenirCouleurPion(PL_ObtenirPion(PO_defPosition(y,x),plateau)) == NOIR) /*On vérifie la couleur du pion pour chaque position*/ { printf("o"); /*Le caractère 'o' est utilisé pour les pions NOIRs*/ } else { printf("+"); /*Le caractère '+' est utilisé pour les pions NOIRs*/ } } } printf("|"); printf("\n"); /*On saute une ligne à la fin de chaque ligne parcourue*/ } printf(" ----------"); printf("\n"); } PO_Position OTH_entrerCoup(CO_Couleur couleurJoueurCourant) { char coordCoup[10]; /**<On prévoit une chaine de caractère plus grande au cas où l'utilisateur entre n'importe quoi*/ int entierColonnes, entierLignes; PO_Position positionDuCoup; char* couleurDuJoueur; if(couleurJoueurCourant == NOIR) { couleurDuJoueur = "Noir"; } else { couleurDuJoueur = "Blanc"; } do { printf("Joueur %s c'est à vous de jouer, entrez les coordonnées de votre coup svp : ", couleurDuJoueur); scanf("%s", coordCoup); } while (!OTH_chaineValide(coordCoup)); OTH_chaineEnEntiers(coordCoup, &entierColonnes, &entierLignes); positionDuCoup = PO_defPosition(entierLignes,entierColonnes),PI_CreerPion(couleurJoueurCourant); return positionDuCoup; } void OTH_entrerCoupTournoi(PO_Position* position, int* booleen){ char coup[100]; int posX,posY; fgets(coup,sizeof(coup),stdin); *booleen = !(strcmp(coup,"passe\n")==0) ; if(*booleen){ posY = coup[0]-'a'+1; posX = coup[1]-'0'; *position = PO_defPosition(posX,posY); } } void affichageFinPartie (CO_Couleur couleur){ if (couleur == NOIR){ printf("victoire des noir \n"); } else { printf("victoire des blanc \n"); } } void affichageAide() { printf("Aide du programme othello \n"); printf("Les options possibles sont : \n"); printf(" othello JoueurVSia blanc|noir \n"); printf(" permet de jouer contre l'ordinateur en choisissant la couleur \n"); printf(" par defaut la profondeur d'analyse est egale a 5 \n"); printf(" othello JoueurVSJoueur \n"); printf(" permet de faire jouer deux joueur chacun leur tour sur la même machine \n"); printf(" othello tournoi blanc|noir \n"); printf(" permet de faire jouer le programme dans un mode 'tournoi' en lui donnant les blancs ou les noirs \n"); printf(" par defaut la profondeur d'analyse est egale a 5 \n"); } void affichagecoupTournoi(C_Coup coup , int booleen){ if (booleen==1 ){ PO_Position position = C_Obtenir_Position_Coup(coup); int posX = PO_ObtenirX(position); int posY = PO_ObtenirY(position); char Y = 'a' + posY-1; printf("%c%d\n",Y,posX); } else { printf("passe\n"); } }
C
#include<stdio.h> #include<stdlib.h> struct stu *ptr,*buff; //#include"search.c" //int *buff,*ptr; struct stu{ char name[25]; char gen; int rolno; float hei; char grade; }; main(){ ptr=(struct stu *)malloc(1*sizeof(struct stu)); int i,n; printf("\nenter how many students:");scanf("%d",&n); ptr=(struct stu *)realloc(ptr,n*sizeof(struct stu)-1); // struct stu o[n]; FILE *stream; /* for(i=0;i<sizeof(o)/sizeof(struct stu);i++){ printf("enter name,gen,rolno,hei,grade of stu%d\n",i+1); scanf(" %s %c %d %f %c",o[i].name,&o[i].gen,&o[i].rolno,&o[i].hei,&o[i].grade); } stream=fopen("srch.file","w");if(!stream) perror("fopen"),exit(1); fwrite(o,sizeof(o),1,stream); fclose(stream); //rewind(stream); rewind is needed in gets() , puts() functions only.not required in binary reading. ftell also. */ buff=(struct stu *)malloc(1*sizeof(struct stu)); buff=(struct stu *)realloc(ptr,n*sizeof(struct stu)-1); // struct stu buff[n]; stream=fopen("srch.file","r");if(!stream) perror("fopen"),exit(2); fread(buff,sizeof(buff),1,stream); fclose(stream); /* //printf("----------------------------------------------------------\n"); printf("\t\t\t\t==========================================================\n"); printf("\t\t\t\t|s.no|\t name\t\t gen\t rollno\t height\t grade |\n"); printf("\t\t\t\t==========================================================\n"); for(i=0;i<sizeof(buff)/sizeof(struct stu);i++){ printf("\t\t\t\t| %d |\t %-15s %c\t %d\t %.1f\t %c | \n",i+1,buff[i].name,buff[i].gen,buff[i].rolno,buff[i].hei,buff[i].grade); if(i<sizeof(buff)/sizeof(struct stu)-1) printf("\t\t\t\t----------------------------------------------------------\n"); } //printf("----------------------------------------------------------\n"); printf("\t\t\t\t==========================================================\n"); */ char ref; srch_menu(); printf("\nenter ref code:"); scanf(" %c",&ref); search(ref,n); }
C
//using an array //for decade counter #include <avr/io.h> #include <util/delay.h> #include "sevenseg.h" void sevenseg(int); int main (void) { //defining integer array p const int p[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int i; DDRD |= 0xFC; //set 0 as output pin DDRB |= ((1 << DDB0)); while (1) { //loop counting from 0 to 9 for (i=0; i < 10; i++) { sevenseg(p[i]); _delay_ms (1000L); } } /* . */ return 0; }
C
// // Created by zhaomengz on 26/4/17. // #ifndef BIN_LINKEDLIST_H #define BIN_LINKEDLIST_H #include <stddef.h> typedef struct list_node_t { struct list_node_t* prev; struct list_node_t* next; } list_node_t; #define container_of(ptr, type, member) \ (type*)((char*)(ptr)-offsetof(type, member)) #define list_conn(p, n) \ (p)->next = (n); \ (n)->prev = (p) #define list_insert_after(p, node) \ list_conn(node, (p)->next); \ list_conn(p, node) #define list_delete(node) list_conn((node)->prev, (node)->next) #define list_init_head(node) (node)->prev = (node)->next = node #define list_entry(node, type, member) container_of((node), type, member) #endif // BIN_LINKEDLIST_H
C
#include <stdio.h> #define ARRAY_SIZE(array) (sizeof(array) / sizeof(*array)) typedef struct { int day; int month; } Date; typedef struct { char *name; Date startDate; Date endDate; } ZodiacSign; const ZodiacSign ZODIAC_SIGNS[] = { {"Koziorożec", {1, 1}, {19, 1}}, {"Baran", {21, 3}, {19, 4}}, {"Byk", {20, 4}, {20, 5}}, {"Bliźnięta", {21, 5}, {20, 6}}, {"Rak", {21, 6}, {22, 7}}, {"Lew", {23, 7}, {22, 8}}, {"Panna", {23, 8}, {22, 9}}, {"Waga", {23, 9}, {22, 10}}, {"Skorpion", {23, 10}, {21, 11}}, {"Strzelec", {22, 11}, {21, 12}}, {"Wodnik", {20, 1}, {18, 2}}, {"Ryby", {19, 2}, {20, 3}}, {"Koziorożec", {22, 12}, {31, 12}} }; int date_compare(const Date *date1, const Date *date2) { if (date1->month == date2->month) { if (date1->day == date2->day) { return 0; } else { return date1->day > date2->day ? -1 : 1; } } else { return date1->month > date2->month ? -1 : 1; } } void date_print(const Date *date) { printf("%d.%d", date->day, date->month); } const ZodiacSign *findZodiac(const Date *date) { int i; for (i = 0; i < ARRAY_SIZE(ZODIAC_SIGNS); ++i) { if ( date_compare(&ZODIAC_SIGNS[i].startDate, date) != -1 && date_compare(date, &ZODIAC_SIGNS[i].endDate) != -1 ) { return &ZODIAC_SIGNS[i]; } } return NULL; } int main(void) { Date date; printf("Podaj datę urodzin w formacie: dd.mm: "); scanf("%d.%d", &date.day, &date.month); const ZodiacSign *zodiacSign = findZodiac(&date); if (zodiacSign == NULL) { printf("Nie ma takiej daty panie kolego\n"); } else { printf("Twój znak zodiaku to %s\n", zodiacSign->name); } return 0; }
C
#include <iostream> int main(void) { double salary, netSalary; int etype, otHrs, otRate; bool x = true; std::cout << "Enter Emp Type : "; std::cin >> etype; std::cout << "Enter Salary : "; std::cin >> salary; std::cout << "Enter OtHrs : "; std::cin >> otHrs; while(x) { x = true; switch (etype) { case 1 : otRate = 1000; x = false; break; case 2 : otRate = 1500; x = false; break; case 3 : otRate = 1700; x = false; break; default : std::cout << "Enter valid employee type" << endl; std::cout << "Enter Employee Type : "; std::cin >> etype; x = true; break; } } netSalary = salary + otHrs* otRate; std::cout << "Net Salary: "<< netSalary; return 0; }
C
#include <stdio.h> int main() { int sum=0, n; float average=0.0; printf("Input a 10 numbers: \n"); for(int i=1; i<=10; i++) { printf("Number-%d: ", i); ///gets the 10 inputted numbers scanf("%d",&n); sum+=n; /// sum = sum + n } average = sum/10.0; /// formula to get average of 10 num printf("The sum of 10 numbers is %d\n", sum); printf("The average is %f", average); return 0; }
C
/* * Inputs.h * * Created on: Aug 13, 2013 * Author: Ryan */ #ifndef INPUTS_H_ #define INPUTS_H_ #include <Bounce.h> #include <Encoder.h> #include "PinDefinitions.h" struct InputValues { bool mBlueButton; bool mPinkButton; bool mGreenButton; bool mYellowButton; bool mSwitch0; bool mSwitch1; bool mSwitch2; bool mSwitch3; bool mSwitch4; bool mSwitch5; bool mEncoderButton; bool mRedSwitch; bool mBlueSwitch; bool mGreenSwitch; int mEncoderPosition; inline bool operator==(const InputValues& rhs) { bool equal = true; equal &= (mBlueButton == rhs.mBlueButton); equal &= (mPinkButton == rhs.mPinkButton); equal &= (mGreenButton == rhs.mGreenButton); equal &= (mYellowButton == rhs.mYellowButton); equal &= (mSwitch0 == rhs.mSwitch0); equal &= (mSwitch1 == rhs.mSwitch1); equal &= (mSwitch2 == rhs.mSwitch2); equal &= (mSwitch3 == rhs.mSwitch3); equal &= (mSwitch4 == rhs.mSwitch4); equal &= (mSwitch5 == rhs.mSwitch5); equal &= (mEncoderButton == rhs.mEncoderButton); equal &= (mRedSwitch == rhs.mRedSwitch); equal &= (mBlueSwitch == rhs.mBlueSwitch); equal &= (mGreenSwitch == rhs.mGreenSwitch); equal &= (mEncoderPosition == rhs.mEncoderPosition); return equal; } inline bool operator!=(const InputValues& rhs) { return !operator==(rhs); } }; struct Inputs { Bounce mBlueButton; Bounce mPinkButton; Bounce mGreenButton; Bounce mYellowButton; Bounce mSwitch0; Bounce mSwitch1; Bounce mSwitch2; Bounce mSwitch3; Bounce mSwitch4; Bounce mSwitch5; Bounce mEncoderButton; Bounce mRedSwitch; Bounce mBlueSwitch; Bounce mGreenSwitch; Encoder mEncoder; Inputs() : mBlueButton(PIN_BLUE_BUTTON, 10), mPinkButton(PIN_PINK_BUTTON, 10), mGreenButton(PIN_GREEN_BUTTON, 10), mYellowButton(PIN_YELLOW_BUTTON, 10), mSwitch0(PIN_SWITCH_0, 10), mSwitch1(PIN_SWITCH_1, 10), mSwitch2(PIN_SWITCH_2, 10), mSwitch3(PIN_SWITCH_3, 10), mSwitch4(PIN_SWITCH_4, 10), mSwitch5(PIN_SWITCH_5, 10), mEncoderButton(PIN_ENCODER_BUTTON, 10), mRedSwitch(PIN_RED_SWITCH, 10), mBlueSwitch(PIN_BLUE_SWITCH, 10), mGreenSwitch(PIN_GREEN_SWITCH, 10), mEncoder(PIN_ENCODER_A,PIN_ENCODER_B) { } }; static void readInputs(Inputs & inputs, InputValues & inputValues) { inputs.mBlueButton.update(); inputs.mPinkButton.update(); inputs.mGreenButton.update(); inputs.mYellowButton.update(); inputs.mSwitch0.update(); inputs.mSwitch1.update(); inputs.mSwitch2.update(); inputs.mSwitch3.update(); inputs.mSwitch4.update(); inputs.mSwitch5.update(); inputs.mEncoderButton.update(); inputs.mRedSwitch.update(); inputs.mBlueSwitch.update(); inputs.mGreenSwitch.update(); inputValues.mBlueButton = !inputs.mBlueButton.read(); inputValues.mPinkButton = !inputs.mPinkButton.read(); inputValues.mGreenButton = !inputs.mGreenButton.read(); inputValues.mYellowButton = !inputs.mYellowButton.read(); inputValues.mSwitch0 = !inputs.mSwitch0.read(); inputValues.mSwitch1 = !inputs.mSwitch1.read(); inputValues.mSwitch2 = !inputs.mSwitch2.read(); inputValues.mSwitch3 = !inputs.mSwitch3.read(); inputValues.mSwitch4 = !inputs.mSwitch4.read(); inputValues.mSwitch5 = !inputs.mSwitch5.read(); inputValues.mEncoderButton = inputs.mEncoderButton.read(); inputValues.mRedSwitch = inputs.mRedSwitch.read(); inputValues.mBlueSwitch = inputs.mBlueSwitch.read(); inputValues.mGreenSwitch = inputs.mGreenSwitch.read(); inputValues.mEncoderPosition = inputs.mEncoder.read(); } #endif /* INPUTS_H_ */
C
/********************** *** CstFile.c *** **********************/ #include <stdio.h> #include "CstType.h" void cst_read( FILE *fp, cst_type *cst, int byte_no ) { int no; cst_realloc( cst, byte_no ); // cst->byte_no = fread( cst->data, 1, byte_no, fp ); no = fread( cst->data, 1, byte_no, fp ); cst->rp = cst->data; cst->wp = cst->data + no; } void cst_write( FILE *fp, cst_type *cst ) { // fwrite( cst->data, 1, cst->byte_no, fp ); fwrite( cst->data, 1, CST_BYTES(cst), fp ); } cst_type * cst_load_from_file( char *file ) { cst_type *cst; FILE *fp; int byte_no; byte_no = gpFile_size( file ); if ( (fp = fopen ( file, "rb" )) == NULL ) return( NULL ); cst = cst_alloc( byte_no ); cst_read( fp, cst, byte_no ); fclose( fp ); return( cst ); } int cst_write_to_file( cst_type *cst, char *file ) { FILE *fp; if( (fp = fopen( file, "wb" )) == NULL ) return( -1 ); cst_write( fp, cst ); fclose( fp ); return( 1 ); }
C
#include <stdio.h> #define N 8 void show(int a[]); int quickpass(int a[],int i,int j); void quicksort(int a[],int low,int high); int main(void) { int a[N] = {50,36,66,76,36,12,25,95}; printf("原无序记录如下:\n"); show(a); printf("排序过程如下:\n"); quicksort(a,0,N-1); return 0; } //一趟快速排序 int quickpass(int a[],int i,int j) { int tmp; tmp = a[i]; //将a[i]作为基准保存 while(i < j){ //从上界比较 while(i < j && tmp <= a[j]) j--; //将a[j]交换到左边 if(i < j) a[i] =a[j]; //从下界比较 while(i < j && tmp >= a[i]) i++; //将a[i]交换到右边 if(i < j) a[j] = a[i]; } a[i] = tmp; //将基准放到最终的位置 return i; //返回基准的下标 } void quicksort(int a[],int low,int high) { int mid; if(low < high){ mid = quickpass(a,low,high); //一趟快速排序 show(a); quicksort(a,low,mid-1); //基准左边序列进行快速排序 quicksort(a,mid+1,high); //基准右边序列进行快速排序 } } void show(int a[]) { int i; for(i = 0; i < N; i++) printf("%d\t",a[i]); printf("\n"); }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* get_next_line.c :+: :+: */ /* +:+ */ /* By: tblanker <[email protected]> +#+ */ /* +#+ */ /* Created: 2020/01/16 14:00:08 by tblanker #+# #+# */ /* Updated: 2020/03/13 13:46:13 by tblanker ######## odam.nl */ /* */ /* ************************************************************************** */ #include "get_next_line.h" static char *cut_to_newline(char *buffer, char *line) { int i; i = 0; line = (char *)malloc(sizeof(char) * ft_strlen(buffer) + 1); if (!line) { free(buffer); return (NULL); } while (buffer[i] != '\n' && buffer[i] != '\0') { line[i] = buffer[i]; i++; } line[i] = '\0'; return (line); } static char *cut_from_newline(char *buffer) { int i; int j; char *res; j = 0; i = 0; while (buffer[i] != '\n') i++; i++; res = (char *)malloc(sizeof(char) * (ft_strlen(buffer) - i) + 1); if (!res) { free(buffer); return (0); } res[(ft_strlen(buffer) - i)] = '\0'; while (buffer[i]) { res[j] = buffer[i]; j++; i++; } free(buffer); return (res); } static int newline_found(char **line, char **buffer) { char *temp; *line = cut_to_newline(*buffer, *line); temp = cut_from_newline(*buffer); if (!temp || !(*line)) return (-1); *buffer = temp; return (1); } static int buf_concatenate(int ret_val, char **buffer, int fd, char **line) { char temp_buffer[BUFFER_SIZE + 1]; while (ret_val == BUFFER_SIZE && !(ft_strchr(*buffer, '\n'))) { ret_val = read(fd, temp_buffer, BUFFER_SIZE); temp_buffer[ret_val] = '\0'; *buffer = gnl_strjoin(*buffer, temp_buffer); if (!(*buffer)) return (-1); } if (ft_strchr(*buffer, '\n')) return (newline_found(line, buffer)); *line = gnl_strdup(*buffer); free(*buffer); if (!(*line)) return (-1); *buffer = NULL; return (0); } int get_next_line(int fd, char **line) { static char *prev_buffer; char buffer[BUFFER_SIZE + 1]; int ret_val; char *temp; if (prev_buffer && ft_strchr(prev_buffer, '\n')) return (newline_found(line, &prev_buffer)); ret_val = read(fd, buffer, BUFFER_SIZE); if (ret_val == -1 || BUFFER_SIZE < 0) return (-1); buffer[ret_val] = '\0'; temp = gnl_strjoin(prev_buffer, buffer); prev_buffer = gnl_strdup(temp); free(temp); if (!prev_buffer) return (-1); return (buf_concatenate(ret_val, &prev_buffer, fd, line)); }
C
#include <unistd.h> // ASCII code for ESC key #define ESC 27 int main(){ char buffer[2]; while(read(0, buffer, 1)){ write(1, buffer, 1); if(buffer[0] == '.') // terminate the processe once '.' is encountered ! break; } return 0; }
C
/*包含头文件*/ #include<stdio.h> #include<conio.h> #include<stdlib.h> /*类型定义*/ typedef int DataType; typedef struct Node { DataType data; struct Node* prior; struct Node* next; } DListNode, *DLinkList; /*函数声明*/ void PrintDList(DLinkList head); int InsertDList(DLinkList head, int i, char e); /*函数实现*/ int InitDList(DLinkList* head) /*初始化双向循环链表*/ { *head = (DLinkList)malloc(sizeof(DListNode)); if (!head) { return -1; } (*head)->next = *head; /*使头结点的prior指针和next指针指向自己*/ (*head)->prior = *head; return 1; } int InsertDList(DLinkList* L, int i, char e) /*在双向循环链表的第i个位置插入元素e建立双向循环链表。*/ { DListNode* s, *p; int j; p = (*L)->next; j = 1; /*查找链表中第i个结点*/ while (p != *L && j < i) { p = p->next; j++; } if (j > i) { /*如果要位置不正确,返回NULL*/ return 0; } s = (DListNode*)malloc(sizeof(DListNode)); if (!s) { return -1; } s->data = e; /*将s结点插入到双向循环链表*/ s->prior = p->prior; p->prior->next = s; s->next = p; p->prior = s; return 1; } void InvertDList(DLinkList* L) /*对双向循环链表L就地逆置*/ { DListNode* p, *q, *r; p = (*L)->next; /*p指向第一个结点*/ if ((*L) != NULL && (*L) != (*L)->next) { /*如果链表L不为空*/ /*将链表L的第一个结点逆置*/ q = p->next; (*L)->next = p; p->prior = (*L); (*L)->next->next = (*L); (*L)->prior = p; /*将链表L的每个结点依次插入到L的头部*/ while (q != *L) { r = q->next; /*r指向下一个待逆置的结点*/ q->next = (*L)->next; (*L)->next->prior = q; q->prior = (*L); (*L)->next = q; q = r; /*p指向下一个待逆置的结点*/ } } } void main() { DLinkList L; DListNode* p; int i, m, n; DataType a[] = {7, 3, 13, 11, 10, 23, 45, 6}; n = 8; InitDList(&L); for (i = 0; i < n; i++) { InsertDList(&L, i + 1, a[i]); } printf("逆置前:顺序表L中的元素依次为:"); PrintDList(L); InvertDList(&L); printf("逆置后:顺序表L中的元素依次为:"); PrintDList(L); } void PrintDList(DLinkList head) /*输出双向循环链表中的每一个元素*/ { DListNode* p; p = head->next; while (p != head) { printf("%4d", p->data); p = p->next; } printf("\n"); }
C
#include "generate_2d_curves.h" #include "common_math.h" bool generateCircleCurve(Point2D* pCurve, const size_t circlePointsCount, const Point2D* pInitialPoints, const size_t initialPointsCount, const double pointsDistance) { if (howManyPointsForCircleCurve(pInitialPoints, initialPointsCount, pointsDistance) != circlePointsCount) { return false; } const double radius = getPoint2DDistance(pInitialPoints[0], pInitialPoints[1]); double anlgleStep = 2 * M_PI / (double)circlePointsCount; Point2D center = pInitialPoints[0]; for (size_t i = 0; i < circlePointsCount; i++) { double phi = anlgleStep * (double)i; pCurve[i].x = (dataType)(center.x + radius * cos(phi)); pCurve[i].y = (dataType)(center.y + radius * sin(phi)); } return true; } size_t howManyPointsForCircleCurve(const Point2D* pInitialPoints, const size_t initialPointsCount, const double pointsDistance) { if (initialPointsCount != 2) { return 0; } const double radius = getPoint2DDistance(pInitialPoints[0], pInitialPoints[1]); const double perimeter = getCirclePerimeter(radius); return (size_t)((perimeter / pointsDistance) + 0.5); } double getCirclePerimeter(const double radius) { if (radius < 0) { return 0; } return 2 * M_PI * radius; } bool generateStraightLineCurve(Point2D* pCurve, const size_t linePointsCount, const Point2D* pInitialPoints, const size_t initialPointsCount, const double pointsDistance) { if (howManyPointsForStraightLineCurve(pInitialPoints, initialPointsCount, pointsDistance) != linePointsCount) { return false; } const double length = getPoint2DDistance(pInitialPoints[0], pInitialPoints[1]); double lineStep = length / (double)(linePointsCount - 1); Point2D firstPoint = pInitialPoints[0]; Point2D lastPoint = pInitialPoints[1]; Point2D tangentVector = { (dataType)((lastPoint.x - firstPoint.x)/ length), (dataType)((lastPoint.y - firstPoint.y)/ length) }; for (size_t i = 0; i < linePointsCount; i++) { double parameter = lineStep * (double)i; pCurve[i].x = (dataType)(firstPoint.x + parameter * tangentVector.x); pCurve[i].y = (dataType)(firstPoint.y + parameter * tangentVector.y); } return true; } size_t howManyPointsForStraightLineCurve(const Point2D* pInitialPoints, const size_t initialPointsCount, const double pointsDistance) { if (initialPointsCount != 2) { return 0; } const double length = getPoint2DDistance(pInitialPoints[0], pInitialPoints[1]); return (size_t)((length / pointsDistance) + 1.5); }
C
/******************************************************************************* * FILE NAME : client.c * * DESCRIPTION : contains main routine for client * * DATE NAME REFERENCE REASON * 20-Dec-2010 Mohd Sadique PRISM PROJECT Initial Creation * /******************************************************************************* * HEADER FILES ******************************************************************************/ #include <c_header.h> static S32_INT g_connfd = 0; /*store connected socket descriptor */ /*************************************************************** * * * ******************************************************************************/ * * FUNCTION NAME : signal_handler * * DESCRIPTION : signal handler for CTRL-C and send quit message to server * * RETURN VALUES : void * ***************************************************************/ static void signal_handler ( S32_INT signum /*signal number */ ) { (void)client_send ("quit", g_connfd); printf ("\n recieved ctrl-c with signal no %d\n", signum); exit (SUCCESS); } /*End of function */ /******************************************************************************* * FUNCTION NAME: main * * DESCRIPTION: This is the main function for local file search * and displays the contents of the respective file. * * RETURNS: exit status * ******************************************************************************/ S32_INT main () { /*Local Declarations */ S32_INT option = 0; /*store menu option */ return_value ret_val = 0; /*store return value from function */ SCHAR *p_file_name; A_TRACE (DETAILED_TRACE, "-----ENTERING CLIENT-----\n"); (void) signal (SIGINT, signal_handler); while(1 == 1) { /*display menu returns whether to find files or quit */ option = client_display_menu (); /*Search file */ if (1 == option) { /*Establish connection to server */ g_connfd = client_connect_to_server (); /*connection to server couldnt be established */ if (FAILURE == g_connfd) { A_ERROR (CRITICAL, ERROR_CONNECTION); return FAILURE; } /*search_files displays search options and carries on task */ ret_val = client_search_file_req (g_connfd); /*search_files failed */ if (FAILURE == ret_val) { A_ERROR (MAJOR, ERROR_SEARCH); return FAILURE; } ret_val = client_close_connection (g_connfd); /*close_connection failed */ if (FAILURE == ret_val) { A_ERROR (MAJOR, ERROR_CLOSE_CONNECTION); return FAILURE; } } /*End of IF */ else if (2 == option) { /*Establish connection to server */ g_connfd = client_connect_to_server (); /*connection to server couldnt be established */ if (FAILURE == g_connfd) { A_ERROR (CRITICAL, ERROR_CONNECTION); return FAILURE; } p_file_name = (SCHAR *) malloc (sizeof (SCHAR) * 32); if(NULL == p_file_name) { A_ERROR(MAJOR,ERROR_MEMORY); return(FAILURE); } memset(p_file_name,0,32); ret_val = client_get_file_content (p_file_name, g_connfd); if (FAILURE == ret_val) { A_ERROR (MAJOR, ERROR_GET_FILENAME); free(p_file_name); return FAILURE; } free (p_file_name); ret_val = client_close_connection (g_connfd); /*close_connection failed */ if (FAILURE == ret_val) { A_ERROR (MAJOR, ERROR_CLOSE_CONNECTION); return FAILURE; } } else { A_TRACE(DETAILED_TRACE, "-----EXITING CLIENT-----\n"); return SUCCESS; } }//END OF WHILE return (SUCCESS); }/*End of function */
C
#include <stdio.h> int main() { int c,m,n; printf("Enter the range of the nos :\n"); scanf("%d%d",&m,&n); while(m<=n) { if(m%2==0) printf("%d\n",m); m=m+1; } return 0; }
C
//cross-process communication #include <signal.h> #include <stdio.h> #include <stddef.h> #include <fcntl.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <termio.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <python3.7/Python.h> int Actuator; int Sensor; char sensorData[1024]; int pipe_fd[2]; //Using Python function int controlLawDesign(char* x, int a, int b){ PyObject *pModule, *pFunc, *pArgs, *pKargs, *pRes; int res; //import module & function //PySys_SetPath(Py_DecodeLocale(".",NULL)); pModule=PyImport_Import(PyUnicode_FromString("submarineAlgorithm")); pFunc=PyObject_GetAttrString(pModule,"controlLawDesign"); //turn arguments into PyObject pArgs=Py_BuildValue("(s)", x); pKargs=Py_BuildValue("{s:i,s:i}","a",a,"b",b); //call function pRes=PyObject_Call(pFunc,pArgs,pKargs); //check if calling is failed. If success, trans the PyObject into C type :x res=PyLong_AsLong(pRes); //process memory allocation Py_DECREF(pModule); Py_DECREF(pFunc); Py_DECREF(pArgs); Py_DECREF(pKargs); Py_DECREF(pRes); return res; } void gotSensorDataSig(int a){ printf("get signal\n\r"); read(pipe_fd[0],&sensorData,sizeof(sensorData)); } int main(void){ //Open the ACM file int ACM_fd0,ACM_fd1; ACM_fd0=open("/dev/ttyACM0",O_RDWR); ACM_fd1=open("/dev/ttyACM1",O_RDWR); if(ACM_fd0==-1) perror("Can't create ACM0"); if(ACM_fd1==-1) perror("Can't create ACM1"); //Config the UART struct termios Opt0; tcgetattr(ACM_fd0,&Opt0); cfsetispeed(&Opt0,B9600); tcsetattr(ACM_fd0,TCSANOW,&Opt0); struct termios Opt1; tcgetattr(ACM_fd1,&Opt1); cfsetispeed(&Opt1,B9600); tcsetattr(ACM_fd1,TCSANOW,&Opt1); sleep(2); //If ACM_fd0 is Actuator or Sensor. while(1){ char buff[1024]; memset(&buff,'\0',sizeof(buff)); int Len=sizeof(buff); write(ACM_fd0,"name",4); tcflush(ACM_fd0,TCIOFLUSH); read(ACM_fd0,buff,Len); if (strcmp(buff,"My name is Bitchduino.\n")==0){ printf("[pi]:Actuator Connected\n"); Actuator=ACM_fd0; break; } if (strcmp(buff,"My name is Anarduino.\n")==0){ printf("[pi]:Sensor Connected\n"); Sensor=ACM_fd0; break; } printf("%s",buff); usleep(100000); } //If ACM_fd1 is Actuator or Sensor. while(1){ char buff[1024]; memset(&buff,'\0',sizeof(buff)); int Len=sizeof(buff); write(ACM_fd1,"name",4); tcflush(ACM_fd1,TCIOFLUSH); read(ACM_fd1,buff,Len); if (strcmp(buff,"My name is Bitchduino.\n")==0){ printf("[pi]:Actuator Connected\n"); Actuator=ACM_fd1; break; } if (strcmp(buff,"My name is Anarduino.\n")==0){ printf("[pi]:Sensor Connected\n"); Sensor=ACM_fd1; break; } printf("%s",buff); usleep(100000); } //Creat unnamed pipe pipe(pipe_fd); //get parrent process ID const pid_t parrent_ID=getpid(); //Build Children process pid_t child_ID=fork(); switch(child_ID){ //fork error occur case -1: perror("failed to fork first times"); exit(-1); //child process(sensor) //sensoring process case 0:{ char buff[110]; int Len=sizeof(buff); close(pipe_fd[0]); sleep(1); while(1){ //virtual sensor memset(&buff,'\0',sizeof(buff)); write(Sensor,"all",3); tcflush(Sensor,TCIOFLUSH); read(Sensor,buff,Len); tcflush(Sensor,TCIOFLUSH); fflush(stdout); printf("[child process] : %s",buff); //send signal to parrent process kill(parrent_ID,SIGUSR1); //input sensor data into pipe. write(pipe_fd[1],&buff,sizeof(buff)); sleep(1); }; close(pipe_fd[1]); break; } default:{ Py_Initialize(); PyObject *sysPath = PySys_GetObject((char*)"path"); PyList_Append(sysPath,PyUnicode_FromString(".")); close(pipe_fd[1]); signal(SIGUSR1,gotSensorDataSig); while(1){ printf("[parrent process]:sensorData=%d\n\r",controlLawDesign(sensorData,1,0)); fflush(stdout); //printf("[parrent process] : %s",sensorData); write(Actuator,"1",1); tcflush(Actuator,TCIOFLUSH); usleep(100000); write(Actuator,"0",1); tcflush(Actuator,TCIOFLUSH); sleep(2); } close(pipe_fd[0]); Py_Finalize(); break; } } return 0; }
C
/* * ===================================================================================== * * Filename: fileutility.h * * Description: * * Version: 1.0 * Created: 2012年02月17日 19时24分04秒 * Revision: none * Compiler: gcc * * * ===================================================================================== */ #ifndef FILEUTILITY #define FILEUTILITY #define NAME_STRING_MAX 100 #define ARGV_STRING_MAX 100 #define CMD_STRING_MAX 1024*100 typedef enum { FILE_NOT_EXIST = 1, FILE_EXIST = 2 }exist_t; typedef enum { FILE_TEXT = 1, FILE_BINARY = 2, FILE_PERL = 3, FILE_PHP = 4, FILE_JSP = 5, FILE_PYTHON = 6 }file_t; typedef enum { OP_SUCCESS = 1, OP_FAIL = 2 }op_t; typedef struct{ char name[NAME_STRING_MAX]; file_t type; int size; char argv[ARGV_STRING_MAX]; }uufile_t; extern exist_t is_exist(const char *file_name); extern file_t get_file_type(const char *filename); extern op_t read_file(uufile_t *file_info,char *buffer); extern void init_file_info(uufile_t *file_info); extern int get_file_size(const char *filename); extern op_t handle_request_file(uufile_t *file_info,char *send_buffer,int buffer_size); #endif
C
#include<stdio.h> void main() int num; printf("Է: "); scanf("%d", &num); // if else ִ if() ̸ elseif Ȯ // ʰ ü if elseif ´. // if elseif ߺ ʾƾ ϸ ߺ ʴ // if elseif Ͽ single if ۼϴ ͺ // ʿ üũϴ ɾ ִ. if(num<0){ printf("Է 0 ۴. \n"); } else if(num>0){ printf("Է 0 ũ. \n"); } else if(num==0){ printf("Է 0̴. \n"); } return 0; }
C
/* ** EPITECH PROJECT, 2020 ** my_find_prime_sup.c ** File description: ** 02/10/2020 */ #include "my.h" char *my_array_nbr(int nb, int size, char *buffer) { int comm = 0; memset(buffer, '0', size - 1); buffer[size] = '\0'; if (buffer) { for (int i = 0; nb && size; i++, size--) { comm = nb % 10; nb = nb / 10; buffer[size - 1] = comm + '0'; } } for (; *buffer == '0' && *buffer; buffer++); if (*buffer == '\0') { buffer--; } return buffer; }
C
/* * consolaLoca.c * * Created on: 03/07/2014 * Author: utnso */ #include "consolaLoca.h" void consolaLoca(void) { puts( "\nSE INICIO LA CONSOLA. ESCRIBA ALGUN COMANDO, USANDO ESPACIO PARA CADA PARAMETRO.\n"); while (1) { puts( "\nOPERACIONES VALIDAS:\n********** grabar PID BASE INICIO TEMPLATE BUFFER\n********** solicitar PID BASE INICIO TAMANIO TEMPLATE\n********** crear PID TAMANIO\n********** destruir PID ---- 0 LIBERA MEMORIA\n********** algoritmo ALGORITMO---- FIRST-FIT / WORST FIT\n********** retardo RETARDO"); puts( "********** compactacion\n********** dumpMP\n********** dumpEstructuras PID------0 PARA TODAS LAS TABLAS\n********** dumpContenidoMP OFFSET CANTIDAD\n"); char* comando = malloc(100); __fpurge(stdin); fgets(comando, 100, stdin); int operacion = detectarEspacio(comando); if (string_equals_ignore_case(comando, "compactacion\n")) { // porque es el unico comando que va solo, sino es error operacion = 12; } if (string_equals_ignore_case(comando, "dumpMP\n")) { // porque es el unico comando que va solo, sino es error operacion = 6; } if (operacion == -1) { printf("\nOPERACION INCORRECTA.\n\n"); } else { char* op = string_substring_until(comando, operacion); char* restoComando = string_substring_from(comando, operacion + 1); manejarOperacion(op, restoComando); } free(comando); } return; } int detectarLong(char* string) { int fin = strlen(string); // printf("la long es %i\n", fin); int i = 0; while (i < fin) { // printf("el caracter leido es : (%c)\n",string[i]); if (string[i] == '\n') { // printf("SE RETORNA %i\n",i); return i; } i++; } // SI LLEGO ACA ES PORQUE NO HABIA ESPACIO return -1; } int detectarEspacio(char* string) { int fin = strlen(string); // printf("la long es %i\n",fin); int i = 0; while (i < fin) { // printf("el caracter leido es : (%c)\n",string[i]); if (string[i] == ' ') { // printf("SE RETORNA %i\n",i); return i; } i++; } // SI LLEGO ACA ES PORQUE NO HABIA ESPACIO return -1; } void manejarOperacion(char* operacion, char* restoComando) { printf("LA OPERACION ES : (%s)\n", operacion); // printf("RESTO ES : (%s)\n", restoComando); if (string_equals_ignore_case(operacion, "grabar")) { grabarBytesConsola(restoComando); return; } if (string_equals_ignore_case(operacion, "solicitar")) { solicitarBytesConsola(restoComando); return; } if (string_equals_ignore_case(operacion, "crear")) { crearSegmentoConsola(restoComando); return; } if (string_equals_ignore_case(operacion, "destruir")) { destruirSegmentosConsola(restoComando); return; } if (string_equals_ignore_case(operacion, "algoritmo")) { char* strAlgo = string_substring(restoComando, 0, strlen(restoComando) - 1); printf("EL ALGORITMO ACTUAL ES (%s)\n", configuracionUmv->algoritmo); printf("SE QUIERE CAMBIAR A (%s)\n", strAlgo); if (string_equals_ignore_case(strAlgo, "First-fit") || string_equals_ignore_case(strAlgo, "Worst-fit")) { configuracionUmv->algoritmo = strAlgo; printf("\nSE CAMBIO A (%s)\n\n", strAlgo); } else { printf("\nSE INGRESO UN ALGORITMO NO VALIDO\n\n"); } return; } if (string_equals_ignore_case(operacion, "retardo")) { char* strAlgo = string_substring(restoComando, 0, strlen(restoComando) - 1); printf("EL RETARDO ACTUAL ES (%i)\n", configuracionUmv->retardo); int ret = atoi(strAlgo); if (ret >= 0) { configuracionUmv->retardo = ret; printf("\nSE CAMBIO A (%i)\n\n", ret); } else { printf("\nSE INGRESO UN RETORNO NO VALIDO\n\n"); } return; } if (string_equals_ignore_case(operacion, "compactacion")) { printf("SE EJECUTA LA COMPACTACION\n"); pthread_mutex_lock(&wrt); compactacion(); pthread_mutex_unlock(&wrt); return; } if (string_equals_ignore_case(operacion, "dumpMp")) { dumpLoco(2, 0, 0, 0); return; } if (string_equals_ignore_case(operacion, "dumpEstructuras")) { char* strPid = string_substring(restoComando, 0, strlen(restoComando) - 1); int pid = atoi(strPid); if (pid < 0) { puts( "\n++++++++++\nSEGMENTATION FAULT: SE QUIERE GENERAR UN DUMP CON PID < 0\n++++++++++\n"); return; } dumpLoco(1, pid, 0, 0); return; } if (string_equals_ignore_case(operacion, "dumpContenidoMp")) { contenidoMP(restoComando); return; } else { printf("\nOPERACION NO VALIDA!!!! \n\n"); } } void grabarBytesConsola(char* restoComando) { int aux; // PID aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar el PID\n"); return; } char* strPid = string_substring_until(restoComando, aux); int pid = atoi(strPid); printf("EL PID ES (%i)\n", pid); if(pid<=0){ printf( "\n******SEGMENTATION FAULT: PID <= 0 *********\n\n"); return; } restoComando = string_substring_from(restoComando, aux + 1); // printf("EL STRING QUE QUEDA ES (%s)\n", restoComando); // BASE aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar la BASE\n"); return; } char* strBase = string_substring_until(restoComando, aux); int base = atoi(strBase); printf("LA BASE ES (%i)\n", base); restoComando = string_substring_from(restoComando, aux + 1); // printf("EL STRING QUE QUEDA ES (%s)\n", restoComando); // INICIO aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar el INICIO\n"); return; } char* strIni = string_substring_until(restoComando, aux); int inicio = atoi(strIni); printf("EL INICIO ES (%i)\n", inicio); if(inicio<0){ printf( "\n******SEGMENTATION FAULT: OFFSET < 0 *********\n\n"); return; } restoComando = string_substring_from(restoComando, aux + 1); // printf("EL STRING QUE QUEDA ES (%s)\n", restoComando); // TEMPLATE aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar el TEMPLATE\n"); return; } char* strTemplate = string_substring_until(restoComando, aux); printf("EL TEMPLATE ES (%s)\n", strTemplate); restoComando = string_substring(restoComando, aux + 1, strlen(restoComando) - 4); // printf("EL STRING QUE QUEDA ES (%s) con tamanio (%i)\n", restoComando, // strlen(restoComando)); aux = grabarElBuffer(pid, base, inicio, strTemplate, restoComando); if (aux == errorTamanioLibreMenor) { puts( "\n++++++++++\nSEGMENTATION FAULT: EL TAMANIO DEL PEDIDO EXCEDE EL SIZE DEL SEGMENTO\n++++++++++\n"); return; } if (aux == errorNoExisteSegmento) { puts( "\n++++++++++\nSEGMENTATION FAULT: SEGMENTO INVALIDO. NO SE PUEDEN GUARDAR BYTES, PORQUE NO EXISTE EL SEGMENTO\n++++++++++\n"); return; } if (aux == -1) { return; } printf("SE GRABO CORRECTAMENTE\n"); escribirEnDiscoLoco(restoComando, strlen(restoComando) + 1, aux); return; } void solicitarBytesConsola(char* restoComando) { int aux; // PID aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar el PID\n"); return; } char* strPid = string_substring_until(restoComando, aux); int pid = atoi(strPid); printf("EL PID ES (%i)\n", pid); if(pid<=0){ printf( "\n******SEGMENTATION FAULT: PID <= 0 *********\n\n"); return; } restoComando = string_substring_from(restoComando, aux + 1); // printf("EL STRING QUE QUEDA ES (%s)\n", restoComando); // BASE aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar la BASE\n"); return; } char* strBase = string_substring_until(restoComando, aux); int base = atoi(strBase); printf("LA BASE ES (%i)\n", base); restoComando = string_substring_from(restoComando, aux + 1); // printf("EL STRING QUE QUEDA ES (%s)\n", restoComando); // INICIO aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar el INICIO\n"); return; } char* strIni = string_substring_until(restoComando, aux); int inicio = atoi(strIni); printf("EL INICIO ES (%i)\n", inicio); if (inicio < 0) { printf("\n******SEGMENTATION FAULT: OFFSET < 0 *********\n\n"); return; } restoComando = string_substring_from(restoComando, aux + 1); // printf("EL STRING QUE QUEDA ES (%s)\n", restoComando); // TAMANIO aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar el TAMANIO\n"); return; } char* strTam = string_substring_until(restoComando, aux); int tamanio = atoi(strTam); printf("EL TAMANIO ES (%i)\n", tamanio); if (tamanio <= 0) { printf("\nSEGMENTATION FAULT: TAMANIO <= 0\n\n"); return; } restoComando = string_substring_from(restoComando, aux + 1); // printf("EL STRING QUE QUEDA ES (%s)\n", restoComando); aux = detectarLong(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar la TEMPLATE\n"); return; } char* strTem = string_substring_until(restoComando, aux); printf("EL TEMPLATE ES (%s)\n", strTem); char* resu = solicitoMemoria(pid, base, inicio, tamanio, strTem); free(resu); return; } void crearSegmentoConsola(char* restoComando) { int aux; aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar el PID\n"); return; } char* strPid = string_substring_until(restoComando, aux); int pid = atoi(strPid); printf("EL PID ES (%i)\n", pid); if(pid<=0){ printf( "\n******SEGMENTATION FAULT: PID <= 0 *********\n\n"); return; } restoComando = string_substring(restoComando, aux + 1, strlen(restoComando) - 1); // printf("EL STRING QUE QUEDA ES (%s) de tamanio (%i)\n", restoComando, // strlen(restoComando)); int tam = atoi(restoComando); printf("EL TAMANIO ES (%i)\n", tam); if (tam < 0) { printf( "\n****** SEGMENTATION FAULT: NO SE PUEDE CREAR UN SEGMENTO CON TAMANIO NEGATIVO *******\n\n"); return; } pthread_mutex_lock(&wrt); int base = crearSegmento(pid, tam); pthread_mutex_unlock(&wrt); if (base == errorMemOver) { puts( "\n++++++++++\nMEMORY OVERLOAD: NO HAY ESPACIO SUFICIENTE PARA CREAR EL SEGMENTO\n++++++++++\n"); return; } if (base == errorPid0) { puts( "\n++++++++++\nSEGMENTATION FAULT: SE QUIERE CREAR UN SEGMENTO CON PID 0\n++++++++++\n"); return; } if (base == errorTam0) { puts( "\n++++++++++\nSEGMENTATION FAULT: SE QUIERE CREAR UN SEGMENTO CON TAMANIO 0\n++++++++++\n"); return; } printf("SE CREO CON EXITO. LA BASE ES (%i)\n", base); return; } void destruirSegmentosConsola(char* restoComando) { char* strAlgo = string_substring(restoComando, 0, strlen(restoComando) - 1); int pid = atoi(strAlgo); if (pid > 0) { printf("\nSE DESTRUYEN LOS SEGMENTOS DEL PID (%i)\n\n", pid); pthread_mutex_lock(&wrt); destruirSegmentosDePrograma(pid); pthread_mutex_unlock(&wrt); printf("SE EJECUTO LA DESTRUCCION CORRECTAMENTE\n"); return; } if(pid==0){ printf("\nSE DESTRUYEN TODOS LOS SEGMENTOS\n\n"); pthread_mutex_lock(&wrt); limpiarMemoria(); pthread_mutex_unlock(&wrt); }else{ puts( "\n++++++++++\nSEGMENTATION FAULT: EL PID PARA DESTRUIR SEGMENTOS DEBE SER > 0\n++++++++++\n"); return; } return; } void escribirEnDiscoLoco(char* bufferAux, int tamanio, int tipo) { puts("\n¿DESEA ESCRIBIRLO EN DISCO?\n1-SI\n2-NO"); int opcD; __fpurge(stdin); scanf("%i", &opcD); if (opcD == 1) { banderaConsola++; char* nombreBuffer = malloc(14); sprintf(nombreBuffer, "buffer%i.txt", banderaConsola); printf("El nombre del archivo buffer es (%s)\n", nombreBuffer); FILE* archivoBuffer; archivoBuffer = fopen(nombreBuffer, "w"); // printf( // "SE QUIERE ESCRIBIR EN DISCO &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n"); switch (tipo) { case 9: { //string // printf("string\n"); mostrarStringLoco(bufferAux, tamanio); escribirStringLoco(bufferAux, tamanio, archivoBuffer); break; } case 10: { //int str // printf("int\n"); mostrarStringSinNulo(bufferAux, tamanio); escribirStringSinNulo(bufferAux, tamanio, archivoBuffer); break; } case 11: { //char // printf("char\n"); mostrarStringSinNulo(bufferAux, tamanio); escribirStringSinNulo(bufferAux, tamanio, archivoBuffer); break; } case 12: { //int solo // printf("int solo\n"); int *i = (int *) bufferAux; // printf("\n%i\n", *i); fprintf(archivoBuffer, "%i", *i); break; } } // fwrite(bufferAux,tamanio,1,archivoBuffer); fclose(archivoBuffer); printf("SE ESCRIBIO EN DISCO CORRECTAMENTE\n"); free(nombreBuffer); } // free(bufferAux); return; } void escribirStringLoco(char* cadena, int longitud, FILE* archivo) { int o = 0; while (o < longitud) { if (cadena[o] == '\0') { fprintf(archivo, "\\0"); o++; } fputc(cadena[o], archivo); o++; } return; } void mostrarStringLoco(char* cadena, int longitud) { int o = 0; printf("\n"); while (o < longitud) { if (cadena[o] == '\0') { printf("\\0"); } printf("%c", cadena[o]); o++; } printf("\n\n"); } void contenidoMP(char* restoComando) { int aux; // OFFSET aux = detectarEspacio(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar el Offset\n"); return; } char* strOffset = string_substring_until(restoComando, aux); int offset = atoi(strOffset); printf("EL offset ES (%i)\n", offset); if (offset < 0) { puts( "\n++++++++++\nSEGMENTATION FAULT: SE QUIERE PEDIR EL CONTENIDO DE MEMORIA DESDE UN OFFSET NEGATIVO\n++++++++++\n"); return; } restoComando = string_substring_from(restoComando, aux + 1); // printf("EL STRING QUE QUEDA ES (%s)\n", restoComando); // CANTIDAD aux = detectarLong(restoComando); if (aux == -1) { printf( "Error falta un caracter de espacio en el comando para detectar la Cantidad\n"); return; } char* strCant = string_substring_until(restoComando, aux); int cant = atoi(strCant); printf("LA CANTIDAD ES (%i)\n", cant); if (cant < 0) { puts( "\n++++++++++\nSEGMENTATION FAULT: SE QUIERE PEDIR EL CONTENIDO DE MEMORIA CON UN TAMANIO NEGATIVO\n++++++++++\n"); return; } dumpLoco(3, 0, offset, cant); return; } void dumpLoco(int opcion, int pid, int offset, int cantidad) { archivoDump = fopen("Dump.txt", "a"); switch (opcion) { case 1: { fputs(temporal_get_string_time(), archivoDump); fputs("\nESTRUCTURAS DE MEMORIA:\n", archivoDump); puts("SE EJECUTA EL COMANDO DE ESTRUCTURAS DE MEMORIA"); preLectura(); estructurasDeMemoria(pid); postLectura(); fputs( "\n|||||||||||||||||||||||||FIN DE REPORTE||||||||||||||||||||||||||\n\n\n\n", archivoDump); puts("REPORTE GENERADO CORRECTAMENTE\n"); break; } case 2: { fputs(temporal_get_string_time(), archivoDump); fputs("\nSEGMENTOS DE LA MEMORIA:\n", archivoDump); puts("SE EJECUTA EL COMANDO DE REPORTE MEMORIA PRINCIPAL"); preLectura(); loguearSegmentos(listaDeSegmentos); postLectura(); fputs( "\n|||||||||||||||||||||||||FIN DE REPORTE||||||||||||||||||||||||||\n\n\n\n", archivoDump); puts("REPORTE GENERADO CORRECTAMENTE\n"); break; } case 3: { fputs(temporal_get_string_time(), archivoDump); fputs("\nSE MUESTRA EL CONTENIDO DE LA MEMORIA PRINCIPAL:\n", archivoDump); puts("SE EJECUTA EL COMANDO DE CONTENIDO EN LA MEMORIA PRINCIPAL"); preLectura(); contenidoDeLaMp(offset, cantidad); postLectura(); fputs( "\n|||||||||||||||||||||||||FIN DE REPORTE||||||||||||||||||||||||||\n\n\n\n", archivoDump); puts("REPORTE GENERADO CORRECTAMENTE\n"); break; } default: puts("SE ELIGIO UNA OPCION NO VALIDA"); break; } fclose(archivoDump); return; } void mostrarStringSinNulo(char* cadena, int longitud) { int o = 0; printf("\n"); while (o < longitud) { if(cadena[o]!='\0'){ printf("%c", cadena[o]); } o++; } printf("\n\n"); } void escribirStringSinNulo(char* cadena, int longitud, FILE* archivo) { int o = 0; while (o < longitud) { if (cadena[o] != '\0') { fputc(cadena[o], archivo); } o++; } return; }
C
/* ** EPITECH PROJECT, 2017 ** My_rpg ** File description: ** choose_player_name.c */ #include "character.h" /* ** This fct create and init a new text by creating the font and ** setting the size. The string taken as parameter is the string displayed ** by the sfText ** return value sfText * or NULL */ static sfText *init_name_text(char *name, sfVector2f pos) { sfText *text = sfText_create(); sfFont *font = sfFont_createFromFile("./pictures/anir.ttf"); if (!text || !font) return (NULL); sfText_setCharacterSize(text, 80); sfText_setFont(text, font); sfText_setColor(text, sfBlack); sfText_setString(text, name); sfText_setPosition(text, pos); return (text); } /* ** change the string name in the struct character. The c char is the chara ** typed by the user the fct replace the old char by the new one and add ** a '_' at the end of the string ** return value void */ static void change_string(char *name, char c, int *index, sfText *name_print) { if ((c == 8 && *index == 0) || c == 13) return; if (c == 8 && *index > 0) { name[*index] = '\0'; name[*index-1] = '_'; *index-=1; } else if (*index < 11) { name[*index] = c; name[*index+1] = '_'; name[*index+2] = '\0'; *index+=1; } sfText_setString(name_print, name); } static void draw_name_screen(window_t *window, sfText *name_print,\ sfText *text, sfColor color) { DRAW_TXT(window->RenderWindow, name_print, NULL); DRAW_TXT(window->RenderWindow, text, NULL); DRAW(window->RenderWindow); CLEAR(window->RenderWindow, color); } /* ** This fct is the event loop waiting for the user ** to choose is character's name. The main loop is waiting for the user to ** press the enter key and all the event to be treat ** return value 0 or 84 */ static int write_name(window_t *window, char *name,\ sfText *text, sfColor color) { int index = my_strlen(name)+1; sfVector2f pos = {650, 600}; sfText *name_print = init_name_text(name, pos); if (!name_print) return (84); DRAW_TXT(window->RenderWindow, text, NULL); DRAW_TXT(window->RenderWindow, name_print, NULL); DRAW(window->RenderWindow); while (sfRenderWindow_pollEvent(window->RenderWindow, &window->event) || sfKeyboard_isKeyPressed(sfKeyReturn) != sfTrue) { if (window->event.type == sfEvtTextEntered) { change_string(name, (char)window->event.text.unicode,\ &index, name_print); draw_name_screen(window, name_print, text, color); } sfSleep(sfMicroseconds(50000)); } name[index] = '\0'; return (0); } /* ** This fct create a fading screen and call the fct who allow to change the ** user character's name ** return value 0 or 84 */ int choose_name_screen(window_t *window, char *name) { sfColor fading_screen = sfColor_fromRGBA(0, 0, 0, 0); sfText *name_print; sfVector2f pos = {500, 300}; sfText *text = init_name_text("Entre ton nom : ", pos); pos.y+=300; pos.x+=150; name_print = init_name_text(name, pos); if (!text || !name_print) return (84); for (int i = 0; i < 190; i++) { fading_screen.r = i; fading_screen.g = i; fading_screen.b = i; fading_screen.a = i; draw_name_screen(window, name_print, text, fading_screen); } if (write_name(window, name, text, fading_screen) == 84) return (84); return (0); }
C
#include <stdio.h> int main() { char text[10]; int i,alpha=0,num=0,sc=0; for(i=0;i<10;i++) { scanf("%c", &text[i]); } for(i=0;i<10;i++) { if((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z')) { alpha=alpha++; } else if(text[i] >= '0' && text[i] <= '9') { num=num++; } else if(text[i]>=32 && text[i] <=47) { sc=sc++; } } printf("%d,%d,%d",alpha,num,sc); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pipe.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nforay <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/09 13:35:49 by mbourand #+# #+# */ /* Updated: 2020/09/04 15:58:31 by nforay ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" int is_pipe(t_list *command) { t_token *content; if (!command) return (FALSE); content = (t_token*)command->content; return (content->is_operator && !ft_strcmp(content->text, OP_PIPE)); } int get_near_pipes(t_list **command, size_t i) { int res; res = i > 0 ? is_pipe(command[i - 1]) : 0; res |= (is_pipe(command[i + 1]) << 1); return (res); } void pipe_redirection(int pipes, int pipe_index) { size_t i; i = 0; if (pipes & PIPE_AFTER) { if (dup2(g_shell.pipeline[pipe_index][1], STDOUT_FILENO) == -1) ft_perror("Redirection error"); } if (pipes & PIPE_BEFORE) { if (dup2(g_shell.pipeline[pipe_index - 1][0], STDIN_FILENO) == -1) ft_perror("Redirection error"); } while (g_shell.pipeline[i]) { close(g_shell.pipeline[i][0]); close(g_shell.pipeline[i][1]); i++; } }
C
#include<stdio.h> #include<math.h> #define LI long int int main() { int arr[10005]; LI low, high; LI i, j, k; LI maxi; double rootd; LI rooti[10005]; int time; scanf("%d", &time); while(time--) { scanf("%ld %ld", &low, &high); for(i = low; i <= high; i++) { rootd = (double) sqrt(i); rooti[i-low] = (LI) rootd; if(rooti[i-low] == rootd) arr[i-low] = 1; else arr[i-low] = 2; } maxi = high - low; for(i = 2; i <= rooti[maxi]; i++) { for(j = low; j <= high; j++) { if(i <= rooti[j - low]) { if(j % i == 0) arr[j - low] += 2; } } } k = high - low; for(maxi = 0,i = 0; i <= k; i++) { if(arr[maxi] < arr[i]) maxi = i; } printf("Between %ld and %ld, %ld has a maximum of %d divisors.\n", low, high, maxi + low, arr[maxi]); } return 0; }
C
/* Program 2_2.c Toggle Green LED (LD2) on STM32F446RE Nucleo64 using SysTick * * This program uses SysTick to generate 500 ms delay to * toggle the LED. System clock is running at 16 MHz. * SysTick is configure to count down from 3199999 to zero * to give a 500 ms delay. * Created on: 11/8/2021 * Author: SUNIL PAWAR */ #include "stm32f4xx.h" int main(void) { RCC->AHB1ENR |= 1; /* enable GPIOA clock */ GPIOA->MODER &= ~0x00000C00; /* clear pin mode */ GPIOA->MODER |= 0x00000400; /* set pin to output mode */ /* Configure SysTick */ SysTick->LOAD = 3200000 - 1; /* reload with number of clocks per second */ SysTick->VAL = 0; SysTick->CTRL = 5; /* enable it, no interrupt, use system clock */ while (1) { if (SysTick->CTRL & 0x10000) { /* if COUNT flag is set */ GPIOA->ODR ^= 0x00000020; /* toggle green LED */ } } }
C
#include <stdio.h> int main() { int testCases; scanf("%i", &testCases); int i; for (i = 0; i < testCases; i++) { int numberOfFeedbacks; scanf("%i", &numberOfFeedbacks); int j; int feedbackCode; for(j = 0; j < numberOfFeedbacks; j++) { scanf("%i", &feedbackCode); switch (feedbackCode) { case 1: printf("Rolien"); break; case 2: printf("Naej"); break; case 3: printf("Elehcim"); break; case 4: printf("Odranoel"); break; default: break; } printf("\n"); } } }
C
/* Write a function that takes three arguments: a character * and two integers. The character is to be printed. The first * integer specifies the number of times that the character * is to be printed on a line, and the second integer specifies * the number of lines that are to be printed. Write a program * that makes use of this function. */ #include <stdio.h> void chlines(char, int, int); int get_int(void); void flushbuffer(void); int main(void) { char ch; int num_char, num_lines; printf("Enter a character to print: "); ch = getchar(); flushbuffer(); printf("Enter the number of characters that\n" "should be printed on a line: "); num_char = get_int(); printf("Enter the number of lines that are to be printed: "); num_lines = get_int(); chlines(ch, num_char, num_lines); return 0; } void chlines(char ch, int nc, int nl) { int index; while (nl > 0) { for (index = 1; index < nc; index++) putchar(ch); putchar('\n'); nl--; } return; } int get_int(void) { int i; while (scanf("%d", &i) != 1) { flushbuffer(); printf("Please enter an integer value: "); } return i; } void flushbuffer(void) { while (getchar() != '\n') continue; return; }
C
unsigned int h[26],n; int go(int maxh,int cp) { int x,y,max; while(h[cp]>maxh)cp=cp+1; if(h[cp]==0)return 0; x=go(maxh,cp+1); maxh=h[cp]; y=1+go(maxh,cp+1); max=(x>y)?x:y; return max; } int main() { unsigned int i,c,t; scanf("%d",&n); for(i=0;i<n;i++)scanf("%d",&h[i]); h[n]=0; t=go(65535,0); printf("%d",t); return 0; }
C
/* * Project name: C_math (Demonstration of using C Math Library) * Copyright: (c) Mikroelektronika, 2008. * Revision History: 20080110: - initial release; * Description: This program demonstrates usage of standard C math library routines. Compile and run the code through software simulator. * Test configuration: MCU: PIC16F887 http://ww1.microchip.com/downloads/en/DeviceDoc/41291F.pdf Oscillator: HS, 08.0000 MHz Ext. Modules: - SW: mikroC PRO for PIC http://www.mikroe.com/mikroc/pic/ * NOTES: - None. */ const double PI = 3.14159; double doub; char temp_char; static union both { struct flt { unsigned char mant[2]; unsigned hmant:7; unsigned exp:8; unsigned sign:1; } flt; double fl; }; union both uv; void main(){ doub = fabs(-1.3); // 1.3 doub = fabs(-1.3e-5); // 1.3e-5 doub = fabs(1241.3e+15); // 1.2413e18 doub = acos(0.); // 1.570796 doub = acos(0.5); // 1.047198 doub = acos(1.0); // 0.000000 doub = acos(-0.5); // 2.094395 doub = asin(0.); // 0.000000 doub = asin(0.5); // 5.235987e-1 doub = asin(1.0); // 1.570796 doub = asin(-0.5); //-5.235987e-1 doub = atan(0.); // 0.000000 doub = atan(0.5); // 4.636475e-1 doub = atan(1.0); // 7.853982e-1 doub = atan(-1.0); //-7.853982e-1 doub = atan2( 5., 0.); // 0.000000 doub = atan2(2., 1.); // 4.636475e-1 doub = atan2(10., 10.); // 7.853982e-1 doub = atan2(10., -10.); //-7.853982e-1 doub = ceil(0.5); // 1.000000 doub = ceil(-0.5); // 0.000000 doub = ceil(15.258); // 16.000000 doub = ceil(-15.258); //-15.000000 doub = floor(0.5); // 0.000000 doub = floor(-0.5); //-1.000000 doub = floor(15.258); // 15.000000 doub = floor(-15.258); //-16.000000 doub = cos(0.); // 1.000000 doub = cos(PI/2.); // 0.000000 (1.498028e-6) doub = cos(PI/3.); // 0.500008 doub = cos(-PI/3.); // 0.500006 doub = cosh(0.); // 1.000000 doub = cosh(PI/2.); // 2.509176 doub = cosh(PI/3.); // 1.600286 doub = cosh(-PI/3.); // 1.600286 doub = exp(10.25); // 2.828255e+4 doub = exp(0.5); // 1.648721 doub = exp(-0.5); // 0.606530 doub = log10(100.); // 2.000000 doub = log10(500.); // 2.698970 doub = log10(-10.); // invalid (0.00) doub = pow(10.,5.); // 9.999984e+4 doub = pow(10.,-0.5); // 0.316227 doub = sin(0.); // 0.000000 doub = sin(PI/2.); // 1.000000 doub = sin(PI/6.); // 0.499999 doub = sin(-PI/6.); //-0.499999 doub = sinh(0.); // 0.000000 doub = sinh(PI/2.); // 2.301296 doub = sinh(PI/6.); // 0.547853 doub = sinh(-PI/6.); //-0.547853 doub = sqrt(10000.); // 100.0000 doub = sqrt(500.); // 22.36068 doub = sqrt(-100.); // invalid (0.00) doub = tan(-PI/2.); // infinite (-7.626009e+05) doub = tan(0.); // 0.000000 doub = tan(PI/4.); // 0.999998 doub = tan(-PI/4.); //-0.999998 doub = tanh(PI/2.); // 0.917152 doub = tanh(0.); // 0.000000 doub = tanh(PI/4.); // 0.655793 doub = tanh(-PI/4.); //-0.655793 }
C
#include <stdio.h> int main(void) { float balance, rate, monthly_rate, interest, payment; printf("Enter amount of loan: "); scanf("%f", &balance); printf("Enter interest rate: "); scanf("%f", &rate); printf("Enter monthly payment: "); scanf("%f", &payment); monthly_rate = (rate * 0.01f) / 12.0; interest = balance * monthly_rate; balance += interest; balance = balance - payment; printf("Balance after payment 1: $%.2f\n", balance); interest = balance * monthly_rate; balance += interest; balance = balance - payment; printf("Balance after payment 2: $%.2f\n", balance); interest = balance * monthly_rate; balance += interest; balance = balance - payment; printf("Balance after payment 3: $%.2f\n", balance); return 0; }
C
#include <stdio.h> #include <sqlite3.h> #include <stdlib.h> #include <string.h> #include "../address.h" char c_database_name[32] = {0}; /********************** 1、创建数据库文件 2、创建保存联系人信息的表 **********************/ void InitDataBase() { sqlite3 *ppdb; //数据库句柄 int ret = sqlite3_open("address.db", &ppdb); if (ret != SQLITE_OK) { printf("sqlite3_open : %s\n", sqlite3_errmsg(ppdb)); exit(1); } char sql[128] = {0}; //保存数据库语句 sprintf(sql, "create table if not exists address (name text primary key, passwd text);"); ret = sqlite3_exec(ppdb, sql, NULL, NULL, NULL); if (ret != SQLITE_OK) { printf("sqlite3_exec11: %s\n", sqlite3_errmsg(ppdb)); exit(1); } sqlite3_close(ppdb); } void InitDataBase_address() { sqlite3 *ppdb; //数据库句柄 int ret = sqlite3_open("address.db", &ppdb); if (ret != SQLITE_OK) { printf("sqlite3_open : %s\n", sqlite3_errmsg(ppdb)); exit(1); } char sql[128] = {0}; //保存数据库语句 sprintf(sql, "create table if not exists '%s' (name text primary key, tel text);", c_database_name); ret = sqlite3_exec(ppdb, sql, NULL, NULL, NULL); if (ret != SQLITE_OK) { printf("sqlite3_exec11: %s\n", sqlite3_errmsg(ppdb)); exit(1); } sqlite3_close(ppdb); } int i_condition_login = 0; static int send_login(void *para, int columnCount, char **columnValue, char **columnName) { i_condition_login = 1; return 0; } void log_in(Chat *c, int fd) { sqlite3 *ppdb; int result; int ret = sqlite3_open("address.db", &ppdb); if(ret != SQLITE_OK) { printf("sqlite3_open : %s\n", sqlite3_errmsg(ppdb)); } char sql[128] = {0}; sprintf(sql, "select * from address where name = '%s' and passwd = '%s';", c->name, c->passwd); ret = sqlite3_exec(ppdb, sql, send_login, NULL, NULL); if (ret != SQLITE_OK) { printf("sqlite3_exec_add : %s\n", sqlite3_errmsg(ppdb)); } if(1 == i_condition_login) { result = LOGSUCCESS; ret = send(fd, &result, sizeof(result), 0); if(-1 == ret) { perror("send"); } strcpy(c_database_name, c->name); } if(0 == i_condition_login) { result = WRONG; ret = send(fd, &result, sizeof(result), 0); if(-1 == ret) { perror("send"); } } } int i_condition_adduser = 0; static int send_adduser(void *para, int columnCount, char **columnValue, char **columnName) { i_condition_adduser = 1; return 0; } void add_user(Chat *c, int fd) { sqlite3 *ppdb; int result; int ret = sqlite3_open("address.db", &ppdb); if(ret != SQLITE_OK) { printf("sqlite3_open : %s\n", sqlite3_errmsg(ppdb)); } char sql[128] = {0}; sprintf(sql, "select * from address where name = '%s';", c->name); ret = sqlite3_exec(ppdb, sql, send_adduser, NULL, NULL); if (ret != SQLITE_OK) { printf("sqlite3_exec_add : %s\n", sqlite3_errmsg(ppdb)); } if(0 == i_condition_adduser) { sprintf(sql, "insert into address values ('%s', '%s');", c->name, c->passwd); ret = sqlite3_exec(ppdb, sql, NULL, NULL, NULL); if (ret != SQLITE_OK) { printf("sqlite3_exec : %s\n", sqlite3_errmsg(ppdb)); } strcpy(c_database_name, c->name); InitDataBase_address(); result = ADDSUCCESS; ret = send(fd, &result, sizeof(result), 0); if(-1 == ret) { perror("send"); } } else { result = USEREXIST; int ret = send(fd, &result, sizeof(result), 0); if(-1 == ret) { perror("send"); } } sqlite3_close(ppdb); } int sendinfo(void *para, int columnCount, char **columnValue, char **columnName) { int fd = *(int *)para; Chat c; strcpy(c.name, columnValue[0]); strcpy(c.passwd, columnValue[1]); int ret = send(fd, &c, sizeof(c), 0); if(-1 == ret) { perror("send"); } return 0; } void show_user(int fd) { sqlite3 *ppdb; int ret = sqlite3_open("address.db", &ppdb); if (ret != SQLITE_OK) { perror("sqlite3_open"); exit(1); } char sql[128] = "select * from address;"; ret = sqlite3_exec(ppdb, sql, sendinfo, &fd, NULL); if(ret != SQLITE_OK) { printf("sqlite3_exec : %s\n", sqlite3_errmsg(ppdb)); exit(1); } Chat c; strcpy(c.name, "bye"); strcpy(c.passwd, "bye"); ret = send(fd, &c, sizeof(c), 0); if (-1 == ret) { perror("send"); } sqlite3_close(ppdb); } int sendinfo_address(void *para, int columnCount, char **columnValue, char **columnName) { int fd = *(int *)para; Chat c; strcpy(c.name, columnValue[0]); strcpy(c.tel, columnValue[1]); int ret = send(fd, &c, sizeof(c), 0); if(-1 == ret) { perror("send"); } return 0; } void add_info(Chat *c) { sqlite3 *ppdb; int ret = sqlite3_open("address.db", &ppdb); if(ret != SQLITE_OK) { printf("sqlite3_open : %s\n", sqlite3_errmsg(ppdb)); } char sql[128] = {0}; sprintf(sql, "insert into '%s' values ('%s', '%s');", c_database_name, c->name, c->tel); ret = sqlite3_exec(ppdb, sql, NULL, NULL, NULL); if (ret != SQLITE_OK) { printf("sqlite3_exec : %s\n", sqlite3_errmsg(ppdb)); } sqlite3_close(ppdb); } void del_info(Chat *c) { sqlite3 *ppdb; int ret = sqlite3_open("address.db", &ppdb); if(ret != SQLITE_OK) { printf("sqlite3_open : %s\n", sqlite3_errmsg(ppdb)); } char sql[128] = {0}; sprintf(sql, "delete from '%s' where name = '%s';", c_database_name, c->name); ret = sqlite3_exec(ppdb, sql, NULL, NULL, NULL); if (ret != SQLITE_OK) { printf("sqlite3_exec : %s\n", sqlite3_errmsg(ppdb)); exit(1); } sqlite3_close(ppdb); } void update_info(Chat *c, Chat *c1) { sqlite3 *ppdb; int ret = sqlite3_open("address.db", &ppdb); if(ret != SQLITE_OK) { printf("sqlite3_open : %s\n", sqlite3_errmsg(ppdb)); } char sql[128] = {0}; sprintf(sql, "update '%s' set name = '%s', tel = '%s' where name = '%s';", c_database_name, c1->name, c1->tel, c->name); ret = sqlite3_exec(ppdb, sql, NULL, NULL, NULL); if (ret != SQLITE_OK) { printf("sqlite3_exec : %s\n", sqlite3_errmsg(ppdb)); } sqlite3_close(ppdb); } void show_info(int fd) { sqlite3 *ppdb; int ret = sqlite3_open("address.db", &ppdb); if (ret != SQLITE_OK) { perror("sqlite3_open"); exit(1); } char sql[128] = {0}; sprintf(sql, "select * from '%s';", c_database_name); ret = sqlite3_exec(ppdb, sql, sendinfo_address, &fd, NULL); if(ret != SQLITE_OK) { printf("sqlite3_exec : %s\n", sqlite3_errmsg(ppdb)); exit(1); } Chat c; strcpy(c.name, "bye"); strcpy(c.tel, "bye"); ret = send(fd, &c, sizeof(c), 0); if (-1 == ret) { perror("send"); } sqlite3_close(ppdb); } void search_info(Chat *c, int fd) { sqlite3 *ppdb; int ret = sqlite3_open("address.db",&ppdb); if (ret != SQLITE_OK) { perror("sqlite3_open"); exit(1); } char sql[128] = {0}; sprintf(sql,"select * from '%s' where name = '%s';", c_database_name, c->name); ret = sqlite3_exec(ppdb, sql, sendinfo_address, &fd, NULL); if(ret !=SQLITE_OK) { printf("sqlite3_exec : %s\n", sqlite3_errmsg(ppdb)); exit(1); } ret = send(fd,&c,sizeof(c), 0); if(-1 == ret) { perror("send"); } sqlite3_close(ppdb); }
C
#include <stdio.h> #include <stdlib.h> int main() { int i, c; c = 0; for (i = 1; i < 1000; i++) { if(i % 3 == 0 || i % 5 == 0) { c = c + i; printf ("num: %i\n",i); } } printf ("%i\n", c); }