language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
// Filename: peterson_yieldlock_memoryfence.c // Use below command to compile: // gcc -pthread peterson_yieldlock_memoryfence.c -o peterson_yieldlock_memoryfence #include<stdio.h> #include<pthread.h> #include "mythreads.h" int flag[2]; int turn; const int MAX = 1e9; int ans = 0; void lock_init() { // Initialize lock by reseting the desire of // both the threads to acquire the locks. // And, giving turn to one of them. flag[0] = flag[1] = 0; turn = 0; } // Executed before entering critical section void lock(int self) { // Set flag[self] = 1 saying you want // to acquire lock flag[self]=1; // But, first give the other thread the // chance to acquire lock turn = 1-self; // Memory fence to prevent the reordering // of instructions beyond this barrier. __sync_synchronize(); // Wait untill the other thread looses the // desire to acquire lock or it is your // turn to get the lock. while (flag[1-self]==1 && turn==1-self) // Yield to avoid wastage of resources. sched_yield(); } // Executed after leaving critical section void unlock(int self) { // You do not desire to acquire lock in future. // This will allow the other thread to acquire // the lock. flag[self]=0; } // A Sample function run by two threads created // in main() void* func(void *s) { int i = 0; int self = (int *)s; printf("Thread Entered: %d\n",self); lock(self); // Critical section (Only one thread // can enter here at a time) for (i=0; i<MAX; i++) ans++; unlock(self); } // Driver code int main() { pthread_t p1, p2; // Initialize the lock lock_init(); // Create two threads (both run func) Pthread_create(&p1, NULL, func, (void*)0); Pthread_create(&p2, NULL, func, (void*)1); // Wait for the threads to end. Pthread_join(p1, NULL); Pthread_join(p2, NULL); printf("Actual Count: %d | Expected Count:" " %d\n",ans,MAX*2); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_init_convert.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: louregni <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/24 04:55:04 by louregni #+# #+# */ /* Updated: 2019/02/03 05:13:52 by louregni ### ########.fr */ /* */ /* ************************************************************************** */ #include "s_conversion.h" #include "d_info.h" #include "p_chars.h" static void ft_init_char(t_char *charset) { charset[0].conv = 'c'; charset[0].ft_print = &ft_get_char; charset[1].conv = 's'; charset[1].ft_print = &ft_get_string; charset[2].conv = 'p'; charset[2].ft_print = &ft_get_pointer; charset[3].conv = '%'; charset[3].ft_print = &ft_get_char; } static void ft_init_number(t_number *nbr) { nbr->deci[0] = 'i'; nbr->deci[1] = 'd'; nbr->bases[0].conv = 'o'; nbr->bases[0].base = 8; nbr->bases[1].conv = 'x'; nbr->bases[1].base = 16; nbr->bases[2].conv = 'X'; nbr->bases[2].base = 16; nbr->bases[3].conv = 'b'; nbr->bases[3].base = 2; nbr->bases[4].conv = 'u'; nbr->bases[4].base = 10; } void ft_init_convert(t_conv *conv) { ft_init_number(&conv->nbr); ft_init_char(conv->charset); }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* push_swap.h :+: :+: */ /* +:+ */ /* By: lverdoes <lverdoes@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2021/03/03 15:24:14 by lverdoes #+# #+# */ /* Updated: 2021/07/13 12:49:24 by lverdoes ######## odam.nl */ /* */ /* ************************************************************************** */ #ifndef PUSH_SWAP_H # define PUSH_SWAP_H # define SPACE " " # define SPLIT_CHARS "\n \t" # define ERROR "Error" # include "ft_list.h" # include <stdio.h> typedef enum e_id { STACK_A, STACK_B, } t_id; typedef enum e_cmd { PA, PB, SA, SB, SS, RA, RB, RR, RRA, RRB, RRR, } t_cmd; typedef struct s_eleminfo { size_t rank; size_t index; } t_info; typedef struct s_element { size_t rank; int num; } t_elem; typedef struct s_data { int count[11]; int total_push; int total_rots; int total_swap; int total; } t_data; typedef struct s_args { char **args; size_t size; } t_args; typedef struct s_stack { t_list *head; t_list *tail; size_t size; size_t high; size_t low; size_t pos_high; size_t pos_low; t_id id; } t_stack; typedef struct s_variables { t_stack a; t_stack b; size_t total_size; size_t max_rank; t_args args; t_data data; int (*cmd[11])(struct s_variables *); } t_vars; /* init */ void init(t_vars *v, size_t size, char **argv); void check_args(t_vars *v, int argc, char **argv); void check_minmax_int(char *str); void check_digits(char *str); void check_duplicate(t_vars *v, int num, t_list **head_sorted); /* utils */ int ft_exit(char *str); void check_malloc(void *ptr); int intcmp(t_elem *a, t_elem *b); int rankcmp(int *ref, t_elem *e); int finished(t_stack *a, t_stack *b); void print_data(t_vars *v); /* searching */ void find_highest_rank(t_stack *s); void find_lowest_rank(t_stack *s); int push_back(t_stack *a, t_stack *b); int is_correct_rotation_order(t_stack *s); int shortest_path(t_stack *s, size_t pos, size_t limit); /* cmds */ void **cmd(t_cmd cmd, size_t amount); /* solve */ int solve_small(t_stack *a, t_stack *b); int solve_medium(t_stack *a, t_stack *b); int solve_large11(t_vars *v); int solve_huge49(t_vars *v); int solve_huge49edit(t_vars *v); #endif
C
#include "hashMap.h" #include <assert.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /** * Allocates a string for the next word in the file and returns it. This string * is null terminated. Returns NULL after reaching the end of the file. * @param file * @return Allocated string or NULL. */ char* nextWord(FILE* file) { int maxLength = 16; int length = 0; char* word = malloc(sizeof(char) * maxLength); while (1) { char c = fgetc(file); if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '\'') { if (length + 1 >= maxLength) { maxLength *= 2; word = realloc(word, maxLength); } word[length] = c; length++; } else if (length > 0 || c == EOF) { break; } } if (length == 0) { free(word); return NULL; } word[length] = '\0'; return word; } /** * Loads the contents of the file into the hash map. * @param file * @param map */ void loadDictionary(FILE* file, HashMap* map) { assert(file != 0); assert(map != 0); char* word = nextWord(file); while(word != NULL){ hashMapPut(map, word, 1); free(word); word = nextWord(file); } } // with assistance from: // https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#C #define MIN3(a, b, c) ((a) < (b) ? ((a) < (c) ? (a) : (c)) : ((b) < (c) ? (b) : (c))) int levenshtein(char *s1, char *s2) { unsigned int s1len, s2len, x, y, lastdiag, olddiag; s1len = strlen(s1); s2len = strlen(s2); unsigned int column[s1len+1]; for (y = 1; y <= s1len; y++) column[y] = y; for (x = 1; x <= s2len; x++) { column[0] = x; for (y = 1, lastdiag = x-1; y <= s1len; y++) { olddiag = column[y]; column[y] = MIN3(column[y] + 1, column[y-1] + 1, lastdiag + (s1[y-1] == s2[x-1] ? 0 : 1)); lastdiag = olddiag; } } return(column[s1len]); } // updates all values in dictionary compared to levenshtein distance of input word void updateValues(HashMap* map, char* inputWord){ assert(map != 0); assert(inputWord != 0); for(int i=0; i < map->capacity; i++){ HashLink *temp = map->table[i]; while(temp != NULL){ int value = levenshtein(temp->key, inputWord); hashMapPut(map, temp->key, value); temp = temp->next; } } } struct suggestedArray { char word[5][100]; int size; }; // searches through hashmap for words with the lowest levenshtein distance and adds them to // a struct suggestedArray. returns that struct struct suggestedArray *suggestions(HashMap* map){ assert(map != 0); struct suggestedArray *suggestedWords = malloc(sizeof(struct suggestedArray)); assert(suggestedWords != 0); suggestedWords->size = 0; int lowestValue = 1; while(suggestedWords->size < 5){ for(int i=0; i < map->capacity; i++){ HashLink *temp = map->table[i]; while(temp != NULL && suggestedWords->size < 5){ if(temp->value == lowestValue){ strcpy(suggestedWords->word[suggestedWords->size], temp->key); suggestedWords->size++; } temp = temp->next; } } lowestValue++; } return suggestedWords; } /** * Checks the spelling of the word provded by the user. If the word is spelled incorrectly, * print the 5 closest words as determined by a metric like the Levenshtein distance. * Otherwise, indicate that the provded word is spelled correctly. Use dictionary.txt to * create the dictionary. * @param argc * @param argv * @return */ int main(int argc, const char** argv) { HashMap* map = hashMapNew(1000); FILE* file = fopen("dictionary.txt", "r"); clock_t timer = clock(); loadDictionary(file, map); timer = clock() - timer; printf("Dictionary loaded in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC); fclose(file); char inputBuffer[256]; int quit = 0; while (!quit) { printf("Enter a word or \"quit\" to quit: "); scanf("%s", inputBuffer); for(int i=0; i <= strlen(inputBuffer); i++) { inputBuffer[i] = tolower(inputBuffer[i]); } // Implement the spell checker code here.. if(hashMapContainsKey(map, inputBuffer) == 1){ printf("The inputted word %s is spelled correctly.\n", inputBuffer); } else { printf("The inputted word %s is spelled incorrectly.\n", inputBuffer); printf("Did you mean:\n"); updateValues(map, inputBuffer); struct suggestedArray *array = suggestions(map); for(int i=0; i < array->size; i++){ printf("%s\n", array->word[i]); } free(array); } if (strcmp(inputBuffer, "quit") == 0) { quit = 1; } } hashMapDelete(map); return 0; }
C
#include <stdio.h> int inRange(int value) { int mask = (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5) | (1 << 6); //* this is 00000001111100 mask = ~mask; value = value & mask; return value; } int main() { int a; a = 276; //*this is 1 0001 0100 printf("%i", inRange(a)); return 0; }
C
#include <stdio.h> #include <string.h> int main() { char str1[100],str2[100],c[100]; gets (str1); gets (str2); int i,j,k,sum=0; if(strlen(str1)>strlen(str2)) { strcpy(c,str2); strcpy(str2,str1); strcpy(str1,c); } for (i=0;i<strlen(str1);i++) { for (j=0+k;j<strlen(str2);j++) { if (str1[i]==str2[j]) { sum++; k=j; break; } } } printf("%d",sum); return 0; }
C
/** * @file tri_bulle.c * @author Louis MORAND, Benoit ARQUILLIERE * @brief Faire le tri d'un tableau donné en paramètre par bulle * @version 2 * @date 2021-10-09 * * @copyright Copyright (c) 2021 * */ #include <stdio.h> #include "tri_bulle.h" /** * @brief Faire le tri d'un tableau donné en paramètre par bulle * Trie les valeurs du tableau 2 à 2, en bouclant sur le tableau jusqu'a ce qu'il soit trié. * * @param[in] tab Tableau à trier * @param[in] tailletab Taille du tableau passé en paramètre */ void tri_bulle (float *tab, int tailletab){ //on ne peux pas trouver la taille du tableau via sizeoftab/sizeof(char), donc on la passe en parametre float val_inter; int nb_chmgt;//le nombre de changements encore à réaliser sur le tableau do{ nb_chmgt = 0; for (int i =0; i<tailletab-1; i++){ if(tab[i] > tab[i+1]){//Inversion des valeurs du tableau en cas de valeur plus grande située avant une plus petite val_inter = tab[i]; tab[i]=tab[i+1]; tab[i+1]=val_inter; } }//Recherche du nombre de changements encore à réaliser, et donc si le programme doit boucler ou non for (int i =0; i<tailletab-1; i++){ if(tab[i] > tab[i+1]){ nb_chmgt++; } } }while(nb_chmgt !=0); }
C
/* * (C) 2015 Key Zhang * @buildin.c * @Feature: To run buildin commands like : cd pwd clr ... */ #include "buildin.h" #include <stdio.h> #include <string.h> #include <dirent.h> #include <errno.h> #include <time.h> /*Help string*/ char *Help[]={ "help:" }; /*get file stat*/ int stat(const char *path, struct stat *buf); /*run buildin cmds*/ int buildin(/*0: Is not a buildin cmd */ /*1: Is a buildin cmd*/ int arg_c, /*argument count*/ char arg[][MAXLEN + 1] /*arguments*/ ) { /*compare cmds*/ if (!strcmp(arg[0],"cd")) { if (arg_c) b_cd(arg[1]); else b_pwd(); return 1; } if (!strcmp(arg[0],"pwd")) { b_pwd(); return 1; } if (!strcmp(arg[0],"clr")) { b_clr(); return 1; } if (!strcmp(arg[0],"dir")) { if (arg_c > 0) b_dir(arg[1]); else b_dir("."); return 1; } if (!strcmp(arg[0],"echo")) { b_echo(arg_c,arg); return 1; } if (!strcmp(arg[0],"help")) { b_help(); return 1; } if (!strcmp(arg[0],"quit")) { b_quit(); return 1; } if (!strcmp(arg[0],"environ")) { b_env(); return 1; } return 0; } static void b_cd ( /*run cd cmd*/ const char *dst /*dst directory*/ ) { if (dst[0] != 0){ if (!chdir(dst)){ getcwd(pwd,MAXLEN); /* update the current work director */ } else{ /* error process */ if (errno == ENOENT){ fprintf(stdout, "mysh: cd: %s: No such file or directory\n", dst); errno = 0; /* resume */ } else if (errno == ENOTDIR){ fprintf(stdout, "mysh: cd: %s: Not a directory\n", dst); errno = 0; } } } } /*print pwd*/ static void b_pwd() { fprintf(stdout, "%s\n", pwd); } /*clean the screen*/ static void b_clr() { printf("%c%c%c%c%c%c",27,'[','H',27,'[','J' ); } /*show files in the directory*/ static void b_dir(char * dir) { b_ls(dir); } /*echo messages on screen*/ static void b_echo( int arg_c, /*arguments count*/ char arg[][MAXLEN + 1] /*arguments*/ ) { for (int i = 1; i < arg_c; ++i) { fflush(stdout); fprintf(stdout, "%s ", arg[i]); } fprintf(stdout, "%s\n", arg[arg_c]); } /*print help message with more*/ static void b_help() { FILE *fp = fopen("Readme","r"); if (fp==NULL) { fprintf(stderr,"Manual not exist!\n"); return 1; } b_more(fp); } /*quit the shell*/ static void b_quit() { exit(0); } /*show env vars*/ static void b_env() { for (int i = 0; environ[i]; ++i) { fprintf(stdout, "%s\n", environ[i]); } } /*******************************/ /* Private Functions */ /*******************************/ /*more function */ /* To print a long message in parts*/ #define PAGELEN 24 #define LINELEN 512 void b_more( FILE * fp /*The file to print*/ ) { char line[LINELEN]; /* Text Buffer */ int num_of_lines = 0; /* Count of the lines printed*/ int reply; /* The reply of user*/ while (fgets(line, LINELEN, fp)) { if (num_of_lines == PAGELEN) { reply = see_more(); if (reply == 0) break; num_of_lines -= reply; } if (fputs(line, stdout) == EOF) return; num_of_lines++; } } int see_more() { int c; printf("\033[7m more?\033[m"); while ((c = getchar()) != EOF) { if (c == 'q') return 0; if (c == ' ') return PAGELEN; if (c == '\n') return 1; } return 0; } /* Show files unsder the dir*/ static void b_ls(char dirname[]) { DIR *dir_ptr; /*The directory to read*/ struct dirent *direntp; /*The dir info struct*/ if((dir_ptr = opendir(dirname)) == NULL) /* Try to open the dir*/ fprintf(stderr,"ls:cannot open %s\n",dirname); else { while((direntp = readdir(dir_ptr)) != NULL) /* Read the dir info */ dostat(direntp->d_name, dirname); /* */ closedir(dir_ptr); /* Close the dir */ } } /* Analyse the file/dir */ void dostat(char *filename, char *dir) { struct stat info; /* Turn filename into pathname*/ char buf[MAXLEN] = ""; strcat(buf,dir); if (buf[strlen(buf) -1] != '/') /* add '/' if not appended*/ strcat(buf,"/"); strcat(buf,filename); /* Append filename */ if(stat(buf,&info) == -1) perror(filename); else show_file_info(filename,&info); } /* Get username from uid */ #include <pwd.h> char *uid_to_name(uid_t uid) { struct passwd *getpwuid(),*pw_ptr; static char numstr[10]; if((pw_ptr = getpwuid(uid)) == NULL){ sprintf(numstr,"%d",uid); return numstr; } else return pw_ptr->pw_name; } /* Get groupname from gid */ #include <grp.h> char *gid_to_name(gid_t gid) { struct group *getgrgid(),*grp_ptr; static char numstr[10]; if((grp_ptr = getgrgid(gid)) == NULL){ sprintf(numstr,"%d",gid); return numstr; } else return grp_ptr->gr_name; } /* Print the file info */ void show_file_info(char *filename,struct stat *info_p) { char modestr[11]; /* String of the mode */ mode_to_letters(info_p->st_mode,modestr); fprintf(stdout, "%s",modestr); fprintf(stdout, "%2d ",(int)info_p->st_nlink); fprintf(stdout, "%-7s",uid_to_name(info_p->st_uid)); fprintf(stdout, "%-7s",gid_to_name(info_p->st_gid)); fprintf(stdout, "%5ld",(long)info_p->st_size); fprintf(stdout, " %.12s",4+ctime(&(info_p->st_mtime))); fprintf(stdout, " %s\n",filename); } /* Turn authority to str */ void mode_to_letters(int mode,char str[]) { strcpy(str,"----------"); /*Initial string*/ /*Type*/ if(S_ISDIR(mode))str[0] = 'd'; if(S_ISCHR(mode))str[0] = 'c'; if(S_ISBLK(mode))str[0] = 'b'; /*user authority*/ if(mode&S_IRUSR)str[1] = 'r'; if(mode&S_IWUSR)str[2] = 'w'; if(mode&S_IXUSR)str[3] = 'x'; /*group authority*/ if(mode&S_IRGRP)str[4] = 'r'; if(mode&S_IWGRP)str[5] = 'w'; if(mode&S_IXGRP)str[6] = 'x'; /*other authority*/ if(mode&S_IROTH)str[7] = 'r'; if(mode&S_IWOTH)str[8] = 'w'; if(mode&S_IXOTH)str[9] = 'x'; }
C
#include "ft_init_terminal.h" int ft_init_terminal(struct termios *orig_termios, struct termios *new_termios) { char *term_name; int ret; if ((term_name = getenv("TERM")) == NULL) return (-1); ret = tgetent(NULL, term_name); if (ret == -1) { printf("Could not access to the termcap database..\n"); return (-1); } else if (ret == 0) { printf("Terminal type '%s' is not defined in termcap database (or have too few informations).\n", term_name); return (-1); } tcgetattr(STDIN_FILENO, orig_termios); *new_termios = *orig_termios; // new_termios->c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); // new_termios->c_oflag &= ~(OPOST); // new_termios->c_cflag |= (CS8); // new_termios->c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); new_termios->c_lflag &= ~(ICANON | ECHO); new_termios->c_lflag |= ISIG; new_termios->c_cc[VMIN] = 1; new_termios->c_cc[VTIME] = 1; tcsetattr(0, TCSAFLUSH, new_termios); return (0); }
C
#include <stdio.h> #include <stdlib.h> typedef struct PilhaNo cabeca; typedef struct Pilha little; struct PilhaNo { little * primeiro; }; struct Pilha { int numero; little * priximaLista; }; cabeca* inicializarLista(void){ cabeca * novoNo = (cabeca*) malloc(sizeof(cabeca)); novoNo -> primeiro = NULL; printf("Lista Inicializada.\n"); return novoNo; } void adcionarPilha(cabeca *l, int numeroAdd){ little * novoNo = (little*) malloc(sizeof(little)); novoNo->numero = numeroAdd; novoNo->priximaLista = l->primeiro; l-> primeiro = novoNo; printf("Elemento inserido com sucesso.\n"); } void removerPilha(cabeca *l){ little *p = l->primeiro; l->primeiro = p->priximaLista; free(p); } void imprimirLista(cabeca * l){ little* p; for (p = l->primeiro; p !=NULL; p = p->priximaLista){ printf("%i\n",p->numero); } } int main(void) { cabeca * inicio = inicializarLista(); adcionarPilha(inicio, 10); adcionarPilha(inicio, 5); adcionarPilha(inicio, 110); imprimirLista(inicio); printf("\n"); removerPilha(inicio); imprimirLista(inicio); printf("\n"); removerPilha(inicio); imprimirLista(inicio); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include <sys/time.h> double rtclock() { struct timezone Tzp; struct timeval Tp; int stat; stat = gettimeofday (&Tp, &Tzp); if (stat != 0) printf("Error return from gettimeofday: %d",stat); return(Tp.tv_sec + Tp.tv_usec*1.0e-6); } #define size 10000 #define NT 8 int A[size][size]; int B[size][size]; int C[size][size]; int flag[size];//to set flag[i]==1 if arr[i] is maximum int main(int argc, char *argv[]){ if(argc!=2){ printf("Usage path-to-executable seedvalue (example usage: ./a.out 3)\n"); exit(0); } srand(atoi(argv[1]));//Seed for random number command line integer value //generates random number for(int i=0;i<size;i++){ for(int j=0;j<size;j++){ A[i][j]=rand()%1048576; B[i][j]=rand()%1048576; } } double t1=rtclock(); #pragma omp parallel for num_threads(8) for(int i=0;i<size;i++) for(int j=0;j<size;j++) C[j][i]=A[j][i]+B[j][i]; double t2=rtclock(); printf("\nTIME =%f \n",(t2-t1)*1000); } /*Run executable-path <integer-seed-value> *example: ./a.out 3 */
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { char* text = NULL; size_t size = 0; ssize_t len = getline(&text, &size, stdin); if (len > 0) { if (text[len - 1] == '\n') { text[len - 1] = '\0'; len = len - 1; } char lastLetter = text[0]; int lastIndex = 1; int i; for (i = 1; i < len; i++) { if (text[i] == lastLetter) { continue; } text[lastIndex] = text[i]; lastLetter = text[i]; lastIndex++; } text[lastIndex] = '\0'; printf("%s", text); } return (EXIT_SUCCESS); }
C
#include <stdio.h> #include <dirent.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "autil.h" #include "util.h" //char cryptokey[]=DEFAULTTABLE; char cryptokey[]="aBcDeFgHiJkLmNoPqRsTuVwXyZ"; void CryptoKey(char* usrkey) { int cryptokeylen = strlen(cryptokey); int i; for(i=0;i<strlen(usrkey);i++) { if(usrkey[i]=='\n')continue; usrkey[i]++; if(usrkey[i]==cryptokey[i%cryptokeylen])continue; if((usrkey[i]^cryptokey[i%cryptokeylen]) == '\n')continue; usrkey[i] ^= cryptokey[i%cryptokeylen]; } } void DecryptKey(char* usrkey) { int cryptokeylen = strlen(cryptokey); int i; for(i=0;i<strlen(usrkey);i++) { if(usrkey[i]=='\n')continue; if(usrkey[i]==cryptokey[i%cryptokeylen]){ usrkey[i]--; continue; } if((usrkey[i]^cryptokey[i%cryptokeylen]) == '\n'){ usrkey[i]--; continue; } usrkey[i] ^= cryptokey[i%cryptokeylen]; usrkey[i]--; } } void List(char *path) { struct dirent* ent = NULL; char filename[256]; DIR *pDir; pDir=opendir(path); while(NULL != (ent=readdir(pDir))) { if(ent->d_name[0] == '.')continue; if (ent->d_type==8){ char line[1024]; if( ent->d_name == NULL ||strlen( ent->d_name ) < 1 ||ent->d_name[strlen(ent->d_name)-1] == '~' ||ent->d_name[0] == '#' ||strcmptail( ent->d_name, ".bak" ) == 0 ||strcmp( path, "attmagic.bin" ) == 0)continue; sprintf(filename, "%s/%s", path, ent->d_name); FILE * f1 = fopen(filename,"r"); sprintf(filename, "allblues/%s/%s.allblues", path, ent->d_name); remove( filename); FILE * f2 = fopen(filename,"a+"); while( fgets( line, sizeof( line ), f1 ) ){ CryptoKey(line); fputs(line,f2); } fclose(f1); fclose(f2); }else{ if( strcmp( path, "data" ) == 0 && (strcmp( ent->d_name, "autopk" ) == 0 || strcmp( ent->d_name, "map" ) == 0))continue; sprintf(filename, "allblues/%s/%s", path, ent->d_name); if(opendir(filename)==NULL){ if(mkdir(filename, 0x777) == 0){ printf("建立加密文件夾 %s\n", filename); } } sprintf(filename, "%s/%s", path, ent->d_name); List(filename); } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* replace_alias.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mgorczan <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/27 21:53:04 by mgorczan #+# #+# */ /* Updated: 2019/10/27 21:53:05 by mgorczan ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" static void update_args(char ***args) { char **temp; char *temp_str; int total_len; int i; temp = *args; total_len = 0; i = -1; while (temp[++i]) total_len += ft_strlen(temp[i]) + 1; temp_str = ft_strnew(total_len); i = -1; while (temp[++i]) { ft_strcpy(temp_str + ft_strlen(temp_str), temp[i]); ft_strcpy(temp_str + ft_strlen(temp_str), " "); } i = -1; while (temp[++i]) ft_strdel(&temp[i]); ft_memdel((void**)args); *args = write_arg(temp_str); ft_strdel(&temp_str); } static char **replace_on_alias(char **args, int i) { char *str; str = alias_get(args[i]); if (ft_strcmp(str, "") != 0 && ft_strcmp(args[0], "alias") != 0) { ft_strdel(&args[i]); args[i] = str; update_args(&args); } else ft_strdel(&str); return (args); } char **replace_alias(char **argv) { if (argv && argv[0]) argv = replace_on_alias(argv, 0); return (argv); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* env.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cboussau <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/03/25 14:55:13 by cboussau #+# #+# */ /* Updated: 2016/04/04 21:01:00 by cboussau ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" void print_env(t_lst *node) { t_lst *tmp; tmp = node; while (node) { if (!node->line) node = node->next; else { ft_putendl(node->line); node = node->next; } } node = tmp; } static char *cmp_line(t_lst *node, char **arg, char *save) { t_lst *tmp; tmp = node; while (node) { if (ft_strccmp(node->line, *arg, '=') == 0) { save = ft_strdup(node->line); node->line = ft_strdup(*arg); return (save); } node = node->next; } node = tmp; save = NULL; if (!save) { if (check_caract(*arg, '=') == 1) add_elem(node, *arg); else if (check_caract(*arg, '=') != 1) deal_with_command(node, arg); else print_error_opt(*arg); } return (save); } static char **deal_with_arg(t_lst *node, char **arg) { char **save; int i; int j; i = 0; j = 0; while (arg[i]) i++; save = malloc_tab(i); i = 0; while (*arg) { save[i] = cmp_line(node, arg, save[i]); if (!save[i] && *arg && check_caract(*arg, '=') == 1) j++; i++; arg++; } if (j > 0) print_env(node); while (j-- > 0) node = delete_elem(node); return (save); } void restore_env(t_lst *node, char **save) { t_lst *tmp; tmp = node; while (*save) { while (node) { if (ft_strncmp(node->name, *save, ft_strlen(node->name)) == 0) node->line = ft_strdup(*save); node = node->next; } node = tmp; save++; } } int deal_with_env(t_lst *node, char *line) { char **save; char **arg; arg = ft_strsplit(line, ' '); arg++; if (*arg) { if (*arg[0] == '-') save = deal_with_opt(node, arg); else save = deal_with_arg(node, arg); if (!save || !*save) return (-1); restore_env(node, save); free(save); } else print_env(node); return (-1); }
C
#include <stdio.h> int main(int arg, char *argv[]){ int n; const int m=100; n=5; printf("%d\n",n); n=10; printf("%d\n",n); printf("%d\n",m); n=n+5; printf("n=10 %d\n",n); n=n-10; printf("%d\n",n); n=n*3; printf("%d\n",n); n=n/2; printf("%d\n",n); n=n%2; printf("%d\n",n); return 0; }
C
/* Example - To copy a structure to another structure */ # include <stdio.h> # include <string.h> struct date { char month[6]; int day,year; }; void main(void) { struct date tomorrow={"March",1,2011},yesterday, today; /* copying element by element basis */ strcpy(today.month,tomorrow.month); today.day=tomorrow.day; today.year=tomorrow.year; /* copying entire structure to another structure */ yesterday=today; printf("\nYesterday\'s date is %d-%s-%d \n", yesterday.day, yesterday.month,yesterday.year); getch(); return 0; }
C
/* Given a binary tree, compute its "maxDepth" -- the number of nodes along the longest path from the root node down * to the farthest leaf node * * 4 * / \ * 2 5 * / \ / \ * 1 3 4 7 * / \ * 6 8 * \ * 9 */ #include<stdio.h> #include<stdlib.h> struct node{ int data; struct node *right; struct node *left; }; struct node *build(void); void print(struct node *root); int maxDepth(struct node *node); struct node *insert(struct node *root,int data); main() { struct node *root; root=build(); printf("\n\n"); print(root); printf("\n\n"); printf("\nmaxm depth is : %d\n\n",maxDepth(root)); } int maxDepth(struct node *node) { int l,r; l=r=1; if(node == NULL) return 0; if(node->left != NULL) l = 1 + maxDepth(node->left); if(node->right != NULL) r = 1 + maxDepth(node->right); return l>=r ? l : r; } struct node *build(void) { int i,len; int a[]={4,2,5,1,3,4,7,8,6,9}; struct node *root=NULL; len=sizeof(a)/sizeof(int); for(i=0;i<len;++i) root=insert(root,a[i]); return root; } struct node *insert(struct node *root,int data) { if(root == NULL){ root=malloc(sizeof(*root)); root->data=data; root->right=root->left=NULL; } else if(data < root->data) root->left=insert(root->left,data); else root->right=insert(root->right,data); return root; } void print(struct node *root) { if(root != NULL){ print(root->left); printf("\t%d",root->data); print(root->right); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* loop_hook.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: twalton <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/08/22 15:06:04 by twalton #+# #+# */ /* Updated: 2017/08/22 15:06:04 by twalton ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractal.h" static void change_iter(t_fract *fract, char sign) { struct timespec tim; tim.tv_sec = 0; tim.tv_nsec = 50000000; if (sign == '-') { if (fract->max_it > 1) --fract->max_it; } else { if (fract->max_it < 199) ++fract->max_it; } redraw_fract(fract); nanosleep(&tim, NULL); } static void fractal_loop(t_fract *fract) { if (fract->keytog->q) zoom_fract(fract, '+'); if (fract->keytog->e) zoom_fract(fract, '-'); if (fract->keytog->w) move_fract(fract, '+', '\0'); if (fract->keytog->s) move_fract(fract, '-', '\0'); if (fract->keytog->a) move_fract(fract, '\0', '+'); if (fract->keytog->d) move_fract(fract, '\0', '-'); if (fract->keytog->z) change_iter(fract, '-'); if (fract->keytog->x) change_iter(fract, '+'); } int loop_hook(t_info *info) { if (info->julia) fractal_loop(info->fjulia); if (info->mand) fractal_loop(info->fmand); if (info->theo) fractal_loop(info->ftheo); if (info->forth) fractal_loop(info->fforth); if (info->five) fractal_loop(info->ffive); if (info->cool) fractal_loop(info->fcool); return (0); }
C
#include <stdio.h> #include<math.h> int main(void) { int i,t; scanf("%d",&t); for(i=0;i<t;i++) { int a,b,c,d,e,f,g; scanf("%d %d %d %d",&a,&b,&c,&d); e=(a+c-b)/2; //apples f=(a+b-c)/2; //mangoes g=(b+c-a)/2; printf("\n%d %d %d",e,f,g); } // your code goes here return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "IntList.h" IntList createIntList() { IntList list; /* list.size = 0; */ return list; } void initialiseIntList(IntList * intList) { memset(intList, 0, sizeof(IntList)); /* intList->size = 0; */ } int fillIntList(IntList * intList) { int i; for(i = 0; i < INTLIST_SIZE; i++) { intList->list[i] = rand() % INTLIST_RANGE; intList->size++; } return EXIT_SUCCESS; } int insertIntList(IntList * intList, int value) { int i, insertPosition; /* bounds check */ if(intList->size == INTLIST_SIZE) return EXIT_FAILURE; /* find position */ for(i = 0; i < intList->size; i++) { if(value < intList->list[i]) { break; /* i++ in for does not apply if you do break */ } } insertPosition = i; /* insert */ intList->size++; for(i = intList->size - 1; i > insertPosition; i--) { intList->list[i] = intList->list[i-1]; } intList->list[insertPosition] = value; return EXIT_SUCCESS; } int removeIntList(IntList *intList, int value) { int i; for(i = 0; i < intList->size; i++) { if(i == value) { break; } } if(i == intList->size) { return EXIT_FAILURE; } for(; i < intList->size - 1; i++) { intList->list[i] = intList->list[i+1]; } intList->size--; return EXIT_SUCCESS; } void displayIntList(IntList * intList) { int i; for(i = 0; i < intList->size; i++) { printf("pos %d: %d\n", i, intList->list[i]); } printf("size = %d\n", intList->size); } void copyIntList(IntList *start, IntList *dest) { int i; for(i = 0; i < start->size; i++) { dest->list[i] = start->list[i]; } dest->size = start->size; }
C
#include <sys/time.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <stdio.h> int ft_strlen(char *s) { int i; i = 0; while (s[i] != '\0') ++i; return (i); } void ft_putchar(char c) { write(1, &c, 1); } int ft_error(char *str) { write(2, str, ft_strlen(str)); return (0); } void ft_putnbr(int n) { long nb; nb = n; if (nb < 0) { ft_putchar('-'); nb *= -1; } if (nb >= 10) { ft_putnbr(nb / 10); ft_putnbr(nb % 10); } else ft_putchar(nb + '0'); } char *ft_strdup(const char *s1) { int i; int length; char *result; length = 0; while (s1[length]) length++; if (!(result = (char *)malloc(sizeof(char) * (length + 1)))) return (0); i = 0; while (i < length) { result[i] = s1[i]; i++; } result[i] = '\0'; return (result); } void ft_putstr(char *str) { write(1, str, ft_strlen(str)); } int ft_atoi(const char *str) { int sign; int result; int i; i = 0; while ((9 <= str[i] && str[i] <= 13) || str[i] == 32) i++; sign = 1; if (str[i] == '+' || str[i] == '-') { if (str[i] == '-') sign *= -1; i++; } result = 0; while (str[i] >= '0' && str[i] <= '9') { result = result * 10 + (str[i] - '0'); i++; } return (result * sign); } typedef struct s_philo { int p_idx; pthread_t thread; pthread_t m_thread; int n_eat; unsigned long start_time; unsigned long last_eat_time; } t_philo; typedef struct s_vars { int n_philo; int t_die; int t_eat; int t_sleep; int n_must_eat; int n_alive; int flag_died; t_philo *philo; pthread_mutex_t *forks; pthread_mutex_t *eats; pthread_mutex_t pickup; pthread_mutex_t putdown; pthread_mutex_t alive; pthread_mutex_t print; pthread_mutex_t someone_died; // pthread_m } t_vars; typedef enum e_status { THINKING, EATING, SLEEPING, FORK_TAKEN, DIED } t_status; unsigned long get_time(void) { struct timeval tv; if (gettimeofday(&tv, 0)) return (0); //miliseconds(1000ms == 1sec)로 표현 //sec-km / ms-m / microsec(usec)-mm return (tv.tv_sec * 1000 + tv.tv_usec / 1000); } t_vars *get_vars(void) { static t_vars vars; return(&vars); } void print_status_body(t_vars *vars, t_philo *philo, t_status status, char *phrase) { unsigned long time; int philo_no; //인덱스는 0부터 시작하니까 philo_no = philo->p_idx + 1; pthread_mutex_lock((&vars->print));//print 스레드 lock time = get_time() - philo->start_time;//현재 시간 - 최초 시작 시간, 즉 흐른시간 pthread_mutex_lock(&vars->someone_died); if (vars->flag_died) { pthread_mutex_unlock(&vars->someone_died); return ; } pthread_mutex_unlock(&vars->someone_died); ft_putnbr(time); ft_putstr(" "); ft_putnbr(philo_no);//철학자 번호 ft_putstr(phrase);//뭐하고 있는지 free(phrase); if (!(status == DIED)) pthread_mutex_unlock(&vars->print); } int print_status(t_vars *vars, t_philo *philo, t_status status) { char *phrase; phrase = 0; if (status == THINKING) phrase = ft_strdup(" is thinking\n"); else if (status == EATING) phrase = ft_strdup(" is eating\n"); else if (status == SLEEPING) phrase = ft_strdup(" is sleeping\n"); else if (status == DIED) phrase = ft_strdup(" died\n"); else if (status == FORK_TAKEN) phrase = ft_strdup(" has taken a fork\n"); if (phrase == 0) return (0); print_status_body(vars, philo, status, phrase); return (1); } void ft_usleep(unsigned long time) { unsigned long start; unsigned long time_elapsed; start = get_time(); while (1) { time_elapsed = get_time() - start; if (time_elapsed >= time) break ; usleep(1); } } int taken_fork_and_eat(t_vars *vars, t_philo *philo) { int idx; idx = philo->p_idx; pthread_mutex_lock(&vars->pickup);//포크 하나 들었어 pthread_mutex_lock(&vars->forks[idx]);//해당 포크 lock 걸어 print_status(vars, philo, FORK_TAKEN); //그 포크 taken 됨!!! pthread_mutex_lock(&vars->forks[(idx + 1) % vars->n_philo]);//바로 옆에 있는 포크 lock 걸게 함 print_status(vars, philo, FORK_TAKEN);//그것도 포크 taken 됨!!! pthread_mutex_unlock(&vars->pickup);//두개 들었으니까 pickup 은 lock 해제 pthread_mutex_lock(&vars->eats[idx]);//이제 먹는거 lock 걸어 philo->last_eat_time = get_time();//마지막으로 먹은 시간 구해 pthread_mutex_unlock(&vars->eats[idx]);//구했으니 lock 해제 print_status(vars, philo, EATING);// 이제 먹음!!! ft_usleep(vars->t_eat);//먹는 행동을 한다 pthread_mutex_lock(&vars->putdown);//포크 이제 내려놔 pthread_mutex_unlock(&vars->forks[idx]);//해당 포크 lock 해제 pthread_mutex_unlock(&vars->forks[(idx + 1) % vars->n_philo]);//바로 옆에 있는 포크 lock 해제 pthread_mutex_unlock(&vars->putdown);//포크 내려놨으니까 putdown은 lock 해제 if ((++(philo->n_eat) == vars->n_must_eat))//최소 먹어야 하는 숫자 채우면 시뮬레이션 끝내 return (0); return (1); } void *philosophing(void *v_philo) { t_vars *vars; t_philo *philo; vars = get_vars(); philo = (t_philo *)v_philo; while (1) { print_status(vars, philo, THINKING);//생각한다고 말해 if (!taken_fork_and_eat(vars, philo))//포크를 들고 먹지 않으면 break break ; print_status(vars, philo, SLEEPING);//잠잔다고 말해 ft_usleep(vars->t_sleep);//잠을 자 } pthread_mutex_lock(&vars->alive);//삶과 죽음을 주관하는 함수를 lock vars->n_alive -= 1;//먹어야 하는 최소횟수 다 채우고 죽음(죽을 때 되어서 죽었다) pthread_mutex_unlock(&vars->alive);//삶과 죽음을 주관하는 함수를 lock 해제 return (philo); } void *monitoring(void *v_philo) { t_vars *vars; t_philo *philo; philo = (t_philo *)v_philo; vars = get_vars(); while(1) { pthread_mutex_lock(&vars->eats[philo->p_idx]);//먹는 스레드 lock //(현재 - 마지막 식사시간)이 죽을때까지의 시간보다 크다면 if (get_time() - philo->last_eat_time > (unsigned long)vars->t_die) { print_status(vars, philo, DIED); //죽는다 프린트 pthread_mutex_lock(&vars->someone_died);//죽음의 함수 lock vars->flag_died = 1; //사망 플래그 세우고 죽어. pthread_mutex_unlock(&vars->someone_died); //죽음의 함수 unlock } pthread_mutex_unlock(&vars->eats[philo->p_idx]);//먹는 스레드 unlock ft_usleep(5);//모니터링 하는 주기 } } int free_struct(void *s) //here the argument is void to free variables easily! { if (s) free(s); s = 0; return (1); } int free_all(int ret) { t_vars *vars; int i; vars = get_vars(); i = 0; while (i < vars->n_philo) pthread_mutex_destroy(&vars->forks[i++]); i = 0; while (i < vars->n_philo) pthread_mutex_destroy(&vars->eats[i++]); pthread_mutex_destroy(&vars->alive); pthread_mutex_destroy(&vars->print); pthread_mutex_destroy(&vars->someone_died); pthread_mutex_destroy(&vars->putdown); pthread_mutex_destroy(&vars->pickup); free_struct((void *)vars->philo); free_struct((void *)vars->eats); free_struct((void *)vars->forks); return (ret); } int init_mutexes(t_vars *vars) { int i; i = 0; vars->n_alive = vars->n_philo; //생존자 수 == 철학자 수 if(!(vars->forks = malloc(sizeof(pthread_mutex_t) * vars->n_philo))) return (0); //포크 수에 구조체크기 * 철학자 수만큼 malloc if(!(vars->eats = malloc(sizeof(pthread_mutex_t) * vars->n_philo))) return (0); //먹는 행위에 구조체크기 * 철학자 수만큼 malloc //mutex 객체 초기화 //성공시 0 return , 아래 if 조건 default가 != 0, 따라서 실패시 return(0)이라는 뜻 i = 0; while (i < vars->n_philo) if (pthread_mutex_init(&vars->forks[i++], 0)) return (0); i = 0; while (i < vars->n_philo) if (pthread_mutex_init(&vars->eats[i++], 0)) return (0); if (pthread_mutex_init(&vars->pickup, 0)) return (0); if (pthread_mutex_init(&vars->putdown, 0)) return (0); if (pthread_mutex_init(&vars->alive, 0)) return (0); if (pthread_mutex_init(&vars->print, 0)) return (0); if (pthread_mutex_init(&vars->someone_died, 0)) return (0); return (1); } int init(int argc, char **argv) { t_vars *vars; vars = get_vars(); //arg 예외처리, 진짜 초기화는 init mutexes에서 vars->n_philo = ft_atoi(argv[1]); vars->t_die = ft_atoi(argv[2]); vars->t_eat = ft_atoi(argv[3]); vars->t_sleep = ft_atoi(argv[4]); if (argc == 6) { if ((vars->n_must_eat = ft_atoi(argv[5])) <= 0) return (0); } else vars->n_must_eat = -1; if (vars->n_philo < 2) return (0); if (vars->t_die < 0 || vars->t_eat < 0 || vars->t_sleep < 0) return (0); if (!(init_mutexes(vars))) return (0); return (1); } int create_philo_even(t_vars *vars, unsigned long start_time) { int i; int j; i = 0; while ((j = 2 * i) < vars-> n_philo) { vars->philo[j].p_idx = j; vars->philo[j].n_eat = 0; vars->philo[j].start_time = start_time; vars->philo[j].last_eat_time = vars->philo[j].start_time; //philosophing 하는 스레드 따로 if (pthread_create(&vars->philo[j].thread, 0, &philosophing, &vars->philo[j])) return (ft_error("Error: cannot create pthread")); if (pthread_detach((vars->philo[j].thread))) return (ft_error("Error: cannot create pthread")); //monitoring 하는 스레드 따로 if (pthread_create(&vars->philo[j].m_thread, 0, &monitoring, &vars->philo[j])) return (ft_error("Error: cannot create pthread")); if (pthread_detach((vars->philo[j].m_thread))) return (ft_error("Error: cannot create pthread")); i++; } return (1); } int create_philo_odd(t_vars *vars, unsigned long start_time) { int i; int j; i = 0; while ((j = 2 * i + 1) < vars-> n_philo) { vars->philo[j].p_idx = j; vars->philo[j].n_eat = 0; vars->philo[j].start_time = start_time; vars->philo[j].last_eat_time = vars->philo[j].start_time; if (pthread_create(&vars->philo[j].thread, 0, &philosophing, &vars->philo[j])) return (ft_error("Error: cannot create pthread")); //스레드가 독립적으로 동작, 나는 기다려주지 않으니 끝나면 알아서 끝내도록 해라 if (pthread_detach((vars->philo[j].thread))) return (ft_error("Error: cannot create pthread")); if (pthread_create(&vars->philo[j].m_thread, 0, &monitoring, &vars->philo[j])) return (ft_error("Error: cannot create pthread")); if (pthread_detach((vars->philo[j].m_thread))) return (ft_error("Error: cannot create pthread")); i++; } return (1); } int create_philo(t_vars *vars) { unsigned long start_time; if (!(vars->philo = malloc(sizeof(t_philo) * vars->n_philo))) return (0); start_time = get_time(); if (!(create_philo_even(vars, start_time))) return (0); if (!(create_philo_odd(vars, start_time))) return (0); return (1); } int main(int argc, char **argv) { t_vars *vars; if (argc != 5 && argc != 6) return (-1); vars = get_vars(); if (!init(argc, argv) || !create_philo(vars)) return (-1); while (1) { pthread_mutex_lock(&vars->alive); if (vars->n_alive == 0)//먹어야 하는 최소 횟수를 다 채워서 시뮬레이션 종료되는 경우 break ; pthread_mutex_unlock(&vars->alive); pthread_mutex_lock(&vars->someone_died); if (vars->flag_died == 1)//한 명이라도 죽으면 시뮬레이션 종료 (못 먹어서 죽는 경우) return (free_all(0)); pthread_mutex_unlock(&vars->someone_died); ft_usleep(5); } if (vars->flag_died == 0)//먹어야하는 최소횟수 다 채우면 종료 ft_putstr("Every philosopher ate enough!\n"); return(free_all(0)); }
C
//EXERCICIO 4 DA AULA 3 #include <stdio.h> int main () { float deposito , depMaisRend; printf("Por favor, digite o valor depositado no mes na poupanca:\n"); printf("Deposito = "); scanf("%f" , &deposito); depMaisRend = deposito + ( ( deposito * 0.7 ) / 100 ); printf("\nApos um mes de rendimentos tera %f na poupanca.\n" , depMaisRend); return 0; }
C
/* * =========== * Filename: buildin_command.c * Author: Yuanhang Shao * =========== */ #include "myshell.h" int buildin_command(char *command, char **parameters) { extern struct passwd *pwd; if(strcmp(command, "exit") == 0) { printf("\n"); exit(0); } else if(strcmp(command, "help") == 0) { printf("This is myshell for CPDP created by Yuanhang Shao. \n"); return 1; } else if(strcmp(command, "cd") == 0) { char *path = NULL; if(parameters[1] == NULL) { parameters[1] = malloc(3*sizeof(char)); parameters[1][0] = '.'; parameters[1][1] = '.'; parameters[1][2] = '\0'; } if(parameters[1][0] == '~') { path = malloc(strlen(pwd->pw_dir)+strlen(parameters[1])); //'~' makes length 1 more,but instead of '\0' if(path == NULL) { printf("cd:malloc failed.\n"); } strcpy(path,pwd->pw_dir); strncpy(path+strlen(pwd->pw_dir),parameters[1]+1,strlen(parameters[1])); //printf("path with ~:\n%s\n",path); } else { path = malloc(strlen(parameters[1]+1)); if(path == NULL) { printf("cd failed to malloc. \n"); } strcpy(path, parameters[1]); } if(chdir(path) != 0) printf("there is no such dir: %s:%s \n", path, strerror(errno)); free(path); return 1; } else if(strcmp(command, "pwd") == 0) { char *path; char pwd[MAX_LEN]; path = getcwd(pwd, MAX_LEN); if(path == NULL) printf("error! Couldn't getcwd! \n"); else { printf("pwd is: %s \n", path); return 1; } } else if(strcmp(command, "set") == 0) { if(parameters[1] == NULL) printf("Syntax: set MYPATH=env1:env2.\n"); char *path=parameters[1]; int flag=0; while(*path != '\0') { if(*path == '=') { flag=1; break; } ++path; } if(!flag) { printf("Syntax:set MYPATH=env1:env2.\n"); return 0; } char *env_mark; char *env_path; env_mark = strtok(parameters[1], "="); env_path = strtok(NULL, "="); if(strcmp(env_mark, "MYPATH")) { printf("Syntax: set MYPATH=env1:env2. \n"); return 0; } if(!strncmp(env_path, "$MYPATH", strlen("$MYPATH"))) { env_path = env_path + strlen("$MYPATH"); if(*env_path == ':') ++env_path; } char buf[MAX_PROMPT]; //1024 char *old_env = getenv("MYPATH"); if(old_env == NULL) sprintf(buf, "%s\0", env_path); else sprintf(buf, "%s:%s\0", old_env, env_path); if(setenv("MYPATH", buf, 1)) printf("unknow error: set env is failed. \n"); return 1; } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <memory.h> char *trim( char *) ; void main() { char line[50] ; char *ip ; char *cp = line ; char *tmp = "bifurcate_ip = 172.30.10.27 " ; strcpy( cp, tmp ) ; printf("%s\n", cp ) ; cp = strchr(cp, '='); printf("strchr. %s\n", cp ) ; cp = trim(cp + 1); printf("trim. %s\n", cp ) ; ip = strdup(cp); printf("strdup. %s\n", cp ) ; } char *trim( char *s ) { int i, j; //文字列の最後から空白を読み飛ばして除外する for( i = strlen(s)-1; i >= 0 && isspace( s[i] ); i-- ) ; s[i+1] = '\0'; //先頭から空白でない文字まで読み飛ばす for( i = 0; isspace( s[i] ); i++ ) ; //前方の空白を詰める if( i > 0 ) { j = 0; while( s[i] ) s[j++] = s[i++]; s[j] = '\0'; } return s; } /* char *trim(char *cp) { int i; int len; int count=0; len = strlen(cp); i=len; while ( --i >= 0 && (cp[i] == ' ' || cp[i] == '\n') ) count++; cp[i+1] = '\0'; i = 0; while ( cp[i] != '\0' && (cp[i] == ' ' || cp[i] == '\n') ) i++; strcpy(cp, cp+i); return cp; } */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: thninh <thninh@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/27 12:23:12 by thninh #+# #+# */ /* Updated: 2017/03/02 11:55:24 by thninh ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" t_get *ft_manage_fd(int fd, t_get **list) { while (*list && (*list)->fd != fd) list = &(*list)->next; if (!*list) { *list = (t_get*)malloc(sizeof(**list)); (*list)->tmp = NULL; (*list)->fd = fd; (*list)->next = NULL; } return (*list); } char *ft_strjoin_free(const char *s1, const char *s2, int del) { char *str; str = NULL; if (s1 && s2) { str = (char *)malloc(sizeof(char) * (ft_strlen((char *)s1) + ft_strlen((char *)s2)) + 1); if (!str) return (NULL); str = ft_strcat(ft_strcpy(str, s1), s2); if (del == 1) ft_strdel((char **)&s1); if (del == 2) ft_strdel((char **)&s2); if (del == 3) { ft_strdel((char **)&s1); ft_strdel((char **)&s2); } } return (str); } int ft_check_stock(t_get *file, char **line) { char *tmp; if (!file->tmp) return (0); if ((tmp = ft_strchr(file->tmp, '\n'))) { *line = ft_strjoin_free(*line, ft_strsub(file->tmp, 0, tmp - file->tmp), 3); file->tmp = ft_strdup(file->tmp + (tmp - file->tmp) + 1); return (1); } else { *line = ft_strjoin_free(*line, file->tmp, 1); ft_strdel(&(file->tmp)); } return (0); } int ft_check_folder(t_get *file, char **line) { int ret; char *tmp; char *buf; buf = (char *)malloc(sizeof(char) * BUFF_SIZE + 1); if (!buf) return (-1); while ((ret = read(file->fd, buf, BUFF_SIZE))) { if (ret == -1) return (-1); buf[ret] = '\0'; if ((tmp = ft_strchr(buf, '\n'))) { *line = ft_strjoin_free(*line, ft_strsub(buf, 0, tmp - buf), 3); file->tmp = ft_strdup(buf + (tmp - buf) + 1); ft_strdel(&buf); return (1); } else *line = ft_strjoin_free(*line, buf, 1); } if (ret == 0 && **line == '\0') return (0); return (1); } int get_next_line(const int fd, char **line) { static t_get *list = NULL; t_get *cur; if (!line || fd < 0) return (-1); if (*line) *line = NULL; *line = ft_strdup(""); cur = ft_manage_fd(fd, &list); if (ft_check_stock(cur, line)) return (1); return (ft_check_folder(cur, line)); }
C
#include <stdio.h> #include <stdlib.h> #include "queueandlist.h" void init(list *l){ l->head = (node *)malloc(sizeof(node)); l->tail = (node *)malloc(sizeof(node)); l->head = NULL; l->tail = NULL; l->len = 0; } void insert(list *l, int pos, int x){ node *tmp, *p; int i; /* handle errors on position */ if(pos < 0 || pos > l->len) return; /* create a new node */ tmp = (node *)malloc(sizeof(node)); tmp->a = x; /* handle first node case separately */ if(l->head == NULL) { tmp->next = NULL; l->head = tmp; l->tail = tmp; //l->head = l->tail = tmp0; l->len++; return; } /* link the new node on the list at appropriate position*/ p = l->head; for(i = 0; i < pos - 1; i++) p = p->next; if(pos == 0){ tmp->next = l->head; l->head = tmp; } else if(pos == l->len){ tmp->next = NULL; p->next = tmp; l->tail = tmp; } else{ tmp->next = p->next; p->next = tmp; } /* increase length */ l->len++; } int remov(list *l, int pos){ if(pos < 0 || pos >= l->len){ return -1; } int i; node *tmp, *p; tmp = (node *)malloc(sizeof(struct node)); p = l->head; for(i = 0; i < pos - 1; i++){ p = p->next; } if(pos == 0){ tmp = p; l->head = p->next; } else if(pos == l->len - 1){ tmp = p; l->tail = p; l->tail->next = NULL; } else{ tmp = p; p->next = p->next->next; } free(p); l->len--; return tmp->a; } int length(list *l){ return l->len; } void qinit(queue *q){ q->l = (list *)malloc(sizeof(list)); init(q->l); } void enqueue(queue *q, int x){ insert(q->l, q->l->len, x); } int dequeue(queue *q){ return remov(q->l, 0); } int qempty(queue *q){ return q->l->len == 0; } int qfull(queue *q){ return 0; } void qprint(queue *q){ node *temp; temp = q->l->head; while(temp){ printf("%d ", temp->a); temp = temp->next; } printf("\n"); }
C
/*****************************************************************/ /* Class: Computer Programming, Fall 2019 */ /* Author: ù�аa (put your name here) */ /* ID: 108820001 (your student ID here) */ /* Date: 2019.10.15 (put program development started date here */ /* Purpose: Caculating factorial */ /* Change History: 1015 1023 */ /*****************************************************************/ #include<stdio.h> # include<limits.h> int main(void){ //declare values int i, n; //factorial type short s_fac = 1; int i_fac = 1; long l_fac = 1; long long ll_fac = 1; float f_fac = 1; double d_fac = 1; long double ld_fac = 1; //input printf("Enter a posititive number : "); scanf("%d", &n); //caculating n! for(i=1;i<=n;i++){ s_fac *= i; i_fac *= i; l_fac *= i; ll_fac *= i; f_fac *= i; d_fac *= i; ld_fac *= i; } //output printf("Factorial of %d (short) : %hd\n",n ,s_fac ); printf("Factorial of %d (int) : %d\n",n ,i_fac ); printf("Factorial of %d (long) : %ld\n",n ,l_fac ); printf("Factorial of %d (long long) : %lld\n",n ,ll_fac ); printf("Factorial of %d (float) : %f\n",n ,f_fac ); printf("Factorial of %d (double) : %lf\n",n ,d_fac ); printf("Factorial of %d (long double) : %Lf\n",n ,ld_fac ); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #define MAX 10 /* ======================================= * FACULDADE DE CINCIAS SOCIAIS APLICADAS * ATIVIDADE DE AED - PLANO CARTESIANO * ALUNO: EULER MAGNO DE OSMAR JNIOR * MATRCULA: 14321 DATA: 24/06/2019 * ======================================= */ void combo_sort(int matriz[], int tamanho) { int i, j, intervalo, trocado = 1; int aux; intervalo = tamanho; while (intervalo > 1 || trocado == 1) { intervalo = intervalo * 10 / 13; if (intervalo == 9 || intervalo == 10) intervalo = 11; if (intervalo < 1) intervalo = 1; trocado = 0; for (i = 0, j = intervalo; j < tamanho; i++, j++) { if (matriz[i] > matriz[j]) { aux = matriz[i]; matriz[i] = matriz[j]; matriz[j] = aux; trocado = 1; } } } } int main(void){ setlocale(LC_ALL, "Portuguese"); int cont=0; do{ printf("**********************************************\n"); printf("*******************Comb Sort******************\n"); printf("**********************************************\n"); // Inserindo valores para serem ordenados int meuVetor[MAX] = {33, 100, 10, 15, 5, 99, 88, 77, 66, 55}, i=0 ; printf("Vetor antes: \n"); for ( i = 0; i < MAX; i++){ printf("%d " ,meuVetor[i]); } // Ordenando vetor combo_sort(meuVetor, MAX); printf("\nVetor depois: \n"); for ( i = 0; i < MAX; i++){ printf("%d ", meuVetor[i]); } printf("\n"); printf("\nRefazer as opes?"); printf("\n[1 = sim] [2 = nao ]:"); scanf("%d", &cont); system("cls"); while(cont!=1 && cont!=2){ printf("\n Digite uma opo vlida!"); printf("\n [1 = sim] [2 = nao ]:"); scanf("%d", &cont); system("cls"); } }while (cont!=2); return 0; }
C
/* * This program prints array which represents a BST in sorted order * * Output * ------ * * 1 2 3 4 5 * * * Author: @pyav */ #include <stdio.h> #define SUCCESS 0 /* Print in sorted order */ void print_sorted(int arr[], int low, int high) { if (low > high) return; print_sorted(arr, (low * 2) + 1, high); printf("%d ", arr[low]); print_sorted(arr, (low * 2) + 2, high); } /* Main driver code */ int main (void) { /* Array representing data in a BST level-wise */ int arr[] = {4,2,5,1,3}; /* Calculate number of elements */ int no_elems = sizeof(arr) / sizeof(arr[0]); /* Print in sorted order, send last index of array */ print_sorted(arr, 0, no_elems - 1); printf("\n"); return SUCCESS; }
C
#include <libdevice/keymap.h> KeyMapping *keymap_lookup(KeyMap *keymap, Key key) { for (int i = 0; i < keymap->mappings_count; i++) { if (keymap->mappings[i].key == key) { return &keymap->mappings[i]; } } return NULL; }
C
#ifndef Sega2PS2_h #define Sega2PS2_h #include <SegaController.h> typedef struct { word button; String mnemonic; bool isExtendedKey; byte ps2ScanCode; byte ps2SpecialScanCode; } button; // For a list of PS/2 scan codes, see: <https://web.archive.org/web/20180202062621/http://www.computer-engineering.org/ps2keyboard/scancodes2.html> const button buttonsAvailable[] = { { SC_BTN_UP, "SC_BTN_UP", true, 0x75, 0x00 }, // normal: cursor up special: none { SC_BTN_DOWN, "SC_BTN_DOWN", true, 0x72, 0x00 }, // normal: cursor down special: none { SC_BTN_LEFT, "SC_BTN_LEFT", true, 0x6B, 0x00 }, // normal: cursor left special: none { SC_BTN_RIGHT, "SC_BTN_RIGHT", true, 0x74, 0x00 }, // normal: cursor right special: none { SC_BTN_START, "SC_BTN_START", false, 0xFF, 0x76 }, // normal: special special: escape (it's escape if you just pressed and released) { SC_BTN_A, "SC_BTN_A", false, 0x14, 0x5A }, // normal: left control special: enter { SC_BTN_B, "SC_BTN_B", false, 0x29, 0x35 }, // normal: space special: y { SC_BTN_C, "SC_BTN_C", false, 0x11, 0x00 }, // normal: left alt special: none { SC_BTN_X, "SC_BTN_X", false, 0x16, 0x00 }, // normal: 1 special: none { SC_BTN_Y, "SC_BTN_Y", false, 0x1E, 0x00 }, // normal: 2 special: none { SC_BTN_Z, "SC_BTN_Z", false, 0x26, 0x00 }, // normal: 3 special: none { SC_BTN_MODE, "SC_BTN_MODE", false, 0x0D, 0x00 } // normal: tab special: none }; // the number of buttons in the above array const byte BUTTONS = 12; #endif
C
#include <stdio.h> int main() { int input; printf("Masukkan umur\t: "); scanf("%d",&input); printf("Tahun Lahir\t: "); printf("%d\n",2020-input); return 0; }
C
#include<stdio.h> #include<math.h> int isprime(long long int n) { int i; for(i=3;i*i<=n;i+=2) if(n%i==0) return 0; return 1; } int main() { int i,cnt=0; long long int n; for(i=2;1;i++) { n=pow(2,i)-1; if(isprime(n)) { printf("%d\n",n); cnt++; } if(cnt>100) break; } return 0; }
C
/*! * \author: Alan Ernesto González Barrios * \date 2019-03-20 * \mainpage Practica 3 * \section Programa 1 * Seccion de la modificacion numero 1 de la practica 3 * \warning declaration on getpid * \section Programa 2 * Seccion de la modificacion numero 2 de la practica 3 * \warning declaration on getpid * \warning declaration on alarm * \section Programa 3 * Seccion la modificacion numero 3 de la practica 3 * \warning declaration on getpid */ #include <stdlib.h> #include <stdio.h> #include <signal.h> int main () { //! se crea el bucle infinito mientra el valor del entero bucle sea igual a 1 while (1) //! mientras se esta en el bucle se estara imprimiendo en pantalla el texto aqui estoy con su respectivo numero de proceso printf("Process id (%d): Aqui estoy\n", getpid()); return 0; }
C
#include <unistd.h> /** * _putchar - print char with stdout * @ch: char to print * Return: Output. */ int _putchar(char ch) { static int contador; static char buffer[1024]; if (ch == -1) { contador = 0; return (0); } if (ch == -2 || contador == 1024) { write(1, buffer, contador); contador = 0; } if (ch != -1 && ch != -2) { buffer[contador] = ch; contador++; return (1); } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> int main (int argc, char **argv) { if(!fork()) { // child B, forked by A printf("Child B id: [%d] and its Parent A id: [%d] \n", getpid(),getppid()); if(!fork()){ // child E, forked by B printf("Child E id: [%d] and its Parent B id: [%d] \n", getpid(),getppid()); if(!fork()){ //child I, forked by E printf("Child I id: [%d] and its Parent E id: [%d] \n", getpid(),getppid()); } else wait(NULL); } else{ wait(NULL); if(!fork()){ // child F, forked by B printf("Child F id: [%d] and its Parent B id: [%d] \n", getpid(),getppid()); } else wait(NULL); } } else { wait(NULL); if (!fork()){ //child C, forked by A printf("Child C id: [%d] and its Parent A id: [%d] \n", getpid(),getppid()); if(!fork()){ // no child here } else { wait(NULL); if(!fork()){ // child G, forked by C printf("Child G id: [%d] and its Parent C id: [%d] \n", getpid(),getppid()); } else wait(NULL); } } else { wait(NULL); if(!fork()){ //child D, forked by A printf("Child D id: [%d] and its Parent A id: [%d] \n", getpid(),getppid()); } else wait(NULL); } } }
C
#include "SurveySim.h" /* *太阳帆板可旋转,计算一定旋转角度范围内,帆板法线的范围 */ void get_solar_normal_30(double px, double py, double pz, double nx, double ny, double nz,double* n30, double* n30_) { double angle=PANEL_TRANSE_ANGLE/57.29577951; double a = cos(angle); double b = sin(angle); double p = sqrt(px*px+py*py+pz*pz); double n = sqrt(nx*nx+ny*ny+nz*nz); double t_nx30 = a*nx*p/n + b*px; double t_ny30 = a*ny*p/n + b*py; double t_nz30 = a*nz*p/n + b*pz; double t_nx30_ = a*nx*p/n - b*px; double t_ny30_ = a*ny*p/n - b*py; double t_nz30_ = a*nz*p/n - b*pz; n30[0] = t_nx30; n30[1] = t_ny30; n30[2] = t_nz30; n30_[0] = t_nx30_; n30_[1] = t_ny30_; n30_[2] = t_nz30_; } /** * 坐标变化沿某一平面旋转angle,angle单位为 度 * coorO表示原始坐标 * coorR存储变换后的结果 * flag 标识 1:x-y 平面 2: x-z平面 3:y-z 平面 * 转动方向为:例如x-y平面,逆时针转动 */ void CoordinateSpin(double coorO[3], double coorR[3], double angle, int flag) { double arcAngle = angle * PI_180; if (flag > 3 || flag < 1) { // after debug, this should be commented out! return; } if (flag == 1) { coorR[0] = coorO[0] * cos(arcAngle) + coorO[1] * sin(arcAngle); coorR[1] = coorO[0] * (-sin(arcAngle)) + coorO[1] * cos(arcAngle); coorR[2] = coorO[2]; } if (flag == 2) { coorR[0] = coorO[0] * cos(arcAngle) + coorO[2] * sin(arcAngle); coorR[1] = coorO[1]; coorR[2] = coorO[0] * (-sin(arcAngle)) + coorO[2] * cos(arcAngle); } if (flag == 3) { coorR[0] = coorO[0]; coorR[1] = coorO[1] * cos(arcAngle) + coorO[2] * sin(arcAngle); coorR[2] = coorO[1] * (-sin(arcAngle)) + coorO[2] * cos(arcAngle); } } // 绕着x轴逆时针转动 void CoordinateSpin_x(double coorO[3], double coorR[3], double angle ) { double arcAngle = angle * PI_180; coorR[0] = coorO[0]; coorR[1] = coorO[1] * cos(arcAngle) + coorO[2] * sin(arcAngle); coorR[2] = coorO[1] * (-sin(arcAngle)) + coorO[2] * cos(arcAngle); } // 从赤道坐标系变换到黄道坐标系 void CoordinateSpinEquatorial2Ecliptic(double coorO[3], double coorR[3]) { // 沿着x轴旋转 //angle = 23.4522 //cos(angle) = 0.917392 //sin(angle) = 0.394984 double cosa = 0.917392; double sina = 0.397983; coorR[0] = coorO[0]; coorR[1] = coorO[1] * cosa + coorO[2] * sina; coorR[2] =-coorO[1] * sina + coorO[2] * cosa; } /** * *eCoor = ra, *eCoor+1 = dec */ // 从笛卡尔坐标系变换到(天文的)球坐标系 // void Cartesian2Equatorial(double* carCoor, double* eCoor) { // double x1 = carCoor[0], x2 = carCoor[1], x3 = carCoor[2]; // double r = sqrt(x1*x1+x2*x2+x3*x3); // double theta = asin(x3/r); // double tmp = r*cos(theta)+x1; // if( fabs(tmp) < 1e-15 ) // 避免数值问题导致的NAN // tmp = 1e-15; // *(eCoor+1) = theta*180./PI; // *(eCoor+0) = atan(x2/tmp) *360./PI; // // ra只能是正数! // if( *eCoor < 0 ) // *eCoor += 360.; // } // 新版本的误差控制更好! void Cartesian2Equatorial(double* carCoor, double* eCoor) { double x1 = carCoor[0], x2 = carCoor[1], x3 = carCoor[2]; double r = sqrt(x1*x1+x2*x2+x3*x3); double theta = asin(x3/r); double phi=0; if( fabs(x1/r) > 1e-8 && fabs(x2/r) > 1e-8 ){ phi = 2.0*atan(x2/(r*cos(theta)+x1)); } else{ double x = x1*1e8; double y = x2*1e8; phi = 2.0*atan(y/(sqrt(x*x+y*y)+x)); } *(eCoor+0) = phi*180.0/PI; *(eCoor+1) = theta*180.0/PI; // ra只能是正数! if( *eCoor < 0 ) *eCoor += 360.; } double getAngle132(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3) { double cosValue = 0; double angle = 0; double x11 = x1-x3; double y11 = y1-y3; double z11 = z1-z3; double x22 = x2-x3; double y22 = y2-y3; double z22 = z2-z3; double tt = sqrt((x11*x11 + y11*y11 + z11* z11) * (x22*x22 + y22*y22 + z22*z22)); #if defined(_FULL_DEBUG_) if(tt==0) {//实际应用的过程中不可能出现tt=0的情况,因为()和()不可能有至少一个出现在原点。 return 0; } #endif cosValue = (x11*x22+y11*y22+z11*z22)/tt; if (cosValue > 1) { cosValue = 1; } if (cosValue < -1) { cosValue = -1; } angle = acos(cosValue); return angle * 180 * M_1_PI; } double calculateAngle(double ra1, double dec1, double ra2, double dec2) { double x1, y1, z1, x2, y2, z2, angle, cosValue; x1 = cos(dec1 * PI_180) * cos(ra1 * PI_180); y1 = cos(dec1 * PI_180) * sin(ra1 * PI_180); z1 = sin(dec1 * PI_180); x2 = cos(dec2 * PI_180) * cos(ra2 * PI_180); y2 = cos(dec2 * PI_180) * sin(ra2 * PI_180); z2 = sin(dec2 * PI_180); cosValue = x1*x2+y1*y2+z1*z2; if( cosValue < -1.0 ){ return 180.0; }else if( cosValue > 1.0 ){ return 0.0; } angle = acos(x1*x2+y1*y2+z1*z2); return angle * 180 * M_1_PI; //返回值为角度(以度数为单位,不是以弧度为单位) }
C
#include<stdio.h> #include<conio.h> int main() { char str[40]; printf("enter the number"); intrlen; len=lenstr[str]; if(len%2!=0) { str=[(len-1)/2]='*'; } else { str=[len/2]='*'; str=[(len/2)-1]='*'; } printf("%s",str); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <pthread.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <arpa/inet.h> #define TRUE 1 #define SocPath "File" void * Recieve_data(void * sockID) { int clientSocket = *((int *) sockID); while(TRUE) { char data[1024]; int read = recv(clientSocket,data,1024,0); if (read == -1) { perror("Data recieve failed.\nError "); return 0; } data[read] = '\0'; printf("%s\n",data); } } int main() { int clientSocket = socket(AF_UNIX, SOCK_STREAM, 0); if (clientSocket == -1) { perror("Server Socket creation failed\n"); exit(1); } struct sockaddr_un serverAddr; serverAddr.sun_family = AF_UNIX; strcpy(serverAddr.sun_path, SocPath); int con = connect(clientSocket,(struct sockaddr*) &serverAddr, sizeof(serverAddr)); if(con == -1) { perror("Connection failed.\nError "); return 0; } printf("Connection established ............\n"); pthread_t thread; int thread_error = pthread_create(&thread, NULL, Recieve_data, (void *) &clientSocket ); if (thread_error != 0) { perror("Connection failed.\nError "); return 0; } while(TRUE) { char input[1024]; scanf("%s",input); if(strcmp(input,"ALL") == 0) { send(clientSocket,input,1024,0); scanf("%[^\n]s",input); send(clientSocket,input,1024,0); } else if(strcmp(input,"SEND") == 0) { send(clientSocket,input,1024,0); scanf("%s",input); send(clientSocket,input,1024,0); scanf("%[^\n]s",input); send(clientSocket,input,1024,0); } else if(strcmp(input,"CONNECTED") == 0) { send(clientSocket,input,1024,0); } else if(strcmp(input,"EXIT") == 0) { send(clientSocket,input,1024,0); printf("Connection terminated ..........\n"); break; } else { printf("Server : Invalid input\n"); } } }
C
#ifndef F2_POLY_H #define F2_POLY_H #include <stdio.h> #include <inttypes.h> #include "arithm.h" typedef uint64_t f2_poly_t; typedef uint8_t f2_deg_t; // l'ordre des coefficients polynômiaux est du poids fort au poids faible. #define F2_VARN 'X' #define LEN (sizeof(f2_poly_t) << 3) // Pour pouvoir tirer un polynôme au hasard #define RANDOMFILE "/dev/urandom" // Masque pour un polynôme de degré < d, calcule aussi 2^d - 1 #define MASK(d) ( ~((f2_poly_t)0xffffffffffffffff << d) ) // /* Les polynômes sur F2 de degré < 64 sont représentés par des entiers de 64 bits, les coefficients sont ordonnés du poids fort vers le poids faible. Ex. 0x82 : X^7+X. */ /* Calcul sur F_2[X], pour des polynômes de degré au plus 63 */ f2_deg_t f2_poly_deg(f2_poly_t); int f2_poly_print(f2_poly_t, char, FILE *); // écriture polynomiale usuelle, avec pour variable le second argument int f2_poly_div(f2_poly_t *,f2_poly_t *, f2_poly_t, f2_poly_t); // (arg1, arg2) = (quotient, reste) de arg3 par arg4 f2_poly_t f2_poly_rem(f2_poly_t, f2_poly_t); // reste de arg1 par arg2 f2_poly_t f2_poly_gcd(f2_poly_t, f2_poly_t); // pgcd(arg1, arg2) /* Pour tous les calculs modulo. On peut quotienter par un polynôme de degré jusqu'à 63. */ f2_poly_t f2_poly_xtimes(f2_poly_t, f2_poly_t); // retourne X*arg1 mod (arg2) f2_poly_t f2_poly_times(f2_poly_t, f2_poly_t, f2_poly_t); // retourne arg1 * arg2 modulo arg3 f2_poly_t f2_poly_x2n(f2_deg_t, f2_poly_t); // retourne X^{2^arg1} modulo arg 2 f2_poly_t f2_poly_parity(f2_poly_t); //retourne le reste de la division par X+1 (xor des bits) f2_poly_t f2_poly_recip(f2_poly_t); // retourne le polynôme réciproque considéré comme de degré le second argument /* pour renverser l'ordre des bits sur 64 bits : polP = ((polP & 0x5555555555555555ULL) << 1) ^ ((polP & 0xaaaaaaaaaaaaaaaaULL) >> 1); polP = ((polP & 0x3333333333333333ULL) << 2) ^ ((polP & 0xccccccccccccccccULL) >> 2); polP = ((polP & 0x0f0f0f0f0f0f0f0fULL) << 4) ^ ((polP & 0xf0f0f0f0f0f0f0f0ULL) >> 4); polP = ((polP & 0x00ff00ff00ff00ffULL) << 8) ^ ((polP & 0xff00ff00ff00ff00ULL) >> 8); polP = ((polP & 0x0000ffff0000ffffULL) << 16) ^ ((polP & 0xffff0000ffff0000ULL) >> 16); polP = ((polP & 0x00000000ffffffffULL) << 32) ^ ((polP & 0xffffffff00000000ULL) >> 32); */ int f2_poly_irred(f2_poly_t); // vérifie si le polynôme arg1 est irréductible f2_poly_t f2_poly_xn(f2_poly_t, f2_poly_t); // retourne X^{arg1} modulo arg 2 int f2_poly_primitive(f2_poly_t); // vérifie si le polynôme arg1 est primitif uint64_t f2_poly_irred_order(f2_poly_t polP); // renvoie 0 si le polynôme polP n'est pas irréductible, // l'ordre multiplicatif d'une racine, soit de X modulo P sinon // Si cet ordre égale 1 << f2_poly-deg(P), le polynôme est primitif. f2_poly_t f2_poly_random_inf(f2_deg_t); // retourne un polynôme tiré au hasard parmi les polynômes de degré < arg f2_poly_t f2_poly_random(f2_deg_t); // retourne un polynôme tiré au hasard parmi les polynômes de degré = arg f2_poly_t f2_poly_irred_random(f2_deg_t); // retourne un polynôme tiré au hasard parmi les polynômes irréductibles // de degré = arg2 f2_poly_t f2_poly_primitive_random(f2_deg_t); // retourne un polynôme tiré au hasard parmi les polynômes primitifs // de degré = arg2 uint64_t f2_poly_irred_count(f2_deg_t n); uint64_t f2_poly_primitive_count(f2_deg_t n); #endif /* F2_POLY_H */
C
// Created by Fouad Aoude // Copyright Fouad Aoude 2020 #include <stdio.h> #include <conio.h> //#include <curses.h> #include <string.h> #include <stdlib.h> int displayMenu(int); void login(char *, char *, int*, FILE *); int userInterface(int *, char *, char *, FILE *); void createAccount(char *, char *, int *, FILE *); void deposit(char *, double *, FILE *); void withdrawl(char *, double *, FILE *); void checkAccountDetails(char *, char *, double *, FILE*); void cls(); int main(){ int menuOption, i, *loginPtr=0; FILE *accountDetails; char username[30], password[30]; char *usernamePtr, *passwordPtr; usernamePtr = username; passwordPtr = password; do{ if(loginPtr){ userInterface(loginPtr, &username, &password, accountDetails); } menuOption = displayMenu(menuOption); switch(menuOption){ case 1: createAccount(&username, &password, loginPtr, accountDetails); break; case 2: login(&username, &password, loginPtr, accountDetails); break; case 3: break; default: printf("\nPlease select a valid option\n"); } }while(menuOption != 3); }// End main void cls(){ system("cls"); } int displayMenu(int menuOption){ printf("\n\tAoude Bank\n"); printf("\n(1) Create an Account\n"); printf("\n(2) Login\n"); printf("\n(3) Exit\n"); printf("\nPlease Select an Option : \n\n"); scanf("%d", &menuOption); return menuOption; }// End displayMenu void createAccount(char *usernamePtr, char *passwordPtr, int *loginPtr, FILE *accountDetails){ int i, *userid=0; char username[30], password[30]; system("cls"); do{ do{ accountDetails = fopen("accounts.txt", "a+"); // Open file for writing printf("\nPlease Enter a username : \n"); scanf("%s", &username); //printf("\nusernamePtr %s", *usernamePtr); printf("\nPlease Enter a Password : \n"); scanf("%s", &password); if(strlen(username) < 5 && strlen(password) < 10){ printf("\nBoth username and password are too short please try again\n"); } else if(strlen(username) > 30 && strlen(password) > 30){ printf("\nBoth username and password are too long please try again\n"); } else if(strlen(username) < 5){ do{ printf("\nUsername is too short try again\n"); printf("\nPlease Enter a username : \n"); scanf("%s", &username); if(strlen(username) > 30){ printf("Username is too long"); } }while(strlen(username) < 5 && strlen(username) < 30); } else if(strlen(password) < 10){ do{ printf("\nPassword is too short try again\n"); printf("\nPlease Enter a password : \n"); scanf("%s", &password); if(strlen(password) > 30){ printf("Password is too long"); } }while(strlen(password) < 10 && strlen(password) < 30); } }while(strlen(username) < 5 || strlen(password) < 10); }while(strlen(password) < 10 || strlen(username) < 5); if(strlen(username) >= 5 && strlen(password) >= 10 && strlen(username) < 30 && strlen(password) < 30){ userid++; strcpy(usernamePtr, username); strcpy(passwordPtr, password); //loginPtr = 1; fprintf(accountDetails,"Userid\t\tUsername\tPassword\n\n" "%d\t" "\t%s\t" "\t" "%s", userid, usernamePtr, passwordPtr); fclose(accountDetails); system("cls"); printf("\nRegistered Successfully.\n"); } else{ printf("\nThere was an error registering your account please try again later.\n"); } fclose(accountDetails); } // End createAccount void login(char *usernamePtr, char *passwordPtr, int *loginPtr, FILE *accountDetails){ int counter=0, i; char userA[30], passA[30]; system("cls"); accountDetails = fopen("accounts.txt", "r"); do{ if(counter >= 4){ printf("\nToo many incorrect attempts try again later\n"); break; } printf("\n\tLogin\n"); printf("\nPlease enter your username : "); scanf("%s", &userA); printf("\nPlease enter your password : "); scanf("%s", &passA); counter = 0; for(i=0;i<20;i++){ if(strcmp(usernamePtr, userA) == 0 && strcmp(passwordPtr, passA) == 0){ // Notes for 3/9/2020 this is where you left off finish validating the login form. loginPtr = 1; } } if(loginPtr){ system("cls"); printf("\n\nLogged in successfully\n\n"); userInterface(loginPtr, usernamePtr, passwordPtr, accountDetails); break; } else{ printf("\n\nIncorrect username or password please try again\n\n"); loginPtr = 0; counter++; } }while(loginPtr == 0 && counter >= 4 ); }// End login int userInterface(int *loginPtr, char *usernamePtr, char *passwordPtr, FILE *accountDetails){ int menuOption, userid=0; double accountBalance, *accountBalancePtr; accountBalancePtr = &accountBalance; do{ printf("\n\tAoude Bank\n"); printf("\n(1) Deposit\n"); printf("\n(2) Withdrawl\n"); printf("\n(3) Check Account Details\n"); // Notes for 3/10/2020 allow the file to indicate the username and password so you dont have to keep creating an account and continue working on the userinterface printf("\n(4) Log Out\n"); printf("\nPlease Select an Option : \n\n"); scanf("%d", &menuOption); switch(menuOption){ case 1: cls(); deposit(usernamePtr, accountBalancePtr, accountDetails); // Work on the deposit function 3/11/2020 break; case 2: cls(); withdrawl(usernamePtr, accountBalancePtr, accountDetails); break; case 3: cls(); checkAccountDetails(usernamePtr, passwordPtr, accountBalancePtr, accountDetails); break; } }while(menuOption != 4); if(menuOption == 4){ cls(); printf("\nLogged out Successfully\n"); userid = 0; loginPtr = 0; } return 0; }// End userInterface void deposit(char *usernamePtr, double *accountBalancePtr, FILE *accountDetails){ char choice; double deposit; double accountBalance; double deposits[50]; do{ printf("\nHow Much Would You Like to Deposit Today?\n$"); scanf("%lf", &deposit); if(deposit > 10000){ printf("\nPlease Come to The Bank to Deposit Anything Over 10,000\n"); } else if(deposit < 0){ printf("\nInvalid Amount Please Try Again.\n"); cls(); } else{ *accountBalancePtr += deposit; printf("\nNew Balance : $%.2lf\n", *accountBalancePtr); } printf("\nWould You Like to Make Another Deposit? (Y/N) "); scanf("\n%c", &choice); cls(); }while(choice != 'n' && choice != 'N'); }// End deposit void withdrawl(char *usernamePtr, double *accountBalancePtr, FILE *accountDetails){ int i; char choice; double withdrawl, *withdrawlPtr; do{ printf("\nBalance = $%.2lf\n", *accountBalancePtr); if(accountBalancePtr <= 0){ printf("\nInsufficient Funds\n"); break; } printf("\nHow Much Would You Like to Withdrawl Today?\n$"); scanf("%lf", &withdrawl); if(withdrawl > *accountBalancePtr){ printf("\nInvalid Amount Please Try Again.\n"); } else if(withdrawl < 0){ printf("\nInvalid Amount Please Try Again.\n"); } else if(withdrawl > 10000){ printf("\nPlease Come to The Bank to Withdrawl Anything Over 10,000\n"); } else{ *accountBalancePtr -= withdrawl; printf("\nNew Balance : $%.2lf\n", *accountBalancePtr); } printf("\nWould You Like to Make Another Withdrawl? (Y/N) "); scanf("\n%c", &choice); cls(); }while(choice != 'n' && choice != 'N'); } void allWithdrawls(){ } void checkAccountDetails(char *usernamePtr, char *passwordPtr, double *accountBalancePtr, FILE *accountDetails){ int choice, i, accountNumber[10]; char hiddenPassword; char passA[30]; cls(); for(i=0;i<10;i++){ accountNumber[i] = rand(); } do{ printf("Hello %s What Would You Like to Check Today?\n\n", usernamePtr); printf("(1) Check Account Balance\n"); printf("\n(2) Check Account Settings\n"); printf("\n(3) Change Password\n"); printf("\n(4) Return to Previous Menu\n"); scanf("%d", &choice); if(choice == 1){ cls(); printf("\nYour Current Balance is $%.2lf\n", *accountBalancePtr); printf("\nPress Enter to Return to Previous Menu\n\n"); getch(); cls(); } if(choice == 2){ cls(); printf("\nUsername\t%s", usernamePtr); printf("\n\nAccount Number\t%d", accountNumber); printf("\n\nPress Enter to Return to Previous Menu\n\n"); getch(); cls(); } if(choice == 3){ cls(); printf("\nEnter Current Password "); scanf("%s", &passA); if(strcmp(passA, passwordPtr)==0){ printf("\nEnter New Password "); scanf("%s", &passA); do{ if(strlen(passA) < 10){ printf("\nPassword is Too Short Try Again\n"); scanf("%s", &passA); } if(strlen(passA) > 30){ printf("\nPassword is Too Long Try Again\n"); scanf("%s", &passA); } if(strlen(passA) >= 10 && strlen(passA) < 30){ strcpy(passwordPtr, passA); cls(); printf("\nPassword Has Been Updated\n\n"); } }while(strlen(passA) < 10 && strlen(passA) < 30); } else{ printf("\nIncorrect Password\n"); } } }while(choice != 4); }
C
#include "lists.h" <<<<<<< HEAD /** * add_dnodeint_end - adds a new node at the end of a list. ======= /** * add_dnodeint_end - adds a new node at the end of a listint_t list. >>>>>>> 74d1789039337fcdfc2badf178e8c103c26091cd * @head: dlistint_t * @n: int * Return: number of nodes. */ dlistint_t *add_dnodeint_end(dlistint_t **head, const int n) { dlistint_t *copy, *secLast; <<<<<<< HEAD ======= secLast = *head; >>>>>>> 74d1789039337fcdfc2badf178e8c103c26091cd copy = malloc(sizeof(dlistint_t)); if (copy == NULL) return (NULL); copy->n = n; <<<<<<< HEAD copy->next = NULL; if (*head == NULL) *head = copy; else { secLast = *head; while (secLast->next != NULL) secLast = secLast->next; secLast->next = copy; } return (*head); ======= if (*head == NULL) { copy->next = NULL; copy->prev = NULL; *head = copy; } else { while (secLast->next != NULL) secLast = secLast->next; copy->next = NULL; copy->prev = secLast; secLast->next = copy; } return (copy); >>>>>>> 74d1789039337fcdfc2badf178e8c103c26091cd }
C
#include "holberton.h" #include <stdlib.h> /** * create_array - Print the char array * @size: Store the size * @c: Store char *Return: Ptr char */ char *create_array(unsigned int size, char c) { char *t; unsigned int i; if (size == 0) { return (NULL); } t = malloc(sizeof(char) * size); if (t == NULL) { return (NULL); } for (i = 0; i < size; i++) { t[i] = c; } return (t); }
C
//a structure can contain other structures. #include <stdio.h> struct coord { int x, y; }; struct rectangle { struct coord topleft, bottomrt; int base, height, area; } box1; int main( void ) { //user input this: printf("top left x: "); scanf("%d", &box1.topleft.x); printf("top left y: "); scanf("%d", &box1.topleft.y); printf("bottom right x: "); scanf("%d", &box1.bottomrt.x); printf("bottom right y: "); scanf("%d", &box1.bottomrt.y); //calculate b and h for area box1.base = box1.bottomrt.x - box1.topleft.x; box1.height = box1.topleft.y - box1.bottomrt.y; //area box1.area = box1.base * box1.height; printf("The area is %d square units.\n", box1.area); return 0; }
C
#include <stdio.h> long long fib_helper(long long n, long long *values, int nvalues) { if (values[n] != -1) { return values[n]; } else { long long y1 = fib_helper(n-1, values, nvalues); long long y2 = fib_helper(n-2, values, nvalues); values[n] = y1 + y2; return values[n]; } } long long fib_new(long long n) { long long values[100]; values[0] = 0; values[1] = 1; for (int i = 2; i < 100; i++) values[i] = -1; return fib_helper(n, values, 100); } int main(void) { for (long long i = 0; i < 50; i++) { printf("%lld => %lld\n", i, fib_new(i)); } return 0; }
C
#include <stdlib.h> #include "test_buffer.h" rt_buffer_t *buffer_init() { rt_buffer_t *buffer = calloc(1, sizeof(rt_buffer_t)); buffer->size = 1024; buffer->bytes = malloc(buffer->size); return buffer; } void buffer_reset(rt_buffer_t *buffer) { buffer->used = 0; } void buffer_grow(rt_buffer_t *buffer, size_t len) { while (len > buffer->size - buffer->used) { buffer->size *= 2; } buffer->bytes = realloc(buffer->bytes, buffer->size); } void buffer_free(rt_buffer_t *buffer) { free(buffer->bytes); free(buffer); } rt_buffer_ctx_t *buffer_ctx_init(rt_buffer_t *buffer) { rt_buffer_ctx_t *buffer_ctx = calloc(1, sizeof(rt_buffer_ctx_t)); buffer_ctx->buffer = buffer; return buffer_ctx; } void buffer_ctx_reset(rt_buffer_ctx_t *buffer_ctx) { buffer_reset(buffer_ctx->buffer); buffer_ctx->pos = 0; }
C
/* ** EPITECH PROJECT, 2019 ** lemin ** File description: ** error handling */ #include "../../include/my.h" int not_good_input(char *s) { int i = 0; char **buf; int nbr_ants = 0; int rooms = 0; int connections = 0; if (!s) return (1); buf = my_str_to_wordtab(s, '\n'); for (; buf[i]; i++); if (i < 3) return (my_exit(s, buf)); if (is_num(buf[0])) return (my_exit(s, buf)); return (0); } int not_cool_neither(char **tab) { int i = 0; int end = 0; int start = 0; while (tab[i]) { if (my_strcmp(tab[i], "##end") == 1) end = 1; else if (my_strcmp(tab[i], "##start") == 1) start = 1; i++; } if (end == 0 || start == 0) return (1); return (0); } int error(int error) { char *one = "First line must be a digit representing the number of ants\n"; char *two = "Error, check the rooms and connections\n"; char *three = "No start or end\n"; if (error == 1) write(2, one, my_strlen(one)); if (error == 2) write(2, two, my_strlen(two)); if (error == 3) write(2, three, my_strlen(three)); return (84); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<errno.h> #include<sys/sem.h> #include<sys/ipc.h> #include<sys/types.h> #include<sys/shm.h> #define shmsize 10 //shared memory size(to store varible readcount in this case) #define shmkey 222 //key used for shared memory creation char* shmpointer; union semun { int val; struct semid_ds *buf; unsigned short *array; }arg; void wait(int semid) //wait(i.e.,p) { struct sembuf sem={0,-1,0}; semop(semid,&sem,1); } void signal(int semid) //signal(i.e.,v) { struct sembuf sem={0,1,0}; semop(semid,&sem,1); }int creat_init_semph(int key,int initial_val) //function to create and initiate a semaphor with some intial value { int semid; if((semid=semget(key,1, 0666))==-1) { perror("semget\n"); exit(1); } arg.val=initial_val; //semctl(semid,0,SETVAL,arg); return semid; } int creat_shmemory(int key) //function to create shared memory { int shmid; if((shmid=shmget(key,shmsize,0666))==-1) { perror("shmget\n"); exit(1); } return shmid; } char* attach_shmemory(int shmid) //function to attach shared memory to the process area { char* shmpointer; if((shmpointer=shmat(shmid,NULL,0))==(char*)-1) { perror("shmat\n"); exit(1); } return shmpointer; } int getshm() //funtion to return the value stored in shared memory in integer form { char* s=shmpointer; int rcount=0; while(*s!='\0') { rcount=rcount*10+(*s-'0'); s++; } return rcount; } void setshm(int rcount) //function to store readercount in shared memory in string format { char *s=shmpointer; char buf[10]; int i=0; while(rcount) { buf[i++]=(rcount%10)+'0'; rcount/=10; } i--; while(i>=0) *s++=buf[i--]; *s='\0'; } int main() { int mutex=creat_init_semph(0x20,1); //synchronises shared memory between readers(readcount) int writer=creat_init_semph(0x40,1); //synchronises writer and reader(mutual exclusion between writer and reader) int readcount=0; //common varible to be stored in shared memory shmpointer=attach_shmemory(creat_shmemory(shmkey)); //will point to shared memory area //setshm(0); while(1) { printf("waiting for mutex control\n"); wait(mutex); printf("mutex under my control\n"); readcount=getshm()+1; setshm(readcount); //increment readcount by 1 printf("readcount: %d\n",readcount); if(readcount==1) {printf("waiting for writer\n");wait(writer);printf("got writer control\n");} //if first reader then wait for writer printf("writer is %d\n",semctl(writer,0,GETVAL,0)); printf("leaving mutex control..\n"); sleep(10); signal(mutex); printf("reader %d is now reading\n",getpid()); sleep(20); printf("reading over....."); printf("waiting for mutex again\n"); wait(mutex); printf("mutex control again\n"); readcount=getshm()-1; setshm(readcount); printf("readcount now is%d\n",getshm()); if(readcount==0) {printf("releasing writer control//////////////\n");signal(writer);} printf("releasing mutex again\n"); signal(mutex); printf("mutex released\n"); } return 0; }
C
#include<stdio.h> int main(void) { int Number, Counter = 0; printf("How many natural numbers do you want to print?"); scanf("%d", &Number); printf("The first %d natural numbers are", Number); for(Counter = 1; Counter <= Number; Counter++) { printf(" %d", Counter); } printf("."); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* raycast.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vomelchu <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/19 16:06:33 by vomelchu #+# #+# */ /* Updated: 2018/08/19 16:06:35 by vomelchu ### ########.fr */ /* */ /* ************************************************************************** */ #include "wolf.h" void second_part_ray(t_data *data) { if (RAY_DIR_X < 0) { STEP_X = -1; SIDE_DIST_X = (POS_X - MAP_X) * DELTA_DIST_X; } else { STEP_X = 1; SIDE_DIST_X = (MAP_X + 1.0 - POS_X) * DELTA_DIST_X; } if (RAY_DIR_Y < 0) { STEP_Y = -1; SIDE_DIST_Y = (POS_Y - MAP_Y) * DELTA_DIST_Y; } else { STEP_Y = 1; SIDE_DIST_Y = (MAP_Y + 1.0 - POS_Y) * DELTA_DIST_Y; } } void dda_ray(t_data *data) { while (HIT == 0) { if (SIDE_DIST_X < SIDE_DIST_Y) { SIDE_DIST_X += DELTA_DIST_X; MAP_X += STEP_X; SIDE = 0; } else { SIDE_DIST_Y += DELTA_DIST_Y; MAP_Y += STEP_Y; SIDE = 1; } if (data->array[MAP_Y][MAP_X] > 0 && data->array[MAP_Y][MAP_X] < data->max_box) HIT = 1; } } void first_part_ray(t_data *data) { CAMER_X = (double)((data->x * 2) / (double)(WIDTH) - 1); RAY_DIR_X = DIR_X + PLAN_X * CAMER_X; RAY_DIR_Y = DIR_Y + PLAN_Y * CAMER_X; MAP_X = (int)POS_X; MAP_Y = (int)POS_Y; DELTA_DIST_X = fabs(1 / RAY_DIR_X); DELTA_DIST_Y = fabs(1 / RAY_DIR_Y); HIT = 0; second_part_ray(data); dda_ray(data); } void calculate_drawing(t_data *data) { if (SIDE == 0) PERP_WALL_DIST = (MAP_X - POS_X + (1 - STEP_X) / 2) / RAY_DIR_X; else PERP_WALL_DIST = (MAP_Y - POS_Y + (1 - STEP_Y) / 2) / RAY_DIR_Y; LINE_HEIGHT = (int)(HEIGHT / PERP_WALL_DIST); DRAW_START = -LINE_HEIGHT / 2 + HEIGHT / 2; if (DRAW_START < 0) DRAW_START = 0; DRAW_END = LINE_HEIGHT / 2 + HEIGHT / 2; if (DRAW_END >= HEIGHT) DRAW_END = HEIGHT - 1; } void raycasting(t_data *data) { data->x = -1; while (++data->x < WIDTH) { first_part_ray(data); calculate_drawing(data); draw_wall(data); find_floorwall(data); dr_floor(data); if (data->x == WIDTH / 2) chek_door(data); } sprites(data); }
C
#include <stdio.h> // version 1 // arguments: counter, valuables[] // int main(int argc, char *argv[]) // { // int i; // for (i = 1; i < argc; i++) { // printf("%s%s", argv[i], (i == argc) ? "" : " "); // } // printf("\n"); // return 0; // } // version 2 int main(int argc, char *argv[]) { while (--argc > 0) // first argument is the name of this file // printf("%s%s", *(++argv), (argc > 1) ? " " : ""); printf((argc > 1) ? "%s " : "%s", *++argv); printf("\n"); return 0; }
C
/* * File: squareTensorField.c * * MATLAB Coder version : 3.1 * C/C++ source code generated on : 12-May-2016 09:08:19 */ /* Include Files */ #include "rt_nonfinite.h" #include "squareTensorField.h" /* Function Definitions */ /* * SQUAREDTI Input is an MxNx3x3 (4D) or MxNxPx3x3 (5D) tensor field matrix. * The tensor elements will be squared * Arguments : double D[2359296] * Return Type : void */ void squareTensorField(double D[2359296]) { int ii; int jj; int kk; double b[9]; int k; double b_b[9]; int i0; int i1; for (ii = 0; ii < 64; ii++) { for (jj = 0; jj < 64; jj++) { for (kk = 0; kk < 64; kk++) { for (k = 0; k < 9; k++) { b[k] = D[(((ii + (jj << 6)) + (kk << 12)) + (k % 3 << 18)) + 786432 * (k / 3)]; } for (k = 0; k < 3; k++) { for (i0 = 0; i0 < 3; i0++) { b_b[k + 3 * i0] = 0.0; for (i1 = 0; i1 < 3; i1++) { b_b[k + 3 * i0] += b[k + 3 * i1] * b[i1 + 3 * i0]; } } } for (k = 0; k < 3; k++) { for (i0 = 0; i0 < 3; i0++) { D[(((ii + (jj << 6)) + (kk << 12)) + (i0 << 18)) + 786432 * k] = b_b[i0 + 3 * k]; } } } } } } /* * File trailer for squareTensorField.c * * [EOF] */
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #include<limits.h> #define scan1(a) scanf("%d",&a) #define scan2(b,c) scanf("%d %d", &b, &c) #define scan3(d,e,f) scanf("%d %d %d", &d, &e, &f) #define pn() printf("\n"); #define print1(a) printf("%d\n", a) #define print2(a,b) printf("%d %d\n", a, b) #define print3(a,b,c) printf("%d %d %d\n", a, b, c) #define loop(i,n) for(int i=0;i<n;i++) #define max(a,b) (a>b)?a:b #define min(a,b) (a<b)?a:b int arr[100]; void insert(int len, int num) { arr[len] = num; } int count(int num, int len) { int ct = 0; loop(i,len) { if(arr[i] == num) ct++; } return ct; } int findid(int num, int len) { loop(i,len) { if(arr[i] == num) return i; } } int main() { int q; scan1(q); int len = 0, high = 0,low = 9999; loop(i,q) { int qt; scan1(qt); if(qt == 1) { int num; scan1(num); insert(len++, num); if(num > high) high = num; if(num < low) low = num; // print2(high,low); } else if(qt == 2) { int idh = findid(high, len); int idl = findid(low, len); int diff = arr[idh] - arr[idl]; if(high == 0 && low == 9999) print1(-1); else print1(diff); high = 0, low = 9999; arr[idh] = -1, arr[idl] = -1; } else if(qt == 3) { int val = count(high,len); if(val == 0) print1(-1); else print1(val); } else if(qt == 4) { int val = count(low,len); if(val == 0) print1(-1); else print1(val); } } return 0; }
C
#include <stdio.h> int gcd(int u, int v) { int temp; while (v != 0) { temp = u % v; u = v; v = temp; } return u; } int lcm(int u, int v) { int gcd(int u, int v); return u * v / gcd(u, v); } int main(void) { int lcm(int u, int v); printf("10 和 15 的最小公倍数:%i\n", lcm(10, 15)); return 0; }
C
#include<stdio.h> #include<pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void * thread1(void * arg) { pthread_cleanup_push(pthread_mutex_unlock,&mutex); while(1) { printf("thread1 running\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("thread1 applied the condition\n"); pthread_mutex_unlock(&mutex); sleep(4); } pthread_cleanup_pop(0); } void * thread2(void * arg) { while(1) { printf("thread2 running\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("thread2 applied the condition\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main() { pthread_t t1,t2; pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); pthread_create(&t1,NULL,&thread1,NULL); pthread_create(&t2,NULL,&thread2,NULL); do { pthread_cond_signal(&cond); }while(1); sleep(20); pthread_exit(0); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* reso.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: chle-van <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/04 03:26:01 by chle-van #+# #+# */ /* Updated: 2016/12/18 06:50:29 by chle-van ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" int ft_res2(t_piece *list, char **map, int size) { t_map coord; coord.i = 0; coord.j = 0; coord.tmp = list; return (ft_res(list, map, size, coord)); } int ft_res(t_piece *list, char **map, int size, t_map coord) { while (coord.tmp) { if (!coord.tmp->place) while (coord.i <= size - coord.tmp->h) { while (coord.j <= size - coord.tmp->l) { if (map[coord.i][coord.j] == '.') if (ft_tplace(map, coord.tmp, coord.i, coord.j)) { if (!ft_res2(list, map, size)) ft_tplace(map, coord.tmp, coord.i, coord.j); else return (1); } coord.j++; } coord.j = 0; coord.i++; } coord.tmp = coord.tmp->next; } return (ft_allpl(list)); } int ft_tplace(char **map, t_piece *piece, int i, int j) { if (ft_p00(map, i, j, piece)) { if (!piece->place) piece->place = 1; else piece->place = 0; return (1); } return (0); } char ft_dot(t_piece *piece) { if (piece->place) return ('.'); else return (piece->letter); } char ft_diez(t_piece *piece) { if (!piece->place) return ('.'); else return (piece->letter); }
C
// // main.c // CSC362-Programming-Assignment4 // // Created by Andrew Smiley on 3/22/16. // Copyright © 2016 Andrew Smiley. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { int input, sumOfFactors, closeness,currentFactor; sumOfFactors = 0;closeness=0;input=2;currentFactor=0; while(input > 1){ printf("Enter a number: "); scanf("%d", &input); __asm{ mov currentFactor, 0 //we always want to start this out by setting to 0, because they will have retained their value from the last time mov sumOfFactors, 0 mov closeness, 0 loop: inc currentFactor mov eax, currentFactor cmp eax, input je calcperc mov eax, input mov edx, 0 div currentFactor cmp edx, 0 jne loop mov eax, currentFactor add eax, sumOfFactors mov sumOfFactors, eax jmp loop calcperc: mov eax, sumOfFactors sub eax, input cmp eax, 0 jle negate jmp muldiv negate: neg eax jmp muldiv muldiv: mov edx, 0 mov ecx, 100 mul ecx mov edx, 0 div input mov closeness, eax } printf("\nOf the input %d, the closeness was %d, we hit factor %d sum of factors %d\r", input, closeness, currentFactor,sumOfFactors); } /* mov eax, currentFactor sub eax, input cmp currentFactor, 0 //ok so first compare the current factor to the input je calcperc mov eax, input //prepare for division mov edx, 0 div currentFactor cmp edx, 0 //check to see if the remainder is 0, if it is, it's a factor jne loop //if it's not a factor, jump to the start of the loop mov eax, sumOfFactors add eax, currentFactor //if it is a factor, then we want to add it to our sum of factors mov sumOfFactors, eax jmp loop // now we just want to go back to the start of the loop calcperc: mov eax, currentFactor //prepare to write down the recipe! no seriously, prepare to do sum_of_factors-number mov edx, 0 mov ecx, 100 mul eax sub eax, input //prepare for the division bit mov edx, 0 div input mov closeness, eax */ return 0; }
C
/* write by buffer */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *rfp, *wfp; char buf[BUFSIZ]; int n; if((rfp = fopen("190120.txt", "r")) == NULL) { perror("fopen : .txt"); exit(1); } // fopen for read if((wfp = fopen("190120.out", "w")) == NULL) { perror("fopen : .out"); exit(1); } // fopen for write while((n = fread(buf, sizeof(char)*5, 3, rfp)) > 0) { fwrite(buf, sizeof(char)*5, n, wfp); } fclose(rfp); fclose(wfp); return 0; }
C
#include "fonctions.h" /*chaque fonction correspond a un type d'objet. La fonction est appel chaque fois qu'une ligne representant ce type d'objet est rencontr, et elle cr le struct correspondant et l'enregistre dans tabGroupes ou (*tabObjets)*/ /****************************************************************************************************************/ void texteStatiqueToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type texte statique"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } o.valeur=o.nom; (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void ligneToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type ligne"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void saisieTexteToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char* inttemp; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type saisie texte"; o.dansUnGroupe=0; i=0; inttemp=malloc(sizeof(char)*10); while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } o.valeur=o.nom; (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void boutonPoussoirToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type bouton poussoir"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } o.valeur=o.nom; (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void groupeToStruct(char* ligne,FILE* fhtml, int* nbGroupes, groupe** tabGroupes){ char inttemp[10]; int i,j,k; groupe o; o.nom=malloc(sizeof(char)*100); o.nbObjetsContenus=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabGroupes)=realloc((*tabGroupes),(*nbGroupes+1)*sizeof(groupe)); (*tabGroupes)[*nbGroupes]=o; (*nbGroupes)++; } void bouton3DToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type bouton poussoir"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } o.valeur=o.nom; (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void caseACocherToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type case cocher"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void caseACocher3DToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type case cocher 3D"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void listBoxToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type listbox"; o.dansUnGroupe=0; o.tailleTab=3; o.tab=malloc(sizeof(char)*6); o.tab[0]=malloc(sizeof(char)*6); o.tab[0]="coucou"; o.tab[1]="salut"; o.tab[2]="bonjour"; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void listeHierarchiqueToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type liste hirarchique"; o.dansUnGroupe=0; o.tailleTab=3; o.tab=malloc(sizeof(char)*6); o.tab[0]=malloc(sizeof(char)*6); o.tab[0]="coucou"; o.tab[1]="salut"; o.tab[2]="bonjour"; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void popupListeDeroulanteToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type popup liste droulante"; o.dansUnGroupe=0; o.tailleTab=3; o.tab=malloc(sizeof(char)*6); o.tab[0]=malloc(sizeof(char)*6); o.tab[0]="hello world"; o.tab[1]="bonjour le monde"; o.tab[2]="hallo welt"; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void ovaleToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type ovale"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void rectangleToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type rectangle"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void rectangleArrondiToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type rectangle arrondi"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void imageStatiqueToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type image statique"; o.dansUnGroupe=0; o.valeur="4d_image_exemple.jpg"; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void separateurToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type sparateur"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } void grilleDeBoutonsToStruct(char* ligne,FILE* fhtml, int* nbObjets, objet** tabObjets){ char inttemp[10]; int i,j,k; objet o; o.nom=malloc(sizeof(char)*100); o.type=malloc(sizeof(char)*25); o.type="Objet type grille de boutons"; o.dansUnGroupe=0; i=0; while(ligne[i]!='n'||ligne[i+1]!='a'||ligne[i+2]!='m'||ligne[i+3]!='e'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ o.nom[j]=ligne[i]; j=j+1; i=i+1; o.tailleNom=j; } while(ligne[i]!='l'||ligne[i+1]!='e'||ligne[i+2]!='f'||ligne[i+3]!='t'||ligne[i+4]!='='||ligne[i+5]!='"'){ i=i+1; } i=i+6; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.left=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='t'||ligne[i+1]!='o'||ligne[i+2]!='p'||ligne[i+3]!='='||ligne[i+4]!='"'){ i=i+1; } i=i+5; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.top=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='r'||ligne[i+1]!='i'||ligne[i+2]!='g'||ligne[i+3]!='h'||ligne[i+4]!='t'||ligne[i+5]!='='||ligne[i+6]!='"'){ i=i+1; } i=i+7; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.right=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } while(ligne[i]!='b'||ligne[i+1]!='o'||ligne[i+2]!='t'||ligne[i+3]!='t'||ligne[i+4]!='o'||ligne[i+5]!='m'||ligne[i+6]!='='||ligne[i+7]!='"'){ i=i+1; } i=i+8; j=0; while(ligne[i]!='"'){ inttemp[j]=ligne[i]; j=j+1; i=i+1; } o.bottom=(atoi(inttemp)); for(k=0;k<10;k++){ inttemp[k]=0; } (*tabObjets)=realloc((*tabObjets),(*nbObjets+1)*sizeof(objet)); (*tabObjets)[*nbObjets]=o; (*nbObjets)++; } /****************************************************************************************************************/ /*chaque fonction correspond a un type d'objet. La fonction est appel chaque fois qu'une objet correspondant a ce type d'objet est rencontr, elle ecris alors le html correspondant dans fhtml*/ /****************************************************************************************************************/ void texteStatiqueToHtml(objet o, FILE* fhtml){ int i; fprintf( fhtml, "%s", "\t<p>"); fprintf( fhtml, "%s", o.valeur); fprintf( fhtml, "%s", "</p>\n"); } void ligneToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<svg height=\"1000000\" width=\"10000000\">\n"); fprintf( fhtml, "%s", "\t <line x1=\""); fprintf( fhtml, "%d", o.left); fprintf( fhtml, "%s", "\" y1=\""); fprintf( fhtml, "%d", 0); fprintf( fhtml, "%s", "\" x2=\""); fprintf( fhtml, "%d", o.right); fprintf( fhtml, "%s", "\" y2=\""); fprintf( fhtml, "%d", o.bottom-o.top); fprintf( fhtml, "%s", "\" style=\"stroke:rgb(0,0,0);stroke-width:2\" />"); fprintf( fhtml, "%s", "</svg>\n"); } void saisieTexteToHtml(objet o, FILE* fhtml){ int i; fprintf( fhtml, "%s", "\t"); fprintf( fhtml, "%s", o.valeur); fprintf( fhtml, "%s", ": <input type=\"text\" value=\"\">\n"); } void boutonPoussoirToHtml(objet o, FILE* fhtml){ int i; fprintf( fhtml, "%s", "\t<button type=\"button\" onclick=\"alert('"); fprintf( fhtml, "%s", " ");/*retrour du bouton*/ fprintf( fhtml, "%s", "')\">"); fprintf( fhtml, "%s", o.valeur); fprintf( fhtml, "%s", "</button>\n"); } void bouton3DToHtml(objet o, FILE* fhtml){ int i; fprintf( fhtml, "%s", "\t<button type=\"button\" onclick=\"alert('"); fprintf( fhtml, "%s", " ");/*retrour du bouton*/ fprintf( fhtml, "%s", "')\">"); fprintf( fhtml, "%s", o.valeur); fprintf( fhtml, "%s", "</button>\n"); } void caseACocherToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<input type=\"checkbox\" checked> "); } void caseACocher3DToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<input type=\"checkbox\" checked> "); } void listBoxToHtml(objet o, FILE* fhtml){ int i; fprintf( fhtml, "%s", "\t<ul>\n"); for(i=0;i<o.tailleTab;i++){ fprintf(fhtml,"%s","\t\t<li>"); fprintf(fhtml,"%s",o.tab[i]); fprintf(fhtml,"%s","</li>\n"); } fprintf( fhtml, "%s", "\t</ul> \n"); } void listeHierarchiqueToHtml(objet o, FILE* fhtml){ int i; fprintf( fhtml, "%s", "\t<ol>\n"); for(i=0;i<o.tailleTab;i++){ fprintf(fhtml,"%s","\t\t<li>"); fprintf(fhtml,"%s",o.tab[i]); fprintf(fhtml,"%s","</li>\n"); } fprintf( fhtml, "%s", "\t</ol> \n"); } void popupListeDeroulanteToHtml(objet o, FILE* fhtml){ int i; fprintf( fhtml, "%s", "\t<select>\n"); for(i=0;i<o.tailleTab;i++){ fprintf(fhtml,"%s","\t\t<option value=\""); fprintf(fhtml,"%s",o.tab[i]); fprintf(fhtml,"%s","\">"); fprintf(fhtml,"%s",o.tab[i]); fprintf(fhtml,"%s","</option>\n"); } fprintf( fhtml, "%s", "\t</select> \n"); } void ovaleToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<div class=\"h"); fprintf( fhtml, "%d", o.style); fprintf( fhtml, "%s", "\"></div>\n"); } void rectangleToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<div class=\"h"); fprintf( fhtml, "%d", o.style); fprintf( fhtml, "%s", "\"></div>\n"); } void rectangleArrondiToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<div class=\"h"); fprintf( fhtml, "%d", o.style); fprintf( fhtml, "%s", "\"></div>\n"); } void imageStatiqueToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<img src=\""); fprintf( fhtml, "%s", o.valeur); fprintf( fhtml, "%s", "\" alt=\"trulli\" width=\""); fprintf( fhtml, "%d", o.right-o.left); fprintf( fhtml, "%s", "\" height=\""); fprintf( fhtml, "%d", o.bottom-o.top); fprintf( fhtml, "%s", "\">\n"); } void separateurToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<svg height=\"210\" width=\"500\">\n"); fprintf( fhtml, "%s", "\t <line x1=\""); fprintf( fhtml, "%d", o.left); fprintf( fhtml, "%s", "\" y1=\""); fprintf( fhtml, "%d", o.top); fprintf( fhtml, "%s", "\" x2=\""); fprintf( fhtml, "%d", o.right); fprintf( fhtml, "%s", "\" y2=\""); fprintf( fhtml, "%d", o.bottom); fprintf( fhtml, "%s", "\" style=\"stroke:rgb(0,0,0);stroke-width:2\" />"); fprintf( fhtml, "%s", "</svg>\n"); } void grilleDeBoutonsToHtml(objet o, FILE* fhtml){ fprintf( fhtml, "%s", "\t<div class=\"btn-group"); fprintf( fhtml, "%d", o.style); fprintf( fhtml, "%s", "\">\n"); fprintf( fhtml, "%s", "\t<div class=\"btn-line"); fprintf( fhtml, "%d", o.style); fprintf( fhtml, "%s", "\">\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t</div>\n"); fprintf( fhtml, "%s", "\t<div class=\"btn-line"); fprintf( fhtml, "%d", o.style); fprintf( fhtml, "%s", "\">\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t</div>\n"); fprintf( fhtml, "%s", "\t<div class=\"btn-line"); fprintf( fhtml, "%d", o.style); fprintf( fhtml, "%s", "\">\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t</div>\n"); fprintf( fhtml, "%s", "\t<div class=\"btn-line"); fprintf( fhtml, "%d", o.style); fprintf( fhtml, "%s", "\">\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t\t<button class=\"button\">Button</button>\n"); fprintf( fhtml, "%s", "\t</div>\n"); fprintf( fhtml, "%s", "</div>\n"); } /****************************************************************************************************************/ void groupeToCss (groupe* g, FILE* fcss,int* numStyle){ int height; int width; int i; fprintf( fcss, "%s", ".flex-container"); fprintf(fcss, "%d", (*numStyle)) ; fprintf( fcss, "%s", " {\n"); /*partie placement : place la flexbox en fonction de ses coordonnes*/ fprintf( fcss, "%s", "\tposition: absolute;\n"); fprintf( fcss, "\tleft: "); fprintf(fcss, "%d", (g->left)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\ttop: "); fprintf(fcss, "%d", (g->top)) ; fprintf( fcss, "%s", "px;\n"); /*fin de la partie placement*/ /*partie style : determine l'apparence de la flexbox*/ fprintf( fcss, "%s", "\tdisplay: flex;\n"); fprintf( fcss, "%s", "\tbackground-color: Gray;\n"); fprintf( fcss, "%s", "}\n\n"); fprintf( fcss, "%s", ".flex-container"); fprintf(fcss, "%d", (*numStyle)) ; fprintf( fcss, "%s", " > div {\n"); fprintf( fcss, "%s", "\theight: "); fprintf( fcss, "%s", "\tbackground-color: #f1f1f1;\n"); /* fprintf( fcss, "%s", "\tmargin: 10px;\n"); fprintf( fcss, "%s", "\tpadding: 20px;\n"); fprintf( fcss, "%s", "\tfont-size: 30px\n"); fprintf( fcss, "%s", "}\n");*/ /*fin de la partie style*/ g->style=(*numStyle); (*numStyle)++; } void ovaleToCss(objet* o, FILE* fcss, int* numStyle){ fprintf( fcss, "%s", "h"); fprintf(fcss, "%d", (*numStyle)) ; fprintf( fcss, "%s", "{\n"); fprintf( fcss, "%s", "\tposition: absolute;\n"); fprintf( fcss, "%s", "\tleft: "); fprintf(fcss, "%d", (o->left)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\ttop: "); fprintf(fcss,"%d", (o->top)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\theight: "); fprintf( fcss, "%d", o->bottom-o->top); fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\twidth: "); fprintf( fcss, "%d", o->right-o->left); fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\tbackground-color: #555;\n"); fprintf( fcss, "%s", "\tborder-radius: 50%;\n"); } void rectangleToCss(objet* o, FILE* fcss, int* numStyle){ fprintf( fcss, "%s", "h"); fprintf(fcss, "%d", (*numStyle)) ; fprintf( fcss, "%s", "{\n"); fprintf( fcss, "%s", "\tposition: absolute;\n"); fprintf( fcss, "%s", "\tleft: "); fprintf(fcss, "%d", (o->left)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\ttop: "); fprintf(fcss,"%d", (o->top)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\theight: "); fprintf( fcss, "%d", o->bottom-o->top); fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\twidth: "); fprintf( fcss, "%d", o->right-o->left); fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\tbackground-color: #555;\n"); } void rectangleArrondiToCss(objet* o, FILE* fcss, int* numStyle){ fprintf( fcss, "%s", "h"); fprintf(fcss, "%d", (*numStyle)) ; fprintf( fcss, "%s", "{\n"); fprintf( fcss, "%s", "\tposition: absolute;\n"); fprintf( fcss, "%s", "\tleft: "); fprintf(fcss, "%d", (o->left)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\ttop: "); fprintf(fcss,"%d", (o->top)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\theight: "); fprintf( fcss, "%d", o->bottom-o->top); fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\twidth: "); fprintf( fcss, "%d", o->right-o->left); fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\tborder-radius: 25px;\n"); fprintf( fcss, "%s", "\tbackground-color: #555;\n"); } void grilleDeBoutonsToCss(objet* o, FILE* fcss, int* numStyle){ fprintf( fcss, "%s", ".btn-group "); fprintf(fcss, "%d", (*numStyle)) ; fprintf( fcss, "%s", ".button {\n"); fprintf( fcss, "%s", "\tposition: absolute;\n"); fprintf( fcss, "%s", "\tleft: "); fprintf(fcss, "%d", (o->left)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\ttop: "); fprintf(fcss,"%d", (o->top)) ; fprintf( fcss, "%s", "px;\n"); fprintf( fcss, "%s", "\tbackground-color: #4CAF50;\n"); fprintf( fcss, "%s", "\tborder: 1px solid green;\n"); fprintf( fcss, "%s", "\tcolor: white;\n"); fprintf( fcss, "%s", "\tpadding: 15px 32px;\n"); fprintf( fcss, "%s", "\ttext-align: center;\n"); fprintf( fcss, "%s", "\tdisplay: inline-block;\n"); fprintf( fcss, "%s", "\tfont-size: 16px;\n"); fprintf( fcss, "%s", "\tcursor: pointer;\n"); fprintf( fcss, "%s", "\twidth: 150px;\n"); fprintf( fcss, "%s", "\tdisplay: block;\n"); fprintf( fcss, "%s", "\t}\n"); fprintf( fcss, "%s", "\t\n"); fprintf( fcss, "%s", "\t.btn-group .button:not(:last-child) {\n"); fprintf( fcss, "%s", "\tborder-bottom: none;\n"); fprintf( fcss, "%s", "\t}\n"); fprintf( fcss, "%s", "\t.btn-group .button:hover {\n"); fprintf( fcss, "%s", "\tbackground-color: #3e8e41;\n"); fprintf( fcss, "%s", "\t}\n"); fprintf( fcss, "%s", "\t\n"); fprintf( fcss, "%s", ".btn-line"); fprintf(fcss, "%d", numStyle) ; fprintf( fcss, "%s", " .button {\n"); fprintf( fcss, "%s", "\tposition: relative;\n"); fprintf( fcss, "%s", "\tbackground-color: #4CAF50;\n"); fprintf( fcss, "%s", "\tborder: 1px solid green;\n"); fprintf( fcss, "%s", "\tcolor: white;\n"); fprintf( fcss, "%s", "\tpadding: 15px 32px;\n"); fprintf( fcss, "%s", "\ttext-align: center;\n"); fprintf( fcss, "%s", "\ttext-decoration: none;\n"); fprintf( fcss, "%s", "\tdisplay: inline-block;\n"); fprintf( fcss, "%s", "\tfont-size: 16px;\n"); fprintf( fcss, "%s", "\tcursor: pointer;\n"); fprintf( fcss, "%s", "\tfloat: left;\n"); fprintf( fcss, "%s", "\t}\n"); fprintf( fcss, "%s", "\t.btn-line .button:not(:last-child) {\n"); fprintf( fcss, "%s", "\tborder-right: none;\n"); fprintf( fcss, "%s", "\t}\n"); fprintf( fcss, "%s", "\t.btn-line .button:hover {\n"); fprintf( fcss, "%s", "\tbackground-color: #3e8e41;\n"); fprintf( fcss, "%s", "\t}\n"); }
C
#include <stdlib.h> #define NAME "xjs" //mod.h define NAME would not work #include "mod.h" #undef NAME #define NAME "xjs" //it would be warned redefined without undef int testStack(int); int main() { struct names myName = { .firstname="xu", .lastname="jiashu" }; printf("%s %s\n", myName.firstname, myName.lastname); printf("I'm %s\n", NAME); disp(); ddisp; printf("SQUARE:%d\n", SQUARE(5)); int XNAME(3) = 5; XNAME(3) = 3; char XNAME(4)[] = "x4"; printf("XNAME(3):%d\n", x3); printf("XNAME(4):%s\n", x4); printf("MAX(5,3):%d\n", MAX(5,3)); printf("ABS(-4):%d\n", ABS(-4)); testStack(5); double sumdb; sumdb = sum(5, 1.1, 2.1, 3.1, 4.1, 5.1); printf("sum(5, 1.1, 2.1, 3.1, 4.1, 5.1): %g", sumdb); return 0; } int testStack(int n) { if(n == 0) return n; else return testStack(n-1); }
C
#include <stdio.h> int main(void) { char str[1000], *st; int f; scanf("%s", str); st = str; f = 0; while(1) { if(st[0] == 0){ printf("\n"); break; } else if(st[0] == 'w' && st[1] == 'u' && st[2] == 'b') { st = st+3; continue; } else { if(f == 1) printf(" "); while(!(st[0] == 'w' && st[1] == 'u' && st[2] == 'b') && *st != 0) putchar(*st++); f = 1; } } return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main() { int fd; fd = open("guo1", O_WRONLY | O_CREAT | O_TRUNC, 0666); #if 0 close(1); dup(fd); #endif dup2(fd, 1); printf("guohaomeng\n"); close(fd); return 0; }
C
#define BIT_SET(a,b) ((a) |= (1<<b)) #define BIT_CLEAR(a,b) ((a) &= ~(1<<b)) #define BIT_FLIP(a,b) ((a) ^= (1<<b)) #define BIT_CHECK(a,b) (!!((a) & (1<<b))) #include <stdio.h> #include <stdlib.h> int main() { int number,position; printf("Enter a number :"); scanf("%d",&number); printf("\nposition "); scanf("%d",&position); printf("\ncheck : %d",BIT_CHECK(number,position)); printf("\nflip : %d",BIT_FLIP(number,position)); printf("\nclear : %d",BIT_CLEAR(number,position)); printf("\nset : %d",BIT_SET(number,position)); //printf("\ncheck : %d",BIT_CHECK(number,position)); }
C
#include "binaryheap.h" //judge whether the BinaryHeap is full or not , also 1 or 0 int isFull(BinaryHeap bh) { return bh->size == bh->capacity - 1 ? 1 : 0 ; } //judge whether the BinaryHeap is empty or not , also 1 or 0 int isEmpty(BinaryHeap bh) { return bh->size == 0 ? 1 : 0 ; } void swap(ElementType *x, ElementType *y) { ElementType temp; temp = *x; *x = *y; *y = temp; } // get the left child of node under index with startup 1 int leftChildFromOne(int index) { return index * 2; } ElementType deleteMin(BinaryHeap bh) { ElementType minimum; ElementType *data; if(isEmpty(bh)) { Error("failed deleting minimum , for the BinaryHeap is empty, from func deleteMin !"); return -1; } data = bh->elements; minimum = data[1]; swap(&data[1], &data[bh->size]); bh->size-- ; // size-- occurs prior to percolateDownFromOne percolateDownFromOne(1, bh) ; return minimum; } // Attention, the index of the heap starts from 1 void insert(ElementType value, BinaryHeap bh) { int i; if(isFull(bh)) { Error("failed insertion , for the BinaryHeap is full, from func insert!"); return ; } for(i = ++bh->size; bh->elements[i/2] > value; i /= 2) bh->elements[i] = bh->elements[i / 2]; bh->elements[i] = value; } BinaryHeap initBinaryHeap(int capacity) { BinaryHeap bh; ElementType *temp; bh = (BinaryHeap)malloc(sizeof(struct BinaryHeap)); if(!bh) { Error("out of space, from func initBinaryHeap"); return NULL; } bh->capacity = capacity; bh->size = 0; temp = (ElementType *)malloc(capacity * sizeof(ElementType)); if(!temp) { Error("out of space, from func initBinaryHeap"); return NULL; } bh->elements = temp; return bh; } void printBinaryHeap(BinaryHeap bh) { int i; ElementType *temp; if(!bh) Error("printing execution failure, for binary heap is null, from func printBinaryHeap"); temp = bh->elements; for(i = 1; i < bh->capacity; i++) { printf("\n\t index[%d] = ", i); if(i <= bh->size) printf("%d", bh->elements[i]); else printf("NULL"); } printf("\n"); } //print the binary heap who starts from index 0 void printBinaryHeapFromZero(BinaryHeap bh) { int i; ElementType *temp; if(!bh) Error("printing execution failure, for binary heap is null, from func printBinaryHeap"); temp = bh->elements; for(i = 0; i < bh->capacity; i++) { printf("\n\t index[%d] = ", i); if(i < bh->size) printf("%d", bh->elements[i]); else printf("NULL"); } printf("\n"); }
C
#include<stdio.h> void heapSort(int n,int A[]) { int k; for(int i=n-1;i>0;i--) { for(int j=k=i;j>=0;j--) { if(A[k]<A[j]) k=j; } void swapi(int &a,int &b) { int temp; temp=a; a=b; b=temp; } swapi(A[k],A[i]); } } int main() { int A[5]={4,3,2,8,1}; heapSort(5,A); for(int o=0;o<5;o++) { printf("%d",A[o]); } return 0; }
C
#include "basic_operators.h" uint8_t multiply_by_X_classic(uint8_t a) { return (a << 1) ^ ((a >> 7) * GF_2_8_module); } __m256i multiply_by_X_vector(__m256i a) { // _mm256_cmpgt_epi8 - Compare packed 8-bit integers in a and b for greater-than __m256i mask = _mm256_cmpgt_epi8(_mm256_setzero_si256(), a); // _mm256_set1_epi8 - Broadcast 8-bit integer a to all elements of dst mask = _mm256_and_si256(mask, _mm256_set1_epi8(GF_2_8_module)); // _mm256_slli_epi16 - Shift packed 16-bit integers in a left by imm8 while shifting in zeros, and store the results in dst a = _mm256_slli_epi16(a, 1); a = _mm256_and_si256(a, _mm256_set1_epi8(0xFE)); a = _mm256_xor_si256(a, mask); return a; } void multiply_by_X_RAIDIX(__m256i* a) { for (int i = 0; i < 7; i++) { _mm256_store_si256(a + i, _mm256_xor_si256(a[i], a[i + 1])); _mm256_store_si256(a + i + 1, _mm256_xor_si256(a[i + 1], a[i])); _mm256_store_si256(a + i, _mm256_xor_si256(a[i], a[i + 1])); } _mm256_store_si256(a + 1, _mm256_xor_si256(a[1], a[7])); _mm256_store_si256(a + 2, _mm256_xor_si256(a[2], a[7])); _mm256_store_si256(a + 3, _mm256_xor_si256(a[3], a[7])); } uint8_t multiply_A_by_B_classic(uint8_t a, uint8_t b) { uint8_t sum = 0; while (a && b) { if (b & 1) sum ^= a; a = multiply_by_X_classic(a); b = b >> 1; } return sum; } __m256i multiply_A_by_B_vector(__m256i a, uint8_t b) { __m256i sum = _mm256_setzero_si256(); while (b > 0) { if (b & 0x1) { sum = _mm256_xor_si256(sum, a); } a = multiply_by_X_vector(a); b = b >> 1; } return sum; } void multiply_A_by_B_RAIDIX(__m256i* a, uint8_t b, __m256i* sum) { while (b > 0) { if (b & 0x1) { for (int j = 0; j < 8; j++) { _mm256_store_si256(sum + j, _mm256_xor_si256(sum[j], a[j])); } } multiply_by_X_RAIDIX(a); b = b >> 1; } } uint64_t diff_ns(struct timespec start, struct timespec end) { struct timespec diff; //if number of nanoseconds in end less then in start we should take 1 sec if ((end.tv_nsec - start.tv_nsec) < 0) { diff.tv_sec = end.tv_sec - start.tv_sec - 1; diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec; } else { diff.tv_sec = end.tv_sec - start.tv_sec; diff.tv_nsec = end.tv_nsec - start.tv_nsec; } return diff.tv_sec * 1000000000 + diff.tv_nsec; } void print_stripe(uint8_t* const stripe, unsigned int number_of_disks) { for (unsigned int i = 0; i < (number_of_disks + 2) * size_of_strip; i++) { if (!(i % size_of_strip)) printf(" "); printf("%.2X", *(stripe + i)); } printf("\n"); }
C
#include<stdio.h> #include<conio.h> int main() { int a,b,i,d,c=0; scanf("%d %d",&a,&b); for(i=a+1;i<b;i++) { for(d=1;d<=i;d++) { if(i%d==0) { c++; } } if(c==2) { printf("%d",i); } } return 0; }
C
/*1. Develop a C program to perform operations (+,*,-, / and %) on two whole numbers. Identify suitable data types to represent the numbers and resultant values*/ #include<stdio.h> int main() { int a,b,modu; float quotient; int sum,diff,product; printf("Enter any two numbers\n"); scanf("%d%d",&a,&b); sum = a + b; if(a>b) { diff = a - b; } else { diff = b - a; } quotient = (float)a/b; modu = a%b; product = a*b; printf("sum is %d\n",sum); printf("diff is %d\n",diff); printf("product is %d\n",product); printf("Modulus is %d\n",modu); printf("Quotient is %f\n",quotient); return 0; }
C
/** * C Program to accept the array in server, find an element in client and display result in server * 2 way communication using 2 pipes * @author Shivaprasad Bhat * @date 17-12-2020 */ #include "../Headers/headers.h" #define READ 0 #define WRITE 1 int main() { int _pipe1[2], _pipe2[2], _read, _write; int _createPipe1, _createPipe2; int _array[100], _size, _key, i, _flag = 0, _child; // Parent process : Accept the Array printf("Enter the size of the array : "); scanf("%d", &_size); for (i = 0; i < _size; i++) { printf("Enter the element %d : ", i + 1); scanf("%d", &_array[i]); } _createPipe1 = pipe(_pipe1); _createPipe2 = pipe(_pipe2); if (_createPipe1 == -1 || _createPipe2 == -1) { perror("Failed to create pipes\n"); return 0; } _write = write(_pipe1[WRITE], _array, sizeof(_array)); printf("Written %d bytes to the pipe from parent\n\n", _write); _child = fork(); if (_child == 0) { int _readArray[100]; printf("Enter the key to be searched : "); scanf("%d", &_key); close(_pipe1[WRITE]); _read = read(_pipe1[READ], _readArray, sizeof(_readArray)); for (i = 0; i < _size; i++) { if (_readArray[i] == _key) { _flag = 1; break; } } _write = write(_pipe2[WRITE], &_flag, sizeof(_flag)); printf("Written %d bytes to pipe 2 from child\n\n", _write); printf("Result to the pipe 2 is %d\n\n", _flag); } else if (_child > 1) { wait(NULL); int _result; close(_pipe2[WRITE]); _read = read(_pipe2[READ], &_result, sizeof(_result)); printf("Read %d bytes from pipe 2 in parent\n", _read); printf("Result from pipe is is %d\n\n", _result); if (_result == 1) { printf("Element found\n"); } else { printf("Element not found\n"); } } else if (_child < 0) { perror("Failed to create fork\n"); return 1; } return 0; }
C
// // Created by vladworldss on 03.08.18. // #include <stdio.h> #include <string.h> #include "Item.h" #include "Stack.h" int main(int argc, char** argv){ printf("ex4_2 starting...\n"); char* a = argv[1]; int N = strlen(a); stack_init(N); for(int i=0; i<N; i++){ if (a[i] == PLUS){ stack_push(stack_pop() + stack_pop()); } else if (a[i] == MUL){ stack_push(stack_pop() * stack_pop()); } // инициализируем стек нулем, чтобы избежать StackPopError else if((a[i] >= ZERO) && (a[i] <= NINE)){ stack_push(0); } /* переводим число, пока не встретиться НЕ-числовой символ * 123 = * 1. stack.push(0) --> stack([0]) * 2. stack.push(10*stack.pop() --> 10*0 + ('1'-'0')) --> stack([1]) * 3. stack.push(10*stack.pop() --> 10*1 + ('2'-'0')) --> stack([12]) * 3. stack.push(10*stack.pop() --> 10*12 + ('3'-'0')) --> stack([123]) * * В бесконечном цикле происходит постфикс_инкремент указателя строки */ while((a[i] >= ZERO) && (a[i] <= NINE)){ stack_push(10*stack_pop() + (a[i++] - ZERO)); } } printf("%d \n", stack_pop()); }
C
#include<stdio.h> #include<stdlib.h> /* para gerar casos de teste */ void gera(int max) { int i, k; srandom(234556); /* para o que server :) */ for(i=0;i<max;i++) { k=random()%3; if (k==0) printf("a\n"); if (k==1) printf("c\n"); if (k==2) printf("t\n"); } printf("#\n"); exit(0); } #define ABS(X) ((X)>= 0? (X):(-(X))) int main(int v1, char **v2) { char c,velho; // if (v1>1) gera(atoi(v2[1])); c = getchar(); putchar(c); putchar('\n'); getchar(); velho = c; while((c=getchar())!='#') { if (velho==c) { printf("%c\n",c); } else if (ABS(velho-c)=='c'-'a') { printf("t\n"); } else if (ABS(velho-c)=='t'-'c') { printf("a\n"); } else printf("c\n"); velho = c; getchar(); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: atrepyto <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/24 15:54:58 by atrepyto #+# #+# */ /* Updated: 2017/04/12 16:18:12 by atrepyto ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractol.h" void ft_malloc_error(void) { ft_putendl("Malloc error"); exit(0); } static void display_usage(char *s) { ft_putstr("\033[1;31;05mUsage: "); ft_putstr(s); ft_putendl("\033[1;5;34m [Julia]\033[1;5;35m [Mandelbrot]" "\033[1;5;36m [BurningShip]\033[1;5;32m [Cantor]" "\033[1;5;34m [Brain]"); } int chose_fractal(char *s, char *s0) { if (ft_strcmp(s, "Julia") == 0) ft_window(s, 1); else if (ft_strcmp(s, "Mandelbrot") == 0) ft_window(s, 2); else if (ft_strcmp(s, "BurningShip") == 0) ft_window(s, 3); else if (ft_strcmp(s, "Cantor") == 0) ft_window(s, 4); else if (ft_strcmp(s, "Brain") == 0) ft_window(s, 5); else display_usage(s0); return (0); } int main(int ac, char **av) { pid_t pid; if (ac == 2) chose_fractal(av[1], av[0]); else if (ac == 3) { pid = fork(); if (pid == 0) chose_fractal(av[2], av[0]); else if (pid > 0) chose_fractal(av[1], av[0]); else return (1); } else display_usage(av[0]); return (0); }
C
//============================================================================= // // NAbZ[W [clear.h] // Author : shotaro kanamaru // //============================================================================= #ifndef _CLEAR_H_ #define _CLEAR_H_ #include "main.h" //***************************************************************************** // 񋓑̂̒` //***************************************************************************** typedef enum {// bZ[W^Cv TYPE_NORMAL = 0, // m[} TYPE_COMPLETE, // Rv[g TYPE_EMPTY, // ̑ TYPE_MAX, }CLEARTYPE; typedef enum {// STATE_NONE = 0, // ҋ@ STATE_RESET, // Zbg STATE_START, // N STATE_MAX, }CLEARSTATE; typedef enum {// bZ[W̕ MESSAGE_BAND = 0, // MESSAGE_UP, // 㕔 MESSAGE_DOWN, // MESSAGE_ONE, // 1 MESSAGE_TWO, // 2 MESSAGE_THREE, // 3 MESSAGE_FOUR, // 4 MESSAGE_MAX, // ő吔 }CLEARMESSAGE; //***************************************************************************** //\̂̒` //***************************************************************************** typedef struct {// bZ[W D3DXVECTOR3 pos; // ݈ʒu D3DXVECTOR3 move; // ړ D3DXVECTOR3 size; // 傫 D3DXCOLOR col; // F CLEARTYPE type; // bZ[W^Cv bool bUse; // gp }Clear; typedef struct {// ̑ݒ LPDIRECT3DVERTEXBUFFER9 pVtxBuff = NULL; // _obt@ւ̃|C^ LPDIRECT3DTEXTURE9 pTexture[MESSAGE_MAX] = {}; // eNX`ւ̃|C^ CLEARTYPE type; // bZ[W^Cv CLEARSTATE state; // int nCntAll; // ʃJE^ int nCntDraw; // \JE^ bool bSwitch; // ړ̐ؑ }ClearOther; //***************************************************************************** // vg^Cv錾 //***************************************************************************** void InitClear(void); void UninitClear(void); void UpdateClear(void); void DrawClear(void); void SetClearMessage(const CLEARTYPE type); #endif
C
#include <stdio.h> #include <highgui.h> #include <cv.h> #define WIDTH 640 #define HEIGHT 480 int main(int argc, char **argv) { int key=0, hist_size = 256, hist_height = 100; float r=0, range[]={3,128}; float* ranges[]={range}; double area=0; CvScalar s; CvCapture *capture = NULL; IplImage *frameImage; char before, after, result, nichika, labeling, histogram; IplImage *beforeImage = cvCreateImage( cvSize(WIDTH, HEIGHT),IPL_DEPTH_8U,1); IplImage *afterImage = cvCreateImage( cvSize(WIDTH, HEIGHT),IPL_DEPTH_8U,1); IplImage *differenceImage =cvCreateImage( cvSize(WIDTH, HEIGHT),IPL_DEPTH_8U,1); IplImage *nichiImage = cvCreateImage( cvSize(WIDTH, HEIGHT),IPL_DEPTH_8U,1); IplImage *labelingImage = cvCreateImage( cvSize(WIDTH, HEIGHT),IPL_DEPTH_8U,3); cvNamedWindow("before",1); cvNamedWindow("after",1); cvNamedWindow("result",1); cvNamedWindow("nichika",1); cvNamedWindow("labeling",1); cvNamedWindow("histogram",1); if( (capture = cvCreateCameraCapture(0)) == NULL){ printf("no camera\n"); return 0; } while(1){ frameImage = cvQueryFrame( capture ); cvCvtColor( frameImage, beforeImage, CV_BGR2GRAY ); key = cvWaitKey(10); if(key==0x61){ break;} } while(1){ frameImage = cvQueryFrame( capture ); cvCvtColor( frameImage, afterImage, CV_BGR2GRAY ); cvAbsDiff( afterImage, beforeImage, differenceImage ); cvShowImage( "before", beforeImage); cvShowImage( "after", afterImage ); for(int i = 0 ; i < differenceImage->height; i++){ for(int j = 0 ; j < differenceImage->width; j++){ s = cvGet2D( differenceImage, i,j); /* if(30 > s.val[0] > 0){ s.val[0]=10; }else if(60 > s.val[0] > 30){ s.val[0]=20; }else if(90 > s.val[0] > 60){ s.val[0]=30; }else if(120 > s.val[0] > 90){ s.val[0]=40; }else if(s.val[0] > 120){ s.val[0]=50; }*/ } } // cvThreshold( differenceImage, nichiImage, 0, 255, CV_THRESH_BINARY); /* cvZero(labelingImage); CvMemStorage *storage = cvCreateMemStorage(0); CvSeq *cont = NULL; cvFindContours( differenceImage, storage, &cont, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, cvPoint(0,0)); for(;cont;cont = cont->h_next){ area=fabs(cvContourArea(cont, CV_WHOLE_SEQ)); printf("area=%f\n", area); // cvDrawContours( labelingImage, cont, CV_RGB( 255, 0, 0), CV_RGB( 255, 0, 0), 2, 1, 8, cvPoint(0, 0)); CvScalar color = CV_RGB(rand()&255, rand()&255, rand()&255); cvDrawContours( labelingImage, cont, color, color, 1, 1, 8, cvPoint(0, 0)); }*/ //创建一维直方图,统计图像在[0 255]像素的均匀分布 CvHistogram* gray_hist = cvCreateHist(1,&hist_size,CV_HIST_ARRAY,ranges,1); //计算灰度图像的一维直方图 cvCalcHist(&differenceImage,gray_hist,0,NULL); //归一化直方图 cvNormalizeHist(gray_hist,1.0); int scale = 1; //创建一张一维直方图的“图”,横坐标为灰度级,纵坐标为像素个数(*scale) IplImage* hist_image = cvCreateImage (cvSize(hist_size*scale,hist_height),8,1); cvZero(hist_image); //统计直方图中的最大直方块 float max_value = 0; cvGetMinMaxHistValue(gray_hist, 0,&max_value,0,0); //分别将每个直方块的值绘制到图中 for(int i=0;i<hist_size;i++) { float bin_val = cvQueryHistValue_1D(gray_hist,i); //像素i的概率 if(bin_val>r){ r=bin_val; printf("%d/n",i);} int intensity = cvRound(bin_val*hist_height/max_value); //要绘制的高度 cvRectangle(hist_image, cvPoint(i*scale,hist_height-1), cvPoint((i+1)*scale - 1, hist_height - intensity), CV_RGB(255,255,255)); } cvShowImage( "histogram", hist_image); cvShowImage( "result", differenceImage); // cvShowImage( "nichika", nichiImage); // cvShowImage( "labeling", labelingImage); // printf("MAX=%f\n",r); // if(area>1){ // break;} key = cvWaitKey(10); if(key==0x1b){ break; }else if(key==0x61){ frameImage = cvQueryFrame( capture ); cvCvtColor( frameImage, beforeImage, CV_BGR2GRAY ); } } cvReleaseCapture( &capture ); cvReleaseImage( &beforeImage); cvReleaseImage( &afterImage ); cvReleaseImage( &differenceImage ); cvReleaseImage( &nichiImage ); cvReleaseImage( &labelingImage ); cvDestroyWindow( "before" ); cvDestroyWindow( "after" ); cvDestroyWindow( "result" ); cvDestroyWindow( "nichika" ); cvDestroyWindow( "labeling" ); cvDestroyWindow( "histogram" ); return 0; } /* while (1){ // if (capture) after_img=cvQueryFrame(capture); for (int i = 0; i < after_img->height; i++) { for (int j = 0; j < after_img->width; j++) { pixel1 = cvGet2D(after_img, i, j); pixel2 = cvGet2D(before_img, i, j); B = pixel1.val[0] - pixel2.val[0]; G = pixel1.val[1] - pixel2.val[1]; R = pixel1.val[2] - pixel2.val[2]; printf("B=%f,G=%f,R=%f\n", B,G,R); B = 0; G = 0; R = 0; } } cvWaitKey(0); } cvWaitKey(0); cvDestroyWindow("after_image"); cvDestroyWindow("before_image"); cvReleaseImage(&before_img); cvReleaseImage(&after_img); // cvReleaseCapture (&capture); return 0; } */
C
#include <stdio.h> #include <stdlib.h> void print(char**, int); void printint(int**, int,int); void step(int**, int, int); void find_path(int**, int, int, int, int, int, int); int main(int argv, char* argc[]) { if (argv == 1) { printf("input the maze file! ./maze <mazefile>\n"); return 1; } FILE* fp = fopen(argc[1], "r"); int width, height, w, h; int ir, ic, or, oc; fscanf(fp, "w:%d h:%d\n", &width, &height); printf("width:%d height:%d\n", width, height); char** maze = malloc(sizeof(char*) * height); int** mazedat = malloc(sizeof(int*) * height); for (h = 0; h < height; h++) { maze[h] = malloc(sizeof(char) * width); mazedat[h] = malloc(sizeof(int) * width); fgets(maze[h], width+2, fp); for (w = 0; w < width; w++) { switch (maze[h][w]) { case '#': mazedat[h][w] = -1; break; case ' ': mazedat[h][w] = 0; break; case 'I': mazedat[h][w] = 1; ir = h; ic = w; break; case 'O': mazedat[h][w] = 0; or = h; oc = w; break; default: mazedat[h][w] = -2; break; } } } while (mazedat[or][oc] == 0) { step(mazedat,height, width); } find_path(mazedat, height, width, or, oc, ir, ic); printint(mazedat, height, width); } void printint(int** matrix, int height, int width) { int i, j; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if (matrix[i][j] > -1) { if (matrix[i][j] > 0) printf("%2d", matrix[i][j] % 100); else printf(" "); } else if (matrix[i][j] == -3) { printf("--"); } else { printf("##"); } } printf("\n"); } } void step(int** matrix, int height, int width) { int i, j; int** old = malloc(sizeof(int*) * height); // copies matrix for (i = 0; i < height; i++) { old[i] = malloc(sizeof(int) * width); for (j = 0; j < width; j++) { old[i][j] = matrix[i][j]; } } int t, b, l, r; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { t = (i > 0) && (old[i-1][j] > 0); b = (i < height - 1) && (old[i+1][j] > 0); l = (j > 0) && (old[i][j-1] > 0); r = (j < width - 1) && (old[i][j+1] > 0); if ((matrix[i][j] > 0) || ((matrix[i][j] > -1) && (t || b || l || r )) ) { matrix[i][j]++; } } } for (i = 0; i < height; i++) { free(old[i]); } free(old); } void find_path(int** matrix, int height, int width, int oi, int oj, int ii, int ij) { int i, j, next; i = oi; j = oj; next = 2; // matrix[oi][oj] + 1; matrix[i][j] = -3; // sign for path. while ( i != ii || j != ij) { if ((i > 0) && (matrix[i-1][j] == next)) { i--; } else if ((i < height - 1) && (matrix[i+1][j] == next)) { i++; } else if ((j > 0) && (matrix[i][j-1] == next)) { j--; } else if ((j < width - 1) && (matrix[i][j+1] == next)) { j++; } else { printf("this broke while converting data to readable path\n"); exit(-1); } matrix[i][j] = -3; next++; } for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if ((matrix[i][j] != -3) && (matrix[i][j] != -1)) { matrix[i][j] = 0; } } } }
C
#include <stdio.h> int main(void) { int num, start; while (1) { fputs("Ȧ (1), ¦ (2) : ", stdout); scanf("%d", &num); if (num != 1 && num != 2) { puts("߸ ԷԴϴ. 1 Ǵ 2 Էϼ."); } else break; } /* if (num == 1) { for (int i = 3; i <= 9; i += 2) { for (int j = 1; j <= 9; j++) { printf("%d X %d = %d\n", i, j, i*j); } } } else { for (int i = 2; i <= 8; i += 2) { for (int j = 1; j <= 9; j++) { printf("%d X %d = %d\n", i, j, i*j); } } } */ for ((start = (num == 2) ? 2 : 3); start <= 9; start += 2) { for(int i=1; i<=9; i++) printf("%d X %d = %d\n", start, i, start*i); } fputs(" Է : ", stdout); scanf("%d", &num); for (int i = 0; i <= 100; i++) { for (int j = 0; j <= 100; j++) { for (int k = 0; k <= 100; k++) { if ((i*j - k) == num) { printf("(%d) X (%d) - (%d) = (%d)\n", i, j, k, num); } } } } return 0; }
C
#include <stdio.h> #include <unistd.h> main() { char *tmp; char command[1024]; unsigned int size; void *res; int i = 0; sprintf(command, "mv top1.log /tmp/tmp1.log"); fprintf(stderr,"\"%s\" is ready", command); system(command); fprintf(stderr,"\"%s\" is complete", command); exit(0); }
C
/********************************************************** *file name :parser.h *describe : do parser transcode works *copyright :written by dempkwok *time : 2013.6.10 ********************************************************** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "glodef.h" /* #define MAX_SYMBOL_TABLE_SIZE 500 #define MAX_STACK_HEIGHT 2000 #define MAX_CODE_LENGTH 500 #define MAX_LEXI_LEVELS 3 //struct define typedef struct { int kind; // const = 1, var = 2, proc = 3 int name; // name up to 11 chars int val; // number (ASCII value) int level; // L level int addr; // M address } symbol; //used to store instructions in the internal code array typedef struct { int op; int l; int m; } instruct; //function declaration int parser(int printFlag); char* tokenToString (int token); int block (int token); int getToken (void); int statement (int token); int condition (int token); int expression (int token); int term (int token); int factor (int token); void emit (int op, int l, int m); //identifier declaration and define symbol symbol_table[MAX_SYMBOL_TABLE_SIZE]; int symbolCounter= 0; int fetchCounter= 0; int inputTable[MAX_SYMBOL_TABLE_SIZE]; int inputCounter= 0; instruct code[MAX_SYMBOL_TABLE_SIZE*3]; int codeCounter= 0; int stackCounter= 0; int sum = 0; int saveCondition; int stackCounters[MAX_LEXI_LEVELS]; int numLexemes= 0; int currentLevel= 0; int procedureLevel= 0; int jumpLocation[MAX_LEXI_LEVELS]; int doThenCheck = 0; FILE* input; FILE* output; FILE* genout; int printFlag;*/ int parser(int print) { int i; int temp; printFlag= print; int ident[MAX_IDENT_NUM]; input = fopen("scanout.txt","r"); output= fopen("parseout.txt","w"); genout= fopen("genout.txt", "w"); //read in the input from file. here, we're just going to do a dumb print. no checking while (fscanf(input, "%d", &temp) != EOF) { inputTable[inputCounter]= temp; inputCounter++; //if there's an identifier, handle that special case if (temp == identsym) { fscanf(input, "%d", &temp); inputTable[inputCounter] = temp; inputCounter++; fprintf(output,"identsym.%d ", temp); if (printFlag ==1) printf("identsym.%d ", temp); //since we handled this, no need for more printing continue; } if (temp == constsym||temp == beginsym || temp ==intsym ||temp == thensym || temp ==periodsym || temp == dosym || temp==commasym ||temp == semicolonsym) { fprintf(output, "%s \n", tokenToString(temp)); if (printFlag ==1) printf("%s \n", tokenToString(temp)); //since we handled this, no need for more printing continue; } //if there's a number literal, handle that special case else if (temp == numbersym) { fscanf(input, "%d", &temp); inputTable[inputCounter] = temp; inputCounter++; fprintf(output,"numbersym.%d ", temp); if (printFlag ==1) printf("numbersym.%d ", temp); //since we handled this, no need for more printing continue; } //otherwise, pass the input we read to the toString function and print it fprintf(output, "%s ", tokenToString(temp)); if (printFlag ==1) printf("%s ", tokenToString(temp)); } block(getToken()); //still initialized to whatever the last thing we read in was, this is why it works if (temp != periodsym) { fprintf(output,"Expected period at end of program file\n"); if (printFlag ==1) { printf("Expected period at end of program file\n"); printf("Press any key to continue") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } //if we reach this, everthing is correct! hooray! //fprintf(output,"\n\nNo errors, program is syntactically correct\n"); if (printFlag ==1) printf("\n\nNo errors, program is syntactically correct\n"); //print out generated code to submit to the VM printf("\n------GENERATED CODE------\n\n"); for(i = 0; i<codeCounter; i++) { fprintf(genout, "%d %d %d\n\n", code[i].op, code[i].l, code[i].m); if (printFlag ==1) printf("%d %d %d\n\n", code[i].op, code[i].l, code[i].m); } fclose(input); fclose(output); fclose(genout); return 0; } int block(int token) { //3 emits for proper codeCounter for SP,BP, and RA emit(inc,0,1); emit(inc,0,1); emit(inc,0,1); //handle constants if (token == constsym) { symbol newConst; do { //fetch what should be an identifier numbering from scanner token= getToken(); //assign the type of the identifier newConst.kind= 1; if (token != identsym) { fprintf(output, "const, int, procedure must be followed by identifier.\n"); if (printFlag ==1) { printf("const, int, procedure must be followed by identifier.\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } //fetch identifer name (an integer) token = getToken(); if(findinsymbol_table(token)==1) { fprintf(output, "Found a repeated identifier in const defination block .\n"); if (printFlag ==1) { printf("Found a repeated identifier in const defination block .\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } newConst.name = token; token= getToken(); if (token != eqlsym) { fprintf(output, "identifier must be followed by equals symbol\n"); if (printFlag ==1) { printf("identifier must be followed by equals symbol\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token= getToken(); if (token != numbersym) { fprintf(output,"equals symbol must be followed by a number\n"); if (printFlag ==1) { printf("equals symbol must be followed by a number\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token = getToken(); newConst.val= token; //store the sumbol in the symbol table and increment the counter symbol_table[symbolCounter] = newConst; symbol_table[symbolCounter].addr = stackCounter; symbol_table[symbolCounter].level= currentLevel; symbolCounter++; token= getToken(); } while (token == commasym); //run until we meet something that isn't a comma if (token != semicolonsym) { fprintf(output, "Semicolon or comma missing.\n"); if (printFlag ==1) { printf("Semicolon or comma missing.\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token= getToken(); } //found an integer if (token == intsym) { symbol newInt; newInt.kind=2; do { token= getToken(); if (token != identsym) { fprintf(output, "const, int, procedure must be followed by identifier.\n"); if (printFlag ==1) { printf("const, int, procedure must be followed by identifier.\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } //store everything to symbol token = getToken(); if(findinsymbol_table(token)==1) { fprintf(output, "Found a repeated identifier in integer defination block .\n"); if (printFlag ==1) { printf("Found a repeated identifier in integer defination block .\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } newInt.name = token; newInt.val = 0; newInt.addr = stackCounter; //make space on stack emit(inc, 0 ,1); //add symbol to symbol table symbol_table[symbolCounter] = newInt; symbol_table[symbolCounter].level= currentLevel; symbolCounter++; token= getToken(); } while (token == commasym); if (token != semicolonsym) { fprintf(output, "Semicolon or comma missing.\n"); if (printFlag ==1) { printf("Semicolon or comma missing.\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token= getToken(); } //handles procedures if (token == procsym) { symbol newProc; jumpLocation[procedureLevel] = codeCounter; //emit a jump that we will edit later to skip all the declaration code emit(jmp, 0, 0); newProc.kind=3; //should be ident token= getToken(); if (token != identsym) { fprintf(output, "procedure declaration must be followed by identifier\n"); if (printFlag ==1) { printf("procedure declaration must be followed by identifier\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } //this is the name of the proc token = getToken(); if(findinsymbol_table(token)==1) { fprintf(output, "Found a repeated identifier in procedure defination block .\n"); if (printFlag ==1) { printf("Found a repeated identifier in procedure defination block .\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } newProc.name=token; newProc.addr= codeCounter; symbol_table[symbolCounter] = newProc; symbol_table[symbolCounter].level= currentLevel; symbolCounter++; //this should be the semicolon token= getToken(); if (token != semicolonsym) { fprintf(output, "Semicolon missing after procedure declaration\n"); if (printFlag ==1) printf("Semicolon missing after procedure declaration\n"); exit(EXIT_FAILURE); } //this is the first token after the declaration, the start of the function definition token= getToken(); //incremement the lexeme counter because now we are looking at nested procedure declarations currentLevel++; procedureLevel++; //since we're working in a new procedure at this point, set the stack counter to zero. store //current stack value so we can get it back stackCounters[numLexemes] = stackCounter; numLexemes++; stackCounter= 0; //generate code for the procedure token= block(token); //now that we've generated code for this procedure, return to the actual stack values stackCounters[numLexemes]=0; numLexemes--; stackCounter= stackCounters[numLexemes]; if (token != semicolonsym) { fprintf(output, "Semicolon missing at end of procedure description\n"); if (printFlag ==1) { printf("Semicolon missing at end of procedure description\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } //set up next token token= getToken(); procedureLevel--; //edit the jump to skip it all code[jumpLocation[procedureLevel]].m = codeCounter; } //after every declaration, do work token = statement(token); //decrement current level, we need to get out of the recursion --l0 currentLevel--; return token; } int statement(int token) { //global counter, tells where we are in the code list int codeIndex; if (token == identsym) { //we found an identsym, now get that identifier's name token = getToken(); //make sure if this identifier has been declared if(findinsymbol_table(token)==0) { fprintf(output, "Undefined identifier .\n"); if (printFlag ==1) { printf("Undefined identifier .\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } for(codeIndex = 0; codeIndex< symbolCounter; codeIndex++) { if(symbol_table[codeIndex].name == token && symbol_table[codeIndex].kind == 2) { break; //if we found the identifier in our symbol table, stop looping. we will use this index from here out. } } token= getToken(); if (token != becomessym) { fprintf(output, "Incorrect symbol following declaration statement\n"); if (printFlag ==1) { printf("Incorrect symbol following declaration statement\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token= getToken(); token = expression(token); emit(sto,currentLevel - symbol_table[codeIndex].level ,symbol_table[codeIndex].addr); } //Runs when the call command is executed. else if (token == callsym) { stackCounters[numLexemes] = stackCounter; numLexemes++; stackCounter= 0; token= getToken(); if (token != identsym) { fprintf(output, "call must be followed by an identifier\n"); if (printFlag ==1) { printf("call must be followed by an identifier\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } //we found an identsym, now get that identifier's name token = getToken(); if(findinsymbol_table(token)==0) { fprintf(output, "Undefined identifier .\n"); if (printFlag ==1) { printf("Undefined identifier .\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } for(codeIndex = 0; codeIndex< symbolCounter; codeIndex++) { if(symbol_table[codeIndex].name == token && symbol_table[codeIndex].kind == 3) { break; //if we found the identifier in our symbol table, stop looping. we will use this index from here out. } } emit(cal, currentLevel- symbol_table[codeIndex].level, symbol_table[codeIndex].addr); token= getToken(); } //found begin else if (token == beginsym) { //find first element after begin token= getToken(); //do work token= statement(token); do { //found the end declaration of function. don't do more work token= getToken(); //do more work token= statement(token); if (token == endsym) { if(doThenCheck > 0) { continue; } else { //return control to calling function emit(opr, 0,0); if (numLexemes > 0) { stackCounters[numLexemes]=0; numLexemes--; stackCounter= stackCounters[numLexemes]; } continue; } } } while (token == semicolonsym); if (token != endsym) { fprintf(output, "end expected\n"); if (printFlag ==1) printf("end expected\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); exit(EXIT_FAILURE); } token= getToken(); } else if (token == ifsym) { int ctemp; int tempToken; doThenCheck++; //get ready to swap token= getToken(); //do work token= condition(token); if (token != thensym) { fprintf(output, "then expected\n"); if (printFlag ==1) { printf("then expected\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token = getToken(); //set temp to where code counter is in code list ctemp = codeCounter; emit(jpc, 0, 0); //put jpc in code list //do work token= statement(token); //set jump to actual location where we need ot jump to code[ctemp].m = codeCounter; tempToken = getToken(); if(tempToken == elsesym) { doThenCheck++; code[ctemp].m = codeCounter+1; token = tempToken; ctemp = codeCounter; emit(jmp, 0 , 0); token = getToken(); token = statement(token); code[ctemp].m = codeCounter; doThenCheck--; } else { fetchCounter--; } doThenCheck--; } else if (token == whilesym) { int cx2; //store where code counter is before we do work int cx1 =codeCounter; doThenCheck++; token= getToken(); //do work token= condition(token); //store where we count after work is done cx2 = codeCounter; emit(jpc, 0, 0); if (token != dosym) { fprintf(output, "do expected\n"); if (printFlag ==1) { printf("do expected\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token= getToken(); token= statement(token); //emit a new jump to redo code to while emit(jmp, 0, cx1); //edit previous jpc with new count value code[cx2].m = codeCounter; doThenCheck--; } else if(token == insym) { token = getToken(); if (token != identsym) { fprintf(output, "call must be followed by an identifier\n"); if (printFlag ==1) { printf("call must be followed by an identifier\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token = getToken(); if(findinsymbol_table(token)==0) { fprintf(output, "Undefined identifier .\n"); if (printFlag ==1) { printf("Undefined identifier .\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } emit(10, 0,2); token = getToken(); } else if(token == outsym) { token= getToken(); //pass expression to the proper funciton token= expression(token); emit(sio, 0,1); } return token; } //this is called when we encounter a conditional and need to evaluate it int condition(int token) { //if it's an oddsym, just pass it to expression if (token == oddsym) { token= getToken(); token= expression(token); } else { token= expression(token); if (token != eqlsym && token != neqsym && token != lessym && token != leqsym && token != gtrsym && token != geqsym) { fprintf(output, "relational operator expected\n"); if (printFlag ==1) { printf("relational operator expected\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } //sterilize global saveCondition= 0; //enter switch to determine what the conditional is switch (token) { case eqlsym: { saveCondition= EQL; break; } case neqsym: { saveCondition=NEQ; break; } case lessym: { saveCondition= LSS; break; } case leqsym: { saveCondition= LEQ; break; } case gtrsym: { saveCondition= GTR; break; } case geqsym: { saveCondition= GEQ; break; } } token= getToken(); //pass expression to the proper funciton token= expression(token); //emit operator with proper oprcode emit(opr, 0, saveCondition); } return token; } //evaluate math expressions int expression(int token) { int addop; //addition and subtraction if (token == plussym || token == minussym) { addop = token; token= getToken(); token= term(token); //handle negatives if(addop == minussym) emit(opr, 0, NEG); // negate } //send to term function else token= term(token); //run until we run out of operators while (token == plussym || token == minussym) { addop = token; token= getToken(); token= term(token); if (addop == plussym) emit(opr, 0, ADD); // addition else emit(opr, 0, SUB); // subtraction } return token; } //term handles multiplication and division int term(int token) { if(findinsymbol_table(token)==0) { fprintf(output, "Undefined identifier .\n"); if (printFlag ==1) { printf("Undefined identifier .\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } int mulop; token= factor(token); //while we still have terms while(token == multsym || token == slashsym) { mulop = token; token= getToken(); token= factor(token); if(mulop == multsym) emit(opr, 0, MUL); // multiplication else emit(opr, 0, DIV); // division } return token; } //handles individual factors of expressions int factor(int token) { int j; //if you find a variable if (token == identsym) { token = getToken(); //fetch the value of the identifier from the symbol table for(j = 0; j< symbolCounter; j++) { if(symbol_table[j].name == token) { //if it's a constant, emit the lit if (symbol_table[j].kind == 1) { emit(lit,0, symbol_table[j].val); break; } //else, load up the address of the factor and emit it for the vm. else { emit(lod, currentLevel - symbol_table[j].level , symbol_table[j].addr); break; } } } token= getToken(); } //if we find a numbersym, just emit the number literal else if (token == numbersym) { token = getToken(); emit(lit, 0, token); token= getToken(); } //if we find a left parenthesis, evaluate as a new expression. else if (token == lparentsym) { token= getToken(); token= expression(token); if (token != rparentsym) { fprintf(output, "right parenthesis missing.\n"); if (printFlag ==1) { printf("right parenthesis missing.\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } token= getToken(); } else { fprintf(output, "invalid factor found\n"); if (printFlag ==1) { printf("invalid factor found\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } return token; } int getToken(void) { //get next token from the input table and then increment the global counter int temp= inputTable[fetchCounter]; fetchCounter++; return temp; } void emit(int op, int l, int m) { //if the code counter has gone above the maximum allowable code length, error out if(codeCounter > MAX_CODE_LENGTH) { fprintf(output, "code generation overflow\n"); if (printFlag ==1) { printf("code generation overflow\n"); printf("Press any key to continue...\n") ; getchar(); //system("PAUSE"); } exit(EXIT_FAILURE); } //otherwise add the passed args to the code array else { code[codeCounter].l = l; // lexicographical level code[codeCounter].op = op; //opcode code[codeCounter].m = m; //modifier codeCounter++; stackCounter++; } if (op == sto) stackCounter-= 1; } //a function that takes in integer value and returns a string of the token name to print char* tokenToString(int token) { switch (token) { case (int) plussym: return "plussym"; case (int) minussym: return "minussym"; case (int) numbersym: return "numbersym"; case (int) multsym: return "multsym"; case (int) slashsym: return "slashsym"; case (int) lessym: return "lesssym"; case(int) eqlsym: return "eqlsym"; case (int) gtrsym: return "gtrsym"; case(int) geqsym: return "geqsym"; case(int) leqsym: return "leqsym"; case(int) becomessym: return "becomessym"; case(int) neqsym: return "neqsym"; case (int) lparentsym: return "lparentsym"; case (int) rparentsym: return "rparentsym"; case (int) commasym: return "commasym"; case (int) semicolonsym: return "semicolonsym"; case (int) periodsym: return "periodsym"; case (int) intsym: return "intsym"; case (int) beginsym: return "beginsym"; case (int) identsym: return "identsym"; case (int) endsym: return "endsym"; case (int) ifsym: return "ifsym"; case (int) thensym: return "thensym"; case (int) whilesym: return "whilesym"; case (int) dosym: return "dosym"; case (int) callsym: return "callsym"; case (int) constsym: return "constsym"; case (int) elsesym: return "elsesym"; case (int) procsym: return "procsym"; case (int) insym: return "in"; case (int) outsym: return "outsym"; case (int) nulsym: return "NULL"; default: return "ERR"; } } int findinsymbol_table(int iname) { int count=0; for(count=0; count<=symbolCounter; count++) { if(symbol_table[count].name==iname) return 1; } return 0; }
C
// // Created by trov on 10.09.2019. // #include "../scanner.h" int main() { FILE *fp; fp = fopen("C:/Users/trov/CLionProjects/C-Lexical-Analyzer/tests/value.txt", "r"); // read mode if (fp == NULL) { perror("Error while opening the file.\n"); exit(EXIT_FAILURE); } int i =0; while (i<1000) { fprintf(stdout, "%s\n", get_next_token(fp)->source); i++; } return 0; }
C
// Justin Ventura & Blaine Mason // COSC420 Lab 3: matrix.h #ifndef MATRIX_H #define MATRIX_H #include<stdio.h> #include<stdlib.h> #include<time.h> #include<math.h> #include<mpi.h> // NB: the A here needs to be a struct, not a pointer! #define INDEX(A,i,j) A->cols*i + j // now can do A.data[INDEX(A,i,j)] // use the above to shortcut accessing the array #define ACCESS(A,i,j) A->data[INDEX(A,i,j)] // C needs the "typedef" typedef struct { int rows, cols; // dimensions double* data; // pointer to the data, a flat array } matrix; /* * Matrix fillers and operations. */ void initRandMatrix(matrix *A, int rows, int cols); void copyMatrix(matrix *A, matrix *B); void initMatrix(matrix *A, int rows, int cols); void initIMatrix(matrix *A, int rows, int cols); void printMatrix(matrix *A); matrix transpose(matrix* A); double * addMatrix(matrix *A, matrix *B, MPI_Comm world, int worldSize, int myRank); double * subtractMatrix(matrix *A, matrix *B, MPI_Comm world, int worldSize, int myRank); double * multiplyMatrix(matrix *A, matrix *B, MPI_Comm world, int worldSize, int myRank); double innerProduct(matrix* A, matrix *B, MPI_Comm world, int worldSize, int myRank); double * gauss_jordan(matrix* A, matrix *b, MPI_Comm world, int worldSize, int myRank); #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amorfan <amorfan@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2013/11/30 12:05:14 by amorfan #+# #+# */ /* Updated: 2014/01/10 20:52:08 by amorfan ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" size_t ft_countn(int n); char *ft_check(char *str, int n, size_t countn); char *ft_except(char *str); char *ft_itoa(int n) { char *str; size_t countn; int i; i = 0; countn = 0; str = NULL; if (n == -2147483648) return (str = ft_except(str)); if (n < 0) { n = n * -1; i = 1; } countn = ft_countn(n) + i; if ((str = ft_strnew(countn + 1)) == NULL) return (NULL); ft_check(str, n, countn); if (i == 1) str[0] = '-'; return (str); } size_t ft_countn(int n) { size_t count; count = 0; while (n >= 10) { n = n / 10; count++; } return (count); } char *ft_check(char *str, int n, size_t countn) { str = str + countn; while (countn > 0) { *str = n % 10 + '0'; n = n / 10; countn--; str--; } *str = n % 10 + '0'; return (str); } char *ft_except(char *str) { size_t t; t = 11; str = ft_strnew(11); return (ft_strcpy(str, "-2147483648")); }
C
#include <stdio.h> #include <string.h> #include "ASA.h" #include "AnalisadorLexico.h" #include "AnalisadorSintatico.h" #include "GerenciadorErro.h" #include "Visitante.h" #include "AnalisadorSemantico.h" #include "VisitanteRI.h" #include "CanonizadorRI.h" #include "Gerador.h" /** \brief Destri objetos alocados durante a execuo do programa * Funo chamada na saida do programa */ void finalizaPrograma(); /** \brief Ponto de entrada do programa */ int main(int argc, char** args){ FILE* arquivo = stdin; FILE* arqAss = stdout; if ( argc == 2 || argc == 3 ) { char caminhoArquivo[strlen(args[1])+5]; char *caminhoSaida; if(argc==2){ caminhoSaida=(char*)malloc(sizeof(char) * (strlen(args[1])+5)); }else{ caminhoSaida=(char*)malloc(sizeof(char) * (strlen(args[2])+5)); strcpy(caminhoSaida, args[2]); } strcpy(caminhoArquivo, args[1]); // Se no tiver a exteno .cpm, adicione if(strstr(caminhoArquivo, ".cpm") == NULL ){ if(argc==2){ strcpy(caminhoSaida, caminhoArquivo); strcat(caminhoSaida, ".asm"); } strcat(caminhoArquivo, ".cpm"); }else{ if(argc==2){ for(unsigned int i = 0;i<(strlen(args[1])-4);i++){ caminhoSaida[i]=caminhoArquivo[i]; } strcat(caminhoSaida, ".asm"); } } if(strstr(caminhoSaida, ".asm") == NULL ){ strcat(caminhoSaida, ".asm"); } arquivo = fopen(caminhoArquivo, "r"); arqAss = fopen(caminhoSaida,"w+"); free(caminhoSaida); if(!arquivo){ fprintf(stderr, "Arquivo invalido!"); exit(1); } } else if( argc > 3){ fprintf(stderr, "Argumento invalido!\n"); fprintf(stderr, "Exemplos de uso:\n\tKindaC\n\tKindaC <arquivo_entrada>\n\tKindaC <arquivo_entrada> <arquivo_saida>\n"); exit(1); } atexit(finalizaPrograma); /// Funo chamada na sada do programa, garante que memria ser desalocada inicializaGerenciadorErro(); iniciaAnalisadorLexico(arquivo); NoPrograma* programa = Programa(); AnalisadorSemantico as; as.visita(programa); VisitanteTradutor vt; vt.visita(programa); CanonizadorRI canRI; canRI.visita(vt.pegarFragmento()); Gerador ger(arqAss); ger.visita(vt.pegarFragmento()); imprimeListaErros(); delete programa; /// Destroi a ASA return 0; } /** \brief Destri objetos alocados durante a execuo do programa */ void finalizaPrograma(){ imprimeListaErros(); destruirAnalizadorLexico(); destruirGerenciadorErro(); }
C
/* ** EPITECH PROJECT, 2018 ** handle_size.c ** File description: ** handle size */ #include "malloc.h" #include "show_alloc_mem.h" size_t get_block_size(void) { return (compute_pagesize(sizeof(data_info_t))); } size_t compute_pagesize(size_t size) { size_t new_size = size; size_t page_size = getpagesize(); new_size += page_size - (new_size % page_size); return (new_size); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include <stdint.h> /* , . , . */ typedef enum { Tarif_1, Tarif_2, Tarif_3, Tarif_4 }TarifPhone; typedef struct { char NameAbonent[50]; char PhoneNumber[10]; char TimeSpeek[50]; TarifPhone Tf; }SpeekPhonedef; /********************** **************/ void FillStructs(SpeekPhonedef * str,int *N); /********************** **************/ void Printt_Structs(SpeekPhonedef * str,int *N); /*********************** ******************/ void Search_AbonentData(SpeekPhonedef * str,int *N,FILE *fl); int main(int argc, char *argv[]) { FILE *file; char NameFile[50]; printf("Input NameFile: "); scanf("%s",&NameFile); int N; printf("Input count Abonent: "); scanf("%d",&N); printf("Count Abonent=%d\n",N); SpeekPhonedef *abonents=(SpeekPhonedef *)malloc(N*sizeof(SpeekPhonedef)); FillStructs(abonents,&N); Printt_Structs(abonents,&N); Search_AbonentData(abonents,&N,file); return 0; } /********************** **************/ void FillStructs(SpeekPhonedef * str,int *N) { for(int i=0;i<*N;i++) { printf("Input Name Abonent: "); scanf("%s",&(str[i].NameAbonent)); printf("Input PhoneNumber Abonent: "); scanf("%s",&(str[i].PhoneNumber)); printf("Input TimeSpeek Abonent: "); scanf("%s",&(str[i].TimeSpeek)); int n=0; printf("Input Tarif Abonent: "); scanf("%d",&n); switch(n) { case 1: { str[i].Tf=Tarif_1; break; } case 2: { str[i].Tf=Tarif_2; break; } case 3: { str[i].Tf=Tarif_3; break; } case 4: { str[i].Tf=Tarif_4; break; } } printf("*****************************************\n"); } printf("===============================================\n"); } /********************** **************/ void Printt_Structs(SpeekPhonedef * str,int *N) { printf("OutPut Array : "); for(int i=0;i<*N;i++) { printf(" Name Abonent: %s\n",str[i].NameAbonent); printf(" PhoneNumber Abonent: %s\n",str[i].PhoneNumber); printf(" TimeSpeek Abonent: %s\n",str[i].TimeSpeek); printf(" Tarif Abonent: "); switch(str[i].Tf) { case Tarif_1: { printf(" Tarif-1\n "); break; } case Tarif_2: { printf(" Tarif-2\n "); break; } case Tarif_3: { printf(" Tarif-3\n "); break; } case Tarif_4: { printf(" Tarif-4\n "); break; } } printf("*****************************************\n"); } printf("==============================================\n"); } /*********************** ******************/ void Search_AbonentData(SpeekPhonedef * str,int *N,FILE *fl) { char NameUser[50]; printf("Input Name User: "); scanf("%s",&NameUser); char *buffer; int size = sizeof(SpeekPhonedef); for(int i=0;i<*N;i++) { int a=strcmp(NameUser,str[i].NameAbonent); printf("A=%d\n",a); if(a==0) { fl=fopen("data.bin","w+b"); if(fl==NULL) { printf("Error opening file\n"); } else { printf("Save Data!!!\n"); SpeekPhonedef dt=str[i]; buffer=(char*)(&dt); for(int i=0;i<size;i++) { putc(*buffer++,fl); } } } } fclose(fl); }
C
#include "core/game.h" #include "core/draw.h" #include "core/event.h" /* * Let's please use documentation * above the function rather than * inside it */ void update(struct game *g, Uint32 delta); /* * The entry point */ int main(void) { struct game g; game_init(&g); game_set_render_func(&g, render); game_set_update_func(&g, update); game_set_key_func(&g, key_event); game_set_mouse_moved_func(&g, mouse_moved); game_set_mouse_clicked_func(&g, mouse_clicked); while (g.info.running) game_loop(&g); game_destroy(&g); return 0; } void update(struct game *g, Uint32 delta) { SDL_GetWindowSize(g->screen.window, &g->screen.width, &g->screen.height); debug("delta: %u\n", delta); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* large.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lportay <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/24 15:10:53 by lportay #+# #+# */ /* Updated: 2019/02/04 17:20:17 by lportay ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" /* ** Refine the first block found with a best fit algorithm ** 'm' is the first fittable block found, 'len' its size and 's' the exact size */ static t_mem *best_fit_large(t_mem *m, size_t len, size_t s) { t_mem *v; size_t l; v = m; m = get_next(m); while (m && (l = get_len(m)) != s) { if (l > s && l < len) { v = m; len = l; } m = get_next(m); } if (l == s) cut(m); else { m = v; shorten(m, s); } return (m); } /* ** Make a first fit search to find one spot in the 'large' pool ** ** the condition (len == s) is an exact match on first match, ** it is highly unlikely to happen ** ** Usually it will match a bigger chunk and will try to reduce the size match ** to a perfect fit with 'best_fit_large' */ t_mem *get_mem_large(t_mem **mem, size_t s) { t_mem *m; size_t len; m = *mem; len = 0; while (m && (len = get_len(m)) < s) m = get_next(m); if (len == s) cut(m); else if (m) m = best_fit_large(m, len, s); else if (!m) return (NULL); if (m == *mem) *mem = get_next(*mem); return (m); } void *large_alloc(t_mem **mem, size_t s) { void *r; if (*mem && (r = get_mem_large(mem, s)) != NULL) return (r); else { r = mmap(g_m.pre_alloc + PRE_ALLOC_LEN, s, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); if (r == MAP_FAILED) return (NULL); set_len(r, s); return (r); } }
C
#include <stdio.h> #include <stdlib.h> int main(){ char nome[50], sexo; int idade; idade = 0; printf("Digite seu Nome, sexo e idade:\n"); gets(nome); scanf(" %c",&sexo); scanf("%d", &idade); if(sexo=='F' || sexo=='f' && idade < 25){ printf("%sACEITA\n",nome); } else{ printf("NAO ACEITA\n", nome); } return 0; }
C
#include<stdlib.h> #include<stdio.h> #include<string.h> #include "Productions.h" #include "../Analyizer/AnalyzerCaller.h" #include "../DataType/LinkedList.h" #include "../Analyizer/Print_Tokens/PrintHandler.h" char expected[]; void statement_tail(){ if(match(7, 6) == 0){ // else analyzerCaller(returnedToken); statement(); } else if(match(7, 3) == 0 || match(13, 2) == 0){ //end ; } else{ strcpy(expected, "'else' or 'end' or ';'"); statement_listSync(); goto end; } end:; } void statement_tailSync(){ fprintf(writePtr, " SYNERROR: Found "); fprintf(writePtr, (*returnedToken).tokenChars); fprintf(writePtr, " expected "); fprintf(writePtr, expected); fprintf(writePtr, "\n"); do{ if(match(15,0) == 0){ exit(1); break; }else if(match(7, 3) == 0){ // end break; }else if(match(13, 2) == 0){ // ; break; } analyzerCaller(returnedToken); }while(match_results == -1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* do_sufix_prefix.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: afaraji <afaraji@student.1337.ma> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/03 18:21:00 by afaraji #+# #+# */ /* Updated: 2020/11/03 18:23:09 by afaraji ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/ft_21sh.h" #include "../inc/builtins.h" #include "../inc/parse.h" #include "../inc/ast.h" #include "../inc/exec.h" #include "../inc/ft_free.h" #include "../inc/readline.h" int env_tab_count(int all) { t_variable *node; int count; node = g_var.var; count = 0; while (node) { if (node->env == 0 || all) count++; node = node->next; } return (count); } char **env_to_tab(t_variable *var, int all) { t_variable *node; char **argv; char *tmp; int i; node = var; i = env_tab_count(all); if (!(argv = (char **)malloc(sizeof(char *) * (i + 1)))) return (NULL); i = 0; while (node) { if (node->env == 0 || all) { tmp = ft_strjoin(node->key, "="); argv[i] = ft_strjoin(tmp, node->value); ft_strdel(&tmp); i++; } node = node->next; } argv[i] = NULL; if (i == 0) return (NULL); return (argv); } int do_suffix(t_cmd_suffix *suffix) { t_cmd_suffix *node; int ret; ret = 0; node = suffix; while (node) { if (node->io_redirect) { ret = do_redirect(node->io_redirect); if (ret != 0) return (ret); } node = node->suffix; } return (ret); } int do_simple_cmd(t_simple_cmd *cmd) { int ret; ret = 0; if (cmd->prefix) { ret = do_prefix(cmd->prefix, g_var.var, 0); } if (ret != 0) return (ret); if ((cmd->name || cmd->word) && cmd->suffix) { ret = do_suffix(cmd->suffix); } return (ret); }
C
#include "raylib.h" #include <stdio.h> #include <unistd.h> static const int screenw = 380; static const int screenh = 320; void main() { int delay = 10000; InitWindow(screenw, screenh, "image manipulation"); // void DrawText(const char *text, int posX, int posY, int fontSize, Color color); SetTargetFPS(60); ClearBackground(BLACK); while(!WindowShouldClose()) { for(int i = 300, x = 0; x < 300; i-=5, x+= 5) { BeginDrawing(); ClearBackground(BLACK); usleep(delay); DrawText("hello", x, x, 33, RED); DrawText("hello", i, i, 33, GREEN); DrawText("hello", x, i, 33, YELLOW); DrawText("hello", i, x, 33, BLUE); EndDrawing(); } } CloseWindow(); }
C
//THURSDAY /* Larisa Andrews, Section T, 12/10/15 */ #include <stdio.h> #include <string.h> #include <ctype.h> /* Pre: The original plaintext phrase with spaces is passed in. The function searches for a space. When found, the spece is removed by shifting all remaining elements in the array one space to the left. Post: The plaintext phrase has been modified so it no longer contains spaces. */ void RmSpaces (char plaintext[]); /* Pre: The plaintext phrase with the spaces removed is passed in. Each character in the plaintext phrase is converted to lowercase. Post: The plaintext phrase has been modified so it no longer has any uppercase letters in it. */ void MkLowerCase (char plaintext[]); /* Pre: The plaintext phrase with the spaces removed, the key, the alphabet, the array to store the secret phrase, and the flag are passed in. A true flag value means the function should encrypt the plaintext phrase. A false flag value means the function should decrypt the plaintext phrase. Post: Both the plaintext and the secret phrase arrays are filled. */ void EncryptDecrypt (char encryption[], char plaintext[], char secretkey[], char alphaList[], int flag); /* Pre: The plaintext phrase and the secret phrase are passed in. Post: The plaintext phrase and the secret phrase are printed. */ void PrintOutput (char plaintext[], char encryption[]); int main (int argc, char* argv[]) { char alphabet[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; char key[26] = {'d', 'e', 'f', 'j', 'k', 'l', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'm', 'n', 'o', 'a', 'b', 'c', 'p', 'q', 'r', 'g', 'h', 'i'}; char phrase[100] = "Help me Obi Wan Kenobi You are my only hope"; char secretphrase[100]; //RmSpaces(phrase);//Write your function calls here. MkLowerCase(phrase); return 0; } void RmSpaces (char plaintext[]){ int i; int j; int length; for(i = 0; i < 100; i++ ){ if(plaintext[i] == ' '){ length = strlen(plaintext); for(j = length - 1; j < 0; j++ ){ plaintext[j] = plaintext[j+1]; } plaintext[length] = '\0'; } } printf("%s", plaintext); } void MkLowerCase (char plaintext[]){ int i; for(i = 0; i < 100; i++){ plaintext[i] = tolower(plaintext[i]); } printf("%s", plaintext); } //Write your functions here.
C
#include <stdio.h> #include <limits.h> #include "min_list.h" int iter_minimum(struct node* head); int recursive_minimum(struct node* head); int main(int argc, char *argv[]) { struct node *head = args_to_list(argc, argv); printf("Minimum is %d\n", iter_minimum(head)); printf("Minimum is %d\n", recursive_minimum(head)); return 0; } int iter_minimum(struct node *head) { if (head == NULL) { return INT_MAX; } struct node *curr = head; int min = curr->data; while (curr != NULL) { if (curr->data < min) { min = curr->data; } curr = curr->next; } return min; } int recursive_minimum(struct node *head) { if (head == NULL) { return INT_MAX; } int min = head->data; int new_min = recursive_minimum(head->next); if (new_min < min) { return new_min; } else { return min; } }
C
/* string25.c */ #include<stdio.h> #include<stdlib.h> int main() { char str[30]; printf("qing shuru nin xiangyao de shouji mingcheng: "); scanf("%s", str); printf("wo xiang mai yitai %s de shouji\n", str); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "graph.h" void AddNode(Graph* graph, char* val); void AddGridNode(Graph* graph, char* val, Vec2 position); void AddUndirectedEdge(Graph* graph, Node* first, Node* second); void RemoveUndirectedEdge(Graph* graph, Node* first, Node* second); void AddDirectedEdge(Graph* graph, Node* first, Node* second); void RemoveDirectedEdge(Graph* graph, Node* first, Node* second); void AddWeightedEdge(Graph* graph, Node* first, Node* second, int weight); void RemoveWeightedEdge(Graph* graph, Node* first, Node* second); GHashTable* GetAllNodes(Graph* graph); Graph* GraphAllocate(int type) { Graph* graph = calloc(1, sizeof(Graph)); graph->type = type; if(type & (UNDIRECTED | GRID)) { graph->AddUndirectedEdge = AddUndirectedEdge; graph->RemoveUndirectedEdge = RemoveUndirectedEdge; } else if(type & DIRECTED) { graph->AddDirectedEdge = AddDirectedEdge; graph->RemoveDirectedEdge = RemoveDirectedEdge; } else if(type & WEIGHTED) { graph->AddWeightedEdge = AddWeightedEdge; graph->RemoveWeightedEdge = RemoveWeightedEdge; } graph->GetAllNodes = GetAllNodes; if(graph->type & GRID) { graph->AddGridNode = AddGridNode; //Get hash via Vec2 graph->nodehash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL); } else { graph->AddNode = AddNode; graph->nodehash = g_hash_table_new(g_str_hash, g_str_equal); } graph->nodes = malloc(GRAPH_NODE_ALLOC_INC*sizeof(Node*)); graph->nodeCount = 0; return graph; } void AddNode(Graph* graph, char* val) { Node* node; Vec2 placeholderPosition = {0}; if(graph == NULL || val == NULL) { printf("AddNode: Attempted to add node with value %p to graph %p.\n", val, graph); return; } if(graph->nodeCount != 0 && (graph->nodeCount%GRAPH_NODE_ALLOC_INC) == 0) { graph->nodes = realloc(graph->nodes, (graph->nodeCount+GRAPH_NODE_ALLOC_INC)*sizeof(Node*)); } node = NodeAllocate(val, placeholderPosition); graph->nodes[graph->nodeCount] = node; g_hash_table_insert(graph->nodehash, val, graph->nodes[graph->nodeCount]); graph->nodeCount++; } void AddGridNode(Graph* graph, char* val, Vec2 position) { Node* node; u_int64_t key; if(graph == NULL || val == NULL) { printf("AddNode: Attempted to add node with value %p to graph %p.\n", val, graph); return; } if(graph->nodeCount != 0 && (graph->nodeCount%GRAPH_NODE_ALLOC_INC) == 0) { graph->nodes = realloc(graph->nodes, (graph->nodeCount+GRAPH_NODE_ALLOC_INC)*sizeof(Node*)); } node = NodeAllocate(val, position); graph->nodes[graph->nodeCount] = node; key = GetVec2Key(node->position); g_hash_table_insert(graph->nodehash, (gpointer) GetVec2Key(node->position), graph->nodes[graph->nodeCount]); graph->nodeCount++; } void AddUndirectedEdge(Graph* graph, Node* first, Node* second) { if(graph == NULL || first == NULL || second == NULL) { printf("AddUndirectedEdge: Attempted to add edge to node %p and node %p.\nIn Graph %p.\n", first, second, graph); return; } if(graph->type & GRID) { if(!NodeIsGridNeighbor(first->position, second->position)) { return; } } NodeAddNeighbor(first, second); NodeAddNeighbor(second, first); } void RemoveUndirectedEdge(Graph* graph, Node* first, Node* second) { if(graph == NULL || first == NULL || second == NULL) { printf("RemoveUndirectedEdge: Attempted to add edge to node %p and node %p.\nIn Graph %p.\n", first, second, graph); return; } NodeRemoveNeighbor(first, second); NodeRemoveNeighbor(second, first); } void AddDirectedEdge(Graph* graph, Node* first, Node* second) { if(graph == NULL || first == NULL || second == NULL) { printf("AddDirectedEdge: Attempted to add edge to node %p and node %p.\nIn Graph %p.\n", first, second, graph); return; } NodeAddNeighbor(first, second); } void RemoveDirectedEdge(Graph* graph, Node* first, Node* second) { if(graph == NULL || first == NULL || second == NULL) { printf("RemoveDirectedEdge: Attempted to add edge to node %p and node %p.\nIn Graph %p.\n", first, second, graph); return; } NodeRemoveNeighbor(first, second); } void AddWeightedEdge(Graph* graph, Node* first, Node* second, int weight) { if(graph == NULL || first == NULL || second == NULL) { printf("AddWeightedEdge: Attempted to add edge to node %p and node %p.\nIn Graph %p.\n", first, second, graph); return; } NodeAddWeightedNeighbor(first, second, weight); } void RemoveWeightedEdge(Graph* graph, Node* first, Node* second) { if(graph == NULL || first == NULL || second == NULL) { printf("RemoveWeightedEdge: Attempted to add edge to node %p and node %p.\nIn Graph %p.\n", first, second, graph); return; } NodeRemoveWeightedNeighbor(first, second); } GHashTable* GetAllNodes(Graph* graph) { if(graph == NULL) { printf("GetAllNodes: Attempted to get nodes from graph %p.\n", graph); return NULL; } return graph->nodehash; } void GraphClearVisits(Graph* graph) { int i; for(i = 0; i < graph->nodeCount; i++) { graph->nodes[i]->visited = 0; } } Graph* CreateRandomUnweightedGraphIter(int n) { Graph* graph = GraphAllocate(UNDIRECTED); Node* nodeA, *nodeB; int i, length, edgeNum, randVal; char *nodeValue; edgeNum = n + rand()%n; for(i = 0; i < n; i++) { length = (int) log10(i+1) + 2; nodeValue = malloc(length*(sizeof(char))); sprintf(nodeValue, "%d", i); graph->AddNode(graph, nodeValue); } for(i = 0; i < edgeNum; i++) { randVal = rand()%n; nodeA = graph->nodes[randVal]; randVal = rand()%n; while(graph->nodes[randVal] != nodeA && NodeConnectedUndirected( nodeA, graph->nodes[randVal]) ) { randVal = rand()%n; } nodeB = graph->nodes[randVal]; graph->AddUndirectedEdge(graph, nodeA, nodeB); } return graph; } Graph* CreateLinkedList(int n) { Graph* graph = GraphAllocate(UNDIRECTED); int i, length; char* nodeValue; for(i = 0; i < n; i++) { length = (int) log10(i+1) + 2; nodeValue = malloc(length*sizeof(char)); sprintf(nodeValue, "%d", i); graph->AddNode(graph, nodeValue); } for(i = 0; i < n-1; i++) { graph->AddUndirectedEdge(graph, graph->nodes[i], graph->nodes[i+1]); } return graph; } int numInArray(int num, int* array, int size) { int i; if(array == NULL) { return 0; } for(i = 0; i < size; i++) { if(array[i] == num) { return 1; } } return 0; } Graph* CreateRandomDAGIter(int n) { Graph* graph = GraphAllocate(DIRECTED); int i, j, length, edgeNum, connectsNum, connections[3]; char* nodeValue; edgeNum = rand()%n; for(i = 0; i < n; i++) { length = (int) log10(i+1) + 2; nodeValue = malloc(length*sizeof(char)); sprintf(nodeValue, "%d", i); graph->AddNode(graph, nodeValue); } for(i = 0; i < edgeNum; i++) { connectsNum = rand()%3+1; memset(connections, 0, 3); for(j = 0; j < connectsNum; j++) { connections[j] = rand()%n; while(connections[j] <=i && !numInArray(connections[j], connections, connectsNum)) { connections[j] = rand()%n; } graph->AddDirectedEdge(graph, graph->nodes[i], graph->nodes[connections[j]]); } } return graph; } Graph* CreateRandomCompleteWeightedGraph(int n) { Graph* graph = GraphAllocate(WEIGHTED); int i, j, num, length; char* nodeValue; for(i = 0; i < n; i++) { length = (int) log10(i+1) + 2; nodeValue = malloc(length*sizeof(char)); sprintf(nodeValue, "%d", i); graph->AddNode(graph, nodeValue); } for(i = 0; i < n; i++) { for(j = 0; j < n-1; j++) { num = rand()%n; graph->AddWeightedEdge(graph, graph->nodes[i], graph->nodes[j], num); } } return graph; } Graph* CreateWeightedLinkedList(int n) { Graph* graph = GraphAllocate(WEIGHTED); int i, num, length; char* nodeValue; for(i = 0; i < n; i++) { length = (int) log10(i+1) + 2; nodeValue = malloc(length*sizeof(char)); sprintf(nodeValue, "%d", i); graph->AddNode(graph, nodeValue); } for(i = 0; i < n-1; i++) { num = rand()%n; graph->AddWeightedEdge(graph, graph->nodes[i], graph->nodes[i+1], num); } return graph; } Vec2* GetNeighbors(Vec2 currentPosition, int n, int* size) { int i, nSize, x, y; Vec2 possibleNeighbors[] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1}}; Vec2* neighbors = malloc(2*sizeof(Vec2)); nSize = 0; for(i = 0; i < 4; i++) { x = possibleNeighbors[i].x + currentPosition.x; y = possibleNeighbors[i].y + currentPosition.y; if( x < 0 || x >= n || y < 0 || y >= n) { continue; } nSize++; if(nSize > 2) { neighbors = realloc(neighbors, nSize*sizeof(Vec2)); } neighbors[nSize-1].x = x; neighbors[nSize-1].y = y; } *size = nSize; return neighbors; } Graph* CreateRandomGridGraph(int n) { Graph* graph = GraphAllocate(GRID); int i, j, k, num, length, chance; Vec2 position, neighborPos; Vec2* neighbors; char* nodeValue; Node* nodeA, *nodeB; GHashTable *nodesHash; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { length = (int) log10(i*n+j+1) + 2; nodeValue = malloc(length*sizeof(char)); sprintf(nodeValue, "%d", i*n+j); position.x = i; position.y = j; graph->AddGridNode(graph, nodeValue, position); } } nodesHash = graph->GetAllNodes(graph); for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { position.x = i; position.y = j; nodeA = g_hash_table_lookup(nodesHash, (gpointer) GetVec2Key(position)); neighbors = GetNeighbors(position, n, &length); for(k = 0; k < length; k++) { chance = rand()%2; if(chance) { neighborPos = neighbors[k]; nodeB = g_hash_table_lookup(nodesHash, (gpointer) GetVec2Key(neighborPos)); graph->AddUndirectedEdge(graph, nodeA, nodeB); } } } } return graph; }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> #define INFINITY INT_MAX typedef enum {WHITE, GRAY, BLACK} COLOR; typedef enum {LIST, MATRIX} graphType; typedef struct graphNode{ int node; int pred; void* info; COLOR color; //list adj; }graphNode; typedef struct graphMatrix{ int** adjMatrix; int sizeOfMatrix;//grandezza effettiva della matrice graphNode* nodes; }graphMatrix; typedef struct graphList{ graphNode* adjList; int sizeOfArray; int bound; }graphList; typedef struct graph{ graphMatrix* GRAPHMATRIX; graphList* GRAPHLIST; graphType t; int numNodes;//numero nodi del grafo }graph; graph* makeGraph(graph*, graphType, int ); graph* makeMatrix(graph*); graph* addVertMat(graph*, void*); graph* addLinkMat(graph*, int, int, int); graph* removeVertMat(graph*, int); int main(){ graph* k; k=makeGraph(k, MATRIX, 5); k=makeMatrix(k); int i, j; for(i=0; i<k->GRAPHMATRIX->sizeOfMatrix; i++){ for(j=0; j<k->GRAPHMATRIX->sizeOfMatrix; j++){ printf("%d ", k->GRAPHMATRIX->adjMatrix[i][j]); } printf("\n"); } // k=addLinkMat(k, 5, 6, 3); // k=addLinkMat(k, 4, 4, 0); printf("\n"); for(i=0; i<k->numNodes; i++){ for(j=0; j<k->numNodes; j++){ printf("%d ", k->GRAPHMATRIX->adjMatrix[i][j]); } printf("\n"); } printf("\n"); for(i=0; i<k->numNodes;i++){ printf("%d ", k->GRAPHMATRIX->nodes[i].node); } printf("\n%d, %d", k->numNodes, k->GRAPHMATRIX->sizeOfMatrix); k=removeVertMat(k, 4); printf("\n\\****************************************\\\n"); for(i=0; i<k->numNodes; i++){ for(j=0; j<k->numNodes; j++){ printf("%d ", k->GRAPHMATRIX->adjMatrix[i][j]); } printf("\n"); } printf("\n"); for(i=0; i<k->numNodes;i++){ printf("%d ", k->GRAPHMATRIX->nodes[i].node); } printf("\n%d, %d", k->numNodes, k->GRAPHMATRIX->sizeOfMatrix); return 0; } graph* makeGraph(graph* newGraph, graphType type, int numNodes){ newGraph=NULL; newGraph=(graph*)malloc(sizeof(newGraph)); newGraph->numNodes=numNodes; newGraph->t=type; newGraph->GRAPHLIST=NULL; newGraph->GRAPHMATRIX=NULL; return newGraph; } graph* makeMatrix(graph* newGraph){ graphMatrix* NGM=(graphMatrix*)malloc(sizeof(graphMatrix)); NGM->nodes=(graphNode*)malloc(sizeof(graphNode)*(newGraph->numNodes)); int i, j; NGM->adjMatrix=(int**)malloc(sizeof(int*)*(newGraph->numNodes)); NGM->sizeOfMatrix=newGraph->numNodes; for(i=0; i<newGraph->numNodes; i++){ NGM->adjMatrix[i]=(int*)malloc(sizeof(int)*(newGraph->numNodes)); } for(i=0; i<NGM->sizeOfMatrix;i++){ for(j=0; j<NGM->sizeOfMatrix; j++){ NGM->adjMatrix[i][j]=i+j+2; } } for(i=0; i<NGM->sizeOfMatrix; i++){ NGM->nodes[i].info=NULL; NGM->nodes[i].color=WHITE; NGM->nodes[i].node=i; } newGraph->GRAPHMATRIX=NGM; return newGraph; } graph* addVertMat(graph* GRAPH, void* toAdd){ int i=0, j=0; if(GRAPH!=NULL){ if(GRAPH->GRAPHMATRIX!=NULL){ if(GRAPH->numNodes<=GRAPH->GRAPHMATRIX->sizeOfMatrix){ GRAPH->GRAPHMATRIX->sizeOfMatrix=GRAPH->GRAPHMATRIX->sizeOfMatrix+((GRAPH->GRAPHMATRIX->sizeOfMatrix)/2); GRAPH->GRAPHMATRIX->adjMatrix= (int**)realloc(GRAPH->GRAPHMATRIX->adjMatrix, GRAPH->GRAPHMATRIX->sizeOfMatrix*sizeof(int*)); for(i = GRAPH->numNodes; i < GRAPH->GRAPHMATRIX->sizeOfMatrix; i++){ GRAPH->GRAPHMATRIX->adjMatrix[i] = NULL; } for (i = 0; i < GRAPH->GRAPHMATRIX->sizeOfMatrix; i++){ GRAPH->GRAPHMATRIX->adjMatrix[i] = (int*)realloc(GRAPH->GRAPHMATRIX->adjMatrix[i], (GRAPH->GRAPHMATRIX->sizeOfMatrix)*sizeof(int)); } for(i=GRAPH->numNodes; i<GRAPH->GRAPHMATRIX->sizeOfMatrix; i++){ GRAPH->GRAPHMATRIX->nodes[i].info=NULL; for(j=0; j<=GRAPH->numNodes; j++){ GRAPH->GRAPHMATRIX->adjMatrix[i][j]=INFINITY; GRAPH->GRAPHMATRIX->adjMatrix[j][i]=INFINITY; } } GRAPH->GRAPHMATRIX->nodes=(graphNode*)realloc(GRAPH->GRAPHMATRIX->nodes, sizeof(graphNode)*(GRAPH->GRAPHMATRIX->sizeOfMatrix)); } GRAPH->GRAPHMATRIX->nodes[GRAPH->numNodes].color=WHITE; GRAPH->GRAPHMATRIX->nodes[GRAPH->numNodes].info=toAdd; GRAPH->GRAPHMATRIX->nodes[GRAPH->numNodes].node=GRAPH->numNodes; GRAPH->numNodes++; } } return GRAPH; } graph* addLinkMat(graph* GRAPH, int from, int to, int weight){ if(GRAPH!=NULL){ if(GRAPH->GRAPHMATRIX!=NULL){ if(from<GRAPH->numNodes && to<GRAPH->numNodes){ GRAPH->GRAPHMATRIX->adjMatrix[from][to]=weight; } } } return GRAPH; } graph* removeLinkMat(graph* GRAPH, int from, int to){ if(GRAPH!=NULL){ if(GRAPH->GRAPHMATRIX!=NULL){ if(from<GRAPH->numNodes && to<GRAPH->numNodes){ GRAPH->GRAPHMATRIX->adjMatrix[from][to]=INFINITY; } } } } graph* removeVertMat(graph* GRAPH, int toDel){ graphNode* nodeToDel; void* l; int i; int j; if(GRAPH!=NULL){ if(GRAPH->GRAPHMATRIX!=NULL){ if(toDel<GRAPH->numNodes){ nodeToDel=(GRAPH->GRAPHMATRIX->nodes)+toDel; for(i=toDel; i<GRAPH->numNodes-1; i++){ GRAPH->GRAPHMATRIX->nodes[i]=GRAPH->GRAPHMATRIX->nodes[i+1]; GRAPH->GRAPHMATRIX->nodes[i].node--; } for(i=toDel; i<(GRAPH->numNodes)-1; i++){ for(j=0; j<toDel; j++){ GRAPH->GRAPHMATRIX->adjMatrix[i][j]=GRAPH->GRAPHMATRIX->adjMatrix[i+1][j]; } } for(i=0; i<toDel; i++){ for(j=toDel; j<(GRAPH->numNodes)-1; j++){ GRAPH->GRAPHMATRIX->adjMatrix[i][j]=GRAPH->GRAPHMATRIX->adjMatrix[i][j+1]; } } for(i=toDel; i<(GRAPH->numNodes)-1; i++){ for(j=toDel; j<(GRAPH->numNodes)-1; j++){ GRAPH->GRAPHMATRIX->adjMatrix[i][j]=GRAPH->GRAPHMATRIX->adjMatrix[i+1][j+1]; } } GRAPH->numNodes--; free(nodeToDel->info); free(nodeToDel); } } } return GRAPH; } /***********************************CALCOLO TRASPOSTO************************/ //void BFDMatGraph(adjMatGraph* Ngraph, int toStart){ /* void BFDMatGraph(graph* toVisit, int toStart){ graphMatrix* Ngraph=toVisit->GRAPHMATRIX; int i=0, visiting=0; fifoNode* tail=NULL; fifoNode* now=NULL; for(i=0; i<Ngraph->numNodes; i++){ Ngraph->nodes[i].color=WHITE; Ngraph->nodes[i].pred=INFINITY; } Ngraph->nodes[toStart].color=GRAY; tail=enqueue(tail, (void*)toStart); while(tail!=NULL){ now=readFifo(tail); visiting=(int)(now->el); printf("N%d \n",visiting); for(i=0; i<Ngraph->numNodes; i++){ if(Ngraph->adjMatrix[visiting][i]!=INFINITY){ printf("in i:%d\n", i); if(Ngraph->nodes[i].color==WHITE){ printf("and this is white\n"); tail=enqueue(tail, (void*)i); Ngraph->nodes[i].pred=visiting; Ngraph->nodes[i].color=GRAY; } } } if(tail==NULL){ printf("wat\n"); }else{ printf("end %d \n", visiting); printf("\n%d\n", *(int*)(tail->el)); Ngraph->nodes[visiting].color=BLACK; tail=tail->next; } } } */
C
#include"../../include/logger.h" #include<stdio.h> int main(void) { logger *log; char* filename="demo.log"; log_level level=DEBUG; setup_logger(&log,filename,level); if(log!=NULL) { printf("logger:info\nfilename: %s level: %d\n",log->filename,log->level); fclose(log->fp); remove(log->filename); return 0; } return -1; }
C
#include <unistd.h> #include <stdio.h> #include "smalloc.h" sm_container_ptr sm_first = 0x0 ; sm_container_ptr sm_last = 0x0 ; sm_container_ptr sm_unused_containers = 0x0 ; // Task 2-1 void sm_container_split(sm_container_ptr hole, size_t size) { sm_container_ptr itr = 0x0 ; sm_container_ptr remainder = hole->data + size ; remainder->data = ((void *)remainder) + sizeof(sm_container_t) ; remainder->dsize = hole->dsize - size - sizeof(sm_container_t) ; remainder->status = Unused ; remainder->next = hole->next ; remainder->next_unused = hole->next_unused; hole->next = remainder ; hole->next_unused = 0x0; if (sm_unused_containers == hole) { sm_unused_containers = remainder; } else { for (itr = sm_unused_containers; itr->next != 0x0; itr = itr->next_unused) { if (itr->next_unused == hole) { itr->next_unused = remainder; } } } if (hole == sm_last) sm_last = remainder ; } void * sm_retain_more_memory(int size) { sm_container_ptr hole ; int pagesize = getpagesize() ; int n_pages = 0 ; n_pages = (sizeof(sm_container_t) + size + sizeof(sm_container_t)) / pagesize + 1 ; hole = (sm_container_ptr) sbrk(n_pages * pagesize) ; if (hole == 0x0) return 0x0 ; hole->data = ((void *) hole) + sizeof(sm_container_t) ; hole->dsize = n_pages * getpagesize() - sizeof(sm_container_t) ; hole->status = Unused ; return hole ; } // Task 2-1 void * smalloc(size_t size) { sm_container_ptr hole = 0x0 ; sm_container_ptr itr = 0x0 ; sm_container_ptr itr2 = 0x0 ; for (itr = sm_unused_containers; itr != 0x0 ; itr = itr->next_unused) { if (size == itr->dsize) { if (itr == sm_unused_containers) { sm_unused_containers = itr->next_unused; itr->next_unused = 0x0; } else { for (itr2 = sm_unused_containers; itr2 != 0x0; itr2->next_unused) { if (itr2->next_unused == itr) { itr2->next_unused = itr->next_unused; itr->next_unused = 0x0; } } } itr->status = Busy; return itr->data ; } else if (size + sizeof(sm_container_t) < itr->dsize) { if (hole != 0x0 && hole->dsize > itr->dsize) hole = itr; else if (hole == 0x0) hole = itr; } } if (hole == 0x0) { hole = sm_retain_more_memory(size) ; if (hole == 0x0) return 0x0 ; if (sm_first == 0x0) { sm_first = hole ; sm_last = hole ; sm_unused_containers = hole; hole->next = 0x0 ; hole->next_unused = 0x0; } else { sm_last->next = hole ; sm_last = hole ; for (itr = sm_unused_containers; itr != 0x0; itr = itr->next_unused) { if (itr->next_unused == 0x0) { itr->next_unused = hole; break; } } hole->next = 0x0 ; hole->next_unused = 0x0; } } sm_container_split(hole, size) ; hole->dsize = size ; hole->status = Busy ; return hole->data ; } // Task 2-1 void sfree(void * p) { sm_container_ptr itr ; sm_container_ptr itr_unused = 0x0 ; sm_container_ptr free ; int unused_flag = 0; int free_flag = 0; for (itr = sm_first ; itr->next != 0x0 ; itr = itr->next) { if (itr == sm_unused_containers) { if (free_flag == 1) { free->next_unused = sm_unused_containers; sm_unused_containers = free; break; } unused_flag = 1; itr_unused = itr; } if (itr_unused != 0x0 && itr == itr_unused->next_unused) itr_unused = itr; if (itr->data == p) { free = itr; itr->status = Unused ; free_flag = 1; if (unused_flag == 1) { free->next_unused = itr_unused->next_unused; itr_unused->next_unused = free; break; } } } // Task 2-2 for (itr = sm_first ; itr->next != 0x0 ; itr = itr->next) { if (itr->next_unused == itr->next) { itr->dsize += itr->next->dsize + sizeof(sm_container_t); itr->next_unused = itr->next->next_unused; itr->next = itr->next->next; } if (itr->next == 0x0) break; } } void print_sm_containers() { sm_container_ptr itr ; int i = 0 ; printf("==================== sm_containers ====================\n") ; for (itr = sm_first ; itr != 0x0 ; itr = itr->next, i++) { char * s ; printf("%3d:%p:%s:", i, itr->data, itr->status == Unused ? "Unused" : " Busy") ; printf("%8d:", (int) itr->dsize) ; for (s = (char *) itr->data ; s < (char *) itr->data + (itr->dsize > 8 ? 8 : itr->dsize) ; s++) printf("%02x ", *s) ; printf("\n") ; } printf("=======================================================\n") ; } void print_sm_uses() { sm_container_ptr itr; int i = 0; size_t total_size = 0; size_t busy_size = 0; size_t unused_size = 0; for (itr = sm_first; itr != 0x0; itr = itr->next, i++) { char * s; total_size += itr->dsize; if (itr->status == Unused) unused_size += itr->dsize; else busy_size += itr->dsize; } fprintf(stderr, "Total memory retained by smalloc so far : %d\n", (int) total_size); fprintf(stderr, "Total memory allocated by smalloc at this moment : %d\n", (int) busy_size); fprintf(stderr, "Total memory retained by smalloc but not currently allocated : %d\n", (int) unused_size); }
C
#pragma once ///Analog channels (on the 4051) /*#define aCharged_N 6 #define aCharged_P 2 //also Pwr #define aCharging_N 3 #define aCharging_P 1 #define aUnderV 0 #define aUnused 4*/ enum aChannels {aCharged_PalsoPwr=6, aCharged_N=2, aCharging_N=3, aCharging_P=1, aUnderV=0, aUnused=4}; /* get here to send voltage strings according to (from the client code): {"ADCValuePwr", "ADCValueChdN", "ADCValueChgngP", "ADCValueChgngN", "ADCValueUV", "ADCValueUnused"}; */ const aChannels anaInpSel[]= {aCharged_PalsoPwr, aCharged_N, aCharging_P, aCharging_N, aUnderV, aUnused}; int anaValues[/*SAME AS ABOVE, don' wanna dynam alloc*/6]; int getIndexFromEnum(aChannels chan) { int n =sizeof(anaInpSel) / sizeof(anaInpSel[0]); for (int i = 0; i < n; i++) { if (anaInpSel[i]==chan) return i; } return 99; } #define anaPinA 0 #define anaPinB 2 #define anaPinC 14 void anaPinSetup() { pinMode(anaPinA, OUTPUT); pinMode(anaPinB, OUTPUT); pinMode(anaPinC, OUTPUT); } void SelectAnaChannel(int i) { digitalWrite(anaPinA, i & 0x01); digitalWrite(anaPinB, i & 0x02); digitalWrite(anaPinC, i & 0x04); delay(1); } int readAnaValues() { int n = sizeof(anaValues)/sizeof(anaValues[0]); for (int i=0; i<n; i++) { SelectAnaChannel(i); analogRead(A0); anaValues[i]=analogRead(A0); } } void handleADC() { String payload; int n = sizeof(anaInpSel)/sizeof(anaInpSel[0]); float *vals = new float[n]; for (int i=0; i<n; i++) { SelectAnaChannel(anaInpSel[i]); analogRead(A0); vals[i] = (((float)analogRead(A0))/71.5); //conv to volts payload += vals[i]; payload += " "; } // "ChargedLED", if (vals[getIndexFromEnum(aCharged_PalsoPwr)] - vals[getIndexFromEnum(aCharged_N)] > 2.0) payload += "ON"; else payload += "OFF"; payload += " "; //"ChargingLED", if (vals[getIndexFromEnum(aCharging_P)] - vals[getIndexFromEnum(aCharging_N)] > 2.0) payload += "ON"; else payload += "OFF"; payload += " "; //"UnderVLED" if (vals[getIndexFromEnum(aUnderV)] >.25) payload += "ON"; else payload += "OFF"; payload += " "; //// Serial.println(payload); server.send(200, "text/plane", payload); //Send ADC value only to client ajax request delete vals; }
C
// RUN: %clang_dfsan -fno-sanitize=dataflow -O2 -fPIE -DCALLBACKS -c %s -o %t-callbacks.o // RUN: %clang_dfsan -O2 -mllvm -dfsan-event-callbacks %s %t-callbacks.o -o %t // RUN: %run %t FooBarBaz 2>&1 | FileCheck %s // Tests that callbacks are inserted for store events when // -dfsan-event-callbacks is specified. #include <assert.h> #include <sanitizer/dfsan_interface.h> #include <stdio.h> #include <string.h> #ifdef CALLBACKS // Compile this code without DFSan to avoid recursive instrumentation. extern dfsan_label LabelI; extern dfsan_label LabelJ; extern dfsan_label LabelIJ; extern dfsan_label LabelArgv; extern size_t LenArgv; void __dfsan_store_callback(dfsan_label Label) { if (!Label) return; static int Count = 0; switch (Count++) { case 0: assert(Label == LabelI); break; case 1: assert(Label == LabelJ); break; case 2: assert(Label == LabelIJ); break; default: assert(0); } fprintf(stderr, "Label %u stored to memory\n", Label); } void __dfsan_load_callback(dfsan_label Label) { if (!Label) return; fprintf(stderr, "Label %u loaded from memory\n", Label); } void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len) { assert(Len == LenArgv); for (int I = 0; I < Len; ++I) { assert(Start[I] == LabelArgv); } fprintf(stderr, "Label %u copied to memory\n", Start[0]); } void __dfsan_cmp_callback(dfsan_label CombinedLabel) { if (!CombinedLabel) return; fprintf(stderr, "Label %u used for branching\n", CombinedLabel); } #else // Compile this code with DFSan and -dfsan-event-callbacks to insert the // callbacks. dfsan_label LabelI; dfsan_label LabelJ; dfsan_label LabelIJ; dfsan_label LabelArgv; size_t LenArgv; int main(int Argc, char *Argv[]) { assert(Argc == 2); int I = 1, J = 2; LabelI = 1; dfsan_set_label(LabelI, &I, sizeof(I)); LabelJ = 2; dfsan_set_label(LabelJ, &J, sizeof(J)); LabelIJ = dfsan_union(LabelI, LabelJ); // CHECK: Label 1 stored to memory volatile int Sink = I; // CHECK: Label 1 loaded from memory // CHECK: Label 1 used for branching assert(Sink == 1); // CHECK: Label 2 stored to memory Sink = J; // CHECK: Label 2 loaded from memory // CHECK: Label 2 used for branching assert(Sink == 2); // CHECK: Label 2 loaded from memory // CHECK: Label 3 stored to memory Sink += I; // CHECK: Label 3 loaded from memory // CHECK: Label 3 used for branching assert(Sink == 3); // CHECK: Label 3 used for branching assert(I != J); LenArgv = strlen(Argv[1]); LabelArgv = 4; dfsan_set_label(LabelArgv, Argv[1], LenArgv); char Buf[64]; assert(LenArgv < sizeof(Buf) - 1); // CHECK: Label 4 copied to memory void *volatile SinkPtr = Buf; memcpy(SinkPtr, Argv[1], LenArgv); // CHECK: Label 4 copied to memory SinkPtr = &Buf[1]; memmove(SinkPtr, Buf, LenArgv); return 0; } #endif // #ifdef CALLBACKS