language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * mixed_intersection.c * */ #include "mixed_intersection.h" #include "bitset_util.h" /* Compute the intersection of src_1 and src_2 and write the result to * dst. */ void array_bitset_container_intersection(const array_container_t *src_1, const bitset_container_t *src_2, array_container_t *dst) { if (dst->capacity < src_1->cardinality) array_container_grow(dst, src_1->cardinality, INT32_MAX, false); const int32_t origcard = src_1->cardinality; dst->cardinality = 0; for (int i = 0; i < origcard; ++i) { // could probably be vectorized uint16_t key = src_1->array[i]; // next bit could be branchless if (bitset_container_contains(src_2, key)) { dst->array[dst->cardinality++] = key; } } } /* * Compute the intersection between src_1 and src_2 and write the result * to *dst. If the return function is true, the result is a bitset_container_t * otherwise is a array_container_t. */ bool bitset_bitset_container_intersection(const bitset_container_t *src_1, const bitset_container_t *src_2, void **dst) { const int newCardinality = bitset_container_and_justcard(src_1, src_2); if (newCardinality > DEFAULT_MAX_SIZE) { *dst = bitset_container_create(); if (*dst != NULL) { bitset_container_and_nocard(src_1, src_2, *dst); ((bitset_container_t *)*dst)->cardinality = newCardinality; } return true; // it is a bitset } *dst = array_container_create_given_capacity(newCardinality); if (*dst != NULL) { ((array_container_t *)*dst)->cardinality = newCardinality; bitset_extract_intersection_setbits_uint16( ((bitset_container_t *)src_1)->array, ((bitset_container_t *)src_2)->array, BITSET_CONTAINER_SIZE_IN_WORDS, ((array_container_t *)*dst)->array, 0); } return false; // not a bitset } bool bitset_bitset_container_intersection_inplace( bitset_container_t *src_1, const bitset_container_t *src_2, void **dst) { const int newCardinality = bitset_container_and_justcard(src_1, src_2); if (newCardinality > DEFAULT_MAX_SIZE) { *dst = src_1; bitset_container_and_nocard(src_1, src_2, src_1); ((bitset_container_t *)*dst)->cardinality = newCardinality; return true; // it is a bitset } *dst = array_container_create_given_capacity(newCardinality); if (*dst != NULL) { ((array_container_t *)*dst)->cardinality = newCardinality; bitset_extract_intersection_setbits_uint16( ((bitset_container_t *)src_1)->array, ((bitset_container_t *)src_2)->array, BITSET_CONTAINER_SIZE_IN_WORDS, ((array_container_t *)*dst)->array, 0); } bitset_container_free(src_1); return false; // not a bitset }
C
#include "Task.h" #define SIZEOFTASK sizeof(task_t) #define CHECKPOINTER(PTR) {\ if(PTR == NULL) \ {\ return 0;\ }} struct task { task_id_t uid; task_func_t task_func; void *params; /* input data for task_func */ time_t interval_in_secs; /* time until next run, 0 if not recurring */ timeval_t next_runtime; }; task_t *TaskCreate(task_func_t task_func, void *params, time_t interval_in_secs) { task_t* new_task = (task_t*)malloc(SIZEOFTASK); CHECKPOINTER(new_task); new_task->uid = UIDCreate(); if(1 == UIDIsBad(new_task->uid)) { return NULL; } new_task->task_func = task_func; new_task->params = params; new_task->interval_in_secs = interval_in_secs; new_task->next_runtime.tv_sec = interval_in_secs; new_task->next_runtime.tv_usec = 0; return new_task; } void TaskDestroy(task_t *task) { free(task); task = NULL; } task_id_t TaskGetID(const task_t *task) { return task->uid; } int TaskRun(const task_t *task) { return (task->task_func(task->params)); } int TaskIsSame(const task_t *task1, const task_t *task2, void *params) { (void)params; return (UIDIsSame(task1->uid, task2->uid)); } timeval_t TaskGetRunTime(const task_t *task) { return task->next_runtime; } void TaskUpdateNextRun(task_t *task) { task->next_runtime.tv_sec += task->interval_in_secs ; } time_t TaskGetTimeInterval(task_t *task) { return task->interval_in_secs; }
C
#include<stdio.h> int main () { int n,a,sum,temp; printf("input a integer : "); scanf("%d",&n); printf("Before swapping : %d.\n",n); temp = n%10; int count = (int)log10(n);//No of digits //remove last digit & add first digit n = (n/10)*10 + n/pow(10,count); //remove first digit and swap with last digit n = n % (int)pow(10,count) + temp*pow(10,count); printf("After swapping : %d.\n",n); return 0; }
C
#include "CustomAssertions.h" #include "unity.h" void assertFile(char *Source, char *Target,int lineNumber) { long unsigned int srcFileSize, targetFileSize, position ; unsigned int srcData,targetData ,srcfileStatus = 0,targetFileStatus = 0; char ErrorMsg[1024] ={}; InStream *src = initInStream(); InStream *target = initInStream(); src = openInStream(Source, "rb" , src); target = openInStream(Target, "rb" , target); fseek(src->file,0,SEEK_END); fseek(target->file,0,SEEK_END); srcFileSize = ftell(src->file); targetFileSize = ftell(target->file); UNITY_TEST_ASSERT_EQUAL_UINT32(srcFileSize,targetFileSize,lineNumber,"The target file size does not match the source file size!"); rewind(src->file); rewind(target->file); while(1) { srcData = streamReadBits(src,8); targetData = streamReadBits(target,8); srcfileStatus = checkEndOfFile(src) ; targetFileStatus = checkEndOfFile(target); if(srcfileStatus) { closeInStream(src); freeInStream(src); } if(targetFileStatus) { closeInStream(target); freeInStream(target); } UNITY_TEST_ASSERT_EQUAL_UINT8(srcfileStatus,targetFileStatus,lineNumber,"Target file ended earlier or later than the source file!"); if (srcData != targetData) { position = ftell(target->file); sprintf(ErrorMsg,"At position 0x%x, target data does not match source data!",position); UNITY_TEST_ASSERT_EQUAL_UINT8(srcData,targetData,lineNumber,ErrorMsg); } if(srcfileStatus == 1 || targetFileStatus == 1) break; } }
C
#include "../includes/ft_printf.h" static void ntoa_format_handle_hash(t_specifier *specifier, char *buf, size_t *buf_index, unsigned int base) { if (specifier->flags & FLAGS_HASH) { if (!(specifier->flags & FLAGS_PRECISION) && *buf_index && ((*buf_index == specifier->precision) || *buf_index == specifier->width) && (specifier->type != 'p')) { if (buf[*buf_index - 1] == '0') (*buf_index)--; if (*buf_index && (base == 16U) && buf[*buf_index - 1] == '0') (*buf_index)--; } if ((base == 16U) && !(specifier->flags & FLAGS_UPPERCASE) && (*buf_index < NTOA_BUFFER_SIZE)) buf[(*buf_index)++] = 'x'; else if ((base == 16U) && (specifier->flags & FLAGS_UPPERCASE) && (*buf_index < NTOA_BUFFER_SIZE)) buf[(*buf_index)++] = 'X'; if (*buf_index < NTOA_BUFFER_SIZE) buf[(*buf_index)++] = '0'; } } static size_t ntoa_format(t_specifier *specifier, char *buf, size_t buf_index, unsigned int base) { if (specifier->width && (specifier->flags & FLAGS_ZEROPAD) && ((specifier->flags & FLAGS_NEGATIVE) || (specifier->flags & (FLAGS_PLUS | FLAGS_SPACE)))) specifier->width--; while ((buf_index < specifier->precision) && (buf_index < NTOA_BUFFER_SIZE)) buf[buf_index++] = '0'; while ((specifier->flags & FLAGS_ZEROPAD) && (buf_index < specifier->width) && (buf_index < NTOA_BUFFER_SIZE)) buf[buf_index++] = '0'; ntoa_format_handle_hash(specifier, buf, &buf_index, base); if (buf_index < NTOA_BUFFER_SIZE) { if (specifier->flags & FLAGS_NEGATIVE) buf[buf_index++] = '-'; else if (specifier->flags & FLAGS_PLUS) buf[buf_index++] = '+'; else if (specifier->flags & FLAGS_SPACE) buf[buf_index++] = ' '; } return (print_buf_rev(specifier, buf, buf_index)); } size_t ft_ntoa(t_specifier *specifier, unsigned long long value, unsigned int base) { char buf[NTOA_BUFFER_SIZE]; size_t buf_index; char *digits; int uppercase; buf_index = 0U; uppercase = 0; digits = "0123456789abcdef0123456789ABCDEF"; if (!value && specifier->type != 'p') specifier->flags &= ~FLAGS_HASH; if (!(specifier->flags & FLAGS_PRECISION) || value) { if (specifier->flags & FLAGS_UPPERCASE) uppercase = 16; buf[buf_index++] = digits[(char)(value % base) + uppercase]; value /= base; while (value && (buf_index < NTOA_BUFFER_SIZE)) { buf[buf_index++] = digits[(char)(value % base) + uppercase]; value /= base; } } return (ntoa_format(specifier, buf, buf_index, base)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_convert_base.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dtse <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/07/21 13:09:36 by dtse #+# #+# */ /* Updated: 2016/07/21 13:09:38 by dtse ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> #include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } int ft_atoi(char *str) { int i; long result; int neg; i = 0; neg = 1; result = 0; while (str[i] < 33) i++; if (str[i] == '-' || str[i] == '+') { if (str[i] == '-') neg = -1; i++; } while (str[i] >= '0' && str[i] <= '9') { result = result * 10 + str[i] - '0'; i++; } return (result * neg); } void ft_putnbr_base(int nbr, char *base) { int i; i = 0; while(base[i]) i++; if (nbr < 0) { ft_putchar('-'); nbr *= -1; } if (nbr >= i) { ft_putnbr_base(nbr / i, base); ft_putnbr_base(nbr % i, base); } else ft_putchar(base[nbr]); } char *ft_convert_base(char *nbr, char *base_from, char *base_to) { char *base_f; char *base_t; int num; // int num_10; //dummy variables base_f = base_from; base_t = base_to; num = ft_atoi(nbr); printf("num = %d\n", num); ft_putnbr_base(num, "0123456789"); // printf("num_10 = %d\n", num_10); return (0); }
C
// Find the maximum value in an array. // Created by // ... (z0000000) // ... (z0000000) // Created on 2017-08-?? // Tutor's name (dayHH-lab) #include <stdio.h> #include <stdlib.h> #define MAX_LENGTH 1024 int arrayMax (int size, int array[MAX_LENGTH]); // DO NOT CHANGE THIS MAIN FUNCTION int main (int argc, char *argv[]) { // Get array size int size; printf ("Enter array size: "); scanf ("%d", &size); // Declare array int array[MAX_LENGTH]; printf ("Enter array values: "); // Initialise array values int i = 0; while (i < size) { scanf ("%d", &array[i]); i++; } printf ("Maximum value is %d.\n", arrayMax (size, array)); return EXIT_SUCCESS; } // Return the largest value in a given array. int arrayMax (int size, int array[MAX_LENGTH]) { int i=0; int max=array[1]; while(i<size) { if(array[i]>max) { max=array[i]; } i++; } return max; }
C
#include "include/header.h" int init(Cube* C) { memcpy(C->faces, "UUUURRRRFFFFDDDDLLLLBBBB", sizeof(char) * 24); C->last_move[0] = 'x'; C->last_move[1] = ' '; return 1; } int print_cube(Cube* C) { printf("\n"); printf(" %s@ %s@\n", color(C->faces[0]), color(C->faces[1])); printf(" %s@ %s@\n", color(C->faces[2]), color(C->faces[3])); printf("%s@ %s@ %s@ %s@ %s@ %s@\n", color(C->faces[16]), color(C->faces[17]), color(C->faces[8]), color(C->faces[9]), color(C->faces[4]), color(C->faces[5])); printf("%s@ %s@ %s@ %s@ %s@ %s@\n", color(C->faces[18]), color(C->faces[19]), color(C->faces[10]), color(C->faces[11]), color(C->faces[6]), color(C->faces[7])); printf(" %s@ %s@\n", color(C->faces[12]), color(C->faces[13])); printf(" %s@ %s@\n", color(C->faces[14]), color(C->faces[15])); printf(" %s@ %s@\n", color(C->faces[23]), color(C->faces[22])); printf(" %s@ %s@\n", color(C->faces[21]), color(C->faces[20])); printf("\n"); return 1; } int u(Cube *C) { C->last_move[0] = 'U'; C->last_move[1] = ' '; char t1; char t2; t1 = C->faces[4]; t2 = C->faces[5]; C->faces[4] = C->faces[20]; C->faces[5] = C->faces[21]; C->faces[20] = C->faces[16]; C->faces[21] = C->faces[17]; C->faces[16] = C->faces[8]; C->faces[17] = C->faces[9]; C->faces[8] = t1; C->faces[9] = t2; t1 = C->faces[0]; C->faces[0] = C->faces[2]; C->faces[2] = C->faces[3]; C->faces[3] = C->faces[1]; C->faces[1] = t1; return 1; } int up(Cube *C) { C->last_move[0] = 'U'; C->last_move[1] = '\''; char t1; char t2; t1 = C->faces[4]; t2 = C->faces[5]; C->faces[4] = C->faces[8]; C->faces[5] = C->faces[9]; C->faces[8] = C->faces[16]; C->faces[9] = C->faces[17]; C->faces[16] = C->faces[20]; C->faces[17] = C->faces[21]; C->faces[20] = t1; C->faces[21] = t2; t1 = C->faces[0]; C->faces[0] = C->faces[1]; C->faces[1] = C->faces[3]; C->faces[3] = C->faces[2]; C->faces[2] = t1; return 1; } int r(Cube *C) { C->last_move[0] = 'R'; C->last_move[1] = ' '; char t1; char t2; t1 = C->faces[1]; t2 = C->faces[3]; C->faces[1] = C->faces[9]; C->faces[3] = C->faces[11]; C->faces[9] = C->faces[13]; C->faces[11] = C->faces[15]; C->faces[13] = C->faces[22]; C->faces[15] = C->faces[20]; C->faces[20] = t2; C->faces[22] = t1; t1 = C->faces[4]; C->faces[4] = C->faces[6]; C->faces[6] = C->faces[7]; C->faces[7] = C->faces[5]; C->faces[5] = t1; return 1; } int rp(Cube* C) { C->last_move[0] = 'R'; C->last_move[1] = '\''; char t1; char t2; t1 = C->faces[1]; t2 = C->faces[3]; C->faces[1] = C->faces[22]; C->faces[3] = C->faces[20]; C->faces[20] = C->faces[15]; C->faces[22] = C->faces[13]; C->faces[13] = C->faces[9]; C->faces[15] = C->faces[11]; C->faces[9] = t1; C->faces[11] = t2; t1 = C->faces[4]; C->faces[4] = C->faces[5]; C->faces[5] = C->faces[7]; C->faces[7] = C->faces[6]; C->faces[6] = t1; return 1; } int f(Cube *C) { C->last_move[0] = 'F'; C->last_move[1] = ' '; int t1; int t2; t1 = C->faces[2]; t2 = C->faces[3]; C->faces[2] = C->faces[19]; C->faces[3] = C->faces[17]; C->faces[17] = C->faces[12]; C->faces[19] = C->faces[13]; C->faces[12] = C->faces[6]; C->faces[13] = C->faces[4]; C->faces[4] = t1; C->faces[6] = t2; t1 = C->faces[8]; C->faces[8] = C->faces[10]; C->faces[10] = C->faces[11]; C->faces[11] = C->faces[9]; C->faces[9] = t1; return 1; } int fp(Cube *C) { C->last_move[0] = 'F'; C->last_move[1] = '\''; int t1; int t2; t1 = C->faces[2]; t2 = C->faces[3]; C->faces[2] = C->faces[4]; C->faces[3] = C->faces[6]; C->faces[4] = C->faces[13]; C->faces[6] = C->faces[12]; C->faces[12] = C->faces[17]; C->faces[13] = C->faces[19]; C->faces[17] = t2; C->faces[19] = t1; t1 = C->faces[8]; C->faces[8] = C->faces[9]; C->faces[9] = C->faces[11]; C->faces[11] = C->faces[10]; C->faces[10] = t1; return 1; } int move(Cube *C, char* m) { if (m[0] == 'R') { if (m[1] == ' ') { return r(C); } else { return rp(C); } } if (m[0] == 'U') { if (m[1] == ' ') { return u(C); } else { return up(C); } } if (m[0] == 'F') { if (m[1] == ' ') { return f(C); } else { return fp(C); } } return 0; } int copy_cube(Cube *C1, Cube *C2) { memcpy(C1->faces, C2->faces, sizeof(char) * 24); C1->last_move[0] = C2->last_move[0]; C1->last_move[1] = C2->last_move[1]; return 1; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> //#include <stdbool.h> typedef struct node_type { char *key; struct node_type *left, *right; }NodeT; /// create a node NodeT *createNode(char *givenKey) { NodeT *p = (NodeT*)malloc(sizeof(NodeT)); strrev(givenKey); if (p) { p->key = givenKey; p->left = p->right = NULL; /* leaf node */ } return p; } /// stack typedef struct node_stack { NodeT *p; struct node_stack* next; }NodeS; NodeS* newNode(NodeT *p) { NodeS* stackNode = (NodeS*)malloc(sizeof(NodeS)); stackNode->p = p; stackNode->next = NULL; return stackNode; } int isEmpty(NodeS* root) { return !root; } void push(NodeS **root, NodeT *p) { NodeS* stackNode = newNode(p); stackNode->next = *root; *root = stackNode; printf("\n%s pushed to stack", p->key); } NodeT *pop(NodeS **root) { if (isEmpty(*root)) { puts("\nerror"); return NULL;} NodeS* temp = *root; *root = (*root)->next; NodeT *popped = temp->p; free(temp); return popped; } void peek(NodeS* root) { if (isEmpty(root)) puts("\nNo element in stack"); printf("\n%s is the top element", root->p->key); } void preorder(NodeT *p) { if (p != NULL) { printf("%s ", p->key); preorder(p->left); preorder(p->right); } } int main() { FILE *pIn = fopen("in.txt", "r"); NodeS* root = NULL; char prefix[256] = "", nr[10] = "", symbol[2] = ""; int ch = fgetc(pIn), i = 0; while (ch != '\n') { prefix[i] = ch; i++; ch = getc(pIn); } int l = strlen(prefix); prefix[l] = '\0'; NodeT *p = NULL; for (i = l-1; i >= 0; i--) { if (isdigit(prefix[i])) { int j = 0; while(prefix[i] != ' ') { nr[j] = prefix[i]; i--; j++; } nr[j] = '\0'; p = createNode(nr); push(&root,p); } else { //puts("\nelse: "); //pop(&root); //peek(root); //pop(&root); symbol[0] = prefix[i]; symbol[1] = '\0'; //printf("\n%s is symbol\n", symbol); //peek(root); p = createNode(symbol); //printf("%s is symbol\n", symbol); //pop(&root); //peek(root); p->left = pop(&root); //peek(root); //printf("\n1)%s ",p->left->key); p->right = pop(&root); //peek(root); //printf("\n2)%s \n",p->right->key); push(&root,p); //peek(root); i--; } //printf("%s ",p->key); } puts("\nPRE: "); preorder(pop(&root)); /*NodeT *p = createNode("spring"); push(&root, p); p = createNode("summer"); push(&root, p); p = createNode("warm"); p->left = pop(&root); printf("\n%s popped from stack", p->left->key); peek(root); p->right = pop(&root); printf("\n%s popped from stack", p->right->key); //peek(root); push(&root,p); p = createNode("fall"); push(&root, p); p = createNode("winter"); push(&root, p);*/ //printf("\n%s popped from stack\n", pop(&root)->key); //printf("\n%s popped from stack\n", pop(&root)->key); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> char *center(char *s, int n) { char *ret = (char *)malloc(n * sizeof(char)); int i, j; int slen = strlen(s); if (ret == NULL) { printf("Out of memory"); } for (i = 0; i < n; i++) { ret[i] = '-'; } for (j = 0; j < slen; j++) { ret[(n - slen) / 2 + j] = s[j]; } return ret; } int main(void) { char s[] = "cat"; char *ret; ret = center(s, 5); printf("%s\n", ret); free(ret); ret = center(s, 6); printf("%s\n", ret); free(ret); ret = center(s, 7); printf("%s\n", ret); free(ret); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** my_strlen ** File description: ** the lenght of the string */ #include "my.h" int my_strlen(char *str) { int nb; nb = 0; while (str[nb] != '\0') nb++; return (nb); }
C
#include "holberton.h" /** * powX- powers a number b to the p's power * @b: base * @p: power * Return: return b to the power of a */ unsigned long int powX(int b, int p) { unsigned long int ans = 1; while (p) { ans *= b; p--; } return (ans); } /** * set_bit - prints the binary representation of a number * @n: input integer * @index: returns the value of a bit at a given index * Return: 1 for ssucess -1 for failure */ int set_bit(unsigned long int *n, unsigned int index) { unsigned long int test; if (index > sizeof(n) * BIT_SIZE - 1) return (-1); test = powX(2, index); *n = *n | test; return (1); }
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include "computer.h" #define GENERAL_ERROR -1 /*void tnt_explode(?????) { }*/ /** * Checks if the current player taking turn is a automatic player. * @param game The game struct * @return either the current player if a automatic player, else general * error. */ int is_automatic_player(Game* game) { if (game->turn == 'x') { if (game->xAuto) { return PLAYER_X; } } else { if (game->oAuto) { return PLAYER_O; } } return GENERAL_ERROR; } void automatic_coordinates_calc(Game* game) { int moveCount = (game->turn == 'x') ? game->xMoveCount : game->oMoveCount; int x = (game->gridSize % 10) + 32 + moveCount; int y = (x % 10) + 23 + moveCount; //TODO: check that calcualted coordiantes don't already exist on board }
C
#include<stdio.h> #include<malloc.h> #include<stdlib.h> int findmedian(int *,int *,int); int median(int *,int); int max(int,int); int min(int,int); int * malloc_int(int *,int); int a_cmp(int,int); void testcases(); struct test { int input1[20]; int n1; int input2[20]; int n2; int output; }testDB[10]={{{1,2,3},3,{4,5,6},3,3}, {{4,5,6},3,{1,2,3},3,3}, {{1,3,5,7,9,11},6,{2,4,6,8},4,'\0'}, {{1,1,1},3,{1,1,1},3,1}, {{11,12,12,13,13,14,14,14,15,15,16},11,{1,2,3,3,3,3,3,3,3,3,3},11,7}, {{1,2,3,4},4,{5,6,7,8},4,4}, {{1,3,11},3,{2,6,7},3,4}, {{1},1,{1,2,3},3,'\0'}, {{-1,2,3},3,{1,2,3},3,2}, {{0,1,2},3,{-1,0,1},3,0}}; int max(int a,int b) { return ((a>b)?a:b); } int min(int a, int b) { return ((a>b)?b:a); } int median(int a[],int n) { if(n%2==0) return (a[n/2]+a[n/2-1])/2; else return a[n/2]; } int findmedian(int a[],int b[],int n) { int m1,m2; if(n==1) return ((a[0]+b[0])/2); if(n==2) return ((max(a[0],b[0])+min(a[1],b[1]))/2); if(n>2) { m1=median(a,n); m2=median(b,n); if(m1==m2) return m1; if(m1>m2) { if(n%2==0) return (findmedian(b+n/2-1,a,n-n/2+1)); else return (findmedian(b+n/2,a,n-n/2)); } if(m1<m2) { if(n%2==0) return (findmedian(a+n/2-1,b,n-n/2+1)); else return (findmedian(a+n/2,b,n-n/2)); } } } int * malloc_int(int ip[],int n) { int i,*a; a=(int *)malloc(sizeof(int)*n); for(i=0;i<n;i++) a[i]=ip[i]; return a; } int a_cmp(int a,int b) { if(a==b) return 0; else return 1; } void testcases() { int i,*a,*b,op,check; for(i=0;i<10;i++) { a=malloc_int(testDB[i].input1,testDB[i].n1); b=malloc_int(testDB[i].input2,testDB[i].n2); if(testDB[i].n1==testDB[i].n2) { op=findmedian(testDB[i].input1,testDB[i].input2,testDB[i].n1); check=a_cmp(testDB[i].output,op); } else check=0; if(check==0) printf("passed\n"); else printf("failed\n"); free(a); free(b); } } int main() { testcases(); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* builtin_exit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: drecours <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/31 12:11:37 by drecours #+# #+# */ /* Updated: 2018/01/15 12:55:28 by drecours ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../inc/header.h" //REMPLACER LOCALE->RET PAR DERNIERE VALEUR DE RETOUR OBTENUE int quit(char **input) { tcsetattr(STDIN_FILENO, TCSADRAIN, &g_old_term); ft_putstr_fd("Bye!", STDOUT_FILENO); custom_return(); if (!input[1]) exit(0); exit(ft_atoi(input[1])); return (0); } int builtin_exit(char **input, t_env **env) { int i; int flag; (void)env; i = -1; flag = ((input[1] && !input[2]) || !input[1]) ? 0 : 1; if (input[1]) { if (input[1][0] == '-') ++i; while (input[1][++i]) if (!(input[1][i] >= '0' && input[1][i] <= '9')) { flag = 1; break ; } } if (flag == 0) return (quit(input)); ft_putstr_fd((i == 0) ? "exit: Expression Syntax." : "exit: Badly formed number.", STDOUT_FILENO); custom_return(); return (1); }
C
int i, j; void main() { i = 8; j = 0; do { j++; i--; if (i % 2 == 0) continue; j++; if (i == 1) break; } while (i!=10); assert(i == 1, "i must be 1"); assert(j == 11, "j must be 11"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { /*init strings for input and output names*/ char* inputName; char* outputName; /*init of other variables*/ int numStates; if (argc==3) /*both input name and output name provided*/ { inputName = argv[1]; outputName = argv[2]; } else if (argc==2) /*only input name provided, use default output name*/ { inputName = argv[1]; outputName = "output.mif"; } else /*improper usage, tell the user he/she is doing it wrong*/ { printf("Usage: %s INPUT_FILE [OUTPUT_FILE]\n", argv[0]); return -1; } printf("Welcome to LED Cube Designer 1.0\n"); /*open the given files*/ FILE* fpi = fopen(inputName, "r"); FILE* fpo = fopen(outputName, "w"); fscanf(fpi, "%i", &numStates); /*get the number of states to be read*/ if (numStates>64) { printf("Sorry, but a maximum of 64 states is allowed\n"); return -1; } int ledArray[numStates][64]; printf("Initialized array for %i states.\n", numStates); int temp; /*read the states into the ledArray*/ for(int a=0; a<numStates; a++) { /*this will be repeated for every single state that we read*/ /*printf("about to start state loop for the %ith time\n", a);*/ for(int y=60; y>47; y-=4) { for(int x=0; x<49; x+=16) { for(int z=0; z<4; z++) { fscanf(fpi, "%i", &temp); /*printf("Read in %i,storing at (%i, %i)\n", temp, a, y-x+z);*/ ledArray[a][y-x+z]=temp; } } } } printf("Read design into array. Get that pen!\n"); fprintf(fpo, "DEPTH = 64;\nWIDTH = 64;\nADDRESS_RADIX = UNS;\n"); fprintf(fpo, "DATA_RADIX = BIN;\nCONTENT\nBEGIN\n"); /*write the ledArray into the output file*/ for(int s=0; s<numStates; s++) { fprintf(fpo, "%i : ", s); /*this will be repeated for every single state that is in the array*/ for(int t=0; t<64; t++) { fprintf(fpo, "%i", ledArray[s][t]); } fprintf(fpo, ";\n"); } fprintf(fpo, "END;\n"); /*close the given files*/ fclose(fpi); fclose(fpo); /*print a success message*/ printf("Successfully Generated a MIF File.\n"); return 0; }
C
#include <string.h> #include <ctype.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> /* User created libraries */ #include "accounts.h" #include "server.h" #define WITHDRAW "withdraw\0" #define DEPOSIT "deposit\0" #define SERVE "serve\0" #define QUERY "query\0" #define END "end\0" #define QUIT "quit\0" #define CREATE "create\0" #define EMPTY_STRING "" #define SLEEP_TIME 6 /* TODO make sure to change to 20 before submission */ /* Global Variables */ AccountStoragePtr ACCOUNTS; pthread_t timer_thread; pthread_mutex_t lock; int acceptor_socket; int* SOCKETS; int killSocket(int sockfd) { int socket_index; socket_index = 0; while( socket_index < MAX_ACCOUNTS) { if( SOCKETS[socket_index] == sockfd) { SOCKETS[socket_index] = 0; return 1; } socket_index++; } return 0; } int isThreadInSession(int thread, AccountStoragePtr all_accounts) { int i; i = 0; // find the thread index while( i < MAX_ACCOUNTS ) { if( all_accounts->threads[i] == thread) { break; } i++; } // didn't find the thread if( i == MAX_ACCOUNTS && all_accounts->threads[i-1] != thread ) { return 0; } if( all_accounts->accounts[i] && all_accounts->accounts[i]->in_session ) { return 1; } return 0; } /* Eliminate all sockets */ void shutdownServer() { int i, close_sockets_flag; printf("Closing server and all threads...\n"); close_sockets_flag = closeAllSockets(); if( close_sockets_flag == 1 ){ i = 0; while(i < MAX_ACCOUNTS) { destroyAccount(ACCOUNTS->accounts[i]); i++; } free(ACCOUNTS); free(SOCKETS); close(acceptor_socket); exit(1); } if( close_sockets_flag == 0){ error("ERROR Could not shutdown."); } } int closeAllSockets() { int socket_index; int n; socket_index = 0; while(SOCKETS[socket_index] != 0){ printf("Socket: %i being closed right now \n", SOCKETS[socket_index] ); n = write(SOCKETS[socket_index], "quit", 4); if(n < 0) return 0; close(SOCKETS[socket_index]); socket_index += 1; } return 1; } void signal_handler(int signo) { if(signo == SIGINT){ shutdownServer(); } } ClientResponsePtr handleClientCommand(int thread, ClientRequestPtr client_information) { float balance; AccountPtr account; int success; char message[255]; ClientResponsePtr return_value; return_value = malloc(sizeof(struct client_response)); account = getThreadAccount(thread, ACCOUNTS); if(strcmp(client_information->argument, EMPTY_STRING) == 0){ if(strcmp(client_information->command, QUERY) == 0){ if( !isThreadInSession(thread, ACCOUNTS)) { return_value->command_performed = 0; strcpy(return_value->message, "Not connected to an account"); return return_value; } balance = accountGetBalance(thread,ACCOUNTS); return_value->balance = balance; return_value->is_query = 1; return_value->command_performed = 1; sprintf(message,"%f", balance); strcpy(return_value->message, message); bzero(message,255); return return_value; } if(strcmp(client_information->command, END) == 0){ if( !isThreadInSession(thread, ACCOUNTS)) { return_value->command_performed = 0; strcpy(return_value->message, "Not connected to an account"); return return_value; } accountEndConnection(thread, ACCOUNTS); return_value->balance = 1; return_value->is_query = 0; return_value->command_performed = 1; strcpy(return_value->message, "Session ended."); return return_value; } if(strcmp(client_information->command, QUIT) == 0){ accountEndConnection(thread, ACCOUNTS); return_value->balance =-1; return_value->is_query = 0; return_value->command_performed = 1; return return_value; } } else { if(strcmp(client_information->command, WITHDRAW) == 0){ if( !isThreadInSession(thread, ACCOUNTS)) { return_value->command_performed = 0; strcpy(return_value->message, "Not connected to an account"); return return_value; } return_value->command_performed = 0; success = accountWithdraw(thread, atof(client_information->argument), ACCOUNTS); if( success == 1 ){ return_value->command_performed = 1; strcpy(return_value->message, "Withdraw success."); return return_value; } strcpy(return_value->message, "Could not withdraw funds."); return return_value; } if(strcmp(client_information->command, DEPOSIT) == 0){ if( !isThreadInSession(thread, ACCOUNTS)) { return_value->command_performed = 0; strcpy(return_value->message, "Not connected to an account"); return return_value; } accountDeposit(thread, atof(client_information->argument), ACCOUNTS); strcpy(return_value->message, "Deposit success."); return_value->command_performed = 1; return return_value; } if(strcmp(client_information->command, CREATE) == 0){ if( isThreadInSession(thread, ACCOUNTS)) { return_value->command_performed = 0; strcpy(return_value->message, "Cannot create account"); return return_value; } account = accountCreate(client_information->argument, ACCOUNTS); if( account != NULL ) { return_value->command_performed = 1; strcpy(return_value->message, "Account created."); return return_value; } strcpy(return_value->message, "Account already exists."); return_value->command_performed = 0; return return_value; } if(strcmp(client_information->command, SERVE) == 0){ // check if thread is already serving an account if( isThreadInSession(thread, ACCOUNTS)) { return_value->command_performed = 0; strcpy(return_value->message, "Already connected to an account"); return return_value; } success = accountServe(thread, client_information->argument, ACCOUNTS); if( success == 1 ) { strcpy(return_value->message, "Serving account."); return_value->command_performed = 1; return return_value; } strcpy(return_value->message, "Account not found."); return_value->command_performed = 0; return return_value; } } strcpy(return_value->message, "Invalid command."); return_value->command_performed = 0; return return_value; } /* Thread that runs every twenty seconds, which prints the account information*/ /* List 1. Write mutex stuff to this */ void *writeAccountsEveryTwentySeconds(void *arg) { int account_index; while(1){ sleep(SLEEP_TIME); pthread_mutex_lock(&lock); if(ACCOUNTS->accounts[0] != NULL){ printf("Accounts: [\n"); for(account_index = 0; account_index <= MAX_ACCOUNTS; account_index++){ accountPrint(ACCOUNTS->accounts[account_index]); } printf("];\n"); } // for(socket_index = 0; socket_index <= MAX_ACCOUNTS; socket_index++){ // printf("%i \n", SOCKETS[socket_index]); // } pthread_mutex_unlock(&lock); } pthread_exit(NULL); } /* Add socket to global array of sockets if not full */ int addSocket(int sockfd) { int socket_index; socket_index = 0; while(SOCKETS[socket_index] != 0){ socket_index += 1; } if(SOCKETS[socket_index] != 0) return 0; SOCKETS[socket_index] = sockfd; return 1; } ClientRequestPtr getCommandFromBuffer(char* buffer) { char* tmp_buffer; char* first_word; char* second_word; char* tmp_token; int i; ClientRequestPtr structured_client_information; const char delimiter[2] = " "; tmp_buffer = buffer; structured_client_information = malloc(sizeof(struct client_request)); first_word = malloc(sizeof(tmp_buffer)); second_word = malloc(sizeof(tmp_buffer)); /* First Word */ tmp_token = malloc(sizeof(tmp_buffer)); tmp_token = strtok( tmp_buffer, delimiter); i = 0; while( tmp_token != NULL ){ if(i == 0){ first_word = tmp_token; } if(i == 1){ second_word = tmp_token; break; } tmp_token = strtok(NULL, delimiter); i += 1; } //structured_client_information->command = malloc(sizeof(client_command[0])); structured_client_information->command = first_word; //structured_client_information->argument = malloc(sizeof(client_command[1])); structured_client_information->argument = second_word; return structured_client_information; } void createClientServiceThread(void * params) { SockInfo cs_sockinfo = (SockInfo) params; int n; char buffer[256]; int kill_socket_in_array_flag; char message[255]; ClientRequestPtr client_information; ClientResponsePtr handle_client_response; printf("In client service socket: %i \n", cs_sockinfo->sockfd); n = write(cs_sockinfo->sockfd, "Connected to server. Ready for commands", 255); if( n < 0) { error("ERROR on writing to socket"); } bzero(buffer, 256); // Read commands from socket while( read(cs_sockinfo->sockfd, buffer, 255) > 0){ client_information = getCommandFromBuffer(buffer); printf("Command: %s, %s \n", client_information->command,client_information->argument); if(strcmp(client_information->command, "quit") == 0) { break; } // send command to handler handle_client_response = handleClientCommand(cs_sockinfo->sockfd, client_information); if(handle_client_response->command_performed != 1) { printf("command not executed\n"); }else{ printf("command executed\n"); } if( strlen(handle_client_response->message) >0) { sprintf(message,"'%s'", handle_client_response->message); write(cs_sockinfo->sockfd, message, 255); } free(handle_client_response); if(handle_client_response->is_query == 0 && handle_client_response->balance == -1){ break; } bzero(buffer, 256); bzero(message, 255); } // deal with a quit signal accountEndConnection(cs_sockinfo->sockfd, ACCOUNTS); // end the connection, if one is open write(cs_sockinfo->sockfd, "quit", 4); kill_socket_in_array_flag = killSocket( cs_sockinfo->sockfd); if( kill_socket_in_array_flag == 0){ error("ERROR in removing socket from SOCKETS array \n"); } printf("Exiting socket %i\n", cs_sockinfo->sockfd); close(cs_sockinfo->sockfd); pthread_exit(NULL); } void createSessionAcceptorThread(void* params) { //TCP/IP server logic int sockfd; socklen_t clilen; struct sockaddr_in serv_addr, cli_addr; /* Creating a socket */ sockfd = socket( AF_INET, SOCK_STREAM, 0 ); if( sockfd < 0 ){ error("ERROR opening socket"); } acceptor_socket = sockfd; /* Binding a socket and the server address */ bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons( 3500 ); if( bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0 ){ error("ERROR on binding"); } /* Now that we have a socket in place with its server address, * that for each client connection, we create a client service thread * that gets invoked */ int conn_count = 0; pthread_t threads[SOMAXCONN]; int tids[SOMAXCONN]; int add_to_socket_flag = 0; while(conn_count <= SOMAXCONN){ listen(sockfd, SOMAXCONN); clilen = sizeof(cli_addr); SockInfo cs_sockinfo = malloc(sizeof(SockInfo)); cs_sockinfo->sockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if(cs_sockinfo->sockfd < 0){ error("ERROR on accept"); } /* Add socket to sockets global array */ add_to_socket_flag = addSocket(cs_sockinfo->sockfd); if(add_to_socket_flag == 0) error("ERROR on adding to sockets array"); tids[conn_count] = pthread_create( &threads[conn_count], NULL, (void*(*)(void*))createClientServiceThread, (void*)cs_sockinfo); conn_count++; } close(sockfd); pthread_join(threads[conn_count], NULL); pthread_exit(NULL); } int main(int argc, char** argv){ int timer_thread_tid; signal(SIGINT, signal_handler); ACCOUNTS = (AccountStoragePtr) malloc(sizeof(struct account_storage)); SOCKETS = malloc(sizeof(int) * SOMAXCONN); ACCOUNTS->last_account_index = 0; //Session Acceptor Thread pthread_t thread; int rc, i; i = 0; UserArgs test_obj = malloc(sizeof(UserArgs)); test_obj->argc = argc; test_obj->argv = argv; if( pthread_mutex_init(&lock, NULL) != 0 ) { printf("\n mutex init failed \n"); return 1; } timer_thread_tid = pthread_create(&timer_thread, NULL, (void*(*)(void*))writeAccountsEveryTwentySeconds, NULL); rc = pthread_create( &thread, NULL, (void*(*)(void*))createSessionAcceptorThread, (void* )NULL); if( rc != 0 ){ printf("pthread_create failed \n"); return 0; } pthread_join(timer_thread, NULL); pthread_join(thread, NULL); return 0; }
C
#include "helpers.h" #include <stdio.h> #include <math.h> // Convert image to grayscale int sepiablue(int blue, int green, int red); int sepiagreen(int blue, int green, int red); int sepiared(int blue, int green, int red); int avg(int blue, int green, int red); //void swap (void *f, void *l); void grayscale(int height, int width, RGBTRIPLE image[height][width]) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int avg1 = avg(image[i][j].rgbtBlue, image[i][j].rgbtGreen, image[i][j].rgbtRed); image[i][j].rgbtBlue = avg1; image[i][j].rgbtGreen = avg1; image[i][j].rgbtRed = avg1; } } //FILE *test = fopen("test.txt","w"); //fprintf(test,"height is: %i \n Width is: %i \n",height,width); return; } // Convert image to sepia void sepia(int height, int width, RGBTRIPLE image[height][width]) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int blue = sepiablue(image[i][j].rgbtBlue, image[i][j].rgbtGreen, image[i][j].rgbtRed); int green = sepiagreen(image[i][j].rgbtBlue, image[i][j].rgbtGreen, image[i][j].rgbtRed); int red = sepiared(image[i][j].rgbtBlue, image[i][j].rgbtGreen, image[i][j].rgbtRed); image[i][j].rgbtBlue = blue; image[i][j].rgbtGreen = green; image[i][j].rgbtRed = red; } } return; } void swap(BYTE *f, BYTE *l) { BYTE temp = 0; temp = *f; *f = *l; *l = temp; return; } // Reflect image horizontally void reflect(int height, int width, RGBTRIPLE image[height][width]) { int w = width - 1; int re = 0; BYTE *temp = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < (width / 2); j++) { re = w - j; swap(&image[i][j].rgbtBlue, &image[i][re].rgbtBlue); swap(&image[i][j].rgbtGreen, &image[i][re].rgbtGreen); swap(&image[i][j].rgbtRed, &image[i][re].rgbtRed); } } return; } // Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE tempimage[height][width]; // Temp variable to store modified data temp/ float avgb = 0; // to store average of blue float avgg = 0; // to store average of green float avgr = 0; // to store average of red for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (i == 0 && j == 0) // to blur the first pixcel first row first column { avgb = 0; avgg = 0; avgr = 0; avgb = ((image[i][j].rgbtBlue + image[i][j + 1].rgbtBlue + image[i + 1][j].rgbtBlue + image[i + 1][j + 1].rgbtBlue) / 4.0); avgg = ((image[i][j].rgbtGreen + image[i][j + 1].rgbtGreen + image[i + 1][j].rgbtGreen + image[i + 1][j + 1].rgbtGreen) / 4.0); avgr = ((image[i][j].rgbtRed + image[i][j + 1].rgbtRed + image[i + 1][j].rgbtRed + image[i + 1][j + 1].rgbtRed) / 4.0); tempimage[i][j].rgbtBlue = round(avgb); tempimage[i][j].rgbtGreen = round(avgg); tempimage[i][j].rgbtRed = round(avgr); } else if (i == 0 && j == (width - 1)) // to blur the pixcel in first row last column { avgb = 0; avgg = 0; avgr = 0; avgb = ((image[i][j].rgbtBlue + image[i][j - 1].rgbtBlue + image[i + 1][j].rgbtBlue + image[i + 1][j - 1].rgbtBlue) / 4.0); avgg = ((image[i][j].rgbtGreen + image[i][j - 1].rgbtGreen + image[i + 1][j].rgbtGreen + image[i + 1][j - 1].rgbtGreen) / 4.0); avgr = ((image[i][j].rgbtRed + image[i][j - 1].rgbtRed + image[i + 1][j].rgbtRed + image[i + 1][j - 1].rgbtRed) / 4.0); tempimage[i][j].rgbtBlue = round(avgb); tempimage[i][j].rgbtGreen = round(avgg); tempimage[i][j].rgbtRed = round(avgr); } else if (i == (height - 1) && j == (width - 1)) // to blur the pixcel in last row last column { avgb = 0; avgg = 0; avgr = 0; avgb = ((image[i][j].rgbtBlue + image[i][j - 1].rgbtBlue + image[i - 1][j].rgbtBlue + image[i - 1][j - 1].rgbtBlue) / 4.0); avgg = ((image[i][j].rgbtGreen + image[i][j - 1].rgbtGreen + image[i - 1][j].rgbtGreen + image[i - 1][j - 1].rgbtGreen) / 4.0); avgr = ((image[i][j].rgbtRed + image[i][j - 1].rgbtRed + image[i - 1][j].rgbtRed + image[i - 1][j - 1].rgbtRed) / 4.0); tempimage[i][j].rgbtBlue = round(avgb); tempimage[i][j].rgbtGreen = round(avgg); tempimage[i][j].rgbtRed = round(avgr); } else if (i == (height - 1) && j == 0) // to blur the first pixcel last row. { avgb = 0; avgg = 0; avgr = 0; avgb = ((image[i][j].rgbtBlue + image[i][j + 1].rgbtBlue + image[i - 1][j].rgbtBlue + image[i - 1][j + 1].rgbtBlue) / 4.0); avgg = ((image[i][j].rgbtGreen + image[i][j + 1].rgbtGreen + image[i - 1][j].rgbtGreen + image[i - 1][j + 1].rgbtGreen) / 4.0); avgr = ((image[i][j].rgbtRed + image[i][j + 1].rgbtRed + image[i - 1][j].rgbtRed + image[i - 1][j + 1].rgbtRed) / 4.0); tempimage[i][j].rgbtBlue = round(avgb); tempimage[i][j].rgbtGreen = round(avgg); tempimage[i][j].rgbtRed = round(avgr); } else if ((i == (height - 1) || i == 0) && j != 0 && j != (width - 1)) // To Blur horizontal edges { avgb = 0; avgg = 0; avgr = 0; if (i == 0) // To blur the top row { for (int c = i ; c < i + 2; c++) { for (int d = j - 1; d < j + 2; d++) { avgb += image[c][d].rgbtBlue; avgg += image[c][d].rgbtGreen; avgr += image[c][d].rgbtRed; } } } else if (i == (height - 1)) // To blur the bottom row { for (int c = i - 1; c < i + 1; c++) { for (int d = j - 1; d < j + 2; d++) { avgb += image[c][d].rgbtBlue; avgg += image[c][d].rgbtGreen; avgr += image[c][d].rgbtRed; } } } tempimage[i][j].rgbtBlue = round(avgb / 6); tempimage[i][j].rgbtGreen = round(avgg / 6); tempimage[i][j].rgbtRed = round(avgr / 6); } else if ((j == (width - 1) || j == 0) && i != 0 && i != (height - 1)) // To Blur vertical edges { avgb = 0; avgg = 0; avgr = 0; if (j == 0) // to blur the first row { for (int c = j ; c < j + 2; c++) { for (int d = i - 1; d < i + 2; d++) { avgb += image[d][c].rgbtBlue; avgg += image[d][c].rgbtGreen; avgr += image[d][c].rgbtRed; } } } else if (j == (width - 1)) // To blur the last row { for (int c = j - 1; c < j + 1; c++) { for (int d = i - 1; d < i + 2; d++) { avgb += image[d][c].rgbtBlue; avgg += image[d][c].rgbtGreen; avgr += image[d][c].rgbtRed; } } } tempimage[i][j].rgbtBlue = round(avgb / 6); tempimage[i][j].rgbtGreen = round(avgg / 6); tempimage[i][j].rgbtRed = round(avgr / 6); } else if (i != 0 && i != (height - 1) && j != 0 && j != (width - 1)) // to Blur the entire body except edges { avgb = 0; avgg = 0; avgr = 0; for (int c = i - 1; c < i + 2; c++) // loop to pick 3 rows { for (int d = j - 1; d < j + 2; d++) // loop to pick 3 columns { avgb += image[c][d].rgbtBlue; avgg += image[c][d].rgbtGreen; avgr += image[c][d].rgbtRed; } } tempimage[i][j].rgbtBlue = round(avgb / 9); tempimage[i][j].rgbtGreen = round(avgg / 9); tempimage[i][j].rgbtRed = round(avgr / 9); } } } for (int r = 0; r < height; r++) // to assign actual values from temp variable to main variable { for (int s = 0; s < width; s++) { image[r][s].rgbtBlue = tempimage[r][s].rgbtBlue; image[r][s].rgbtGreen = tempimage[r][s].rgbtGreen; image[r][s].rgbtRed = tempimage[r][s].rgbtRed; } } return; } int avg(int blue, int green, int red) // to get average for of 3 int. { float avg = round((blue + green + red) / 3.0); return avg; } int sepiablue(int blue, int green, int red) // Sepia blue Algorithm { float t = round((float)(red * .272) + (green * .534) + (blue * .131)); if (t > 255) { t = 255; } return t; } int sepiagreen(int blue, int green, int red) //Sepia green Algorithm { float t = round((float)(red * .349) + (green * .686) + (blue * .168)); if (t > 255) { t = 255; } return t; } int sepiared(int blue, int green, int red) //Sepia red Algorithm { float t = round((float)(red * .393) + (green * .769) + (blue * .189)); if (t > 255) { t = 255; } return t; }
C
#include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <netdb.h> #include "common.h" #include "client.h" void error( char *s ) { fprintf( stderr, "%s : %s", s, strerror( errno ) ); exit(1); } int open_socket( char *host, char *port ) { struct addrinfo *res; struct addrinfo hints; memset( &hints, 0, sizeof(hints) ); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if( getaddrinfo(host,port,&hints,&res) == -1 ) error("Can not resolve the address"); int d_sock = socket( res->ai_family, res->ai_socktype, res->ai_protocol ); if( d_sock == -1 ) error("Cant not open socket"); int c = connect( d_sock, res->ai_addr, res->ai_addrlen ); freeaddrinfo(res); if( c == -1 ) error("Cant not connect to socket"); printf("Client is connecting\n"); return d_sock; } int say( int socket, char *s ) { int result = send( socket, s, strlen(s), 0 ); if( result == -1 ) fprintf(stderr, "%s : %s\n","Error talking to server", strerror(errno) ); return result; } int main( int argc, char const *argv[] ) { int d_sock; d_sock = open_socket("codekissyoung.com","30000"); if( argc < 2 ) printf("client arg1"); int tmpLen = strlen(argv[1]); Node *dataBuf = (Node*)malloc( sizeof(Node) + tmpLen + 1 ); dataBuf -> bufSize = tmpLen + 1; dataBuf -> nodeSize = sizeof(Node) + dataBuf -> bufSize; memset( dataBuf->buf, 0, dataBuf -> bufSize ); memmove( dataBuf->buf, argv[1], dataBuf -> bufSize ); printf("nodeSize = %d\n bufSize = %d\n buf = %s\n",dataBuf->nodeSize,dataBuf->bufSize,dataBuf->buf); if( send( d_sock, (char*)dataBuf, dataBuf->nodeSize, 0 ) == -1 ) error("send error!\n"); close(d_sock); return 0; }
C
/** @file stk_sequence.h * This header provides the typedefs and definitions required to interface * to the Sequence module APIs */ #ifndef STK_SEQUENCE_H #define STK_SEQUENCE_H #include "stk_common.h" /** * \typedef stk_sequence_id * A Sequence ID is a 64 bit unsigned number. * \see stk_acquire_sequence_id() and stk_create_sequence() */ typedef stk_uint64 stk_sequence_id; /** * \typedef stk_sequence_type * A Sequence Type defines the type of data contained in the sequence. * This is largely left for user usage, though STK defines some typical types. * \see stk_create_sequence() */ typedef stk_uint16 stk_sequence_type; /** * \typedef stk_generation_id * The generation ID is a 16 bit unsigned number and is used to manage uniqueness of the sequence. * For example, data flow modules will bump the generation each time a sequence is sent ensuring * each sequeunce sent is uniquely identifed. * \see stk_create_sequence() */ typedef stk_uint16 stk_generation_id; /** * \typedef stk_sequence_metadata_t * Sequences can store data and meta data. This is the type used to manage meta data. * [Meta data is not yet implemented] */ typedef void * stk_sequence_metadata_t; /** * \typedef stk_sequence_t * This is the Sequence object * \see stk_create_sequence() */ typedef struct stk_sequence_stct stk_sequence_t; /** * \typedef stk_sequence_iterator_t * This defines an iterator to step through each data element in a sequence * \see stk_sequence_iterator() and stk_iterate_sequence() */ typedef struct stk_sequence_iterator_stct stk_sequence_iterator_t; /** Definition of an invalid Sequence ID */ #define STK_SEQUENCE_ID_INVALID 0 #define STK_SEQUENCE_TYPE_INVALID 0 /*!< Invalid Sequence - never used */ #define STK_SEQUENCE_TYPE_DATA 1 /*!< Sequence is a Data sequence */ #define STK_SEQUENCE_TYPE_KVPAIR 2 /*!< Sequence is set of Key Value Pairs */ #define STK_SEQUENCE_TYPE_MGMT 3 /*!< Sequence is Management data */ #define STK_SEQUENCE_TYPE_REQUEST 4 /*!< Sequence is a request */ #define STK_SEQUENCE_TYPE_QUERY 5 /*!< Sequence is a query (read only request) */ #define STK_SEQUENCE_TYPE_SUBSCRIBE 6 /*!< Sequence is a subscription (persistent request) */ /** Macro to ease mapping of types to strings */ #define STK_SEQ_TYPE_TO_STRING(_type) \ _type == STK_SEQUENCE_TYPE_DATA ? "Data" : \ _type == STK_SEQUENCE_TYPE_MGMT ? "Management" : \ _type == STK_SEQUENCE_TYPE_KVPAIR ? "Key/Value Pair" : \ _type == STK_SEQUENCE_TYPE_REQUEST ? "Request" : \ _type == STK_SEQUENCE_TYPE_QUERY ? "Query" : \ "" /** The callback signature to be used for functions being passed to stk_iterate_sequence() */ typedef stk_ret (*stk_sequence_cb)(stk_sequence_t *seq, void *data, stk_uint64 sz, stk_uint64 user_type, void *clientd); #endif
C
#include <stdlib.h> #include <stdio.h> #include <time.h> #include "random.h" #include <time.h> //1.2.a double random_double(double a, double b){ return (double) ((b - a) * (rand() / (RAND_MAX + 1.0)) + a); } //1.2.b float random_float(float a, float b){ return (float) ((b - a) * (rand() / (RAND_MAX + 1.0)) + a); } //1.2.c size_t random_size_t(size_t a, size_t b){ return (size_t) ((b - a) * (rand() / (RAND_MAX + 1.0)) + a); } //1.2.d int random_int(int a, int b){ return (int) ((b - a) * (rand() / (RAND_MAX + 1.0)) + a); } //1.2.e unsigned char random_uchar(unsigned char a, unsigned char b){ return (unsigned char) ((b - a) * (rand() / (RAND_MAX + 1.0)) + a); } //1.2.f void random_init_string(unsigned char * c, size_t n){ for (int i = 0; i < n; ++i) { c[i] = random_uchar('A','Z'); } }
C
#include <SimpleModbusMaster_DUE.h> //////////////////// Port information /////////////////// // interval at which to blink (milliseconds) ////////////////////modbus//////////// #define baud 115200 #define timout 50 #define polling 200 // скорость опроса по модбус #define retry_count 10 #define TxEnablePin 0 // Tx/Rx пин RS485 #define Slave_ID 10 //Общая сумма доступной памяти на ведущем устройстве, чтобы хранить данные #define TOTAL_NO_OF_REGISTERS 255 unsigned long previousMillis = 0; // will store last time LED was updated const long interval = 250; //////////////////modbus//////////////// union fread_t{ float f; uint16_t u[2]; }t; enum { PACKET1, PACKET2, PACKET3, PACKET4, PACKET5, PACKET6, PACKET7, TOTAL_NO_OF_PACKETS // leave this last entry }; // Масив пакетов модбус Packet packets[TOTAL_NO_OF_PACKETS]; // Массив хранения содержимого принятых и передающихся регистров unsigned int regs[TOTAL_NO_OF_REGISTERS]; void setup_mega() { // Настраиваем пакеты // Шестой параметр - это индекс ячейки в массиве, размещенном в памяти ведущего устройства, в которую будет // помещен результат или из которой будут браться данные для передачи в подчиненное устройство. В нашем коде - это массив reg // Пакет,SLAVE адрес,функция модбус,адрес регистра,количесво запрашиваемых регистров,локальный адрес регистра. modbus_construct(&packets[PACKET1], Slave_ID, READ_HOLDING_REGISTERS, 0, 23, 0); modbus_construct(&packets[PACKET2], Slave_ID, READ_HOLDING_REGISTERS, 23, 23, 23); modbus_construct(&packets[PACKET3], Slave_ID, READ_HOLDING_REGISTERS, 47, 23, 47); modbus_construct(&packets[PACKET4], Slave_ID, READ_HOLDING_REGISTERS, 71, 23, 71); modbus_construct(&packets[PACKET5], Slave_ID, READ_HOLDING_REGISTERS, 95, 23, 95); // Пакет,SLAVE адрес,функция модбус,адрес регистра,данные,локальный адрес регистра. modbus_construct(&packets[PACKET6], Slave_ID, PRESET_MULTIPLE_REGISTERS, 95, 23, 95); // инициализируем протокол модбус modbus_configure(&Serial, baud, timout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs); } void up_reg(){ t.u[0] = regs[0]; t.u[1] = regs[1]; TempZ[0] = t.f; t.u[0] = regs[2]; t.u[1] = regs[3]; TempZ[1] = t.f; t.u[0] = regs[4]; t.u[1] = regs[5]; TempZ[2] = t.f; t.u[0] = regs[6]; t.u[1] = regs[7]; TempZ[3] = t.f; t.u[0] = regs[8]; t.u[1] = regs[9]; Temp_out = t.f; t.u[0] = regs[10]; t.u[1] = regs[11]; Temp_in = t.f; t.u[0] = regs[12]; t.u[1] = regs[13]; Humid1 = t.f; t.u[0] = regs[14]; t.u[1] = regs[15]; NH3 = t.f; t.u[0] = regs[16]; t.u[1] = regs[17]; Tmax = t.f; t.u[0] = regs[18]; t.u[1] = regs[19]; Tmin = t.f; t.u[0] = regs[20]; t.u[1] = regs[21]; Tmax_i = t.f; t.u[0] = regs[22]; t.u[1] = regs[23]; Tmin_i = t.f; flagZ_1 = regs[38]; flagZ_2 = regs[39]; flagZ_3 = regs[40]; flagZ_4 = regs[41]; // CO_2 = regs[8]; // nh.u[1] = regs[9]; // nh.u[0] = regs[10]; // tmax.u[1] = regs[11]; // tmax.u[0] = regs[12]; // tmin.u[1] = regs[13]; // tmin.u[0] = regs[14]; // flag_wind = regs[15]; // lux = regs[16]; // tmax_i.u[1] = regs[17]; // tmax_i.u[0] = regs[18]; // tmin_i.u[1] = regs[19]; // tmin_i.u[0] = regs[20]; // t_1.u[1] = regs[21]; // t_1.u[0] = regs[22]; // Temp_in = t_0.f; // Temp_out = t_1.f; // Temp = t1.f; // Temp1 = t2.f; // Humid1 = h.f; // NH3 = nh.f; // Tmax = tmax.f; // Tmin = tmin.f; // Tmax_i = tmax_i.f; // Tmin_i = tmin_i.f; // terminal.println(regs[98]); // regs[93]= VentTempStart; // regs[94]= VentTempStop; // regs[95]= VentTime; // regs[96] = button; // regs[97]= relay; if (!flag_send) { heat = regs[98] ; Blynk.virtualWrite(V55, regs[98]);/* code */ } else if (heat!=regs[98]) { regs[98]=heat; terminal.println(regs[98]); } else { flag_send = false; // Blynk.virtualWrite(V55, regs[98]); } // }
C
#include "common_local.h" void arr_transposition(int *arr, int row, int col) { int i, j; int *trans_arr; trans_arr = (int *)malloc(col * row * sizeof(int)); for(i = 0; i < row; ++i) { for(j = 0; j < col; ++j) { trans_arr[j * col + i] = arr[i * row + j]; } } for(i = 0; i < col; ++i) { for(j = 0; j < row; ++j) { printf("%d ", trans_arr[i * col + j]); } printf("\n"); } printf("\n"); } int main() { int arr[][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; arr_transposition(arr, 4, 4); return 0; }
C
/* * ex_4-12_recursive_itoa.c -- Ex KnR book * * Adapt the ideas of printd to write a recursive version of itoa; * that is, convert an integer into a string by calling a recursive routine. * * Written by Harold André * E-mail <[email protected]> * * Started on Sat Oct 26 12:47:50 2013 Harold André * Last update Sat Oct 26 14:10:05 2013 Harold André * * gcc -Wall -o ex_4-12_recursive_itoa ex_4-12_recursive_itoa.c * */ #include <stdio.h> #define MAXCHAR 100 char ascii_int[MAXCHAR]; /* printd: print n in decimal */ void printd(int); /* itoa: convert integer to string */ void itoa(int, char []); int main(void) { int i = 12345678; printd(i); itoa(i, ascii_int); printf("\nitoa: decimal: %d -> string: %s\n", i, ascii_int); i = 987; itoa(i, ascii_int); printf("\nitoa: decimal: %d -> string: %s\n", i, ascii_int); return 0; } /* printd: print n in decimal */ void printd(int n) { if (n < 0) { putchar('-'); n = -n; } if (n / 10) printd(n / 10); putchar(n % 10 + '0'); } void itoa(int n, char s[]) { static int i; /* static variable is initialized with 0 by convention */ if (n < 0) { s[i++] = '-'; n = -n; } if (n / 10) itoa(n / 10, s); else i = 0; s[i++] = (n % 10 + '0'); s[i] = '\0'; }
C
#include <stdio.h> #include "main.h" #include "string.h" /** * _memcpy - Copies the first @n bytes of the memory area * pointed to by @src into the memory area pointed to by @dest. * @dest: A pointer to the memory area to be filled. * @src: A pointer to the memory area to be copied. * @n: The number of bytes to be copied. * * Return: A pointer to the copied memory area @dest. */ char *_memset(char *s, char b, unsigned int n) { }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: giabanji <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/12/04 18:10:49 by giabanji #+# #+# */ /* Updated: 2017/12/05 19:07:54 by giabanji ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int ft_isdisc(char s) { if (s == 's' || s == 'S' || s == 'p' || s == 'd' || s == 'i' || s == 'O' || s == 'u' || s == 'U' || s == 'x' || s == 'X' || s == 'c' || s == 'C' || s == '%') return ((int)s); if (s == '\0') return (1); return (0); } void ft_joinchar(char **line, char c) { char *tmp; size_t size; if (!(*line)) { *line = (char *)malloc(sizeof(char) * 2); *line[0] = c; *line[1] = '\0'; } else { tmp = ft_strdup(*line); ft_memdel((void **)line); size = ft_strlen(tmp); *line = (char *)malloc(sizeof(char) * (size + 2)); *line = ft_strcpy(*line, tmp); *line[size] = c; *line[size + 1] = '\0'; free(tmp); } } int ft_printf(char *str, ...) { char *line; int i; if (!str) return (0); i = -1; while (str[++i]) { if (str[i] != '%') ft_joinchar(&line, str[i]); else if (str[i] == '%') { i++; ft_validconvers(&line, i, &str); while (str[i] || ft_isdisc(str[i]) < 1) i++; i--; } } if (str[0] != '\0') ft_pustr(line); ft_putchar('\n'); return (0); }
C
#include<stdio.h> #include<stdlib.h> void matrizIdentidade(int M[][5], int l); void imprimeMatriz(int M[][5], int l); main(){ int Matriz[5][5]; matrizIdentidade(Matriz, 5); imprimeMatriz(Matriz,5); system("pause"); } void imprimeMatriz(int M[][5], int l){ int i, j; for(i=0; i<l; i++){ for(j=0; j<5; j++){ printf("%d ", M[i][j]); } printf("\n"); } } void matrizIdentidade(int M[][5], int l){ int i, j; for(i=0; i<l; i++){ for(j=0; j<5; j++){ if(i==j) M[i][j] = 1; else M[i][j] = 0; } } }
C
#include<stdio.h> #include<unistd.h> #include<stdlib.h> struct process { int pid,bt,wt,tat,pri; }; int main() { int n,i,n1=0,n2=0,n3=0,p=1,q=1,r=1; int total_waiting_time=0,total_tat=0,quant=4,quantRR=10 ; int c1=0,c2=0,c3=0,t=0; // for waiting times. int Rembt[3]; printf("\t\t\t============================\n\n\t\tRange OF Queue1 Priority is 1-10 i.e Round Robin\n"); printf("\n\t\tRange OF Queue2 Priority is 11-20 i.e Priority Scheduling\n"); printf("\n\t\tRange OF Queue3 Priority is 21-30 i.e FCFS\n\n\n"); printf("\t\t\t============================\n"); printf("ENTER THE NUMBER of processes : "); scanf("%d",&n); printf("\n__________________________________\n"); struct process p1[n],p2[n],p3[n],temp; printf("\nENTER Process Number | Priority | |Burst Time : \n"); for(i=1;i<=n;i++) { printf("\nFOR PROCESS %d\n",i); struct process temp1; scanf("%d",&temp1.pid); scanf("%d",&temp1.bt); A: scanf("%d",&temp1.pri); if(temp1.pri>=1 && temp1.pri<=10) { p3[p++]=temp1; n3++; //n1 size of q1 } else if(temp1.pri>=11 && temp1.pri<=20) { p2[q++]=temp1; n2++; //n2 size of q2 } else if(temp1.pri>=21 && temp1.pri<=30) { p1[r++]=temp1; n1++; //n3 size of q3 } else { printf("Invalid Priority\n"); goto A; } } /* COPYING EACH PROCESS'S BURST TIME AND SUMS IT UP */ int s1=0,s2=0,s3=0; for (int i = 1 ; i <= n1 ; i++){ s1+=p1[i].bt; p1[i].wt=0; } for (int i = 1 ; i <= n2 ; i++){ s2+=p2[i].bt; p2[i].wt=0; } for (int i = 1 ; i <= n3 ; i++){ s3+=p3[i].bt; p3[i].wt=0; } Rembt[1]=s1; Rembt[2]=s2; Rembt[3]=s3; int count_time=0; int bt1_Left[n1],bt2_Left[n2],bt3_Left[n3] ; for (int i=1;i<=n1;i++){ bt1_Left[i]=p1[i].bt ; } for (int i=1;i<=n2;i++){ bt2_Left[i]=p2[i].bt ; } for (int i=1;i<=n3;i++){ bt3_Left[i]=p3[i].bt ; } /*SORTING ON THE BASIS OF PRIORITIES FOR PRIORITY SCHEDULING IN QUEUE2*/ int pos,j; for(i=1;i<=n2;i++) { pos=i; for(j=i+1;j<=n2;j++) { if(p2[j].pri>p2[pos].pri) { pos=j; } } temp=p2[i]; p2[i]=p2[pos]; p2[pos]=temp; } while (1) { /*STARTING FROM QUEUE1 i.e K=1*/ bool Done = true; for (int k=1;k<=3;k++) { count_time=0; if(Rembt[k]>0) { Done=false ; if(Rembt[k]>quantRR) { if(k==1&&n1!=0) { t+=c1 ; count_time=0; while (1) { bool done = true; for(int i=1;i<=n1;i++) { if(bt1_Left[i]>0) { done=false; if (bt1_Left[i]>quant) { if(count_time+quant>10) { bt1_Left[i]-=10-count_time; t+= 10-count_time ; count_time=10; break; } t+=quant; count_time += quant; bt1_Left[i] -= quant; } else { if(count_time+p1[i].bt>10) { bt1_Left[i]-= 10-count_time ;t+= 10-count_time; count_time=10; break; } t=t+bt1_Left[i]; p1[i].wt += t - p1[i].bt; count_time+=p1[i].bt; bt1_Left[i] = 0; } } if(count_time>=10) { break; } } if (done == true || count_time>=10) break; } printf("\nWaiting time is:%d\n",p1[i].wt) ; Rembt[k] -= quantRR; c1=0; c2+=quantRR; c3+=quantRR; } else if(k==2 && n2!=0) // q2 STARTING Priority Algo. { //calculating WAITING TIME.... count_time=0; for(i=1; i<=n2 ; i++) { if(bt2_Left[i]<=0 && bt2_Left[i+1]<=0 ) { continue; } else if(bt2_Left[i]<=0 && bt2_Left[i+1]>0 ) { p2[i+1].wt += p2[i].bt + p2[i].wt +c2 ; continue; } p2[i].wt += c2 ; while(bt2_Left[i]!=0) { if(count_time==10) { break; } bt2_Left[i]-= 1; count_time++; } if(count_time>10) { break; } if(i==n2) { break; } if(bt2_Left[i]==0) { p2[i+1].wt = p2[i].bt + p2[i].wt ; } } printf("\nhWaiting time is:%d\n",p2[i].wt) ; Rembt[k]-=quantRR; c2=0; c1+=quantRR; c3+=quantRR; } // end of q2 else if(k==3&&n3!=0) { //calculating WAITING TIME------------------------- count_time=0; for(i=1; i<=n3 ; i++) { if(bt3_Left[i]<=0 && bt3_Left[i+1]<=0 ) { continue; } else if(bt3_Left[i]<=0 && bt3_Left[i+1]>0 ) { p3[i+1].wt+=p3[i].bt+p3[i].wt+c3; continue; } p3[i].wt+=c3 ; while(bt3_Left[i]!=0) { if(count_time==10) { break; } bt3_Left[i]-=1; count_time+=1; } if(count_time>10) break; if(i==n3) { break; } if(bt3_Left[i]==0) { p3[i+1].wt=p3[i].bt+p3[i].wt ; } } printf("\nhWaiting time is:%d\n",p3[i].wt) ; Rembt[k]-=quantRR; c1+= quantRR; c2+=quantRR; c3=0; } } else { if(k==1&&n1!=0) // q1 { t+=c1; while(1) { bool done=true; for (int i=1;i<=n1;i++) // to traverse each process. { if(bt1_Left[i] > 0) { done=false; // There is a pending process in q1 if(bt1_Left[i]>quant) { t+=quant; bt1_Left[i]-=quant; } else { t=t+bt1_Left[i]; p1[i].wt=t-p1[i].bt; bt1_Left[i]=0; } } } if(done == true) { break; } } c1=0; c2+=Rembt[k]; c3+=Rembt[k]; Rembt[k]=0; } // End of q1. else if(k==2&&n2!=0) // q2 { for(i=1;i<=n2;i++) { if(i==1&&n2==1) { p2[i].wt+=c2; bt2_Left[k]=0; break; } if(i==n2) { bt2_Left[i]=0; break; } if(bt2_Left[i]<=0 && bt2_Left[i+1]<=0 ) { continue; } else if(bt2_Left[i]<=0 && bt2_Left[i+1]>0 ) { p2[i+1].wt = p2[i].bt + p2[i].wt +c2 ; continue; } p2[i].wt += c2 ; bt2_Left[i]=0; p2[i+1].wt = p2[i].bt + p2[i].wt ; } c2=0; c3+=Rembt[k]; c1+=Rembt[k]; Rembt[k]=0; } else if(k==3&&n3!=0) // q3 { for(i=1;i<=n3;i++) { if(i==1 && n3==1) { p3[i].wt+=c3 ;bt3_Left[k]=0; break; } if(i==n3) { bt3_Left[i]=0; break; } if(bt3_Left[i]<=0 && bt3_Left[i+1]<=0 ) { continue; } else if(bt3_Left[i]<=0 && bt3_Left[i+1]>0 ) { p3[i+1].wt = p3[i].bt + p3[i].wt +c3 ; continue; } p3[i].wt += c3 ; bt3_Left[i]=0; p3[i+1].wt = p3[i].bt + p3[i].wt ; } c3=0; c2+= Rembt[k]; c1+= Rembt[k]; Rembt[k]=0; } } } } if (Done == true){ break; } } /*CALCULATING TURNAROUND TIME*/ int wt_sum=0,tat_sum=0; for (int i=1;i<=n1;i++) { p1[i].tat=p1[i].bt+p1[i].wt; wt_sum+=p1[i].wt; tat_sum+=p1[i].tat; } for (int i=1;i<=n2;i++) { p2[i].tat=p2[i].bt+p2[i].wt; wt_sum+=p2[i].wt; tat_sum+=p2[i].tat; } for (int i=1;i<=n3;i++) { p3[i].tat=p3[i].bt+p3[i].wt; wt_sum+=p3[i].wt; tat_sum+=p3[i].tat; } printf("\t\t\tCalculating the result\n\t\t\tPLEASE WAIT..."); sleep(1); system("cls"); printf("\t\t\t============================\n\n\t\tRange OF Queue1 Priority is 1-10 i.e Round Robin\n"); printf("\n\t\tRange OF Queue2 Priority is 11-20 i.e Priority Scheduling\n"); printf("\n\t\tRange OF Queue3 Priority is 21-30 i.e FCFS\n\n\n"); printf("\t\t\t==================================PROCESSES QUEUE TABLE=====================================\n"); printf("\n\t\tProcess Number |\tPriority |\tBurst Time |\tWaiting Time |\tTurn Around Time"); //printf("\n\nQUEUE1 : \n"); for (int i=1;i<=n1;i++) { printf("\n\t\t%d \t\t%d \t\t%d \t\t%d \t\t%d\n",p1[i].pid,p1[i].pri,p1[i].bt,p1[i].wt,p1[i].tat); } //printf("\nQUEUE2 : \n"); for (int i=1;i<=n2;i++) { printf("\n\t\t%d \t\t%d \t\t%d \t\t%d \t\t%d\n",p2[i].pid,p2[i].pri,p2[i].bt,p2[i].wt,p2[i].tat);} //printf("\nQUEUE3 : \n"); for (int i=1;i<=n3;i++) { printf("\n\t\t\t%d \t\t%d \t\t%d \t\t%d \t\t%d\n",p3[i].pid,p3[i].pri,p3[i].bt,p3[i].wt,p3[i].tat); } printf("\n"); }
C
#include<stm32f4xx.h> int inA,inB; int main(void) { RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); //Enable Peripheral clock for GPIOA GPIO_InitTypeDef GPIO_InitStructure; // Structure definition GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; // Enable GPIO Pin 5 (of GPIOA) GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; // Pinmode to OuTPUT GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //// Push pull GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; // // Pull Down model GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; // Speed to Fast speed GPIO_Init(GPIOA,&GPIO_InitStructure); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); //Enable Peripheral clock for GPIOC GPIO_InitTypeDef GPIO_InitStructure1; // Structure definition GPIO_InitStructure1.GPIO_Pin = GPIO_Pin_7; // Enable GPIO Pin 7 (of GPIOC) GPIO_InitStructure1.GPIO_Mode = GPIO_Mode_IN; // Pinmode to INPUT GPIO_InitStructure1.GPIO_OType = GPIO_OType_PP; //// Push pull GPIO_InitStructure1.GPIO_PuPd = GPIO_PuPd_DOWN; // // Pull Down model GPIO_InitStructure1.GPIO_Speed = GPIO_Speed_50MHz; // Speed to Fast speed GPIO_Init(GPIOC,&GPIO_InitStructure1); GPIO_InitTypeDef GPIO_InitStructure2; // Structure definition GPIO_InitStructure2.GPIO_Pin = GPIO_Pin_9; // Enable GPIO Pin 9 (of GPIOA) GPIO_InitStructure2.GPIO_Mode = GPIO_Mode_IN; // Pinmode to INPUT GPIO_InitStructure2.GPIO_OType = GPIO_OType_PP; //// Push pull GPIO_InitStructure2.GPIO_PuPd = GPIO_PuPd_DOWN; // // Pull Down model GPIO_InitStructure2.GPIO_Speed = GPIO_Speed_50MHz; // Speed to Fast speed GPIO_Init(GPIOA,&GPIO_InitStructure2); while(1) { inA = GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_7); inB = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_9); if(inA ==1 && inB ==1 ) { GPIO_SetBits(GPIOA,GPIO_Pin_5); } if(inA ==0 && inB ==0 ) { GPIO_ResetBits(GPIOA,GPIO_Pin_5); } if(inA ==1 && inB ==0 ) { GPIO_ResetBits(GPIOA,GPIO_Pin_5); } if(inA ==0 && inB == 1 ) { GPIO_ResetBits(GPIOA,GPIO_Pin_5); } } return 0; }
C
#include "log.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #include <string.h> void loge(const char *format, ...) { FILE *f; va_list ap; char out[512]; time_t t = time(NULL); struct tm tm = {0}; char *after_date = &out[21]; tm = *localtime(&t); strftime(out, 22, "[%Y-%m-%d:%H:%M:%S]", &tm); strcpy(after_date, "[ERROR]"); f = fopen("session.log", "a"); va_start(ap, format); vsprintf(after_date + 8, format, ap); va_end(ap); out[28] = ' '; fprintf(stdout, "%s\n", out); fprintf(f, "%s\n", out); fclose(f); } void logi(const char *format, ...) { FILE *f; va_list ap; char out[512]; time_t t = time(NULL); struct tm tm = {0}; char *after_date = &out[21]; tm = *localtime(&t); strftime(out, 22, "[%Y-%m-%d:%H:%M:%S]", &tm); strcpy(after_date, "[INFO]"); f = fopen("session.log", "a"); va_start(ap, format); vsprintf(after_date + 7, format, ap); va_end(ap); out[27] = ' '; fprintf(stdout, "%s\n", out); fprintf(f, "%s\n", out); fclose(f); }
C
#include <stdio.h> #include <stdlib.h> // TODO: define add, sub, mul, divi as functions which take two integer arguments and return the result // we can't use "div" because it is already defined int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int divi(int a, int b) { return a / b; } // TODO: define function array here. funcs[0] will point to add and so on int (*funcs[4])(int, int) = {add, sub, mul, divi}; int main(int argc, char **argv) { if(argc != 4) { printf("Call: %s [op from 0-3] a b\n", argv[0]); printf("op is either 0 (for add), 1 (for sub), 2 (for mul), or 3 (for divi)\n"); printf("a and b are the arguments\n"); printf("%s 1 5 3 would return 2 (because it is 5-3)\n", argv[0]); return 1; } int op = atoi(argv[1]); int a = atoi(argv[2]); int b = atoi(argv[3]); printf("%i\n", (funcs[op])(a, b)); }
C
/* * led.c * * Created on: 2014年10月18日 * Author: daniel */ #include "led.h" #include <string.h> // 初始化所有LED引脚 BaseType_t InitLED( void ) { BaseType_t ret = pdTRUE; GPIO_InitTypeDef GPIO_InitStructure; // Enable GPIO Peripheral clock RCC_APB2PeriphClockCmd(LED_INTERNAL_GPIO_CLK | LED_RED_GPIO_CLK | LED_GREEN_GPIO_CLK, ENABLE); // Configure pin in output push/pull mode GPIO_InitStructure.GPIO_Pin = LED_INTERNAL_Pin; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(LED_INTERNAL_GPIO, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = LED_RED_Pin; GPIO_Init(LED_RED_GPIO, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = LED_GREEN_Pin; GPIO_Init(LED_GREEN_GPIO, &GPIO_InitStructure); return ret; } static BaseType_t cmd_led( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString ) { BaseType_t bOn; const char * pcParameter; BaseType_t xParameterStringLength; pcParameter = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameterStringLength); configASSERT( pcParameter ); bOn = (*pcParameter == '1') ? pdTRUE : pdFALSE; pcParameter = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameterStringLength); configASSERT( pcParameter ); if (strcasecmp(pcParameter, "debug") == 0) { if (bOn) DEBUG_LED_ON; else DEBUG_LED_OFF; } else if (strcasecmp(pcParameter, "red") == 0) { if (bOn) RED_LED_ON; else RED_LED_OFF; } else if (strcasecmp(pcParameter, "green") == 0) { if (bOn) GREEN_LED_ON; else GREEN_LED_OFF; } return pdFALSE; } const CLI_Command_Definition_t cmd_def_led = { "led", "\r\nled debug|red|gree 0|1 \r\n Control color LED.\r\n", cmd_led, /* The function to run. */ 2 };
C
#include "producent.h" void error(const char *msg) { perror(msg); exit(1); } void cbInit(circ_buffer_t *cb, size_t capacity, size_t sz) { cb->buffer=malloc(capacity*sz); if(cb->buffer==NULL) error("cb_init: malloc error"); cb->buffer_end=(char*)cb->buffer+capacity*sz; cb->capacity=capacity; cb->count=0; cb->sz=sz; cb->head=cb->buffer; cb->tail=cb->buffer; } void cbFree(circ_buffer_t *cb) { free(cb->buffer); } void cbPush(circ_buffer_t *cb, const void* item) { memcpy(cb->head, item, cb->sz); cb->head=(char*)cb->head+cb->sz; if(cb->head==cb->buffer_end) cb->head=cb->buffer; cb->count++; generated++; } void cbPop(circ_buffer_t *cb, void* item) //wyślij 112KB=114 688 bajtów { while(cb->count<179); //za malo blokow w buf - w 112KB jest 179 bloków po 640B if(poped%10==0) //1,25MB/114 688B=10 cb->tail=cb->buffer; memcpy(item,cb->tail,114688); cb->tail=(char*)cb->tail+114688; if(cb->tail==cb->buffer_end) cb->tail=cb->buffer; cb->count-=179; poped++; } void genData(circ_buffer_t *cb, char A) //stworz blok rozmariu 640bajtów { if(cb->count==cb->capacity) return; char arr[640]; //amount of data i want to generate+1; if(A<='Z') { memset(arr,(int)A, 640); //arr[641]='\0'; cbPush(cb,arr); //dodaj tyle bajtów do buffora } if(A>'Z') { memset(arr,(int)A+6,640); //arr[641]='\0'; cbPush(cb,arr); } } void writeRaport(circ_buffer_t *cb) { clock_gettime(CLOCK_MONOTONIC, &monotime); time_t curtime=boottime+monotime.tv_sec; clock_gettime(CLOCK_REALTIME, &realtime); size_t inMag=cb->count*cb->sz; size_t percent=inMag*100/1250000; fprintf(fdR,"Connected clients: %d, in magazine: %zu, percent: %zu. Mono time: %s, WallTime: %s. Amount of sent blocks: %d, flow of data: %d\n", connectedClients, inMag, percent, ctime(&curtime), ctime(&realtime.tv_sec), poped, ((generated-poped)*640)); fflush(fdR); }
C
/* ** EPITECH PROJECT, 2018 ** lemin ** File description: ** find shortest path */ #include "lemin.h" static void verify_tunnel(l_list_t **list, room_t *data, l_list_t *next) { void *tmp; tmp = initialize_list(data, next); if (!tmp) return; push(list, tmp); data->marked = true; } static void add_other_tunnels(l_list_t **list, l_list_t *cur, l_list_t *sec_cur) { for (sec_cur = sec_cur->next; sec_cur; sec_cur = sec_cur->next) { if (!(((room_t *)sec_cur->data)->marked)) { verify_tunnel(list, sec_cur->data, \ ((l_list_t *)cur->data)->next); } } } static l_list_t *navigate_layer(l_list_t **list) { l_list_t *cur; l_list_t *sec_cur; for (cur = *list; cur; cur = cur->next) { sec_cur = ((room_t *)((l_list_t *)cur->data)->data)->tunnels; if (!sec_cur) continue; for (room_t *r = sec_cur->data; r && r->marked; \ sec_cur = sec_cur->next, r = (room_t *)(sec_cur) ? sec_cur->data : NULL); if (sec_cur) { push((l_list_t **)&(cur->data), mark_room(sec_cur)); add_other_tunnels(list, cur, sec_cur); } } return (check_end(*list)); } static l_list_t *find_first_path(room_t *start, int room_nb) { l_list_t *list = NULL; l_list_t *return_tmp = NULL; void *tmp; tmp = initialize_list(start, NULL); if (tmp == NULL) return (NULL); push(&list, tmp); start->marked = true; for (int i = 0; i < room_nb; i++) { return_tmp = navigate_layer(&list); if (return_tmp != NULL) return (return_tmp); } return (NULL); } l_list_t *bfs(room_t *start, int room_nb, l_list_t *path_list) { if (!path_list) return (find_first_path(start, room_nb)); return (NULL); }
C
#include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> union hospital { char names[10][8],choice,pass,hos_type,name[20],sname[20],stype[20],locat[20],dest[20],member[20]; int limit,age; long int contact,contact_num,count; }; int main() { union hospital hos; int i,n,j,max=1; printf("\t\tCHRIST HOSPITAL MANAGEMENT SYSTEM"); printf("\nEnter the number of patients entered in the emergency room = "); scanf("%d", &n); printf("\nEnter names of %d patients = ",n ); for (i=0; i< n; i++) { scanf("%s", hos.names[i]); } printf("\n\t\tNames\n"); for (i=0; i<n; i++) { printf("\t\t%s\n", hos.names[i]); } printf("\n1. For The Admitting of the Pateints :: \n2. For Medicine Enquiry :: \n"); printf("\nenter your choice = "); scanf("%d",&hos.choice); switch(hos.choice) { case 1 : printf("\nA. For registration of Patient\n"); printf("Press A for filling up of the registration form"); scanf("%c",&hos.pass); hos.pass = getchar(); { switch(hos.pass) { case 'A': printf("Enter the Pateint name : "); scanf("%s",hos.name); printf("Enter the Pateint Contact number : "); scanf("%ld",&hos.contact); printf("\n\n Pateint name %s\n Contact number : %ld",hos.name,hos.contact); } break; } /*default: printf("invalid choice");*/ break; case 2 : printf("\na. CARDIO MEDICINES :: \nb. AYURVEDICE MEDICINES :: \n"); printf("\nEnter your choice = "); scanf("%c",&hos.hos_type); hos.hos_type = getchar(); { switch(hos.hos_type) { case 'a': printf("\nEnter how many patients wants the medicine = "); scanf("%d",&hos.limit); do { printf("\nEnter the Patient name = "); scanf("%s",hos.stype); printf("\nEnter age = "); scanf("%d",&hos.age); printf("\n Patient name = %s\n Age = %d\n\n",hos.stype,hos.age); max++; } while(max<=hos.limit); break; case 'b': printf("\nEnter how many patients wants the medicine = "); scanf("%d",&hos.limit); // printf("\t\t\t%d",hos.limit); int a; char name[30]; a=(hos.limit); while(1<=a) { printf("\n\nEnter the Patient name = "); scanf("%s",hos.stype); strcpy(name,hos.stype); printf("\nEnter age = "); scanf("%d",&hos.age); printf("\n\nPatient name = %s\nAge = %d",name,hos.age); a--; } break; } } break; default : printf("Invalid choice\n" ); break; } getch(); return 1; }
C
#include<stdio.h> #include<string.h> int main (void) { //Declaração de variaveis char texto1[80], texto2[80]; int r, letraT1, letraT2, a; //Completar as strings printf("Texto1: "); scanf("%s", texto1); printf("Texto2: "); scanf("%s", texto2); //Comparar Textos for( r = 0; a == 0; r++) { letraT1 = texto1[r]; letraT2 = texto2[r]; a = letraT1 - letraT2; if(a < 0) { printf("%s vem antes de %s", texto1, texto2); break; }else if(a>0) { printf("%s vem antes de %s", texto2, texto1);break; } } return 0; }
C
#include "../debug/debug.h" #include "cmd.h" #include <errno.h> #include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/statvfs.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> bool do_cmd(cmd *c) { if (!c) DEBUG_PRINT("cmd was null\n"); if (!strcmp(c->argv[0], "blocks")) { do_blocks(c); } else if (!strcmp(c->argv[0], "cd")) { do_cd(c); } else if (!strcmp(c->argv[0], "cat")) { do_cat(c); } else if (!strcmp(c->argv[0], "chmod")) { do_chmod(c); } else if (!strcmp(c->argv[0], "close")) { do_close(c); } else if (!strcmp(c->argv[0], "cp")) { do_cp(c); } else if (!strcmp(c->argv[0], "creat")) { do_creat(c); } else if (!strcmp(c->argv[0], "link")) { do_link(c); } else if (!strcmp(c->argv[0], "ls")) { do_ls(c); } else if (!strcmp(c->argv[0], "lseek")) { do_lseek(c); } else if (!strcmp(c->argv[0], "mkdir")) { do_mkdir(c); } else if (!strcmp(c->argv[0], "mount")) { do_mount(c); } else if (!strcmp(c->argv[0], "mv")) { do_mv(c); } else if (!strcmp(c->argv[0], "open")) { do_open(c); } else if (!strcmp(c->argv[0], "pwd")) { do_pwd(c); } else if (!strcmp(c->argv[0], "read")) { do_read(c); } else if (!strcmp(c->argv[0], "rmdir")) { do_rmdir(c); } else if (!strcmp(c->argv[0], "stat")) { do_stat(c); } else if (!strcmp(c->argv[0], "su")) { do_su(c); } else if (!strcmp(c->argv[0], "symlink")) { do_symlink(c); } else if (!strcmp(c->argv[0], "touch")) { do_touch(c); } else if (!strcmp(c->argv[0], "umount")) { do_umount(c); } else if (!strcmp(c->argv[0], "unlink")) { do_unlink(c); } else if (!strcmp(c->argv[0], "write")) { do_write(c); } else if (!strcmp(c->argv[0], "quit")) { for (int i = 0; i < NUM_MINODES; i++) { if (minode_arr[i].ref_count) { minode_arr[i].ref_count = 1; put_minode(&minode_arr[i]); } } for (int i = 0; i < NUM_MOUNT_ENTRIES; i++) { if (mount_entry_arr[i].fd) _umount(mount_entry_arr[i].mnt_path); } exit(0); } else { printf("command not recognized: %s\n", c->argv[0]); } return 0; } int parse_cmd(char *line, cmd *c) { // split by whitespace into cmd struct int i = 0; char *s = strtok(line, " "); for (; s; i++) { c->argv[i] = s; s = strtok(NULL, " "); } c->argc = i; // NULL terminate argv c->argv[i] = NULL; return i; }
C
#include<stdio.h> #define pi 3.14 int main() { float r,pi,area; printf("Enter the Radius: "); scanf("%f",&r); area=pi*r*r; printf("Area of the circle is %f",area); return 0; } //now run
C
#include "types.h" #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { printf(1,"Freepages at start: %d\n",freepages()); char* buf = malloc(10000000); memset(buf,0,10000000); printf(1,"Freepages after malloc: %d\n",freepages()); dedup(); printf(1,"Freepages after dedup: %d\n",freepages()); memset(buf,1,1000000); printf(1,"Freepages after writing a little: %d\n",freepages()); dedup(); for(int i=0;i<1000000;i++) { if(buf[i]!=1) { printf(1,"Uh-oh! Found some junk in my frunk! at %d, %p: %d!\n", i, &buf[i], buf[i]); exit(); } } for(int i=1000000;i<10000000;i++) { if(buf[i]) { printf(1,"Uh-oh! Found some junk in my trunk! at %d, %p: %d!\n", i, &buf[i], buf[i]); exit(); } } printf(1,"Freepages after dedup: %d\n",freepages()); memset(buf+1000000,1,9000000); printf(1,"Freepages after writing the rest: %d\n",freepages()); dedup(); printf(1,"Freepages after dedup: %d\n",freepages()); exit(); }
C
#include "lua.h" #include "lauxlib.h" #include <stdio.h> #include <stdlib.h> typedef struct { int x; int y; } lua_point; lua_point* lua_point_create(int x, int y) { lua_point* output = NULL; output = malloc(sizeof(lua_point)); if (output) { output->x = x; output->y = y; } return output; } void lua_point_delete(lua_point* p) { free(p); } static int createPoint(lua_State* L) { int x = lua_tointeger(L, 1); int y = lua_tointeger(L, 2); if (x == 0 || y == 0) { return luaL_error(L, "Error creating point, invalid parameters"); } lua_point* p = lua_point_create(x, y); lua_point** output = lua_newuserdata(L, sizeof(lua_point*)); if (output != NULL && p != NULL) { *output = p; luaL_getmetatable(L, "test_luaPoint"); lua_setmetatable(L, -2); printf("Success x=%d y=%d\n", p->x, p->y); return 1; } else { if (p) { lua_point_delete(p); } return luaL_error(L, "Failure allocating memory"); } } static int getPointX(lua_State* L) { lua_point** p = luaL_checkudata(L, 1, "test_luaPoint"); if (p == NULL) { return luaL_error(L, "parameter is not a point"); } lua_pushinteger(L, (*p)->x); return 1; } static int getPointY(lua_State* L) { lua_point** p = luaL_checkudata(L, 1, "test_luaPoint"); if (p == NULL) { return luaL_error(L, "parameter is not a point"); } lua_pushinteger(L, (*p)->y); return 1; } static int pointGC(lua_State* L) { lua_point** p = lua_touserdata(L, 1); lua_point_delete(*p); printf("Garbage Collector called\n"); return 0; } static const struct luaL_Reg pointLib[] = { {"create", createPoint}, {NULL, NULL} }; static const struct luaL_Reg pointFunctions[] = { {"getX", getPointX}, {"getY", getPointY}, {NULL, NULL} }; /* int luaopen_lib_lua_email(lua_State* L) { luaL_newmetatable(L, "test_luaPoint"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, pointGC); lua_settable(L, -3); luaL_setfuncs(L, pointFunctions, 0); luaL_newlib(L, pointLib); return 1; } */
C
#include<stdio.h> #include<conio.h> void main() { int arr1[50],arr2[50],arr3[100],m,n,i,j,k=0; printf("enter the no of elements1:\n"); scanf("%d",&m); printf("enter the elements\n"); for(i=0;i<m;i++) { scanf("%d",&arr1[i]); } printf("enter the no of elements 2:\n"); scanf("%d",&n); printf("enter the elements\n"); for(i=0;i<n;i++) { scanf("%d",&arr2[i]); } i=0; j=0; while(i<m && j<n) { if(arr1[i] < arr2[j]) { arr3[k]=arr1[i]; i++; } else { arr3[k]=arr2[j]; j++; } k++; } if(i>=m) { while(j<n) { arr3[k]=arr2[j]; j++; k++; } } if(j>=n) { while(i<m) { arr3[k]=arr1[i]; i++; j++; } }printf("merged array:\n"); for(i=0;i<m+n;i++) { printf("%d\n",arr3[i]); } getch(); }
C
#include <stdio.h> #include <unistd.h> #include <signal.h> #include <stdlib.h> #include <string.h> void handler(int sig); void handler2(int sig); void handler(int sig) { printf("Caught signal %s\n", strsignal(sig)); signal(sig, SIG_DFL); if (sig == SIGTSTP) signal(SIGCONT, handler); else if (sig == SIGCONT) signal(SIGTSTP, handler); raise(sig); } // void handler2(int sig) { // if (sig == SIGTSTP) signal(SIGCONT, handler); /* if sig is SIGSTP */ // else if (sig == SIGCONT) signal(SIGTSTP, handler); /* if sig is SIGCONT */ // } int main(int argc, char **argv){ printf("Starting the program\n"); signal(SIGTSTP, handler); /* SIGSTP */ signal(SIGINT, handler); /* SIGINT */ signal(SIGCONT, handler); /* SIGCONT */ while(1) { sleep(2); } return 0; }
C
#include "binary_tree.h" int main() { struct node *root_node = NULL; root_node = insert(root_node,5,NULL); root_node = delete_node(root_node,5); root_node = insert(root_node,7,NULL); root_node = insert(root_node,3,NULL); root_node = insert(root_node,6,NULL); root_node = insert(root_node,9,NULL); root_node = insert(root_node,12,NULL); root_node = insert(root_node,1,NULL); print_preorder(root_node); root_node = delete_node(root_node,7); printf("----------------------\n"); //printf("%d\n", lookup(root_node,11)->data); //printf("%d\n", lookup(root_node,12)->data); print_preorder(root_node); destroy_tree(root_node); return 1; }
C
/* ** EPITECH PROJECT, 2019 ** PSU_navy_2018 ** File description: ** fill an empty map with ships thanks to positions */ #include "./../include/navy.h" char **fill_the_map_with_pos(char **map, char **pos) { int i = 0; char **ship = NULL; while (map != NULL && pos[i] != NULL) { ship = my_str_to_word_array(pos[i], ":"); map = place_that_ship(map, ship); ship = free_cleanly_str_tab(ship); i = i + 1; } return (map); }
C
/* * errors.h * * Created on: 3 févr. 2018 * Author: jerome */ #ifndef ERRORS_H_ #define ERRORS_H_ #include "stdio.h" #include <stdlib.h> #define ERROR(file,line,info) ({char s[100]; sprintf(s,"ERROR %s:%d - %s\n",file, line, info); printf(s);;exit(1);}) #define ASSERT(cond,file,line) ({if ( (cond) == false){char s[100]; sprintf(s,"ERROR %s:%d\n",file, line); printf(s);exit(1) ;}}) #endif /* ERRORS_H_ */
C
#define PI 3.14159 float area(float); void main(void) { float radius; printf("Enter Radius Of Sphere"); scanf("%f",&radius); printf("Area Of Sphere Is %2f",area(radius)); } float area(float rad) { return(PI*rad*rad); }
C
#ifndef MATH_H_INCLUDED #define MATH_H_INCLUDED const float PI = 3.14159265359f; inline float degToRad(float deg) { return float((deg * PI) / 180); } inline float radToDeg(float rad) { return float((rad * 180 ) / PI); } inline float lerp(float a, float b, float t) { return a + t * (b - a); } #endif // MATH_H_INCLUDED
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <unistd.h> #include <errno.h> #include <netdb.h> int i = 0; int send_image(int socket, char *imagen) { /** * Esta función se encarga de enviar toda la información de la imagen ingresada por * el usuario por medio del socket. * * Parámetros de entrada: * socket: Es el socket por el cual se va a enviar la imagen. * imagen: Es la ruta de la imagen que se va a enviar. * * Valores de salida: * Retorna un 0 cuando finaliza el programa. * */ FILE *picture; int size, read_size, stat, packet_index; char send_buffer[10240], read_buffer[256]; packet_index = 1; picture = fopen(imagen, "r"); fseek(picture, 0, SEEK_END); size = ftell(picture); fseek(picture, 0, SEEK_SET); write(socket, (void *)&size, sizeof(int)); do { stat = read(socket, &read_buffer, 255); } while (stat < 0); printf("Datos enviados\n"); while (!feof(picture)) { read_size = fread(send_buffer, 1, sizeof(send_buffer) - 1, picture); do { stat = write(socket, send_buffer, read_size); } while (stat < 0); packet_index++; bzero(send_buffer, sizeof(send_buffer)); } char server_response[256]; recv(socket, &server_response, sizeof(server_response), 0); if (strcmp(server_response, "") != 0) { printf("Respuesta del servidor: %s\n", server_response); } else { printf("Respuesta del servidor: Conexión rechazada -> IP no admitida\n"); } return 0; } int main(int argc, char *argv[]) { /** * Está es la función principal del cliente. Se encarga de crear el socket del cliente, * solicitar la ruta de la imagen y hacer de la función para enviar la imagen por el socket. * * Parámetros de entrada: * argv[1]: Recibe la IP del sevidor al cual conectarse. * * Valores de salida: * Retorna un 1 si ocurre algún error a la hora de conectarse al servidor. * Retorna un 0 cuando finaliza el programa. * * */ int socket_desc; struct sockaddr_in server; char *parray; FILE *picture; if (argv[1] == NULL) { printf("IP del servidor no ingresada como parámetro\nFinalizando programa...\n"); exit(0); } while (i == 0) { char imagen[100]; printf("\nIngrese la ruta y nombre de la imagen: "); scanf("%s", imagen); if (strcmp(imagen, "fin") == 0) { break; } picture = fopen(imagen, "r"); if (picture == NULL) { printf("error: No se encontró la imagen ingresada\n\n"); } else { socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (socket_desc == -1) { printf("No se pudo crear el socket"); } memset(&server, 0, sizeof(server)); server.sin_addr.s_addr = inet_addr(argv[1]); server.sin_family = AF_INET; server.sin_port = htons(8585); if (connect(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0) { close(socket_desc); puts("Error conectando con el servidor\n"); return 1; } puts("Conectado con el servidor\n"); send_image(socket_desc, imagen); close(socket_desc); } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* edit_link_sectors.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pitriche <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/24 15:22:57 by pitriche #+# #+# */ /* Updated: 2020/01/28 11:32:29 by ydemange ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nukem.h" static void link_wall(t_sector *cur, t_walls *set, int id) { t_walls *wall; wall = cur->walls; while (wall) { if ((wall->x1 == set->x1 && wall->x2 == set->x2 && wall->y1 == set->y1 && wall->y2 == set->y2) || (wall->x1 == set->x2 && wall->x2 == set->x1 && wall->y1 == set->y2 && wall->y2 == set->y1)) { set->sec_lnk = id + 1; set->is_cross = 1; set->wall_tex = 0; return ; } wall = wall->next; } } static void link_sector(t_sector *root, t_sector *cur, unsigned id) { t_walls *wall; unsigned i; i = 0; while (root) { wall = (i != id ? cur->walls : 0); while (wall) { link_wall(root, wall, i); wall = wall->next; } root = root->next; i++; } } void link_sectors(t_al *al) { t_sector *cur; unsigned id; cur = al->sect; id = 0; while (cur) { link_sector(al->sect, cur, id); cur = cur->next; id++; } }
C
#include <stdio.h> #define len 1000 int stackA[len],stackB[len],stackC[len]; int topA=0,topB=0,topC=0; void Push(int *stack,int val,int *top) { if(*top>=len) printf("STACK OVERFLOW\n"); else { stack[*top]=val; (*top)++; } } int Pop(int *stack, int *top) { if(*top<0) printf("EMPTY STACK! No VALUES LEFT TO POP\n"); else { int x=stack[(*top)]; (*top)--; return x; } } void duplicate_stack(int *stack) { int t=0; printf("Original stack at address %p:\n",&stackA); while(t<topA) printf("%d ",stack[t]),t++; topA=topA-1; while(topA>=0) Push(stackB,Pop(stack,&topA),&topB); topB=topB-1; while(topB>=0) Push(stackC,Pop(stackB,&topB),&topC); t=0; printf("\nDuplicated stack at address %p:\n",&stackC); while(t<topC) printf("%d ",stackC[t]),t++; } int main() { int n,val; printf("Enter number of values you wish to push in stack: "); scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&val); Push(stackA,val,&topA); } duplicate_stack(stackA); return 0; }
C
/* Projet : ELE216 - Laboratoire 1 Date : 21 janvier 2021 Par : Gabriel Gandubert et Hugo Cusson-Bouthillier Logiciel : Sublime text & Eclipse Definition : Encapsulation des criteres de recherche pour la base de donnee de films Contient: Structure des criteres qui permet de separer les types de criteres (commandes) La structure est defini ici, mais le "typedef" est dans le module critere.h. FONCTIONS PUBLIQUES: % Division et comparaison d'une ligne du fichier des titres. h_donnee_titre parse_ligne_titre_et_critere(const char* const ligne, pt_critere const critere); % Division et comparaison d'une ligne du fichier des noms. h_donnee_nom parse_ligne_nom_et_critere( const char* const ligne, pt_critere const critere); % Division et comparaison d'une ligne du fichier des cotes. h_donnee_cote parse_ligne_cote_et_critere( const char* const ligne, pt_critere const critere); FONCTIONS PRIVEEs : % Compare la chaine 1 avec la chaine 2 afin de determiner si la chaine 1 est comprise dans la chaine 2. unsigned int str1_dans_str2(const char* str1, const char* str2); % Compare la chaine 1 avec la chaine 2 afin de determiner si la chaine 2 est unsigned int str2_dans_str1(const char* str1, const char* str2); % Compare l'annee et l'interval afin de determiner si l'annee est comprise dans l'interval donne. unsigned int annee_dans_interval(const char* interval, const char* annee); % Compare la cote et l'interval afin de determiner si la cote est comprise dans l'interval donne. unsigned int cote_dans_interval(const char* interval, const char* cote); */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ // Header file #include "parser.h" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ /* CONSTANTES D'IMPLEMENTATION */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ // Separateur des elements de la base de donne de type TSV (tab separated values). #define TOKEN_TSV ' ' // Constantes specifiques a la base de donnees des titres de films. #define NOMBRE_COLONNE_TITRE 9 #define TITRE_INDEX_COLONNE_TITRE 2 #define TITRE_INDEX_COLONNE_ID 0 #define TITRE_INDEX_COLONNE_ANNEE 5 // Constantes specifiques a la base de donnees des noms d'acteurs. #define NOMBRE_COLONNE_NOM 6 #define NOM_INDEX_COLONNE_ID 0 #define NOM_INDEX_COLONNE_NOM 1 #define NOM_INDEX_COLONNE_TITRES 5 // Constantes specifiques a la base de donnees des cotes des films. #define NOMBRE_COLONNE_COTE 3 #define COTE_INDEX_COLONNE_ID_TITRE 0 #define COTE_INDEX_COLONNE_COTE 1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ /* IMPLLEMENTATION FONCTIONS PUBLIQUES */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ /* * @note HLR17: Parser de la base de donnee des titres de films. */ h_donnee_titre parse_ligne_titre_et_critere( const char* const ligne , pt_critere const critere ){ // Variables de separation de la ligne en donnees h_table_string table_ligne; h_donnee_titre donnees_ligne; // Verification des tableau pour des valeurs non nul. if( !ligne || !critere) return NULL; // Separation de la ligne en colonne et validation de l'operation. if( !( table_ligne = table_string_creer(ligne,TOKEN_TSV) ) || table_string_get_taille(table_ligne) != NOMBRE_COLONNE_TITRE ){ return NULL; } // Extraction des donnees pertinentes de la ligne afin de comparer. if(!( donnees_ligne=donnee_titre_creer( table_string_get_element_n(table_ligne,TITRE_INDEX_COLONNE_ID), table_string_get_element_n(table_ligne,TITRE_INDEX_COLONNE_TITRE), table_string_get_element_n(table_ligne,TITRE_INDEX_COLONNE_ANNEE), ligne ))){ table_string_liberer(table_ligne); free(table_ligne); return NULL; } /* * @note HLR29: Appel des fonctions de comparaison dans parser. */ // Comparaison des donnees de la ligne avec les criteres. if(!comparer_donnee_titre_critere(donnees_ligne,critere)){ table_string_liberer(table_ligne); donnee_titre_liberer(donnees_ligne); return NULL; } // Liberation du tableau de la ligne separee. table_string_liberer(table_ligne); // La comparaison a trouver une ligne respectant les criteres. return donnees_ligne; } //---------------------------------------------------------------------------------------- /* * @note HLR16: Parser de la base de donnee des noms d'acteurs. */ h_donnee_nom parse_ligne_nom_et_critere( const char* const ligne , pt_critere const critere ){ // Variables de separation de la ligne en donnees h_donnee_nom donnees_ligne; h_table_string table_ligne; // Verification des tableau pour des valeurs non nul. if( !ligne || !critere) return NULL; // Separation de la ligne en colonne table_ligne=table_string_creer(ligne,TOKEN_TSV); // Validation de la ligne separee et du nombre de colonnes trouvee. if( !table_ligne || table_string_get_taille(table_ligne)!=NOMBRE_COLONNE_NOM ){ return NULL; } // Extraction des donnees de la ligne necessaire uniquement. donnees_ligne=donnee_nom_creer( table_string_get_element_n(table_ligne,NOM_INDEX_COLONNE_ID), table_string_get_element_n(table_ligne,NOM_INDEX_COLONNE_NOM), table_string_get_element_n(table_ligne,NOM_INDEX_COLONNE_TITRES), ligne ); // Si l'extraction a echouee, echec. if(!donnees_ligne){ table_string_liberer(table_ligne); free(table_ligne); return NULL; } /* * @note HLR29: Appel des fonctions de comparaison dans parser. */ // Comparaison des criteres avec les donnees de la ligne. if(!comparer_donnee_nom_critere(donnees_ligne,critere)){ table_string_liberer(table_ligne); donnee_nom_liberer(donnees_ligne); return NULL; } // Envoyer les donnees valides. return donnees_ligne; } //---------------------------------------------------------------------------------------- /* * @note HLR18: Parser de la base de donnee des cotes de films. */ h_donnee_cote parse_ligne_cote_et_critere( const char* const ligne , pt_critere const critere ){ // Variables de separation de la ligne en donnees h_donnee_cote donnees_ligne; h_table_string table_ligne; // Verification des tableau pour des valeurs non nul. if( !ligne || !critere) return NULL; // Separation de la ligne en colonne table_ligne=table_string_creer(ligne,TOKEN_TSV); // Validation de la ligne separee et du nombre de colonnes trouvee. if( !table_ligne || table_string_get_taille(table_ligne)!=NOMBRE_COLONNE_COTE ){ return NULL; } // Extraction des donnees de la ligne necessaire uniquement. donnees_ligne=donnee_cote_creer( table_string_get_element_n(table_ligne,COTE_INDEX_COLONNE_ID_TITRE), table_string_get_element_n(table_ligne,COTE_INDEX_COLONNE_COTE), ligne ); // Si l'extraction a echouee, echec. if(!donnees_ligne){ table_string_liberer(table_ligne); free(table_ligne); return NULL; } /* * @note HLR29: Appel des fonctions de comparaison dans parser. */ // Comparaison des criteres avec les donnees de la ligne. if(!comparer_donnee_cote_critere(donnees_ligne,critere)){ table_string_liberer(table_ligne); donnee_cote_liberer(donnees_ligne); return NULL; } // Envoyer les donnees valides. return donnees_ligne; } /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
C
#include "holberton.h" #include <stdio.h> /** * puts_half - Entry point * @str: one * Return: Always 0 (Success) */ void puts_half(char *str) { int contador, par, impar; for (contador = 0 ; str[contador] != '\0' ; contador++) { } if (contador % 2 == 0) { for (par = contador / 2 ; par < contador ; par++) _putchar(str[par]); } else { for (impar = ((contador + 1) / 2) ; impar < contador ; impar++) _putchar(str[impar]); } _putchar(10); }
C
#include <stdio.h> #include <stdlib.h> int ans[100005]; typedef struct NODE { int v; struct NODE *next; } Node; Node *e[100005]; Node *end[100005]; void dfs(int x) { Node *now = e[x]; ans[x] = 1; while (now != NULL) { const int v = now->v; if (ans[v] == 0) dfs(v); ans[x] += ans[v]; now = now->next; } } int main() { int n; scanf("%d", &n); int st; for (int i = 1; i < n; i++) { int x, y; scanf("%d %d", &x, &y); if (i == 1) st = x; if (end[x] == NULL) { e[x] = end[x] = calloc(0, sizeof(Node)); } else { end[x]->next = calloc(0, sizeof(Node)); end[x] = end[x]->next; } end[x]->v = y; } dfs(st); for (int i = 1; i <= n; i++) { printf("%d", ans[i] - 1); if (i == n) printf("\n"); else printf(" "); } }
C
#ifndef __TOBIE_IMAGE_H__ #define __TOBIE_IMAGE_H__ /** * timage_comp 与 timage_crop返回的错误号 * 请定义更多错误类型 */ typedef enum { TIAMGE_OK = 0, TIAMGE_UNKNOWN_IMAGE_TYPE } timage_error_code_e; /** * 公用数据结构 * # position * # rectangle * # buffer */ typedef struct { int x; int y; } timage_position_t; typedef struct { int width; int height; } timage_rectangle_t; typedef struct { void *buf; int size; } timage_buffer_t; /** * 图片处理前后存储类型 * 原图和目的图都可以是 * # file * # blob */ typedef enum { TIAMGE_F2F = 0, TIAMGE_F2B, TIMAGE_B2F, TIMAGE_B2B } timage_store_type_e; typedef struct { timage_store_type_e type; union { char *from_path; timage_buffer_t from_buffer; }; union { char *to_path; timage_buffer_t to_buffer; }; } timage_store_t; /** * 缩略请求结构体 */ typedef struct { char *lua; /* 计算脚本 */ timage_store_t store; /* 存储位置 */ timage_rectangle_t rect; /* 缩略大小 */ int xaxis; /* x轴裁剪比例 0~10 */ int yaxis; /* y轴裁剪比例 0~10 */ } timage_comp_req_t; /** * 裁剪请求结构体 */ typedef struct { char *lua; /* 计算脚本 */ timage_store_t store; /* 存储位置 */ timage_position_t position; /* 裁剪位置 */ timage_rectangle_t rect; /* 裁剪大小 */ } timage_crop_req_t; /** * 全局初始化函数,初始化图形库等 * @param data: 自定义参数 * @return 成功返回0 */ typedef int (*timage_init)(void *data); /** * 全局销毁函数 * @param data: 自定义参数 */ typedef void (*timage_destory)(void *data); /** * 图片缩略处理函数 * @param req: 请求参数,req中返回值内存由应用释放 * @param data: 自定义参数 * @return 成功返回0,否则返回错误号 */ typedef int (*timage_comp)(timage_comp_req_t *req, void *data); /** * 图片裁剪处理函数 * @param req: 请求参数,req中返回值内存由应用释放 * @param data: 自定义参数 * @return 成功返回0,否则返回错误号 */ typedef int (*timage_crop)(timage_crop_req_t *req, void *data); /** * 图片处理操作接口结构体 */ typedef struct { timage_init init; timage_destory destory; timage_comp comp; timage_crop crop; } timage_t; #endif
C
#include <glib.h> #include <stdio.h> #include "handle_device.h" #define NB_OF_DEVICES 2 /* The problem to solve is following: You monitor devices, which are sending data to you. Each device have a unique name. Each device produces measurements. Challange is: Compute number of messages you got or read from the devices. The solution can be in any language (preferably C/C++). The scope is open, you must decide how the “devices” will work in your system. The solution should be posted on GitHub or a similar page for a review. Please add Makefile and documentation explaining us how to run your code. */ /** * @brief Static method used as a callback for SIGINT process signal * @param[in] user_data: data passed to the callback method * @return always returns TRUE */ static gboolean measurement_signal_cb(gpointer user_data); /** * @brief Static method used as a callback for SIGINT process signal * @param[in] user_data: data passed to the callback method * @return always returns TRUE */ static gboolean measurement_signal_cb(gpointer user_data) { printf("main(): Shutting down...\n"); g_main_loop_quit((GMainLoop*) user_data); return TRUE; } /** * @brief Main method of the measurement process * @return EXIT_SUCCESS if everything went OK, EXIT_FAILURE otherwise */ int main(void) { int exit_code = EXIT_FAILURE; GMainLoop* loop = NULL; device_types monitored_devices[NB_OF_DEVICES] = {TEMPERATURE, HUMIDITY}; printf("main(): Measurement process started\n"); loop = g_main_loop_new(NULL, FALSE); if (NULL == loop) { printf("main(): Failed to create main loop\n"); } else { if (TRUE == initialize_devices(monitored_devices, sizeof(monitored_devices)/sizeof(monitored_devices[0]))) { guint sigint_source_id = 0; sigint_source_id = g_unix_signal_add(SIGINT, &measurement_signal_cb, loop); /* ctrl+c to finish the running program */ g_main_loop_run(loop); (void)g_source_remove(sigint_source_id); exit_code = EXIT_SUCCESS; } g_main_loop_unref(loop); } if(EXIT_SUCCESS == exit_code) { deinitialize_devices(monitored_devices, sizeof(monitored_devices)/sizeof(monitored_devices[0])); } printf("main(): Measurement process terminated\n"); return exit_code; }
C
/* ** EPITECH PROJECT, 2018 ** my_malloc ** File description: ** show_alloc_mem.c */ #include <unistd.h> #include "my_malloc.h" int print_address_in_hexa(unsigned long long int ptr) { my_putnbr(ptr); return 0; unsigned long nbr2; char nbrc; int size = 0; if ((ptr / 16) != 0) size = print_address_in_hexa(ptr / 16); nbr2 = ptr % 16; if (nbr2 >= 10 && nbr2 <= 15) nbrc = (char)(nbr2 + 55); else nbrc = (char)(nbr2 + '0'); write(1, &nbrc, 1); return (size + 1); } void my_putnbr(long long int nbr) { char tmp; if (nbr < 0) { nbr *= -1; write(1, "-", 1); } if (nbr / 10 != 0) my_putnbr(nbr / 10); tmp = (char)((nbr % 10) + '0'); write(1, &tmp, 1); } void my_putstr(char *str) { for (int i = 0 ; str[i] ; i++) write(1, &str[i], 1); } void show_alloc_mem(void) { t_block tmp = base_list_g; void *breakPoint = sbrk(0); if (!breakPoint) return; my_putstr("break : 0x"); print_address_in_hexa((unsigned long long int)breakPoint); my_putstr("\n"); while (tmp) { my_putstr("0x"); print_address_in_hexa((size_t)tmp + BLOCK_SIZE); my_putstr(" - 0x"); print_address_in_hexa((size_t)tmp + BLOCK_SIZE + tmp->size); my_putstr(" : "); my_putnbr((long long int)tmp->size); if (tmp->free == 0) { my_putstr(" bytes\n"); } else { my_putstr(" freed bytes\n"); } tmp = tmp->next; } }
C
#include"list.h" #include<stdlib.h> #include<stdio.h> List * newList(){ List * list = malloc(sizeof(List)); list->head = NULL; list->tail = NULL; list->index = 0; list->insert = insertList; list->read = readData; list->remove = removeData; list->delete = delete; return list; } void insertList(List * list, int index, Data value){ if(list->index == 0){ Node * currNode = malloc(sizeof(Node)); currNode -> data = value; list -> head = currNode; list -> tail = currNode; list -> head -> prev = NULL; list -> tail -> next = NULL; list -> index = list->index + 1; } else if(list->index <= index){ Node * currNode = malloc(sizeof(Node)); currNode -> data = value; list -> tail -> next = currNode; currNode -> prev = list -> tail; currNode -> next = NULL; list -> tail = currNode; list -> index = list -> index+1; } } void removeData(List * list, int index){ Node * currNode=NULL; int i=0; if(index >= list->index) return; if(list -> index == 0) return; else{ if(list->head == list->tail){ free(list->head); list->head = NULL; list->tail = NULL; return; }else if(index == (list->index - 1)){ currNode = list->tail; list->tail->prev->next = NULL; list->tail = list->tail->prev; list->index = list->index - 1; return; } else if(index == 0) { currNode = list->head; list->head = list->head->next; list->head->prev = NULL; list->index = list->index - 1; return; } else if(index > 0){ currNode = list->head; while(i != index) { currNode = currNode->next; i++; } currNode->next->prev = currNode->prev; currNode->prev->next = currNode->next; list->index = list->index - 1; return; } } free(currNode); currNode = NULL; } Data * readData(List * list, int index){ if(index > list->index) return NULL; else{ Node * currNode = list->head; int i = 0; while(currNode -> next != NULL && i < index ) { currNode -> next -> prev = currNode; currNode = currNode -> next; i++; } return &currNode -> data; } } void * delete(List * list){ free(list -> head); free(list -> tail); free(list); list=NULL; }
C
#include<stdio.h> main() { int num,z; int res=0; printf("enter number "); scanf("%d",&num); int x=num; while (num>0) { z=num%10; res=res+z; num=num/10; } printf("sum of digits of %d is %d\n",x,res); }
C
#include <stdio.h> int main(void) { int dan = 0, num = 1; printf("몇 단? : "); scanf_s("%d", &dan); while (num < 10) { printf("%d X %d = %d\n", dan, num, dan*num); num++; } return 0; } /* while (1) printf("%d X %d = %d \n", dan, num, dan*num); num++; 숫자 1은 '참'을 의미하는 대표적인 값이다. 따라서 이 값이 반복의 조건을 대신하면, 그 결과는 항상 '참'이 되어 빠져나가지 못하는 반복문이 구성된다. 실제로 특정 기능을 완성하기 위해서 break문과 함께 위의 형태로 무한루프를 구성하기도 한다. 즉, 무한루프는 프로그래머의 실수로만 만들어지는 것이 아니라, 필요에 의해서 만들어지기도 한다. */
C
数据结构课程设计——哈夫曼加密解密算法2008年10月13日 14:56课程描述:对于存储在磁盘上的ASCII格式文件(汉字不能识别),根据字符出现的频率作为字符权值,利用Huffman算法进行处理,形成Huffman树,得到Huffman码,利用Huffman码对字符进行加密,已二进制的形式存储到磁盘。 再利用Huffman码对加密后的文件解密。 #include<stdio.h> typedef struct LNode{ /*-------------链表-------------------*/ int data; struct LNode *next; }LNode,*Linklist; typedef struct Character{ /*-------------字符结构体-------------*/ char data; /*--------------字符值----------------*/ int frequency; /*-------------字符出现频率-----------*/ }Character; typedef struct HTNode{ /*-------------哈夫曼接点-------------*/ char data; /*-------------接点值-----------------*/ unsigned int weight; /*--------------权值------------------*/ unsigned int parent,lchild,rchild; }HTNode,*HuffmanTree; Linklist L; /*-------------链表头接点--------------*/ Character T[256]; /*-----存放信息中出现的字符(不含汉字)----*/ HuffmanTree HT; /*--------------存放哈夫曼接点--------------*/ char *HC[257],*HA[256]; /*------HC中紧密存放哈夫曼编码,HA中按字符值位置存放该字符的编码,如A存放于HA中第65号元---*/ int len=0; /*-------------信息中出现的字符数量-----------*/ int s1,s2; int i,j; char ch; char Infile[10],Outfile[10],decfile[10]; /*------分别为源信息文件,加密后的2进制文件(解密源文件),解密后的文件------*/ FILE *fp,*fin,*fout; void Create_L(int n) /*------对有n接点建一条带头接点的链表(头插法)-----*/ { int i; Linklist p,k; L=(Linklist)malloc(sizeof(LNode)); k=L; for(i=1;i<=n;i++) { p=(Linklist)malloc(sizeof(LNode)); p->next=NULL; p->data=i; k->next=p;k=p; } } void Init() /*-------初始化,统计Infile中的字符数目len及每个字符出现的频率------*/ { /*-------将这len个字符存于T[0]到T[len-1]中,然后按频率值将这len个字符按升序排列------*/ void QuickSort(Character A[],int p,int r); printf("Input the Infilename:\n"); scanf("%s",Infile); if((fp=fopen(Infile,"r"))==NULL) { printf("Cannot open Infile!\n"); exit(0); } for(i=0;i<256;i++) { T[i].data=i; T[i].frequency=0; } while(!feof(fp)) { ch=fgetc(fp); T[ch].frequency++; } for(i=0,j=0;i<256;i++) { while(!T[i].frequency&&i<256) T[i++].data=0; if(i<256) T[j++]=T[i]; } len=j; Create_L(len); QuickSort(T,0,len-1); fclose(fp); } void QuickSort(Character A[],int p,int r) /*--------冒泡法对A数组元素按频率升序排列---------*/ { Character t; for(i=p;i<r;i++) for(j=p;j<r-i;j++) if(A[j].frequency>A[j+1].frequency) { t=A[j]; A[j]=A[j+1]; A[j+1]=t; } } void Select() /*------------取出链表的前两个权值最小的元素,将新增元素按升序规则插于链表-------*/ { Linklist p,q; int w,t; p=L->next; s1=p->data; q=p->next; s2=q->data; w=HT[s1].weight+HT[s2].weight; q->data=i; L->next=q; free(p); while(q->next) { if(w>HT[q->next->data].weight) { t=q->data;q->data=q->next->data;q->next->data=t;} q=q->next; } } void HuffmanCoding(int n) /*-------对n种字符进行编码存于*HA[257]中---------*/ { int m,c,f,start; int lencd; HuffmanTree p; char *cd; if(n<=1) return; m=2*n-1; HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode)); for(p=HT+1,i=1;i<=n;++i,++p) { p->data=T[i-1].data; p->weight=T[i-1].frequency; p->parent=0; p->lchild=0; p->rchild=0; } for(;i<=m;++i,++p) { p->data=0; p->weight=0; p->parent=0; p->lchild=0; p->rchild=0; } for(i=n+1;i<=m;++i) { Select(); HT[s1].parent=i; HT[s2].parent=i; HT[i].lchild=s1; HT[i].rchild=s2; HT[i].weight=HT[s1].weight+HT[s2].weight; } cd=(char *)malloc(n*sizeof(char)); for(start=0;start<n;start++) cd[i]='\0'; for(i=1;i<=n;++i) { start=0; for(c=i,f=HT[i].parent;f!=0;f=HT[f].parent,c=HT[c].parent) { if(HT[f].lchild==c) cd[start++]='0'; else cd[start++]='1'; } lencd=start; HC[i]=(char *)malloc((lencd+1)*sizeof(char)); ch=HT[i].data; HA[ch]=(char *)malloc((lencd+1)*sizeof(char)); for(start=lencd-1,j=0;start>=0;start--) { HC[i][j]=cd[start]; j++; } HC[i][j]='\0'; strcpy(HA[ch],HC[i]); } free(cd); } void Encrytion() /*-------按HA中的编码把Infile文件中的每一个字符翻译成2进制文件存于outfile文件中----*/ { printf("Input the outfilename:\n"); scanf("%s",Outfile); if((fout=fopen(Outfile,"a"))==NULL) { printf("Cannot open outfile!\n"); exit(0); } if((fin=fopen(Infile,"r"))==NULL) { printf("Cannot open Infile in the Encrytion!\n"); exit(0); } while(!feof(fin)) { ch=fgetc(fin); fputs(HA[ch],fout); } fclose(fin); fclose(fout); } void Decryption() /*--------对存于outfile文件中的密文解码,从哈夫曼树的根接点按0,1分别选择左右子树, 直到叶子接点,输出叶子接点值-----*/ { int m=2*len-1; if((fin=fopen(Outfile,"r"))==NULL) { printf("Cannot open sourcefile!\n"); exit(0); } printf("Input the decfile!\n"); scanf("%s",decfile); if((fout=fopen(decfile,"a"))==NULL) { printf("Cannot open decfile!\n"); exit(0); } while(!feof(fin)) { i=m; while(HT[i].lchild&&HT[i].rchild) { ch=fgetc(fin); if(ch=='0') i=HT[i].lchild; else if(ch=='1') i=HT[i].rchild; else { printf("END!\n"); exit(0); } } printf("%c",HT[i].data); fprintf(fout,"%c",HT[i].data); } fclose(fin); fclose(fout); } /*----------------主函数----------------------*/ void main() { void Init(); /*---------------声明部分-------------------*/ void HuffmanCoding(int n); void Encrytion(); void Decryption(); Init(); /*--------------初始化函数------------------*/ HuffmanCoding(len); /*--------------编码函数--------------------*/ Encrytion(); /*--------------加密函数--------------------*/ Decryption(); /*--------------解密函数--------------------*/ }
C
#define NATIVE_MODULE "$math" #include <math.h> #include "ext_math.h" #include "list.h" module_t ext_math_module = {false, NULL, false, NULL}; static bool check_one_vector(cList *l1, Int *len_ret) { Int i,len; len=list_length(l1); for (i=0; i<len; i++) { if (list_elem(l1,i)->type != FLOAT) { cthrow(type_id, "Arguments must be lists of floats."); return false; } } *len_ret=len; return true; } static bool check_vectors(cList *l1, cList *l2, Int *len_ret) { Int i,len; len=list_length(l1); if (list_length(l2)!=len) { cthrow(range_id, "Arguments are not of the same length."); return false; } for (i=0; i<len; i++) { if (list_elem(l1,i)->type != FLOAT) { cthrow(type_id, "Arguments must be lists of floats."); return false; } if (list_elem(l2,i)->type != FLOAT) { cthrow(type_id, "Arguments must be lists of floats."); return false; } } *len_ret=len; return false; } NATIVE_METHOD(minor) { Int i,len; cList *l,*l1,*l2; INIT_2_ARGS(LIST,LIST); l1=LIST1; l2=LIST2; if (!check_vectors (l1,l2,&len)) RETURN_FALSE; l=list_new(len); l->len=len; for (i=0; i<len; i++) { Float p,q; p=list_elem(l1,i)->u.fval; q=list_elem(l2,i)->u.fval; list_elem(l,i)->type=FLOAT; list_elem(l,i)->u.fval=p<q ? p : q; } CLEAN_RETURN_LIST(l); } NATIVE_METHOD(major) { Int i,len; cList *l,*l1,*l2; INIT_2_ARGS(LIST,LIST); l1=LIST1; l2=LIST2; if (!check_vectors (l1,l2,&len)) RETURN_FALSE; l=list_new(len); l->len=len; for (i=0; i<len; i++) { Float p,q; p=list_elem(l1,i)->u.fval; q=list_elem(l2,i)->u.fval; list_elem(l,i)->type=FLOAT; list_elem(l,i)->u.fval=p>q ? p : q; } CLEAN_RETURN_LIST(l); } NATIVE_METHOD(add) { Int i,len; cList *l,*l1,*l2; INIT_2_ARGS(LIST,LIST); l1=LIST1; l2=LIST2; if (!check_vectors (l1,l2,&len)) RETURN_FALSE; l=list_new(len); l->len=len; for (i=0; i<len; i++) { Float p,q; p=list_elem(l1,i)->u.fval; q=list_elem(l2,i)->u.fval; list_elem(l,i)->type=FLOAT; list_elem(l,i)->u.fval=p+q; } CLEAN_RETURN_LIST(l); } NATIVE_METHOD(sub) { Int i,len; cList *l,*l1,*l2; INIT_2_ARGS(LIST,LIST); l1=LIST1; l2=LIST2; if (!check_vectors (l1,l2,&len)) RETURN_FALSE; l=list_new(len); l->len=len; for (i=0; i<len; i++) { Float p,q; p=list_elem(l1,i)->u.fval; q=list_elem(l2,i)->u.fval; list_elem(l,i)->type=FLOAT; list_elem(l,i)->u.fval=p-q; } CLEAN_RETURN_LIST(l); } NATIVE_METHOD(dot) { Int i,len; cList *l1,*l2; Float s; INIT_2_ARGS(LIST,LIST); l1=LIST1; l2=LIST2; if (!check_vectors (l1,l2,&len)) RETURN_FALSE; for (s=0.0,i=0; i<len; i++) { Float p,q; p=list_elem(l1,i)->u.fval; q=list_elem(l2,i)->u.fval; s+=p*q; } CLEAN_RETURN_FLOAT(s); } NATIVE_METHOD(distance) { Int i,len; cList *l1,*l2; Float s; INIT_2_ARGS(LIST,LIST); l1=LIST1; l2=LIST2; if (!check_vectors (l1,l2,&len)) RETURN_FALSE; for (s=0.0,i=0; i<len; i++) { Float p,q,d; p=list_elem(l1,i)->u.fval; q=list_elem(l2,i)->u.fval; d=p-q; s+=d*d; } CLEAN_RETURN_FLOAT(sqrt(s)); } NATIVE_METHOD(cross) { Int len; cList *l,*l1,*l2; cData *f,*f1,*f2; INIT_2_ARGS(LIST,LIST); l1=LIST1; l2=LIST2; if (!check_vectors (l1,l2,&len)) RETURN_FALSE; if (len!=3) THROW((range_id,"The vectors are not of length 3.")); l=list_new(len); l->len=len; f=list_elem(l,0); f1=list_elem(l1,0); f2=list_elem(l2,0); f[0].type=f[1].type=f[2].type=FLOAT; f[0].u.fval=f1[1].u.fval*f2[2].u.fval-f1[2].u.fval*f2[1].u.fval; f[1].u.fval=f1[2].u.fval*f2[0].u.fval-f1[0].u.fval*f2[2].u.fval; f[2].u.fval=f1[0].u.fval*f2[1].u.fval-f1[1].u.fval*f2[0].u.fval; CLEAN_RETURN_LIST(l); } NATIVE_METHOD(scale) { Int i,len; cList *l,*l1; Float f; INIT_2_ARGS(FLOAT,LIST); l1=LIST2; f=FLOAT1; if (!check_one_vector (l1,&len)) RETURN_FALSE; l=list_new(len); l->len=len; for (i=0; i<len; i++) { Float p; p=list_elem(l1,i)->u.fval; list_elem(l,i)->type=FLOAT; list_elem(l,i)->u.fval=p*f; } CLEAN_RETURN_LIST(l); } NATIVE_METHOD(is_lower) { Int i,len; cList *l1,*l2; INIT_2_ARGS(LIST,LIST); l1=LIST1; l2=LIST2; if (!check_vectors (l1,l2,&len)) RETURN_FALSE; for (i=0; i<len; i++) { Float p,q; p=list_elem(l1,i)->u.fval; q=list_elem(l2,i)->u.fval; if (p>=q) { CLEAN_RETURN_INTEGER(0); } } CLEAN_RETURN_INTEGER(1); } NATIVE_METHOD(transpose) { Int i,len,len1; cList *l,*l1; cData *e,*o; INIT_1_ARG(LIST); l1=LIST1; len=list_length(l1); if (!len) { l1=list_dup(l1); CLEAN_RETURN_LIST(l1); } e=list_elem(l1,0); for (i=0; i<len; i++) { if (e[i].type!=LIST) THROW((type_id,"The argument must be a list of lists.")); } len1=list_length(e[0].u.list); if (!len1) { l1=list_dup(e[0].u.list); CLEAN_RETURN_LIST(l1); } for (i=1; i<len; i++) { if (list_length(e[i].u.list)!=len1) THROW((range_id,"All sublists must be of the same length")); } l=list_new(len1); l->len=len1; o=list_elem(l,0); for (i=0; i<len1; i++) { cList *l2; cData *k; Int j; l2=list_new(len); l2->len=len; o[i].type=LIST; o[i].u.list=l2; k=list_elem(l2,0); for (j=0; j<len; j++) data_dup(&k[j],list_elem(e[j].u.list,i)); } CLEAN_RETURN_LIST(l); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> #include <fcntl.h> #include <sys/stat.h> #define BUF_SIZE 1000 #define MAX_CLT 256 void* ThreadMain(void* args); void* HandleTCPClient(int clt_sock); void error_handling(char* message); void Recv_IMG(int sock); void update_db(char* msg,int clt_sock); int clt_cnt =0; int clt_socks[MAX_CLT]; pthread_mutex_t mutx; int main(int argc, char *argv[]) { struct sockaddr_in ser_addr,clt_addr; int clt_addr_len; pthread_t t_id,f_id; if(argc!=2) { printf("Usage : %s <port>\n", argv[0]); exit(1); } //socket create pthread_mutex_init(&mutx, NULL); int ser_sock = socket(PF_INET, SOCK_STREAM, 0); if(ser_sock == -1) error_handling("socket() error"); memset(&ser_addr, 0, sizeof(ser_addr)); ser_addr.sin_family = AF_INET; ser_addr.sin_addr.s_addr=htonl(INADDR_ANY); ser_addr.sin_port = htons(atoi(argv[1])); //IP, PORT bind if(bind(ser_sock, (struct sockaddr*) &ser_addr, sizeof(ser_addr))==-1) error_handling("bind() error"); //listen if(listen(ser_sock,5) ==-1) error_handling("listen() error"); //accept printf("\nServer Waiting.........\n\n"); while(1) { int clt_addr_len = sizeof(clt_addr); int clt_sock= accept(ser_sock, (struct sockaddr*)&clt_addr, &clt_addr_len); if(clt_sock == -1) error_handling("accept() error"); else { printf("--------------\n"); puts("Connect!"); } pthread_mutex_lock(&mutx); clt_socks[clt_cnt++] = clt_sock; pthread_mutex_unlock(&mutx); pthread_create(&t_id, NULL, ThreadMain, (void*)&clt_sock); pthread_detach(t_id); printf("How Many Client? %d\n",clt_cnt); printf("--------------\n"); } close(ser_sock); return 0; } void* ThreadMain(void* args) { int clt_sock = *((int*)args); int i; HandleTCPClient(clt_sock); pthread_mutex_lock(&mutx); for(i=0; i<clt_cnt;i++) { if(clt_sock == clt_socks[i]) { while(i++<clt_cnt-1) clt_socks[i] = clt_socks[i+1]; break; } } clt_cnt--; pthread_mutex_unlock(&mutx); printf("--------------\n"); puts("Disonnect!"); printf("How Many Client? %d\n",clt_cnt); printf("--------------\n\n"); close(clt_sock); return NULL; } void* HandleTCPClient(int clt_sock) { int i; int str_len=0; char msg[BUF_SIZE]; while((str_len = read(clt_sock,msg,sizeof(msg)))!=0) { pthread_mutex_lock(&mutx); for(i=0; i<clt_cnt; i++) write(clt_socks[i],msg,str_len); update_db(msg,clt_sock); pthread_mutex_unlock(&mutx); } } void update_db(char* msg,int clt_sock) { char* data = msg; int sock =clt_sock; switch(data[0]) { case 69 : printf("\n-------------------------------------\n"); printf("Send Message to Android : CCTV ON DB Update : status\n"); printf("-------------------------------------\n\n\n"); break; case 70 : printf("\n-------------------------------------\n"); printf("Send Message to Android : CCTV OFF DB Update : status\n"); printf("-------------------------------------\n\n\n"); break; case 71 : printf("\n-------------------------------------\n"); printf("Recieved a Picture DB Update : picture\n"); Recv_IMG(sock); printf("-------------------------------------\n\n\n"); break; case 72 : printf("\n-------------------------------------\n"); printf("Send Message to Android : MESSAGE PLAY DB Update : status\n"); printf("-------------------------------------\n\n\n"); break; default : break; } } void Recv_IMG(int socket) { char filename[20]; int filesize =0; int total=0,recv_len; int fp; char buf[BUF_SIZE]; int sock = socket; int temp; bzero(filename,20); recv(sock, filename,sizeof(filename),0); printf("filename : %s ",filename); read(sock, &filesize,sizeof(filesize)); printf("filesize : %d \n",filesize); fp = open(filename,O_RDWR|O_CREAT|O_TRUNC); while(1) { memset(buf,0x00,BUF_SIZE); recv_len= recv(sock, buf, BUF_SIZE,0); write(fp,buf,recv_len); temp =total; total+=recv_len; if(total >=filesize) { printf("finish file\n"); break; } } printf("file translating is completed\n"); close(fp); } void error_handling(char *message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
C
#include "holberton.h" /** * append_text_to_file - Appends text_content to an existing file. * @filename: Name of the file. * @text_content: The content to be written to the file. * Return: 1 if success. -1 if non-existent file or filename, couldn't open or * write the contents to the file. */ int append_text_to_file(const char *filename, char *text_content) { /* create a file descriptor and a buffer */ int fd = 0; size_t buffersize = 0; /* check if exist a text */ if (filename == NULL) return (-1); /* open the text with conditions */ fd = open(filename, O_WRONLY | O_APPEND); /* check if the fd get the text */ if (fd == -1) return (-1); /* check if exists a content in the text */ if (text_content != NULL) { /* save the chars of text in the buffer */ while (text_content[buffersize] != '\0') buffersize++; /* check if write not fail */ if (write(fd, text_content, buffersize) == -1) return (-1); } /* close the text */ close(fd); return (1); }
C
#include <stdio.h> int main(void) { int number = 0b110010; printf("Number in decimal: %d\n", number); printf("Number in hex: %x\n", number); printf("Number in octal: %o\n", number); return 0; }
C
//getch et putc pour cacher le mot de passe #include<stdio.h> #include<string.h> #include<time.h> #include<stdlib.h> #define F fflush(stdin); const char nomCat[]= "CATEGORIES"; const char nomProd[] = "PRODUCTS"; const char nomSupp[] = "change"; const char nomUser[] = "USERS"; int id_auto = 0; int id_cat = 0; int id_vente = 0; // MES STRUCTURES typedef struct { int s, mn, h, j, m, a; }DATE; typedef struct { char libelle[25]; int idCat; //UNIQUE }CATEGORIE; typedef struct { char cat[25], nom[15], code[7]; DATE d; int prix; int qte; //qui se met jour chaque vente; }ARTICLE; typedef struct { int id; char etat[6], nom[10], prenom[20], tel[10], login[6], mdp[15], statut[7]; }USER; typedef struct { int idVente; DATE heureVente; //numro de vente est sous le format : AAAAMMDDHHmmSS. SPRINTF ARTICLE articleVente; int montantVente; char nomV[15], prenomV[20], telV[10], loginV[6], num[15]/*num numero vente*/; }VENTE; typedef struct { int nbrV, montV; }ETAT; // MES MODULES void afficherMenuUser(); //AFFICHAGE DU MENU DE L'UTILISATEUR void afficherMenuAdmin(); //AFFICHAGE DU MENU DE L'ADMIN void menuConnexion(char nom[], FILE *f, char nomfP[], FILE *fP, char nomfC[], FILE *fC, char nomfS[], FILE *fS, FILE *f5, FILE *f6);//C'EST LA QUE TOUT SE PASSSE C'EST LUNIQUE MODULE APPELE DANS LE MAIN() void modifUser(char nom[], FILE *f); //C'EST UN MENU QUI PROPOSE L'AJOUT ET LE BLOCAGE D'UTILISATEUR MAIS AUSSI LE DEBLOCAGE FILE* blockUser(char [],char nomf[], FILE *f); // BLOCAGE D'UTILISATEUR FILE* unblockUser(char [], char nomf[], FILE *f); // DEBLOCAGE D'UTILISATEUR void listeUser(char nom[],FILE*); // LISTE DES UTILISATEURS ET ADMINS FILE* addUser(char nom[]); // AJOUT D'UTILISATEURS int idUser(char nom[], FILE*); //CE MODULE PERMET DE COMPTER LE NOMBRE DUTILISATEUR DANS LE FICHIER USERS ET RETOURNE LE NOMBRE DUTILISATEURS TOTAL, //AINSI LE PROCHAIN UTILISATEUR AJOUTE AURA L'ID DU NOMBRE TOTAL D'UTILISATEURS + 1, ON EN A BESOIN POUR EVITER LA REDONDANCE D'ID FILE* passer123(char [], char[], FILE*); //ON LUI PASSE LE LOGIN DE L'UTILISATEUR CONNECTE SI LUTILISATEUR A POUR MOT DE PASSE CELA SIGNIFIE QUE C'EST SA PREMIERE CONNEXION //DONC ON LUI FAIT CHANGER SON MOT DE PASSE ET LE SAUVEGARDE DANS LE FICHIER USERS USER saveInfosUser(char login[], char nom[], FILE *f); int searchLogin(char nom[], char nomf[], FILE *f); void modifProd(char nom[], FILE *f, char nomf2[], FILE *f2, char nomf3[], FILE *f3); //C'EST UN MENU QUI PROPOSE L'AJOUT, LA SUPPRESSION ET LA MODIFICATION DE STOCK DE PRODUIT FILE* modifStock(char code[], char nom[], FILE*); //MODULE QUI PERMET DE CHANGER LA QUANTITE EN STOCK DU PRODUIT ON PASSE PAR LE CODE DU PRODUIT FILE* supProd(char code[], char nomf[], FILE *f, char nomf2[], FILE *f2); // MODULE QUI SUPPRIME LE PRODUIT ON LUI PASSE LE CODE FILE* addProd(char nom[], int N, char nomCat[], FILE *f2); //AJOUT DE PRODUIT int searchProd(char nom[], char nomf[], FILE *f); //RECHERCHE DE PRODUITS PAR LE CODE void listeProd(char nom[], FILE*); //LISTE DE PRODUIT FILE* addCat(char nom[], int N); // AJOUT DE CATEGORIE void listeCat(char nom[],FILE*); //LISTE DE CATEGORIES int searchCat(char nom[], char nomf[], FILE *f); //RECHERCHE DU LIBELLE DE LA CATEGORIE DANS LE FICHIER CATEGORIES int verifnumber(char[]); //VERIFICATION DU NUMERO DE TELEPHONE DATE hora(); // MODULE RECUPERANT LA DATE ACTUELLE int idCat(char nom[],FILE*); //CE MODULE PERMET DE COMPTER LE NOMBRE DE CATEGORIES DANS LE FICHIER CATEGORIES ET RETOURNE LE NOMBRE TOTAL DE CATEGORIES, AINSI LA PROCHAINE //CATEGORIE AJOUTEE AURA L'ID DU NOMBRE TOTAL DE CATEGORIES + 1, ON EN A BESOIN POUR EVITER LA REDONDANCE D'ID int saisiePositive(char[]); FILE* vente(USER, char nom[], FILE*, FILE *f2, FILE *f3); //ARTICLE/RECU/ETAT FILE* vente(USER, char nom[], FILE*, FILE *f2, FILE *f3); //ARTICLE/RECU/ETAT FILE* addArticle(FILE *f, char nom[], char code[], char cat[], char nomV[], int prix, int qte, int monV); //RECU FILE* addTotal(FILE *f, char nom[], int monT); //RECU FILE* addEtat(FILE *f, char nom[], int monT, int nbrV); //ETAT TODAY main() { FILE *f, *f2, *f3, *f4, *f5, *f6; menuConnexion(nomUser, f, nomProd, f2, nomCat, f3, nomSupp, f4, f5, f6); } void menuConnexion(char nom[], FILE *f, char nomfP[], FILE *fP, char nomfC[], FILE *fC, char nomfS[], FILE *fS, FILE *f5, FILE *f6)// TU ENTRES TON LOGIN ET TON MOT DE PASSE SILS CORRESPONDENT A UN ENREGISTREMENT DANS LE FICHIER USERS, ON AFFICHE LE MENU ADMIN //SI CEST UN ADMIN EN LUI PASSANT LES INFOS DE LADMIN CONNECTE, OU ALORS LE MENU DE LUTILISATEUR SI CEST UN USER NON BLOQUE EN LUI PASSANT LES INFOS //DE LUSER { f = fopen(nom,"rb"); USER u; char login[6], mdp[15], choix; int cpt,i; F //MENU DE CONNEXION printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t============================BIENVENUE CHER USER !===================================\n"); printf("\t\t\t\t\t====================================================================================\n"); puts(""); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t============================ENTRER LE LOGIN SVP :===================================\n"); printf("\t\t\t\t\t====================================================================================\n"); gets(login);puts(""); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t============================ENTRER LE MOT DE PASSE :================================\n"); printf("\t\t\t\t\t====================================================================================\n"); gets(mdp);puts(""); if(strcmp("passer123", mdp)!=0) //PASSER123 NA PAS ETE CRYPTE { for(i=0;i<strlen(mdp);i++) { if(mdp[i]!='/0') { mdp[i]+=45; } } } system("PAUSE"); system("CLS"); if(f) { rewind(f); while(fread(&u, sizeof(u), 1, f) != 0) //ON PARCOURT LE FICHIER DUTILISATEUR ET ON REGARDE SI LE LOGIN ET LE MOT DE PASSE CORRESPONDENT A UN ENREGISTREMENT DANS LE FICHIER { if(strcmp(u.login, login) == 0 && strcmp(u.mdp, mdp) == 0) // TEST DE VALIDITE DU MOT DE PASSE ET LOGIN { if(strcmp(u.etat,"user")==0 && strcmp(u.statut,"bloque")!=0) //MDP ET LOGIN VALIDES ON REGARDE SI CEST UN USER NON BLOQUE OU SI CEST UN ADMIN { printf("\n\t\t\t\t\t\t\t\t AUTHENTIFICATION REUSSIE !\n"); passer123(login, nom, f); // TEST DE LA PREMIERE CONNEXION SI LE MOT DE PASSE EST EGAL A PASSER123 ON LE MODIFIE COMEBABY: printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t===========================BIENVENUE CHER %s!====================================\n",u.login); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================1-EFFECTUER UNE VENTE=====================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================2-LISTE DES ARTICLES======================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t=================================3-QUITTER==========================================\n"); printf("\t\t\t\t\t====================================================================================\n"); do{ F printf("FAITES VOTRES CHOIX SVP : \n"); scanf("%c",&choix);puts(""); if(choix!='1' && choix !='2' && choix!='3') { printf("\n\t\t\t\t\tCHOIX INDISPONIBLE !\n"); } }while(choix!='1' && choix !='2' && choix!='3'); system("CLS"); switch(choix) { case '1': vente(saveInfosUser(login,nom,f),nomfP,fP,f5,f6); system("PAUSE"); system("CLS"); goto COMEBABY; break; case '2': listeProd(nomfP,fP); system("PAUSE"); system("CLS"); goto COMEBABY; break; case '3': break; } cpt = 1; } if(strcmp(u.etat,"admin")==0) { printf("\n\t\t\t\t\t\t\t\t AUTHENTIFICATION REUSSIE !\n"); HERE : printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t===========================BIENVENUE CHER %s!====================================\n",u.login); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================1-LISTE DES UTILISATEURS==================================\n"); printf("\t\t\t\t\t==========================2-MODIFICATION D'UTILISATEUR==============================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================3-LISTE DES PRODUITS======================================\n"); printf("\t\t\t\t\t==========================4-MODIFICATION DE PRODUIT=================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================5-LISTE DES CATEGORIES====================================\n"); printf("\t\t\t\t\t==========================6-AJOUT DE CATEGORIE======================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================7-EFFECTUER UNE VENTE=====================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t================================8-QUITTER===========================================\n"); printf("\t\t\t\t\t====================================================================================\n"); do{ F printf("FAITES VOTRES CHOIX SVP : \n"); scanf("%c",&choix); if(choix!='1' && choix !='2' && choix!='3' && choix!='4' && choix !='5' && choix!='6' && choix!='7' && choix !='8') { printf("\n\t\t\t\t\tCHOIX INDISPONIBLE !\n"); } }while(choix!='1' && choix !='2' && choix!='3' && choix!='4' && choix !='5' && choix!='6' && choix!='7' && choix !='8'); system("CLS"); switch(choix) { case '1': listeUser(nom, f); system("PAUSE"); system("CLS"); goto HERE; break; case '2': modifUser(nom, f); system("PAUSE"); system("CLS"); goto HERE; break; case '3': listeProd(nomfP,fP); system("PAUSE"); system("CLS"); goto HERE; break; case '4': modifProd(nomfP, fP, nomfC, fC, nomfS, fS); system("PAUSE"); system("CLS"); goto HERE; break; case '5': listeCat(nomfC, fC); system("PAUSE"); system("CLS"); goto HERE; break; case '6': addCat(nomfC,saisiePositive("CATEGORIES")); system("PAUSE"); system("CLS"); goto HERE; break; case '7': vente(saveInfosUser(login,nom,f),nomfP,fP,f5,f6); system("PAUSE"); system("CLS"); goto HERE; break; case '8': break; } cpt = 1; break; } } else { cpt = 0; } } fclose(f); } if(cpt==0) { printf("\n\t\t\t\t\t\t\t\tUTILISATEUR INEXISTANT!\n"); } } // switch(choix) // { // case '1': // vente(); // break; //// case '2': //// etaToday(); //// break; // case '3': // break; // } void modifUser(char nom[], FILE *f) { char choix, login[6]; COMEHERE: printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t============================BIENVENUE CHER ADMIN !==================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================1-AJOUT D'UTILISATEUR=====================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================2-BLOCAGE D'UTILISATEUR===================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================3-DEBLOCAGE D'UTILISATEUR=================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t=================================4-QUITTER==========================================\n"); printf("\t\t\t\t\t====================================================================================\n"); do{ F printf("FAITES VOTRES CHOIX SVP : \n"); scanf("%c",&choix);puts("");puts(""); if(choix!='1' && choix !='2' && choix !='3' && choix !='4') { printf("\n\t\t\t\t\tCHOIX INDISPONIBLE !\n"); } }while(choix!='1' && choix !='2' && choix!='3' && choix !='4'); switch(choix) { case '1': addUser(nom); system("PAUSE"); system("CLS"); goto COMEHERE; break; case '2': printf("Entrer le login de l'utilisateur a bloquer : \n"); scanf("%s",&login); blockUser(login, nom, f); system("PAUSE"); system("CLS"); goto COMEHERE; break; case '3': printf("Entrer le login de l'utilisateur a debloquer : \n"); scanf("%s",&login); unblockUser(login, nom, f); system("PAUSE"); system("CLS"); goto COMEHERE; break; case '4': break; } } void modifProd(char nom[], FILE *f, char nomf2[], FILE *f2, char nomf3[], FILE *f3) { char choix , code[7]; IWANTUHERE: printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t============================BIENVENUE CHER ADMIN !==================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================1-AJOUT DE PRODUIT(S)=====================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================2-MISE A JOUR DE STOCK(S)=================================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t==========================3-SUPPRESSION DE PRODUIT(S)===============================\n"); printf("\t\t\t\t\t====================================================================================\n"); printf("\t\t\t\t\t=================================4-QUITTER==========================================\n"); printf("\t\t\t\t\t====================================================================================\n"); do{ F printf("FAITES VOTRES CHOIX SVP : \n"); scanf("%c",&choix);puts(""); if(choix!='1' && choix !='2' && choix!='3' && choix != '4') { printf("\n\t\t\t\t\tCHOIX INDISPONIBLE !\n"); } }while(choix!='1' && choix !='2' && choix!='3'&& choix != '4'); switch(choix) { case '1': addProd(nom, saisiePositive("PRODUITS"), nomf2, f2); system("PAUSE"); system("CLS"); goto IWANTUHERE; break; case '2': printf("ENTRER LE CODE DU PRODUIT DONT LA QUANTITE EN STOCK EST A MODIFIER : \n"); scanf("%s",&code); modifStock(code, nom, f); system("PAUSE"); system("CLS"); goto IWANTUHERE; break; case '3': printf("ENTRER LE CODE DU PRODUIT A SUPPRIMER : \n"); scanf("%s",&code); supProd(code, nom, f, nomf3, f3); system("PAUSE"); system("CLS"); goto IWANTUHERE; break; case '4': break; } } FILE* addCat(char nomf2[], int N) // AJOUT DE CATEGORIE { FILE *f = fopen(nomf2, "a"); CATEGORIE cat; F int i, id_cat = idCat(nomf2,f); //RECUPERATION DU NOMBRE TOTAL DE CATEGORIES CONTENUES DANS LE FICHIER printf("\t\t\t\t\t==========================1-AJOUT DE CATEGORIE======================================\n"); printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); if(f) { for(i=0; i<N; i++) // { printf("CATEGORIE %d------------------------------------------------------------------------------------------------------------------------------------------------------------\n",i+1); do{ printf("Entrer le libelle de la categorie : \n"); gets(cat.libelle);puts(""); strupr(cat.libelle); if(searchCat(cat.libelle,nomf2,f)==1) { printf("\n\t\t\t\t\t\tLIBELLE DEJA EXISTANT ! \n"); } else { cat.idCat = ++id_cat; fwrite(&cat, sizeof(cat), 1, f); } }while(searchCat(cat.libelle,nomf2,f)==1); } fclose(f); } return f; } void listeCat(char nomf2[], FILE *f) //LISTE DE CATEGORIES { f = fopen(nomf2, "rb"); CATEGORIE cat; printf("\t\t\t\t\t==========================5-LISTE DES CATEGORIES====================================\n"); if(f) { while(fread(&cat, sizeof(cat), 1, f) != 0) { printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("ID : %d\n",cat.idCat); printf("Libelle : %s\n",cat.libelle); } fclose(f); } } int idCat(char nomf2[], FILE *f) //OUVERTURE DU FICHIER BINAIRE EN MODE LECTURE, PUIS DECOMPTE ET RETOUR DU NOMBRE DE CATEGORIE { f = fopen(nomf2,"rb"); CATEGORIE cat; int cpt=0; if(f) { while(fread(&cat, sizeof(cat), 1, f) != 0) { cpt++; } fclose(f); } return cpt; } int verifnumber(char tel[]) //VERIFICATION DU NUMERO DE TELEPHONE SI LE CPT=0 NUMERO INVALIDE SINON VALIDE, { int cpt=1, i; if(strlen(tel)!=9) { cpt=0; }else{ if((tel[0]!='7' || (tel[1]!='0' && tel[1]!='6' && tel[1]!='7' && tel[1]!='8'))) //TEST DES 2 PREMIERS CHIFFRES { cpt=0; } else { for(i=2; i<strlen(tel); i++) { if(tel[i]!='9' && tel[i]!='8' && tel[i]!='7' && tel[i]!='6' && tel[i]!='5' && tel[i]!='4' && tel[i]!='3' && tel[i]!='2' && tel[i]!='1' && tel[i]!='0') { cpt=0; //TEST DES 7 DERNIERS CHIFFRES } } } } return cpt; } DATE hora() //RECUPERATION DE LA DATE ET L'HEURE { DATE h; time_t now; time(&now); struct tm *local = localtime(&now); h.j = local ->tm_mday; h.m = local ->tm_mon+1; h.a = local->tm_year+1900; h.h = local->tm_hour; h.mn = local->tm_min; h.s = local->tm_sec; return h; } int saisiePositive(char msg[]) //RECOIT UN MESSAGE ET RETOURNE UN NOMBRE POSITIF { int N; do{ printf("COMBIEN DE %s VOULEZ-VOUS SAISIR ? \n", msg); scanf("%d",&N); }while(N<=0); return N; } int searchCat(char nom[], char nomf[], FILE *f) //VERIFIE SI LE LIBELLE PASSE EN PARAMETRES EST CONTENU DANS LE FICHIER DE CATEGORIES SI OUI CPT=1 { f = fopen(nomf, "rb"); int cpt=0; CATEGORIE cat; if(f) { while(fread(&cat, sizeof(cat), 1, f) != 0) { if(strcmp(nom,cat.libelle)==0) { cpt=1; break; } } fclose(f); } return cpt; } int searchProd(char nom[], char nomf[], FILE *f)//VERIFIE SI LE CODE PASSE EN PARAMETRES EST CONTENU DANS LE FICHIER D'ARTICLE SI OUI CPT=1 { f = fopen(nomf, "rb"); int cpt=0; ARTICLE a; if(f) { while(fread(&a, sizeof(a), 1, f) != 0) { if(strcmp(nom,a.code)==0) { cpt=1; break; } } fclose(f); } return cpt; } int searchLogin(char nom[], char nomf[], FILE *f) //VERIFIE SI LE LOGIN PASSE EN PARAMETRES EST CONTENU DANS LE FICHIER DE USERS SI OUI CPT=1 { f = fopen(nomf, "rb"); int cpt=0; USER u; if(f) { while(fread(&u, sizeof(u), 1, f) != 0) { if(strcmp(nom,u.login)==0) { cpt=1; break; } } fclose(f); } return cpt; } void listeProd(char nom[], FILE *f) //PARCOURS DU FICHERS DARTICLES ET AFFICHAGE DES DONNEES DES ARTICLES { f = fopen(nom,"rb"); ARTICLE a; printf("\t\t\t\t\t==========================3-LISTE DES PRODUITS======================================\n"); if(f) { while(fread(&a, sizeof(a), 1, f) != 0) { printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("Libelle : %s\n",a.nom); printf("Code : %s\n",a.code); printf("Categorie : %s\n",a.cat); printf("Prix : %d FCFA\n",a.prix); printf("Quantite en stock : %d\n",a.qte); printf("Ajoute le %d-%d-%4d a %d:%d:%d\n",a.d.j,a.d.m,a.d.a,a.d.h,a.d.mn,a.d.s); } fclose(f); } } FILE* addProd(char nom[], int N, char nomf2[], FILE *f2)//DANS CE MODULE ON DOIT AJOUTER UN PRODUIT, DABORD ON ENTRE LA CATEGORIE DE LARTICLE SEULEMENT //SI ELLE EXISTE PEUT ON AJOUTER LE PRODUIT ENSUITE ON VERIFIE SI LE CODE ENTRE NEST PAS DEJA EXISTANT SIL NE LEST PAS ON CONTINUE LAJOUT { FILE *f = fopen(nom,"ab"); f2 = fopen(nomf2,"rb"); ARTICLE a; CATEGORIE cat; int i; printf("\t\t\t\t\t==========================1-AJOUT DE PRODUIT======================================\n"); printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); if(f) { for(i=0; i<N; i++) { printf("ARTICLE %d--------------------------------------------------------------------------------------------------------------------------------------------------------------\n",i+1); do{ F printf("Entrer la categorie de l'article : \n"); gets(a.cat);puts(""); strupr(a.cat); if(searchCat(a.cat,nomf2,f2)!=1) { printf("\n\t\t\t\t\t\t\t\t\tCATEGORIE INEXISTANTE !\n"); } }while(searchCat(a.cat,nomf2,f2)!=1); do{ do{ printf("Entrer le code de l'article (7 caracteres): \n"); gets(a.code);puts(""); }while(strlen(a.code)!=7); if(searchProd(a.code,nom,f)==1) { printf("\n\t\t\t\t\t\t\t\t\tCODE DEJA EXISTANT ! \n"); } }while(searchProd(a.code,nom,f)==1); printf("Entrer le libelle de l'article : \n"); gets(a.nom);puts(""); do{ printf("Entrer le prix de l'article : \n"); scanf("%d",&a.prix);puts(""); }while(a.prix<=0); do{ printf("Entrer la quantite en stock de l'article : \n"); scanf("%d",&a.qte);puts(""); }while(a.qte<=0); a.d = hora(); fwrite(&a, sizeof(a), 1, f); } fclose(f); } return f; } FILE* modifStock(char code[], char nom[], FILE *f) //N OUVRE LE FICHIER EM MODE LECTURE ECRITURE, SI LE CODE ENTRE NEST PAS CONTENU DANS LE FICHIER DE PRODUITS ON AFFICHE CODE INEXISTANT, //SINON ON ENTRE LA NEW QUANTITE DU PRODUIT //ON REECRIT LA NOUVELLE QUANTITE DANS LE FICHIER ET ENSUITE ON FAIT UN BREAK POUR QUITTER UNE FOIS LA MODIFICATION FAITE { f = fopen(nom,"rb+"); ARTICLE a; int qte; F printf("\t\t\t\t\t==========================2-MISE A JOUR DE STOCK(S)=================================\n"); printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); if(f) { if(searchProd(code,nom,f)!=1) { printf("\n\t\t\t\t\t\t\t\tCODE INEXISTANT ! \n"); } else { do{ F printf("Entrer la nouvelle quantite : \n"); scanf("%d",&qte);puts(""); }while(qte<0); rewind(f); while(fread(&a, sizeof(a), 1, f) != 0) { if(strcmp(a.code, code) == 0) { a.qte = qte; fseek(f, -sizeof(a), 1); fwrite(&a, sizeof(a), 1, f); break; } } printf("\n\t\t\t\t\t\t\t\t MODIFICATION REUSSIE !\n"); } fclose(f); } return f; } FILE* supProd(char code[], char nomf[], FILE *f, char nomf2[], FILE *f2) // ICI ON VA UTILISER DEUX FICHIERS,LE PREMIER EST CELUI //DES PRODUITS LAUTRE UN FICHIER VIDE, SI LE CODE ENTRE EST TROUVE DANS LE FICHIER DE PRODUITS ON COPIE TOUS LES ENREGISTREMENTS DONT //LES CODES SONT DIFFERENTS DE CELUI ENTRE, ON SUPPRIME LE FICHIER DE PRODUITS PUIS ON RENOMME LE DEUXIEME FICHIER, SINON ON AFFICHE //ARTICLE INEXISTANT { f = fopen(nomf, "rb"), f2 = fopen(nomf2, "wb"); ARTICLE a; if(f) { if(f2) { if(searchProd(code,nomf,f)==1) { rewind(f); while(fread(&a, sizeof(a), 1, f) != 0) { if(strcmp(code,a.code)!=0) { fwrite(&a, sizeof(a), 1, f2); } } printf("\n\t\t\t\t\t\t\t\t SUPPRESSION REUSSIE !\n"); } else{ printf("\n\t\t\t\t\t\t\t\t ARTICLE INEXISTANT !\n"); } fclose(f2); } fclose(f); } remove(nomf); rename(nomf2,nomf); return f; } FILE* addUser(char nom[])//ON VERIFIE DABORD SI LE LOGIN NEST PAS DEJA EXISTANT SIL NE LEST PAS ON AJOUTE LUTILISATEUR OU LADMIN, SI CEST UN ADMIN IL MET SON MOT // DE PASSE MAIS SI CEST UN USER IL A POUR MOT DE PASSE passer123 { FILE *f = fopen(nom,"ab"); USER u; char rep[3]; int cpt, k; printf("\t\t\t\t\t==========================1-AJOUT D'UTILISATEUR=====================================\n"); printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); if(f) { do{ F printf("Voulez-vous ajouter un utilisateur ou un administrateur ? \n"); printf("Tapez 'user' pour utilisateur ou 'admin' pour administrateur. \n"); gets(u.etat); strlwr(u.etat);puts(""); }while(strcmp(u.etat,"user")!=0 && strcmp(u.etat,"admin")!=0); do{ do{ printf("Entrer le login : \n"); gets(u.login); puts(""); strupr(u.login); }while(strlen(u.login)!=5); if(searchLogin(u.login,nom,f)==1) { printf("\n\t\t\t\t\t\t\t\tLOGIN DEJA EXISTANT \n"); } }while(searchLogin(u.login,nom,f)==1); printf("Entrer le nom : \n"); gets(u.nom);puts(""); printf("Entrer le(s) prenom(s) : \n"); gets(u.prenom);puts(""); do{ printf("Entrer le numero de telephone: \n"); gets(u.tel);puts(""); }while(verifnumber(u.tel)!=1); strcpy(u.statut,"actif"); if(strcmp(u.etat,"user")==0) { strcpy(u.mdp,"passer123"); } else { if(strcmp(u.etat,"admin")==0) { printf("Entrer le mot de passe : \n"); gets(u.mdp);puts(""); for(k=0; k<strlen(u.mdp); k++) //CRYPTAGE DU MOT DE PASSE { if(u.mdp[k] != '\0') { u.mdp[k]+=45; } } } } // u.id = ++id_auto; u.id = idUser(nom,f)+1; fwrite(&u, sizeof(u), 1, f); printf("\n\t\t\t\t\t\t\t\t ENREGISTREMENT EFFECTUE !\n"); fclose(f); } return f; } void listeUser(char nom[],FILE *f) { f = fopen(nom,"rb"); USER u; int k; printf("\t\t\t\t\t==========================1-LISTE DES UTILISATEURS==================================\n"); if(f) { while(fread(&u, sizeof(u), 1, f)!= 0) { { printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("ID : %d\n",u.id); printf("Statut : %s\n",u.etat); printf("Nom : %s\n",u.nom); printf("Prenom(s) : %s\n",u.prenom); printf("Telephone : %s\n",u.tel); printf("Login : %s\n",u.login); for(k=0; k<strlen(u.mdp); k++) { if(u.mdp[k] != '\0') { u.mdp[k]-=45; //DECRYPTAGE DU MOT DE PASSE } } printf("Mot de passe : %s\n",u.mdp); printf("Etat : %s\n",u.statut); } } fclose(f); } } int idUser(char nom[], FILE *f) //OUVERTURE DU FICHIER BINAIRE EN MODE LECTURE, PUIS DECOMPTE ET RETOUR DU NOMBRE D'UTILISATEUR { f = fopen(nom,"rb"); USER u; int cpt=0; if(f) { while(fread(&u, sizeof(u), 1, f) != 0) { cpt++; } fclose(f); } return cpt; } FILE* blockUser(char login[],char nomf[], FILE *f) //ON OUVRE LE FICHIER EM MODE LECTURE ECRITURE ON CHERCHE LE LOGIN DANS LE FICHIER, SI ON LE TROUVE LE LOGIN ET QUE CE NEST PAS UN ADMIN //ON MET LE STATUT DE LUTILISATEUR A BLOQUE ET ON REECRIT LENREGISTREMENT DANS LE FICHIER ET ENSUITE ON FAIT UN BREAK POUR QUITTER UNE //FOIS LA MODIFICATION FAITE, SI ON NE TROUVE PAS LE LOGIN DANS LE FICHIER OU SI CEST UN ADMIN LE COMPTEUR EST A 0, ET A LA SORTIE DU PARCOURS DU FICHIER //ON LUI AFFICHE QUE LUTILISATEUR EST INEXISTANT SI cpt=0 OU SI cpt=1 LE BLOCAGE A ETE UN SUCCES. { f = fopen(nomf,"rb+"); USER u; F printf("\t\t\t\t\t==========================2-BLOCAGE D'UTILISATEUR(S)================================\n"); printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); if(f) { if(searchLogin(login, nomf, f)==1) { rewind(f); while(fread(&u, sizeof(u), 1, f) !=0) { if(strcmp(u.login, login) == 0 && strcmp(u.etat,"user")==0) { strcpy(u.statut,"bloque"); fseek(f, -sizeof(u), 1); fwrite(&u, sizeof(u), 1, f); break; } } printf("\n\t\t\t\t\t\t\t\tUtilisateur bloque avec succes ! \n"); } else { printf("\n\t\t\t\t\t\t\t\tUtilisateur non existant ! \n"); } fclose(f); } return f; } FILE* unblockUser(char login[],char nomf[], FILE *f) //ON OUVRE LE FICHIER EM MODE LECTURE ECRITURE ON CHERCHE LE LOGIN DANS LE FICHIER, SI ON LE TROUVE ET QUE CE NEST PAS UN ADMIN //LE COMPTEUR EST A 1 ON MET LE STATUT DE LUTILISATEUR A DEBLOQUE ET ON REECRIT LENREGISTREMENT DANS LE FICHIER ET ENSUITE ON FAIT UN BREAK POUR QUITTER UNE //FOIS LA MODIFICATION FAITE, SI ON NE TROUVE PAS LE LOGIN DANS LE FICHIER OU SI CEST UN ADMIN LE COMPTEUR EST A 0, ET A LA SORTIE DU PARCOURS DU FICHIER //ON LUI AFFICHE QUE LUTILISATEUR EST INEXISTANT SI cpt=0 OU SI cpt=1 LE DEBLOCAGE A ETE UN SUCCES. { f = fopen(nomf,"rb+"); USER u; F printf("\t\t\t\t\t==========================3-BLOCAGE D'UTILISATEUR(S)================================\n"); printf("------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); if(f) { if(searchLogin(login, nomf, f)==1) { rewind(f); while(fread(&u, sizeof(u), 1, f) !=0) { if(strcmp(u.login, login) == 0 && strcmp(u.etat,"user")==0) { strcpy(u.statut,"actif"); fseek(f, -sizeof(u), 1); fwrite(&u, sizeof(u), 1, f); break; } } printf("\n\t\t\t\t\t\t\t\tUtilisateur debloque avec succes ! \n"); } else { printf("\n\t\t\t\t\t\t\t\tUtilisateur non existant ! \n"); } fclose(f); } return f; } FILE* passer123(char login[], char nom[], FILE *f) //SI CEST LA PREMIERE CONNEXION DE LUTILISATEUR IL DOIT CHANGER SON MOT DE PASSE { f = fopen(nom,"rb+"); USER u; int k; char mdp[15]; if(f) { rewind(f); while(fread(&u, sizeof(u), 1, f) != 0) { if(strcmp(login,u.login)==0) { if(strcmp(u.mdp, "passer123") == 0) { printf("CHER %s, VEUILLEZ ENTRER VOTRE NOUVEAU MOT DE PASSE : \n",u.login); gets(mdp); for(k=0; k<strlen(mdp); k++) //CRYPTAGE DU MOT DE PASSE { if(mdp[k] != '\0') { mdp[k]+=45; } } strcpy(u.mdp,mdp); fseek(f, -sizeof(u), SEEK_CUR); //REECRIT LE NEW PASSWORD DANS LE FICHIER fwrite(&u, sizeof(u), 1, f); printf("\n\t\t\t\t\t\t\t\t MODIFICATION DU MOT DE PASSE REUSSIE !\n"); break; } } } fclose(f); } return f; } USER saveInfosUser(char login[], char nom[], FILE *f) //RECHERCHES LES INFORMATIONS DE LUSER DONT LE LOGIN EST PASSE EN PARAMETRES { USER user, u; f = fopen(nom,"rb"); if(f) { rewind(f); while(fread(&u,sizeof(u),1,f) != 0) { if(strcmp(u.login, login) == 0){ user = u; break; } } fclose(f); } return user; } FILE* vente(USER u, char nom[], FILE *f, FILE *f2, FILE *f3) { FILE *f4; VENTE v; ARTICLE a; int cpt, qte, nbrV=-1, monV=0, nbrArt=0; //SI LE NBR DE VENTE EST EGAL A 0 ALORS ON OUVRE LE FICHIER RECU EN ECRITURE SI NBV>0 ON LOUVRE EN MODE AJOUT char rep[3], rep2[3], nomfich[100], saveNomfich[100], code[7], etat[100]; f = fopen(nom, "rb+"); if(f) { do{ do{ F printf("Souhaitez-vous effectuer une vente ?\n"); gets(rep);puts(""); strlwr(rep); if(strcmp(rep,"oui")!=0 && strcmp(rep,"non")!=0) { printf("\nVEUILLEZ REPONDRE PAR 'OUI' OU 'NON' ! \n"); } }while(strcmp(rep,"oui")!=0 && strcmp(rep,"non")!=0); if(strcmp(rep,"oui")==0) { printf("ENTRER LE CODE DU PRODUIT :\n"); gets(code);puts(""); rewind(f); while(fread(&a, sizeof(a), 1, f) != 0) { if(strcmp(a.code,code)==0) { cpt = 1; do{ printf("ENTRER LA QUANTITE A ACHETER : \n"); scanf("%d",&qte); }while(qte<=0); if(a.qte == 0) //LA QUANTITE DE LARTICLE EST EGALE A ZERO { printf("\t\t\t\t\t\t\t\t\tSTOCK EPUISE !\n"); } else { if(qte>a.qte) //LA DEMANDE SUPERIEURE A LOFFRE { do{ F printf("\nVoulez-vous prendre la quantite en stock restante : %d ? \n",a.qte); gets(rep2);puts(""); strlwr(rep2); if(strcmp(rep2,"oui")!=0 && strcmp(rep2,"non")!=0) { printf("\nVEUILLEZ REPONDRE PAR 'OUI' ou 'NON' ! \n"); } }while(strcmp(rep2,"oui")!=0 && strcmp(rep2,"non")!=0); if(strcmp(rep2,"oui")==0) { printf("\t\t\t\t\t\t\t\t\tACHAT VALIDE ! \n"); nbrV++; strcpy(v.loginV,u.login); strcpy(v.nomV,u.nom); strcpy(v.prenomV,u.prenom); strcpy(v.telV,u.tel); strcpy(v.articleVente.cat,a.cat); strcpy(v.articleVente.code,code); strcpy(v.articleVente.nom,a.nom); v.articleVente.prix = a.prix; v.articleVente.qte = a.qte; v.heureVente = hora(); v.montantVente = v.articleVente.prix * v.articleVente.qte; monV += v.montantVente; nbrArt += v.articleVente.qte; a.qte = 0; fseek(f, -sizeof(a), 1); fwrite(&a, sizeof(a), 1, f); if(nbrV==0) //PREMIERE VENTE { v.idVente = ++id_vente; sprintf(v.num, "%d%d%d%d%d%d", v.heureVente.j, v.heureVente.m, v.heureVente.a, v.heureVente.h, v.heureVente.mn, v.heureVente.s); sprintf(nomfich,"C:\\Users\\compaq\\Desktop\\COURS ISI\\LANGAGE C\\MON EXAM\\BILLS\\%s_%s_%d_%s.txt","RECU",v.num,v.idVente,v.loginV); sprintf(etat,"C:\\Users\\compaq\\Desktop\\COURS ISI\\LANGAGE C\\MON EXAM\\BILLS\\ETAT\\%s_%d%d%d.txt","ETAT_", v.heureVente.a, v.heureVente.m, v.heureVente.j); f2=fopen(nomfich,"w"); if(f2) { fprintf(f2,"%d--------------------%s\n", v.idVente, v.num); fprintf(f2,"%s %s 00221%s\n", v.prenomV,v.nomV,v.telV); fprintf(f2,"%s le %d/%d/%d a %d:%d:%d\n", v.loginV,v.heureVente.j, v.heureVente.m, v.heureVente.a, v.heureVente.h, v.heureVente.mn, v.heureVente.s); fprintf(f2,"---------%s---------\n","LISTE DES ACHATS"); fprintf(f2,"%s--------%s\n", v.articleVente.code, v.articleVente.cat); fprintf(f2,"-%s\n", v.articleVente.nom); fprintf(f2," %d FCFA * %d = %dFCFA\n", v.articleVente.prix ,v.articleVente.qte,v.montantVente); fprintf(f2,"%s","----------------------------------\n"); fclose(f2); } // } else { if(nbrV>0) //PLUS DUNE VENTE { addArticle(f3,nomfich,v.articleVente.code, v.articleVente.cat,v.articleVente.nom,v.articleVente.prix ,v.articleVente.qte,v.montantVente); } } } else { break; } } else //LA QUANTITE DEMANDEE EST DISPO { printf("\t\t\t\t\t\t\t\t\tACHAT VALIDE ! \n"); nbrV++; strcpy(v.loginV,u.login); strcpy(v.nomV,u.nom); strcpy(v.prenomV,u.prenom); strcpy(v.telV,u.tel); strcpy(v.articleVente.cat,a.cat); strcpy(v.articleVente.code,code); strcpy(v.articleVente.nom,a.nom); v.articleVente.prix = a.prix; v.articleVente.qte = qte; v.heureVente = hora(); v.montantVente = v.articleVente.prix * v.articleVente.qte; monV += v.montantVente; nbrArt += v.articleVente.qte; a.qte = a.qte - qte; fseek(f, -sizeof(a), 1); fwrite(&a, sizeof(a), 1, f); if(nbrV==0) //PREMIERE VENTE { v.idVente = ++id_vente; sprintf(v.num, "%d%d%d%d%d%d", v.heureVente.j, v.heureVente.m, v.heureVente.a, v.heureVente.h, v.heureVente.mn, v.heureVente.s); sprintf(nomfich,"C:\\Users\\compaq\\Desktop\\COURS ISI\\LANGAGE C\\MON EXAM\\BILLS\\%s_%s_%d_%s.txt","RECU",v.num,v.idVente,v.loginV); sprintf(etat,"C:\\Users\\compaq\\Desktop\\COURS ISI\\LANGAGE C\\MON EXAM\\BILLS\\ETAT\\%s_%d%d%d.txt","ETAT_", v.heureVente.a, v.heureVente.m, v.heureVente.j); f2=fopen(nomfich,"w"); if(f2) { fprintf(f2,"%d--------------------%s\n", v.idVente, v.num); fprintf(f2,"%s %s 00221%s\n", v.prenomV,v.nomV,v.telV); fprintf(f2,"%s le %d/%d/%d a %d:%d:%d\n", v.loginV,v.heureVente.j, v.heureVente.m, v.heureVente.a, v.heureVente.h, v.heureVente.mn, v.heureVente.s); fprintf(f2,"---------%s---------\n","LISTE DES ACHATS"); fprintf(f2,"%s--------%s\n", v.articleVente.code, v.articleVente.cat); fprintf(f2,"-%s\n", v.articleVente.nom); fprintf(f2," %d FCFA * %d = %d FCFA\n", v.articleVente.prix ,v.articleVente.qte,v.montantVente); fprintf(f2,"%s","----------------------------------\n"); fclose(f2); } } else { if(nbrV>0) //PLUS DUNE VENTE { addArticle(f3,nomfich,v.articleVente.code, v.articleVente.cat,v.articleVente.nom,v.articleVente.prix ,v.articleVente.qte,v.montantVente); } } } } break; } else { cpt = 0; } } if(cpt==0) { printf("\t\t\t\t\t\t\t\t\tCODE INEXISTANT !\n"); } } else { addTotal(f3,nomfich,monV); addEtat(f4,etat,monV,nbrArt); break; } }while(1); fclose(f); } return f; } FILE* addArticle(FILE *f, char nom[], char code[], char cat[], char nomV[], int prix, int qte, int monV) { f = fopen(nom, "a"); if(f) { fprintf(f,"%s--------%s\n", code, cat); fprintf(f,"-%s\n",nomV); fprintf(f," %d FCFA * %d = %d FCFA\n", prix ,qte,monV); fprintf(f,"%s","----------------------------------\n"); fclose(f); } return f; } FILE* addTotal(FILE *f, char nom[], int monT) { f = fopen(nom, "a"); if(f) { fprintf(f,"\tTOTAL : %d FCFA\n", monT); fprintf(f,"%s","----------------------------------\n"); fclose(f); } return f; } FILE* addEtat(FILE *f, char nom[], int monT, int nbrV) { ETAT e; f = fopen(nom, "a"); e.montV = monT; e.nbrV = nbrV; if(f) { fprintf(f,"%d articles ---> %d FCFA\n", e.nbrV, e.montV); fclose(f); } return f; } //void afficheEtat(FILE *f, char nom[]) //{ // ETAT e; // f = fopen(nom,"r"); // int m=0, n=0; // while(!feof(f)) // { // fscanf(f,"%d articles ---> %d FCFA", e.nbrV, e.montV); // m+= e.nbrV; // n+= e.montV; // } // printf("%d %dFCFA",n,m); //}
C
/* ** t_listString_remove.c for lib in /home/flavian.gontier/projects/libmy/src/list/t_listString ** ** Made by flavian gontier ** Login <[email protected]> ** ** Started on Fri Jan 27 01:22:50 2017 flavian gontier ** Last update Sun Apr 09 13:49:01 2017 flavian gontier */ #include "libmy.h" static void shift_elements(t_listString *list, int start_index) { int index; int limit; index = start_index; limit = (int)(list->count - 1); while (index < limit) { list->elements[index] = list->elements[index + 1]; index = index + 1; } } int listString_removeIndex(t_listString *list, size_t index) { if (index >= list->count) return (EXIT_ERROR); free(list->elements[index]); shift_elements(list, index); list->count -= 1; return (EXIT_SUCCESS); } /* ** remove the first element encountered from the beginning */ int listString_remove(t_listString *list, const char *elem) { int index; if (list == NULL || elem == NULL || list->count == 0) return (EXIT_ERROR); index = listString_contains(list, elem); if (index == -1) return (EXIT_ERROR); listString_removeIndex(list, index); return (EXIT_SUCCESS); }
C
/* ** EPITECH PROJECT, 2020 ** CPE_dante_2019 ** File description: ** prism_generator */ #include <stdlib.h> #include <stdio.h> #include <stddef.h> #include "dante.h" #include "my.h" int is_cell_visited(list_t *wall, char **maze, int x, int y) { int x_visited = 0; int y_visited = 0; if (x != wall->width_maze - 1) x_visited += (maze[y][x + 1] == 'n') ? 1 : 0; if (y != wall->height_maze - 1) y_visited += (maze[y + 1][x] == 'n') ? 1 : 0; if (y != 0 && y_visited == 0) y_visited += (maze[y - 1][x] == 'n') ? 1 : 0; if (x != 0 && x_visited == 0) x_visited += (maze[y][x - 1] == 'n') ? 1 : 0; if (x_visited == 1 || y_visited == 1) return (1); return (0); } int get_x_cell(char **maze, list_t *wall, chain_t *pickup_wall, int *x) { if (pickup_wall->x_cell != 0) { if (maze[pickup_wall->y_cell][pickup_wall->x_cell - 1] == 'n') { *x = pickup_wall->x_cell - 1; return (1); } } if (pickup_wall->x_cell != wall->width_maze - 1) { if (maze[pickup_wall->y_cell][pickup_wall->x_cell + 1] == 'n') { *x = pickup_wall->x_cell + 1; return (1); } } *x = pickup_wall->x_cell; return (0); } int get_y_cell(char **maze, list_t *wall, chain_t *pickup_wall, int *y) { if (pickup_wall->y_cell != 0) { if (maze[pickup_wall->y_cell - 1][pickup_wall->x_cell] == 'n') { *y = pickup_wall->y_cell - 1; return (1); } } if (pickup_wall->y_cell != wall->height_maze - 1) { if (maze[pickup_wall->y_cell + 1][pickup_wall->x_cell] == 'n') { *y = pickup_wall->y_cell + 1; return (1); } } *y = pickup_wall->y_cell; return (0); } int prism_loop(list_t *wall, char **maze) { chain_t *pickup_wall = NULL; int x_cell = 0; int y_cell = 0; set_wall_from_cell(wall, maze, x_cell, y_cell); while (wall->length != 0) { pickup_wall = get_random_wall(wall); if (is_cell_visited(wall, maze, pickup_wall->x_cell, pickup_wall->y_cell)) { get_x_cell(maze, wall, pickup_wall, &x_cell); get_y_cell(maze, wall, pickup_wall, &y_cell); maze[pickup_wall->y_cell][pickup_wall->x_cell] = '*'; set_wall_from_cell(wall, maze, x_cell, y_cell); } remove_wall(wall, pickup_wall->id, pickup_wall); } return (0); } int prism_generator(char **maze, int perfect, int width, int height) { list_t wall; wall.length = 0; wall.width_maze = width; wall.height_maze = height; wall.head = NULL; prism_loop(&wall, maze); if (perfect == 0) make_imperfect(maze, width, height); return (0); }
C
#include <pthread.h> #include <sys/types.h> #include <stddef.h> #include <syscalls.h> /* For printf. REMOVE WHEN ALL IMPLEMENTED */ #include <stdio.h> #define UNIMPL printf(__func__) int pthread_attr_init(pthread_attr_t* attr) { attr->detachstate=PTHREAD_CREATE_JOINABLE; attr->scope = PTHREAD_SCOPE_SYSTEM; return 0; } int pthread_attr_destroy(pthread_attr_t* attr) { return 0; } int pthread_attr_setscope(pthread_attr_t* attr, int scope) { switch (scope) { case PTHREAD_SCOPE_SYSTEM: attr->scope = scope; return 0; case PTHREAD_SCOPE_PROCESS: return ENOTIMPL; /* Find out if we can support this? */ default: return EINVAL; } } int pthread_attr_getstack(const pthread_attr_t* attr,void** stackAddr,size_t* stackSize) { if (pthread_self() == 0) { *stackSize = 2*1024*1024; *(unsigned long**)stackAddr = (unsigned long*)(0xC0000000-*stackSize); }else SysExit(0); return 0; } int pthread_attr_setdetachstate(pthread_attr_t* attr, int detachstate) { /* TODO: Check. */ attr->detachstate = detachstate; return 0; } int pthread_attr_getdetachstate( const pthread_attr_t* attr, int* detachstate) { *detachstate = attr->detachstate; return 0; } int pthread_attr_getschedparam(const pthread_attr_t* attr, struct sched_param *param) { UNIMPL; return 0; } int pthread_attr_setschedparam(const pthread_attr_t* attr, struct sched_param *param) { UNIMPL; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "ArrayList.h" #include "NameCard.h" int main() { List list; NameCard* pcard; // NameCard 구조체 형으로 포인터pcard을 선언한다. ListInit(&list); // list를 초기화 셋팅한다. pcard = MakeNameCard("이진수", "010-1111-2222"); // pcard 구조체에 MakeNameCard함수로 이름과 전화번호를 저장하였다 LInsert(&list, pcard); // list에 값이 들어있는구조체 주소를 넘겨준다 pcard = MakeNameCard("한지영", "010-2222-5555"); LInsert(&list, pcard); pcard = MakeNameCard("이진수", "010-3333-7777"); LInsert(&list, pcard); // 한지영의 정보를 조회하여 출력 if (LFirst(&list, &pcard)) { // 값의 구조체 주소가 들어 있는 list의 주소와 현재 데이터 값이들어있는 구조체 주소를 인자로 넘겨준다. if (!NameCompare(pcard, "한지영")) { // 현재 값이 들어있는 구조체 주소와 찾는 데이터를 인자로 넘겨주고 값이 같으면 하위구문을 실행한다. ShowNameCardInfo(pcard); // 현재 데이터의 값이 있는 구조체를 인자로 넘겨주어 이름과 전화번호를 출력해준다. } else { while (LNext(&list, &pcard)) { if (!NameCompare(pcard, "한지영")) { ShowNameCardInfo(pcard); break; } } } } // 이진수의 정보를 조회하여 변경 if (LFirst(&list, &pcard)) { if (!NameCompare(pcard, "이진수")) { ChangePhoneNum(pcard, "010-9999-9999"); // 현재 데이터가 들어있는 구조체 주소와 바꿀려는 문자열 데이터를 인자로 넘겨준다(넘어갈때 주소로 넘어감) } else { while (LNext(&list, &pcard)) { if (!NameCompare(pcard, "이진수")) { ChangePhoneNum(pcard, "010-9999-9999"); break; } } } } // 조수진의 정보를 조회하여 삭제 if (LFirst(&list, &pcard)) { if (!NameCompare(pcard, "조수진")) { pcard = LRemove(&list); // 데이터가 있는 구조체 주소 값들이 있는 list주소를 넘겨주고 삭제할 데이터의 주소를 포인터 변수 pcard에 대입한다. free(pcard); // 메모리 할당을 해지해 준다. } else { while (LNext(&list, &pcard)) { if (!NameCompare(pcard, "조수진")) { pcard = LRemove(&list); free(pcard); break; } } } } // 모든 사람들의 정보 출력 printf("현재 데이터 수 : %d \n", LCount(&list)); // 현재 list에 들어있는 값(데이터가 있는 구조체 주소의 개수)의 개수를 출력해준다. if (LFirst(&list, &pcard)) { // list에 저장된 첫번째 값이 있으면 실행 ShowNameCardInfo(pcard); // 현재 데이터에 저장되어 있는 이름과 전화번호를 출력해서준다 while (LNext(&list, &pcard)) // list에 저장된 두번째 값이 있으면 실행 ShowNameCardInfo(pcard); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char const *argv[]){ int data[] = {4,32,53,23,17,53,86,32,12,31}; int N = sizeof(data)/sizeof(data[0]); int i, j, temp; for ( i = 0; i < N - 1; i ++ ){ for ( j = i + 1; j < N; j ++ ){ if( data[ i ] > data[ j ] ) { temp = data[ i ]; data[ i ] = data[ j ]; data[ j ] = temp; } } } for (int i = 0; i < N; i++) { printf("%d ",data[i]); } return 0; }
C
// De bai: kiem tra xem trong mang co gia ri chan nho hon 2019 khong #include<stdio.h> #include<conio.h> main() { int n,MAX,i,imax; printf(" Nhap so phan tu cua tap hop = "); scanf("%i",&n); int array[n]; for(i=0;i<n;i++) { printf(" Nhap phan tu thu %i = ",i+1); scanf("%i",&array[i]); if(array[i]%1!=0) { printf("\n gia tri cua phan tu khong hop le"); i--; } } for(i=0;i<n;i++) { if(array[i]%2==0&&array[i]<2019) printf("\n Ton tai gia tri can tim trong mang :)"); break; } getch(); }
C
#include <u.h> #include <mem/mem.h> #include <ds/ds.h> #include "cc.h" static void ungetch(Lexer *l, int c); static int nextc(Lexer *l); char * tokktostr(Tokkind t) { switch(t) { case TOKIDENT: return "ident"; case TOKNUM: return "number"; case TOKIF: return "if"; case TOKELSE: return "else"; case TOKDO: return "do"; case TOKWHILE: return "while"; case TOKFOR: return "for"; case TOKVOID: return "void"; case TOKCHAR: return "char"; case TOKCHARLIT: return "character literal"; case TOKSHORT: return "short"; case TOKINT: return "int"; case TOKLONG: return "long"; case TOKSIGNED: return "signed"; case TOKUNSIGNED: return "unsigned"; case TOKEOF: return "end of file"; case TOKENUM: return "enum"; case TOKCONST: return "const"; case TOKRETURN: return "return"; case TOKSTR: return "string"; case TOKAUTO: return "auto"; case TOKEXTERN: return "extern"; case TOKSTATIC: return "static"; case TOKVOLATILE: return "volatile"; case TOKSIZEOF: return "sizeof"; case TOKFLOAT: return "float"; case TOKDOUBLE: return "double"; case TOKTYPEDEF: return "typedef"; case TOKUNION: return "union"; case TOKSTRUCT: return "struct"; case TOKGOTO: return "goto"; case TOKSWITCH: return "switch"; case TOKCASE: return "case"; case TOKDEFAULT: return "default"; case TOKCONTINUE: return "continue"; case TOKBREAK: return "break"; case TOKREGISTER: return "register"; case TOKSUBASS: return "-="; case TOKSHR: return ">>"; case TOKSHL: return "<<"; case TOKORASS: return "|="; case TOKNEQ: return "!="; case TOKMULASS: return "*="; case TOKMODASS: return "%="; case TOKLOR: return "||"; case TOKLEQ: return "<="; case TOKLAND: return "&&"; case TOKINC: return "++"; case TOKGEQ: return ">="; case TOKEQL: return "=="; case TOKELLIPSIS: return "..."; case TOKDIVASS: return "/="; case TOKDEC: return "--"; case TOKARROW: return "->"; case TOKANDASS: return "&="; case TOKADDASS: return "+="; case TOKHASH: return "#"; case TOKHASHHASH: return "##"; case TOKDIRSTART: return "Directive start"; case TOKDIREND: return "Directive end"; case TOKHEADER: return "include header"; case '?': return "?"; case '[': return "["; case '+': return "+"; case '%': return "%"; case '&': return "&"; case '*': return "*"; case '}': return "}"; case '{': return "{"; case ']': return "]"; case ')': return ")"; case '(': return "("; case '.': return "."; case '/': return "/"; case '!': return "!"; case ':': return ":"; case ';': return ";"; case '<': return "<"; case '>': return ">"; case ',': return ","; case '-': return "-"; case '|': return "|"; case '=': return "="; case '~': return "~"; case '^': return "^"; case '\\': return "\\"; } panic("internal error converting token to string: %d", t); return 0; } enum { INCLUDEBEGIN, INCLUDEIDENT, INCLUDEHEADER, }; /* makes a token, copies v */ static Tok * mktok(Lexer *l, int kind) { Tok *r; l->tokval[l->nchars] = 0; r = xmalloc(sizeof(Tok)); r->pos.line = l->markpos.line; r->pos.col = l->markpos.col; r->pos.file = l->markpos.file; r->k = kind; r->ws = l->ws; r->nl = l->nl; l->ws = 0; l->nl = 0; switch(kind){ case TOKSTR: case TOKNUM: case TOKIDENT: case TOKCHARLIT: case TOKHEADER: /* TODO: intern strings */ r->v = xstrdup(l->tokval); break; default: r->v = tokktostr(kind); break; } /* The lexer needs to be aware of '<>' style includes. */ switch(l->includestate) { case INCLUDEBEGIN: if(kind == TOKDIRSTART) l->includestate = INCLUDEIDENT; else l->includestate = INCLUDEBEGIN; break; case INCLUDEIDENT: if(kind == TOKIDENT && strcmp(r->v, "include") == 0) l->includestate = INCLUDEHEADER; else l->includestate = INCLUDEBEGIN; break; default: l->includestate = INCLUDEBEGIN; break; } return r; } static int numberc(int c) { return c >= '0' && c <= '9'; } static int hexnumberc(int c) { if(numberc(c)) return 1; if(c >= 'a' && c <= 'f') return 1; if(c >= 'A' && c <= 'F') return 1; return 0; } static int identfirstc(int c) { if(c == '_') return 1; if(c >= 'a' && c <= 'z') return 1; if(c >= 'A' && c <= 'Z') return 1; return 0; } static int identtailc(int c) { if(numberc(c) || identfirstc(c)) return 1; return 0; } static int wsc(int c) { return (c == '\r' || c == '\n' || c == ' ' || c == '\t'); } static void mark(Lexer *l) { l->nchars = 0; l->markpos.line = l->pos.line; l->markpos.col = l->pos.col; } static void accept(Lexer *l, int c) { l->tokval[l->nchars] = c; l->nchars += 1; if(l->nchars > MAXTOKSZ) errorposf(&l->markpos, "token too large"); } static int nextc(Lexer *l) { int c; l->prevpos.col = l->pos.col; l->prevpos.line = l->pos.line; c = fgetc(l->f); if(c == '\n') { l->pos.line += 1; l->pos.col = 1; } else if(c == '\t') l->pos.col += 4; else l->pos.col += 1; return c; } static void ungetch(Lexer *l, int c) /* avoid name conflict */ { l->pos.col = l->prevpos.col; l->pos.line = l->prevpos.line; ungetc(c, l->f); } Tok * lex(Lexer *l) { Tok *t; int c, c2; mark(l); if(l->indirective && l->nl) { l->indirective = 0; t = mktok(l, TOKDIREND); l->nl = 1; return t; } c = nextc(l); if(c == EOF) { if(l->indirective) { l->indirective = 0; return mktok(l, TOKDIREND); } return mktok(l, TOKEOF); } else if(wsc(c)) { l->ws = 1; if(c == '\n') l->nl = 1; do { c = nextc(l); if(c == EOF) { if(l->indirective) { l->indirective = 0; return mktok(l, TOKDIREND); } return mktok(l, TOKEOF); } if(c == '\n') l->nl = 1; } while(wsc(c)); ungetch(l, c); return lex(l); } else if (c == '"') { accept(l, c); for(;;) { c = nextc(l); if(c == EOF) errorf("unclosed string\n"); /* TODO error pos */ accept(l, c); if(c == '\\') { c = nextc(l); if(c == EOF || c == '\n') errorf("EOF or newline in string literal"); accept(l, c); continue; } if(c == '"') /* TODO: escape chars */ return mktok(l, TOKSTR); } } else if (c == '\'') { accept(l, c); c = nextc(l); if(c == EOF) errorf("unclosed char\n"); /* TODO error pos */ accept(l, c); if(c == '\\') { c = nextc(l); if(c == EOF || c == '\n') errorf("EOF or newline in char literal\n"); accept(l, c); } c = nextc(l); accept(l, c); if(c != '\'') errorf("char literal expects '\n"); return mktok(l, TOKCHARLIT); } else if(identfirstc(c)) { accept(l, c); for(;;) { c = nextc(l); if (!identtailc(c)) { ungetch(l, c); return mktok(l, TOKIDENT); } accept(l, c); } } else if(numberc(c)) { accept(l, c); c2 = nextc(l); if(c == '0' && c2 == 'x') { accept(l, c); for(;;) { c = nextc(l); if (!hexnumberc(c)) { while(c == 'u' || c == 'l' || c == 'U' || c == 'L') { accept(l, c); c = nextc(l); } ungetch(l, c); return mktok(l, TOKNUM); } accept(l, c); } } ungetch(l, c2); for(;;) { c = nextc(l); if (!numberc(c)) { while(c == 'u' || c == 'l' || c == 'U' || c == 'L') { accept(l, c); c = nextc(l); } ungetch(l, c); return mktok(l, TOKNUM); } accept(l, c); } } else if(c == '<' && l->includestate == INCLUDEHEADER) { for(;;){ accept(l, c); if(c == EOF) errorf("eof in include\n"); if(c == '>') return mktok(l, TOKHEADER); c = nextc(l); } } else { c2 = nextc(l); if(c == '/' && c2 == '*') { l->ws = 1; for(;;) { do { c = nextc(l); if(c == EOF) { return mktok(l, TOKEOF); } if(c == '\n') l->nl = 1; } while(c != '*'); c = nextc(l); if(c == EOF) return mktok(l, TOKEOF); if(c == '/') return lex(l); if(c == '\n') l->nl = 1; } } else if(c == '/' && c2 == '/') { l->ws = 1; do { c = nextc(l); if (c == EOF) return mktok(l, TOKEOF); } while(c != '\n'); l->nl = 1; ungetch(l, c); return lex(l); } else if(c == '.' && c2 == '.') { /* TODO, errorpos? */ c = nextc(l); if(c != '.') errorf("expected ...\n"); return mktok(l, TOKELLIPSIS); } else if(c == '+' && c2 == '=') return mktok(l, TOKADDASS); else if(c == '-' && c2 == '=') return mktok(l, TOKSUBASS); else if(c == '-' && c2 == '>') return mktok(l, TOKARROW); else if(c == '*' && c2 == '=') return mktok(l, TOKMULASS); else if(c == '/' && c2 == '=') return mktok(l, TOKDIVASS); else if(c == '%' && c2 == '=') return mktok(l, TOKMODASS); else if(c == '&' && c2 == '=') return mktok(l, TOKANDASS); else if(c == '|' && c2 == '=') return mktok(l, TOKORASS); else if(c == '>' && c2 == '=') return mktok(l, TOKGEQ); else if(c == '<' && c2 == '=') return mktok(l, TOKLEQ); else if(c == '!' && c2 == '=') return mktok(l, TOKNEQ); else if(c == '=' && c2 == '=') return mktok(l, TOKEQL); else if(c == '+' && c2 == '+') return mktok(l, TOKINC); else if(c == '-' && c2 == '-') return mktok(l, TOKDEC); else if(c == '<' && c2 == '<') return mktok(l, TOKSHL); else if(c == '>' && c2 == '>') return mktok(l, TOKSHR); else if(c == '|' && c2 == '|') return mktok(l, TOKLOR); else if(c == '&' && c2 == '&') return mktok(l, TOKLAND); else if(c == '#' && c2 == '#') return mktok(l, TOKHASHHASH); else if(c == '\\' && c2 == '\n') return lex(l); else { /* TODO, detect invalid operators */ ungetch(l, c2); if(c == '#' && l->nl) { l->indirective = 1; return mktok(l, TOKDIRSTART); } return mktok(l, c); } panic("internal error\n"); } }
C
/************************************** * pthread-philo2.c * * Programme d'exemple de pthread avec * philosophes qui dinent et mutex * **************************************/ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <string.h> #define PHILOSOPHES 3 static pthread_mutex_t baguette[PHILOSOPHES]; void error(int err, char *msg) { fprintf(stderr,"%s a retourné %d message d'erreur : %s\n",msg,err,strerror(errno)); exit(EXIT_FAILURE); } void mange(int id) { printf("Philosophe [%d] mange\n",id); for(int i=0;i< rand(); i++) { // philosophe mange } } ///AAA void* philosophe ( void* arg ) { int *id=(int *) arg; int left = *id; int right = (left + 1) % PHILOSOPHES; while(true) { // philosophe pense if(left<right) { pthread_mutex_lock(&baguette[left]); pthread_mutex_lock(&baguette[right]); } else { pthread_mutex_lock(&baguette[right]); pthread_mutex_lock(&baguette[left]); } mange(*id); pthread_mutex_unlock(&baguette[left]); pthread_mutex_unlock(&baguette[right]); } return (NULL); } ///BBB int main ( int argc, char *argv[]) { int i; int id[PHILOSOPHES]; int err; pthread_t phil[PHILOSOPHES]; srand(getpid()); for (i = 0; i < PHILOSOPHES; i++) id[i]=i; for (i = 0; i < PHILOSOPHES; i++) { err=pthread_mutex_init( &baguette[i], NULL); if(err!=0) error(err,"pthread_mutex_init"); } for (i = 0; i < PHILOSOPHES; i++) { err=pthread_create(&phil[i], NULL, philosophe, (void*)&(id[i]) ); if(err!=0) error(err,"pthread_create"); } for (i = 0; i < PHILOSOPHES; i++) { pthread_join(phil[i], NULL); if(err!=0) error(err,"pthread_join"); } for (i = 0; i < PHILOSOPHES; i++) { pthread_mutex_destroy(&baguette[i]); if(err!=0) error(err,"pthread_mutex_destroy"); } return (EXIT_SUCCESS); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <linux/input.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <limits.h> #define RB_SIZE 1000 int listen_fd; struct client { struct client *next; struct client *prev; int fd; struct sockaddr_in addr; char buf[RB_SIZE]; int in, out, kill; }; struct client client_head; struct keyboard { struct keyboard *next; int fd, num; char *name; }; struct keyboard *kbd_head; void usage (void) { fprintf (stderr, "usage: keycast KBD...\n"); exit (1); } void * xcalloc (unsigned int a, unsigned int b) { void *p; if ((p = calloc (a, b)) == NULL) { fprintf (stderr, "memory error\n"); exit (1); } return (p); } char * xstrdup (const char *old) { char *new; if ((new = strdup (old)) == NULL) { fprintf (stderr, "out of memory\n"); exit (1); } return (new); } void valgrind_cleanup (void) { exit (0); } void cleanup_clients (void) { struct client *cp, *ncp; for (cp = client_head.next, ncp = cp->next; cp != &client_head; cp = ncp, ncp = cp->next) { if (cp->kill) { fprintf (stderr, "killing client\n"); close (cp->fd); cp->prev->next = cp->next; cp->next->prev = cp->prev; free (cp); } } } void make_kbd (char *kbd, int kid) { struct keyboard *kp; kp = xcalloc (1, sizeof *kp); kp->name = xstrdup (kbd); kp->num = kid; if ((kp->fd = open (kp->name, O_RDONLY)) < 0) { fprintf (stderr, "cannot open keyboard: %s\n", kp->name); exit (1); } fcntl (kp->fd, F_SETFL, O_NONBLOCK); if (!kbd_head) { kbd_head = kp; } else { kp->next = kbd_head; kbd_head = kp; } } void make_client (void) { int fd; socklen_t socklen; struct client *cp; struct sockaddr_in addr; socklen = sizeof cp->addr; fd = accept (listen_fd, (struct sockaddr *) &addr, &socklen); if (fd < 0) { fprintf (stderr, "strange accept error: %s\n", strerror (errno)); return; } cp = xcalloc (1, sizeof *cp); cp->fd = fd; cp->addr = addr; socklen = sizeof cp->addr; fcntl (cp->fd, F_SETFL, O_NONBLOCK); cp->next = &client_head; cp->prev = client_head.prev; client_head.prev->next = cp; client_head.prev = cp; printf ("connection from %s:%d fd %d\n", inet_ntoa (cp->addr.sin_addr), ntohs (cp->addr.sin_port), cp->fd); } void handle_client (struct client *cp) { int thistime, n; char inbuf[1000]; while (1) { n = read (cp->fd, inbuf, sizeof inbuf); if (n < 0) { if (errno == EAGAIN) break; fprintf (stderr, "strange read error: %s\n", strerror (errno)); cp->kill = 1; return; } if (n == 0) { fprintf (stderr, "EOF from client\n"); cp->kill = 1; return; } } while (cp->in != cp->out) { if (cp->out < cp->in) { thistime = cp->in - cp->out; } else { thistime = RB_SIZE - cp->out; } n = write (cp->fd, cp->buf + cp->out, thistime); if (n < 0) { cp->kill = 1; break; } if (n == 0) break; cp->out = (cp->out + n) % RB_SIZE; } } void handle_input (struct keyboard *kp) { struct input_event ev; struct client *cp; char buf[1000]; char *p; int n, len, used, togo, thistime; while (1) { n = read (kp->fd, &ev, sizeof ev); if (n < 0 && errno != EAGAIN) { fprintf (stderr, "input error: %s\n", strerror (errno)); exit (1); } if (n <= 0) return; if (n < sizeof ev) { fprintf (stderr, "unexpected input buffer size\n"); exit (1); } if (ev.value > 1 || ev.code == 0) { continue; } sprintf (buf, "kbd%d: %d %d\n", kp->num, ev.value, ev.code); printf ("%s", buf); len = strlen (buf); for (cp = client_head.next; cp != &client_head; cp = cp->next) { used = (cp->out + RB_SIZE - cp->in) % RB_SIZE; if (used + len >= RB_SIZE - 1) continue; togo = len; p = buf; while (togo > 0) { if (cp->in < cp->out) { thistime = cp->out - cp->in; } else { thistime = RB_SIZE - cp->in; } if (thistime > togo) thistime = togo; memcpy (cp->buf + cp->in, p, thistime); cp->in = (cp->in + thistime) % RB_SIZE; p += thistime; togo -= thistime; } } } } int main (int argc, char **argv) { struct sockaddr_in addr; struct client *cp; struct keyboard *kp; socklen_t addrlen; int c, port, maxfd, idx, kid; FILE *f; char *s; fd_set rset, wset; while ((c = getopt (argc, argv, "")) != EOF) { switch (c) { default: usage (); } } if (optind >= argc) usage (); if (optind == argc) usage (); kid = 0; for (idx = optind; idx < argc; idx++) { s = xstrdup (argv[idx]); printf ("kbd%d: %s\n", kid, s); make_kbd (s, kid++); free (s); } /* kbd = argv[optind++]; */ /* if (optind != argc) */ /* usage (); */ client_head.next = &client_head; client_head.prev = &client_head; /* if ((input_fd = open (kbd, O_RDONLY)) < 0) { */ /* fprintf (stderr, "cannot open keyboard\n"); */ /* exit (1); */ /* } */ /* fcntl (input_fd, F_SETFL, O_NONBLOCK); */ listen_fd = socket (AF_INET, SOCK_STREAM, 0); for (port = 9195; port <= 9200; port++) { memset (&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons (port); if (bind (listen_fd, (struct sockaddr *) &addr, sizeof addr) >= 0) { break; } } listen (listen_fd, 5); addrlen = sizeof addr; getsockname (listen_fd, (struct sockaddr *) &addr, &addrlen); port = ntohs (addr.sin_port); printf ("listening on %d\n", port); f = fopen ("PORT", "w"); fprintf (f, "%d\n", port); fclose (f); while (1) { cleanup_clients (); maxfd = 0; FD_ZERO (&rset); FD_ZERO (&wset); if (listen_fd > maxfd) maxfd = listen_fd; FD_SET (listen_fd, &rset); for (kp = kbd_head; kp; kp = kp->next) { if (kp->fd > maxfd) maxfd = kp->fd; FD_SET (kp->fd, &rset); } /* if (input_fd > maxfd) */ /* maxfd = input_fd; */ /* FD_SET (input_fd, &rset); */ for (cp = client_head.next; cp != &client_head; cp = cp->next) { if (cp->in != cp->out) { if (cp->fd > maxfd) maxfd = cp->fd; FD_SET (cp->fd, &wset); FD_SET (cp->fd, &rset); } } if (select (maxfd + 1, &rset, &wset, NULL, NULL) < 0) { fprintf (stderr, "select error\n"); exit (1); } if (FD_ISSET (listen_fd, &rset)) make_client (); for (kp = kbd_head; kp; kp = kp->next) { if (FD_ISSET (kp->fd, &rset)) handle_input (kp); } for (cp = client_head.next; cp != &client_head; cp = cp->next) { handle_client (cp); } } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char **argv) { // Creation du processus fils pid_t pid = fork(); // Verification de la creation du processus fils if (pid < 0) { printf("Erreur : Le fils n'a pas été cree\n"); return 0; } // Execution dans le processus fils if(pid == 0){ printf("Processus fils - [PID PERE : %d]\n", getppid()); printf("Processus fils - [PID : %d]\n", getpid()); // Retourne le dernier chiffre du PID exit(getpid() % 10); } // Execution dans le processus pere else{ printf("Processus pere - [PID FILS : %d]\n", pid); // Attente de la fin du processus fils int wstatus; wait(&wstatus); if(WIFEXITED(wstatus)){ printf("Code retour fils : %d\n", WEXITSTATUS(wstatus) ); }else{ printf("Le fils ne s'est pas terminé normalement"); } } return 0; }
C
#include <stdio.h> // calcola il numero di bit 1 nella rappresentazione in binario di n // questa funzione deve essese ricorsiva int count1(int n) { // si dia per scontato che n >= 0 // DA COMPLETARE: QUESTA FUNZIONE DEVE ESSERE RICORSIVA } int main(void) { // DA COMPLETARE: // 1) legge da tastiera un intero n >= 0, se non lo fosse lo richiede ad oltranza // 2) chiama count1(n) e ne stampa il risultato return 0; }
C
int centreOfMass(double * V, size_t M, size_t N, size_t P, double * com) { /* Centre of Mass of volumetric image V of size MxNxP V should be pre-processed for beads, an erf-threshold between min and max is probably a good option. */ // Reset, just to be sure... com[0] = 0; com[1] = 0; com[2] = 0; for(size_t xx = 0; xx<M; xx++) for(size_t yy = 0; yy<N; yy++) for(size_t zz = 0; zz<P; zz++) { pos = xx+yy*M+zz*M*N; com[0]+=V[pos] * (xx+1); com[1]+=V[pos] * (yy+1); com[2]+=V[pos] * (zz+1); } com[0]/=(N*P)*M*M/2; com[1]/=(M*N)*N*N/2; com[2]/=(M*N)*P*P/2; }
C
/* A C program that will find its way through a maze using the depth-first search algorithm. This program takes input from a file where the filename is specified in the command line arguments. The input file will only contain two integer values per line of input: • The first valid line gives the size of the 2-D maze (the number of rows given by the first number, then the number of columns given by the second number), valid values are >= 1 • The second valid line gives the coordinates of the starting position in the maze • The third valid line gives the coordinates of the ending position in the maze • The remaining valid lines in the file give the coordinates of blocked positions in the maze */ #include <stdio.h> #include <stdlib.h> #include <string.h> int const TRUE = 1; int const FALSE = 0; int debugMode = 0; typedef struct mazeStruct { char **arr; int xsize, ysize; int xstart, ystart; int xend, yend; } maze; typedef struct stackStruct { int xpos, ypos; struct stackStruct *next; }stack; void IntializeStack(stack **stackHead){ *stackHead = NULL; } stack* Top(stack **head){ return(*head); } //free the allocated memory /*void FreeMaze(maze **maze){ int i; for(i = 0; i < maze.xsize +2; i++){ free(maze->arr[i]); }free(maze->arr); }*/ //check if empty int CheckEmpty(stack *head){ if(head == NULL){ return 1; } else{ return 0; } } void PopStack(stack **head, int debugMode){ stack *temp = *head; if(debugMode == TRUE){ printf("\nPopping From Stack: (%d,%d)\n",temp->xpos, temp->ypos ); } if(*head != NULL){ *head = (*head)->next; free(temp); } else{ return; } } void resetStack(stack** head){ stack* temp = *head; while(*head != NULL){ *head = (*head)->next; free(temp); } } void PushStack(stack **head, int xpos, int ypos){ stack *temp = (stack *)malloc(sizeof(stack)); temp->xpos = xpos; temp->ypos = ypos; temp->next = *head; *head = temp; } void PrintMaze(maze *maze){ int i; int j; for (i = 0; i < maze->xsize + 2; i++) { for (j = 0; j < maze->ysize + 2; j++) printf ("%c", maze->arr[i][j]); printf("\n"); } } void DisplayStack (stack* head){ stack *temp = head; /* base case */ if ( temp == NULL ) { return; } /* recursive case */ DisplayStack (temp->next); printf("(%d,%d)", temp->xpos, temp->ypos); return; } void debugModeInit( int argc, char **argv){ debugMode = FALSE; int i; for ( i = 0; i < argc; i++ ){ if (strcmp(argv[i], "-d") == 0){ debugMode = TRUE; } } } int main (int argc, char **argv) { debugModeInit(argc,argv); int xsize = 0, ysize = 0; int xstart = 0, ystart = 0; int xend = 0, yend = 0; int xpos, ypos; char **string; maze m1; int i,j; stack* head; IntializeStack(&head); FILE *src; /* //debugMode for(i = 0; i < argc; i++) { if (strcmp(argv[i], "-d") == TRUE) { printf("\n Debug Mode\n"); debugMode = TRUE; } else{ string = &argv[i]; } } printf("HELLOOOOO1"); argv[1] = *string; */ /* verify the proper number of command line arguments were given */ if(argc != 2) { printf("Usage: %s <input file name>\n", argv[0]); exit(-1); } /* Try to open the input file. */ if ( ( src = fopen( argv[1], "r" )) == NULL ) { printf ( "Can't open input file: %s", argv[1] ); exit(-1); } /* read in the size, starting and ending positions in the maze */ fscanf (src, "%d %d", &m1.xsize, &m1.ysize); if (m1.xsize <= 0 || m1.ysize <= 0){ printf("Invalid size: Enter Valid Dimesions\n"); exit(0); } fscanf (src, "%d %d", &m1.xstart, &m1.ystart); if((m1.xstart > m1.xsize || m1.xstart < 0 ) || (m1.ystart > m1.ysize || m1.ystart < 0) ){ printf("Invalid start: Enter Valid Dimesions\n"); exit(0); } fscanf (src, "%d %d", &m1.xend, &m1.yend); if((m1.xend > m1.xsize || m1.xend < 0 ) || (m1.yend > m1.ysize || m1.yend < 0) ){ printf("Invalid End: Enter Valid Dimesions\n"); exit(0); } /* print them out to verify the input */ printf ("size: %d, %d\n", m1.xsize, m1.ysize); printf ("start: %d, %d\n", m1.xstart, m1.ystart); printf ("end: %d, %d\n", m1.xend, m1.yend); printf("HELLOOOOO2"); /* allocate the maze */ m1.arr = (char **) malloc (sizeof(char *) * (m1.xsize + 2) ); for (i = 0; i < m1.xsize + 2; i++) m1.arr[i] = (char *) malloc (sizeof(char ) * (m1.ysize + 2) ); /* initialize the maze to empty */ for (i = 0; i < m1.xsize+2; i++) for (j = 0; j < m1.ysize+2; j++) m1.arr[i][j] = '.'; /* mark the borders of the maze with *'s */ for (i=0; i < m1.xsize+2; i++) { m1.arr[i][0] = '*'; m1.arr[i][m1.ysize+1] = '*'; } for (i=0; i < m1.ysize+2; i++) { m1.arr[0][i] = '*'; m1.arr[m1.xsize+1][i] = '*'; } /* mark the starting and ending positions in the maze */ m1.arr[m1.xstart][m1.ystart] = 's'; m1.arr[m1.xend][m1.yend] = 'e'; /* mark the blocked positions in the maze with *'s */ while (fscanf (src, "%d %d", &xpos, &ypos) != EOF) { if(xpos == m1.xstart && ypos == m1.ystart){ printf("Invalid: Blocking Postions Are Blocking Start Postion\n"); exit(0); } else if (xpos > m1.xsize || ypos > m1.ysize){ printf("Invalid: Blocking out Of Maze\n"); exit(0); } else if(xpos < 1 || ypos < 1){ printf("Invalid: Blocking out of maze\n"); exit(0); } else if(xpos == m1.xend && ypos == m1.yend){ printf("Invalid: Blocking Postions Are Blocking End Postion\n"); exit(0); } m1.arr[xpos][ypos] = '*'; } /* prints initial maze */ PrintMaze(&m1); /* puts start position into stack*/ PushStack(&head, m1.xstart, m1.ystart); xpos = m1.xstart; ypos = m1.ystart; while(!CheckEmpty(head) && head != NULL){ if(head->xpos == m1.xend && head->ypos == m1.yend){ break; } if(m1.arr[head->xpos +1][head->ypos] != 'v' && m1.arr[head->xpos+1][head->ypos] != '*'){ m1.arr[head->xpos][head->ypos] = 'v'; xpos= xpos + 1; PushStack(&head, xpos, ypos); continue; } if(m1.arr[head->xpos][head->ypos+1] != 'v' && m1.arr[head->xpos][head->ypos+1] != '*'){ m1.arr[head->xpos][head->ypos] = 'v'; ypos= ypos + 1; PushStack(&head, xpos, ypos); continue; } if(m1.arr[head->xpos-1][head->ypos] != 'v' && m1.arr[head->xpos-1][head->ypos] != '*'){ m1.arr[head->xpos][head->ypos] = 'v'; xpos= xpos -1; PushStack(&head, xpos, ypos); continue; } if(m1.arr[head->xpos][head->ypos -1] != 'v' && m1.arr[head->xpos][head->ypos -1] != '*'){ m1.arr[head->xpos][head->ypos] = 'v'; ypos= ypos - 1; PushStack(&head, xpos, ypos); continue; } PopStack(&head, debugMode); } if(CheckEmpty(head)){ printf("Maze has no solution\n"); exit(0); } else{ // printf("%d\n",head->xpos); printf("\n"); DisplayStack(head); printf("\n"); PrintMaze(&m1); } int n; for(n = 0; n < m1.xsize +2; n++){ free(m1.arr[n]); }free(m1.arr); //resetStack(&head); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "matrix.h" //hw: work on inputNumbers and use strtok() /* We will examine the vector, matrix, and table structures using vanilla C doing this will help learning the following concepts: 1) memory management 2) input, output 3) vector, matrix, and table operations */ //typedef Vector<double> VECTORD; //is matrix Vector<Vector<T>>? MATRIX* createSetupMatrix(int count, const char** values) { if(count > 1 && values != NULL) { int rows, columns; sscanf(values[1], "%d", &rows); if(count > 2) { sscanf(values[2], "%d", &columns); return initializeMatrix(columns, rows); } return initializeMatrix(columns, columns); } return NULL; } int main(int argc, char const *argv[]) { /*double matrixValues[] = {1.0, 1.5, 2.0, 35.0}; MATRIX* matrix = initializeMatrix(2, 2); setMatrixValues(matrixValues, sizeof(matrixValues) / sizeof(double), matrix); logVector(matrix->rows[1]); freeMatrix(&matrix);*/ printf("argc = %d\n", argc); for(int i = 0; i < argc; i++) printf("%s\n", argv[i]); MATRIX* m = createSetupMatrix(argc, argv); inputValues(m); printf("matrixInput _ _ _ _ _ _ _\n"); printMatrix(m); freeMatrix(&m); return 0; }
C
#include <signal.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> void catch_sighup(int signal) { printf("signal : %d\n", signal); printf("prosper youpla boum! c'est le roid u pain dépice!\n"); } int main(void) { printf("pid : %d\n", getpid()); while (1) signal(SIGHUP, catch_sighup); return (0); }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> void funct(int n) { printf("%d\n",n); pthread_exit(NULL); } int main() { int n = 100; pthread_t * p = malloc(sizeof(pthread_t) * n); for (int i = 0; i < n; ++i) { pthread_create(&p[i], NULL, (void*)funct, (void*)i); pthread_join(p[i], NULL); printf("Thread %d created.\n", i); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_realloc_tab.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: qbackaer <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/30 19:41:31 by qbackaer #+# #+# */ /* Updated: 2020/02/06 18:14:33 by qbackaer ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include <stdio.h> static size_t get_size(char **tab) { size_t size; char **ptr; ptr = tab; size = 0; while (*ptr) { size++; ptr++; } return (size + 2); } char **fresh_tab(char *new_entry) { char **new_tab; if (!(new_tab = malloc(sizeof(new_tab) * 2))) exit(EXIT_FAILURE); if (!(new_tab[0] = ft_strdup(new_entry))) exit(EXIT_FAILURE); new_tab[1] = NULL; return (new_tab); } char **ft_realloc_tab(char **old_tab, char *new_entry) { char **new_tab; char **roam_o; char **roam_n; if (!new_entry) return (NULL); if (!old_tab) return (fresh_tab(new_entry)); if (!(new_tab = malloc(sizeof(new_tab) * get_size(old_tab)))) exit(EXIT_FAILURE); roam_n = new_tab; roam_o = old_tab; while (*roam_o) { if (!(*roam_n = ft_strdup(*roam_o))) exit(EXIT_FAILURE); roam_o++; roam_n++; } if (!(*roam_n = ft_strdup(new_entry))) exit(EXIT_FAILURE); roam_n++; *roam_n = NULL; ft_free_tab2(old_tab); return (new_tab); }
C
/* xsh_ls.c - xsh_ls */ #include <xinu.h> #include <stdio.h> /*------------------------------------------------------------------------ * xhs_ls - list the contents of the local file system directory *------------------------------------------------------------------------ */ shellcmd xsh_ls(int nargs, char *args[]) { struct lfdir *dirptr; /* Ptr to in-memory directory */ int32 i; struct ldentry *ldptr; /* Ptr to an entry in directory */ /* For argument '--help', emit help about the 'ls' command */ if (nargs == 2 && strncmp(args[1], "--help", 7) == 0) { printf("Use: %s\n\n", args[0]); printf("Description:\n"); printf("\tlists the names of files\n"); printf("Options:\n"); printf("\t--help\t display this help and exit\n"); return 0; } if (nargs != 1) { printf("illegal option: try --help for more information\n"); return 1; } /* Obtain copy of directory if not already present in memory */ dirptr = &Lf_data.lf_dir; wait(Lf_data.lf_mutex); if (! Lf_data.lf_dirpresent) { if (read(Lf_data.lf_dskdev, (char *)dirptr, LF_AREA_DIR) == SYSERR ) { signal(Lf_data.lf_mutex); fprintf(stderr,"cannot read the directory\n"); } if (lfscheck(dirptr) == SYSERR ) { fprintf(stderr, "THe disk does not contain a Xinu file system\n"); signal(Lf_data.lf_mutex); return 1; } Lf_data.lf_dirpresent = TRUE; } signal(Lf_data.lf_mutex); /* Search directory and list the file names */ for (i=0; i<dirptr->lfd_nfiles; i++) { ldptr = &dirptr->lfd_files[i]; printf("%s\n", ldptr->ld_name); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #define MAX 50 typedef struct Node *Node_pt; typedef struct Node{ Node_pt link; int vtx; } Node; char matrix[MAX][MAX]; char new_matrix[MAX][MAX]; Node_pt list[MAX]; Node_pt new_list[MAX]; int order[MAX]; int discovery_t[MAX]; int finish_t[MAX]; int time = 1; void dfs(int root){ Node_pt tmp = list[root]; discovery_t[root] = time++; while(tmp!=NULL){ if(discovery_t[tmp->vtx]==0){ dfs(tmp->vtx); tmp = tmp->link; } else{ tmp = tmp->link; } } finish_t[root] = time++; } void dfs2(int root){ Node_pt tmp = new_list[root]; discovery_t[root] = time++; while(tmp!=NULL){ if(discovery_t[tmp->vtx]==0){ dfs2(tmp->vtx); tmp = tmp->link; } else{ tmp = tmp->link; } } finish_t[root] = time++; } void dfs3(int root){ discovery_t[root] = time++; for(int i=1; i<MAX; i++){ int j = order[i]; if(discovery_t[j]==0 && new_matrix[root][j]=='1') dfs3(j); } finish_t[root] = time++; } int main(int argc, const char *argv[]) { if(argc<2){ fprintf(stderr, "Usage: ./result input_file\n"); exit(0); } FILE *fp; fp = fopen(argv[1], "r"); char data[MAX][MAX]; int check =0; for(int i=0; i<MAX; i++){ for(int j=0; j<MAX; j++){ data[i][j] = fgetc(fp); if(data[i][j]=='\n') break; if(data[i][j]==EOF){ data[i][j]='\n'; check = 1; break; } } if(check==1) break; } //printf("0. read the original data file\n"); int p,q; for(p=0; p<MAX; p++){ if(data[p][0]=='\0') break; for(q=0; q<MAX; q++){ if(data[p][q]=='\0') break; //printf("%c",data[p][q]); } } fclose(fp); //printf("\n0. represent to type of array\n"); int k=0; for(int i=0; i<p-1; i++){ k=0; for(int j=0; j<p-1; j++){ if(data[i+1][k]=='\n') break; else if(data[i+1][k]=='1' || data[i+1][k]=='0'){ matrix[i][j] = data[i+1][k]; //printf("%c", matrix[i][j]); k++; } else{ k++; j--; } } //printf("\n"); } printf("\n"); printf("1. Array of adjacency list of given graph\n"); //Node_pt list[p-1]; Node_pt node; Node_pt tmp; Node_pt new; for(int x=0; x<p-1; x++){ node = list[x]; printf("list[%d]: %c ",x, data[x+1][0]); for(int y=0; y<p-1; y++){ if(matrix[x][y]=='1'){ new = (Node_pt)malloc(sizeof(Node)); new->vtx = y; if(list[x]==node){ tmp = new; list[x] = new; } else{ tmp->link = new; tmp = new; } printf("-> %c ", data[new->vtx+1][0]); } } new->link = NULL; printf("\n"); } printf("\n"); printf("2. Discovery and finish time of each vertex after step1\n"); for(int i=0; i<p-1; i++){ discovery_t[i] = 0; finish_t[i] = 0; } for(int root=0; root<p-1; root++){ if(discovery_t[root]==0) dfs(root); } for(int i=0; i<p-1; i++){ printf("%c's discovery time is %d\n",data[i+1][0], discovery_t[i]); } printf("\n"); for(int j=0; j<p-1; j++){ printf("%c's finish time is %d\n",data[j+1][0], finish_t[j]); } printf("\n3. Array of adjacency list of transpose graph after step2\n"); for(int i=0; i<p-1; i++){ for(int j=0; j<p-1; j++){ new_matrix[i][j] = matrix[j][i]; } } //Node_pt new_list[p-1]; Node_pt new_node; Node_pt new_tmp; Node_pt new_new; for(int a=0; a<p-1; a++){ new_node = new_list[a]; printf("new_list[%d]: %c ", a, data[a+1][0]); for(int b=0; b<p-1; b++){ if(new_matrix[a][b]=='1'){ new_new = (Node_pt)malloc(sizeof(Node)); new_new->vtx = b; if(new_list[a]==new_node){ new_tmp = new_new; new_list[a] = new_new; } else{ new_tmp->link = new_new; new_tmp = new_new; } printf("-> %c ", data[new_new->vtx+1][0]); } } new_new->link = NULL; printf("\n"); } int max; int memo; for(int i=0; i<p-1; i++){ max = finish_t[i]; memo = i; for(int j=0; j<p-1; j++){ if(finish_t[j]>max){ max=finish_t[j]; memo = j; } } finish_t[memo] = 0; order[i] = memo; } printf("\n"); printf("4. Discovery and finish time of each vertex after step3\n"); for(int i=0; i<p-1; i++){ discovery_t[i] = 0; finish_t[i] = 0; } int group_range[p-1]; time =1; for(int i=0; i<p-1; i++){ int root = order[i]; group_range[i] = -1; if(discovery_t[root]==0){ dfs2(root); // dfs3 is also okay.. group_range[i] = root; } } for(int i=0; i<p-1; i++){ printf("%c's discovery time is %d\n",data[i+1][0], discovery_t[i]); } printf("\n"); for(int j=0; j<p-1; j++){ printf("%c's finish time is %d\n",data[j+1][0], finish_t[j]); } int new_order[p-1]; for(int i=0; i<p-1; i++){ max = finish_t[i]; memo = i; for(int j=0; j<p-1; j++){ if(finish_t[j]>max){ max=finish_t[j]; memo = j; } } finish_t[memo] = 0; new_order[i] = memo; } printf("\n5. SCC result\n"); int group_start[p-1]; k=0; for(int i=0; i<p-1; i++) if(group_range[i]!=-1) group_start[k++] = group_range[i]; for(int i=k; i<p-1; i++) group_start[i] = -1; int scc[p-1][p-1]; for(int i=0; i<p-1; i++) for(int j=0; j<p-1; j++) scc[i][j] = -1; int new_group_start[p-1]; for(int i=0; i<p-1; i++) new_group_start[i] = -1; int idx=0; for(int i=p-2; i>=0; i--){ if(group_start[i]!=-1){ new_group_start[idx] = group_start[i]; idx++; } } int m=0, n=0; for(int j=0; j<p-1; j++){ if(new_order[j]!=new_group_start[m+1]){ scc[m][n] = new_order[j]; n++; } else{ m++; n=0; scc[m][n] = new_order[j]; n++; } } int i=0, j=0; while(new_group_start[i]!=-1){ printf("SCC%d: vertex ", i+1); while(scc[i][j]!=-1){ printf("%c ", data[scc[i][j]+1][0]); j++; } j=0; i++; printf("\n"); } }
C
#include <stdio.h> #include <stdbool.h> bool is_valid_triangle(float a, float b, float c) { return (a + b + c == 180.0); } int main() { float a, b, c; printf("Enter the three angles separated by commas and spaces > "); scanf("%f, %f, %f", &a, &b, &c); printf("%s\n", is_valid_triangle(a, b, c) ? "VALID" : "INVALID"); return 0; }
C
#include "login.h" bool doLogin(char *senha){ if(memcmp(senha,SENHA,strlen(senha))!=0) return false; return true; }
C
/*--------------------------------------------------------------*/ /* */ /* execute_road_construction_event */ /* */ /* execute_road_construction_event.c - creates a patch object */ /* */ /* NAME */ /* execute_road_construction_event.c - creates a patch object */ /* */ /* SYNOPSIS */ /* struct routing_list_object execute_road_construction_event( */ /* struct basin_object *basin) */ /* */ /* */ /* */ /* OPTIONS */ /* */ /* */ /* DESCRIPTION */ /* */ /* reads routing topology from input file */ /* creates neighbourhood structure for each patch in the basin */ /* returns a list giving order for patch-level routing */ /* */ /* */ /* */ /* PROGRAMMER NOTES */ /* */ /*--------------------------------------------------------------*/ #include <string.h> #include <stdio.h> #include "rhessys.h" #include "functions.h" void execute_road_construction_event( struct world_object *world, struct command_line_object *command_line, struct date current_date) { // /*--------------------------------------------------------------*/ // /* Local function definition. */ // /*--------------------------------------------------------------*/ // // struct routing_list_object construct_routing_topology( // char *, // struct basin_object *); void *alloc(size_t, char *, char *); /*--------------------------------------------------------------*/ /* Local variable definition. */ /*--------------------------------------------------------------*/ int i, b; char routing_filename[MAXSTR]; char ext[11]; struct basin_object *basin; for (b=0; b< world[0].num_basin_files; b++) { basin = world[0].basins[b]; free(basin->route_list->list); free(basin->route_list); free(basin->surface_route_list->list); free(basin->surface_route_list); /*--------------------------------------------------------------*/ /* Read in a new routing topology file. */ /*--------------------------------------------------------------*/ sprintf(ext,".Y%4dM%dD%dH%d",current_date.year, current_date.month, current_date.day, current_date.hour); strncpy(routing_filename, command_line[0].routing_filename, MAXSTR); strncat(routing_filename, ext, MAXSTR); printf("\nRedefining Flow Connectivity using %s\n", routing_filename); basin->route_list = construct_routing_topology( routing_filename, basin, command_line, false ); if ( command_line->surface_routing_flag ) { strncpy(routing_filename, command_line->surface_routing_filename, MAXSTR); strncat(routing_filename, ext, MAXSTR); printf("\nRedefining Surface Flow Connectivity using %s\n", routing_filename); } basin->surface_route_list = construct_routing_topology( routing_filename, basin, command_line, true ); if (basin->surface_route_list->num_patches != basin->route_list->num_patches) { fprintf(stderr, "\nFATAL ERROR: in execute_road_construction_event, surface routing table has %d patches, but subsurface routing table has %d patches. The number of patches must be identical.\n", basin->surface_route_list->num_patches, basin->route_list->num_patches); exit(EXIT_FAILURE); } } /* end basins */ return; } /*end execute_road_construction_event.c*/
C
// // AVLtree.c // AVL_Tree // // Created by Trang Nguyen on 3/12/17. // Copyright © 2017 Trang Nguyen. All rights reserved. // #include "AVLtree.h" int Height (AVLNode *root){ if (!root) return -1; else return root->height; } int Max (int a, int b) { if (a > b) { return a; } else { return b; } } AVLNode *SingleRotateLeft(AVLNode *X){ AVLNode *W = X->left; X->left = W->right; W->right = X; X->height = Max(Height(X->left), Height(X->right)) + 1; W->height = Max(Height(W->left), X->height) + 1; return W; } AVLNode *SingleRotateRight(AVLNode *W) { AVLNode *X = W->right; W->right = X->left; X->left = W; W->height = Max(Height(W->right), Height(W->left)) + 1; X->height = Max(Height(X->right), W->height) + 1; return X; } AVLNode *DoubleRotateLeft (AVLNode *Z) { Z->left = SingleRotateRight(Z->left); return SingleRotateLeft(Z); } AVLNode *DoubleRotateRight (AVLNode *Z) { Z->right = SingleRotateLeft(Z->right); return SingleRotateLeft(Z); } AVLNode *Insert(AVLNode *root, AVLNode *parent, int data) { if (!root) { root = (AVLNode*) malloc (sizeof(AVLNode*)); if (!root) { printf("Memory Error"); return NULL; } else { root->data = data; root->height = 0; root->left = root->right = NULL; } } else if (data < root->data) { root->left = Insert(root->left, root, data); if ((Height(root->left) - Height(root->right)) == 2) { if (data < root->left->data) { root = SingleRotateLeft(root); } else { root = DoubleRotateLeft(root); } } } else if (data > root->data) { root->right = Insert(root->right, root, data); if ((Height(root->right) - Height(root->left)) == 2) { if (data < root->right->data) { root = SingleRotateRight(root); } else { root = DoubleRotateRight(root); } } } root->height = Max(Height(root->left), Height(root->right)) + 1; return root; } void PreOrder (AVLNode *root) { if (!root) { printf("0 element\n"); } else { printf("%d\n", root->data); PreOrder(root->left); PreOrder(root->right); } }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> int printCaps(char data) { if (data >= 'a' && data <= 'z') { return (int) data - 32; } else { return (int) data; } } int main(int argc, char* argv[]) { char name[20]; printf("Please enter a name\n"); //scanf("%c", &name); gets(name); if ((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z')) { printf("%c", (char) printCaps(name[0])); } for (int i=0, n = strlen(name); i < n; i++) { if (name[i] == ' ' && name[i + 1] != ' ') { printf("%c", (char) printCaps(name[i + 1])); } } printf("\n"); return 0; }
C
#include<stdio.h> #include<ctype.h> #define size 50 int top=-1; int stack[50]; int isempty(){ if(top==-1) return 1; else return 0; } int isfull(){ if(top==size-1) return 1; else return 0; } void push(int x){ if(isfull()) printf("Stack overflow\n"); else{ top++; stack[top]=x; } } int pop(){ int ele; if(isempty()) printf("Stack underflow\n"); else{ ele=stack[top]; top--; } return ele; } void evaluate(char postfix[]){ char c; int a,b,res,i; for(i=0;postfix[i]!='#';i++){ if(isdigit(postfix[i])){ c=postfix[i]; push(c -'0'); } else if(postfix[i]=='+' || postfix[i]=='-' || postfix[i]=='*' || postfix[i]=='/'){ a=pop(); b=pop(); switch(postfix[i]){ case '+': res=a+b; break; case '-': res=a-b; break; case '*': res=a*b; break; case '/': res=a/b; break; } push(res); } } printf("VALUE OF POSTFIX EXPRESSION IS %d",res); } void main(){ int i; char postfix[30]; printf("Enter # to stop input\n"); printf("Enter a postfix expression\n"); for(i=0;postfix[i]!='#';i++){ scanf("%c",&postfix[i]); if(postfix[i]=='#') break; } evaluate(postfix); }
C
#ifndef _rle_ #define _rle_ // natty dread powered * void * RLE(void * bufSrc, uint *bufSize) { char *bufDst, *sBufPtr, *dBufPtr ; char value ; uint dBufASize, dBufSizeRemain ; long totalCount = *bufSize ; // asign control var with src buf size. uchar repeat ; void *rleBf ; dBufASize = dBufSizeRemain = ((*bufSize)*3)>>1 ; if((dBufPtr = bufDst = (char *)gm_malloc(dBufASize)) == NULL) return NULL ;// { showMsg("unable to alocate dest. buffer in RLE. bye !","error") ; return NULL ; } ; sBufPtr = (char*)bufSrc ; do { value = *sBufPtr ; sBufPtr++ ; (*bufSize)-- ; repeat=1 ; // get value from src buf while((*sBufPtr == value)&&(repeat < 63)&&(*bufSize>1)) // count sucessive same value number { repeat++ ; sBufPtr++ ; (*bufSize)-- ; } ; totalCount -= repeat ; // decrease Control var with the data number from src buf write in the dest buffer. //if(!repeat) showMsg("repeat found of 0 in RLE.","error") ; if((repeat>1)||((value & 0xC0) == 0xC0)) // if sucessiv value or if value use the 2 first bits, RLE { *dBufPtr = (0xC0 | repeat) ; dBufPtr++ ; // write RLE flag and repeat number *dBufPtr = value ; dBufPtr++ ; // write value to be repeteted dBufSizeRemain-=2 ; // decrese free size of the dest. buffer } else { *dBufPtr = value ; dBufPtr++ ; dBufSizeRemain-- ; } // no RLE, just copy (if !repeat, allready copy the data.) if(dBufSizeRemain < 10) // to less free buffer, need realloc. { return NULL ; } } while(*bufSize) ; // stop when finish read source buffer *bufSize = (dBufPtr - bufDst) ; // compute size used by RLE buffer rleBf = gm_malloc(*bufSize) ; memcpy(rleBf,bufDst,*bufSize); free(bufDst) ; return rleBf ; } void * unRLE(void * bufSrc, uint *rleSize, uint *unRleSize) { char *bufDst, *sBufPtr, *dBufPtr, *dBufEnd, value ; ushort repeat, show0error=0 ; uint * bufSize = rleSize ; int totalCount=1 ; uint size ; void * unrleBf ; if(unRleSize) { size = *unRleSize + *rleSize ; totalCount = *unRleSize ; } else size = (*rleSize)*4 ; dBufPtr = bufDst = (char *)malloc(size) ; if(!bufDst) error("alloc error in unRLE.") ; dBufEnd = bufDst + size ; sBufPtr = (char*)bufSrc ; do { value = *sBufPtr ; sBufPtr++ ; if ((value & 0xC0) == 0xC0) // 0xC0 = 11000000 -> rle { repeat = value & 0x3F ; // 0x3F = 00111111 -> count = 2^6 -1 = 63 continuous pixels max value = *sBufPtr ; sBufPtr++ ; // getvalue to repeat if(repeat) { if(unRleSize) totalCount-=repeat ; // write the repeted pixels while(repeat--) { *dBufPtr = value ; dBufPtr++ ; } ; } else if(!show0error) { error("read 0 as repeat in unRLE.") ; show0error++ ; } } else { *dBufPtr = value ; dBufPtr++ ; if(unRleSize) totalCount-- ; } // no rle, just copie value. if(dBufEnd - dBufPtr < 64) // to less free buffer, need realloc. { free(bufDst) ; error("too less buffer to continu unRLE."); return NULL ; /*uint dec, dec2 ; // up about 1ko dec = dBufPtr - bufDst ; dec2 = dBufEnd - bufDst ; if(!(dBufEnd = dBufPtr = bufDst = (char *)realloc(bufDst,dec2 + 10240))) error("error on realloc in unRLE.") ; dBufPtr+=dec ; dBufEnd += dec2+10240 ;*/ } } while((sBufPtr - (char*)bufSrc < *bufSize)&&(totalCount>0)) ; // exit on finish reading all the src buffer, or finish read the number who want. size = dBufPtr - bufDst ; if(!size) error("size of 0 in unRLE."); unrleBf = gm_malloc(size) ; if(!unrleBf) error("alloc error"); memcpy(unrleBf,bufDst,size); free(bufDst) ; if(unRleSize) *unRleSize = size ; else *rleSize = size ; return unrleBf ; // return the dest. buffer } #endif
C
#include "uart.h" #include <string.h> bool uartIsInit = _FALSE; void uartInit(void) { if (uartIsInit) { return; } SIM->SCGC |= SIM_SCGC_UART1_MASK; UART_MODULE->C1 = 0x00; UART_MODULE->C2 = UART_C2_TE_MASK | UART_C2_RE_MASK; // Transmit and receive UART_MODULE->BDH = UART_BDH_SBR(0); UART_MODULE->BDL = UART_BDL_SBR(11); uartIsInit = _TRUE; return; } void uartSend8(u8 data) { while (!(UART_MODULE->S1 & UART_S1_TDRE_MASK)) ; UART_MODULE->D = data; return; } void uartSendArray(char *arr, int size) { for (int i = 0; i < size; ++i) { uartSend8(arr[i]); } } void uartSendString(char *str) { uartSendArray(str, strlen(str)); } bool uartIsDataReady(void) { return (UART_MODULE->S1 & UART_S1_RDRF_MASK); } char uartRead(void) { return UART_MODULE->D; }
C
#include <stdio.h> char lower(const char c) { return c >= 'A' && c <= 'Z' ? c + 'a' - 'A' : c; } main() { char s[] = "CAPITAL"; for (int i = 0; s[i] != '\0'; ++i) s[i] = lower(s[i]); printf("%s\n", s); }
C
#define _XOPEN_SOURCE 500 // FTW flags #include <stdio.h> #include <stdlib.h> #include <malloc.h> // malloc functions #include <dirent.h> // dirent structure #include <sys/stat.h> // mkdir #include <errno.h> // to know which errors are raised #include <string.h> // string functions #include <ftw.h> //nftw dir traversal #include <unistd.h> // dir functions #include <sys/types.h> // for pwd functions #include "dirHelper.c" // split and trim functions char *path; void deleteIt(char *path, char flag); int removeFunction(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf); int recursiveRemove(char *path); int main(int argc,char **argv) { path = malloc(256); char **args; /** Checking argument is given or not **/ if(argc < 2) { printf("\nmyrm: missing operand\n\n"); } else if(argc == 2) { int tokens = split(argv[1], ' ', &args); //printf("%d\n", tokens); if(tokens == 1) { if(strcmp(args[0], "-r") == 0) printf("myrm: missing operand\n"); else deleteIt(args[0], 0); } else { int i; if(strcmp(args[0], "-r") == 0) { for(i = 1; i < tokens; i++) deleteIt(args[i], 1); } else { for(i = 0; i < tokens; i++) deleteIt(args[i], 0); } } } // This is used because our main function is using execvp() we are passing only one string with all arguments given to main function // So valid argc will be only one (if no arguments passed to main) or two else { printf("something went wrong args are not 2 %d\n",argc); } free(path); return 0; } /* This Function will remove files or directories if flag = 1 then remove recursive else flag = 0 then remove only */ void deleteIt(char *path, char flag) { // if dir then rmdir() is to be used if(isDir(path)) { DIR * dir = opendir(path); // checking if directory exist or not if(dir) { if( rmdir(path) != 0) { if(!flag) printf("myrm: cannot remove ‘%s’: %s\n", path, strerror(errno)); else if(errno == EEXIST || errno == ENOTEMPTY) { recursiveRemove(path); } } } else { printf("myrm: cannot remove '%s' : %s\n", path, strerror(errno)); } } // if file unlink() to be used else { // unlink is used to remove files if( unlink(path) != 0) printf("myrm: cannot remove ‘%s’: %s\n", path, strerror(errno)); } } /* Below functions are used to remove directory recursively if it is not empty */ /* Remove Recursive function */ int recursiveRemove(char *path) { /* nftw() walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree. It uses flags. FTW_DEPTH If set, do a post-order traversal, that is, call fn() for the directory itself after handling the contents of the directory and its subdirectories. (By default, each directory is handled before its contents.) */ return nftw(path, removeFunction, 64, FTW_DEPTH | FTW_PHYS); } // This function will be passed as argument to nftw int removeFunction(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int status = remove(fpath); if (status) printf("Unable to remove %s\n", fpath); return status; }
C
#include<stdio.h> #include<math.h> int main() { int x,y; int sonuc; printf("X uzeri y icin x ve y degerlerini giriniz:"); scanf("%d%d",&x,&y); sonuc=pow(x,y); printf("%d uzeri %d = %d",x,y,sonuc); getchar();getchar(); return 0; }
C
// // security.c // // // Created by Nguyen Trung Huan on 26/3/18. // #define BUFFER_LENGTH 100 #include <stdio.h> int main() { char guessedDateStr[BUFFER_LENGTH]; // to input string char guessedKeyStr[BUFFER_LENGTH]; // to input key int date; int key; // Preamble printf("I hope you are not an intruder...\n"); printf("Carefully enter my special day...\n"); printf("Hint: ZILLIONS of people showed up but the media fooled everyone otherwise\n"); // Check date int isDateCorrect = 0; while (isDateCorrect == 0) { printf("\nmmddyyyy : "); scanf("%s", guessedDateStr); if (strcmp(guessedDateStr, "01202017") == 0) { printf("Good job. Onto the next step!"); isDateCorrect = 1; } else { printf("It's a wrong date. Try harder\n"); } } date = atoi(guessedDateStr); // Produce key based on the correct date key = (date << 2) ^ date; printf("\nNow key in the secret key... Do you remember our favorite operations?\n"); int isKeyCorrect = 0; while (isKeyCorrect == 0) { printf("hex (starting with 0x) : "); scanf("%s", guessedKeyStr); int guessedKey = (int)strtol(guessedKeyStr, NULL, 16); if (key == guessedKey) { printf("Congratulations! The password is \"dear_putin\"\n"); isKeyCorrect = 1; } else { printf("Oh no... You can key in the secret key again\n"); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <pthread.h> #include <string.h> #include <videoBuffer.h> pthread_mutex_t videoListLock; void initVideoList(videoList *list) { list->head = NULL; list->tail = NULL; list->length = 0; } void clearVideoList(videoList *list) { videoBuffer *p = NULL; pthread_mutex_lock(&videoListLock); for(p = list->head; p != NULL; ) { videoBuffer *buf = p; p = p->next; free(buf->data); free(buf); } list->length = 0; pthread_mutex_unlock(&videoListLock); } int putVideoBuffer(videoList *list, unsigned char *dat, unsigned int len) { if(list->length >= V_LIST_LEN) { printf("buffer.c: length not enough overwrite!\n"); clearVideoList(list); } videoBuffer *buf = (videoBuffer *)malloc(sizeof(videoBuffer)); if(buf == NULL) { printf("Buffer.c: Memory not enough\n"); return -1; } buf->next = NULL; buf->data = (unsigned char *)malloc(len); buf->len = len; memcpy(buf->data, dat, len); buf->timestamp = 0; pthread_mutex_lock(&videoListLock); if(list->tail != NULL) list->tail->next = buf; list->tail = buf; if(list->length == 0) list->head = buf; list->length++; pthread_mutex_unlock(&videoListLock); return 0; } int getVideoBuffer(videoList *list, unsigned char *outdata, unsigned int *len) { if(list->length <= 0) return -1; pthread_mutex_lock(&videoListLock); if(list->head != NULL) { memcpy(outdata, list->head->data, list->head->len); *len = list->head->len; if(list->head != list->tail) { videoBuffer *temp = list->head; list->head = list->head->next; list->length--; free(temp->data); free(temp); } else { free(list->head->data); free(list->head); list->head = NULL; list->tail = NULL; list->length = 0; } } else { pthread_mutex_unlock(&videoListLock); return -1; } pthread_mutex_unlock(&videoListLock); return 0; }
C
#include <math.h> #include <stdint.h> #include <stdio.h> #include "geometry.h" #include "image.h" #include "luminance_probe.h" #include "multi_probe_least_squares.h" typedef struct { vec2_iterator_t parent; image_t *image; ls_probe_func_t probe; vec2_t *centers; unsigned samples; unsigned i; } least_squares_iterator_t; static int ls_iterator_next(vec2_iterator_t *_it, vec2_t *vec) { least_squares_iterator_t *it = (least_squares_iterator_t *) _it; if (it->i < it->samples) { *vec = it->probe(it->image, it->i, it->centers, it->samples); ++it->i; return 1; } return 0; } ray2_t least_squares_edge(image_t *image, ls_probe_func_t probe, vec2_t *centers, unsigned samples) { least_squares_iterator_t it = { .parent = { .next = ls_iterator_next }, .image = image, .probe = probe, .centers = centers, .samples = samples, .i = 0 }; return linear_regression(&it.parent); } void least_squares_box(vec2_t *centers, vec2_t *corners, image_t *image, unsigned samples) { ray2_t top = least_squares_top(image, centers, samples); ray2_t left = least_squares_left(image, centers, samples); ray2_t bottom = least_squares_bottom(image, centers, samples); ray2_t right = least_squares_right(image, centers, samples); corners[0] = solve_intersection(top, left); corners[1] = solve_intersection(left, bottom); corners[2] = solve_intersection(bottom, right); corners[3] = solve_intersection(right, top); } vec2_t least_squares_probe_top(image_t *image, unsigned i, vec2_t *centers, unsigned count) { vec2_t min = centers[1]; vec2_t max = centers[3]; float pos = min.x + (max.x - min.x) * (i + 1) / (count + 1); return luminance_probe_top(image, (unsigned) pos); } vec2_t least_squares_probe_left(image_t *image, unsigned i, vec2_t *centers, unsigned count) { vec2_t min = centers[0]; vec2_t max = centers[2]; float pos = min.y + (max.y - min.y) * (i + 1) / (count + 1); vec2_t p = luminance_probe_left(image, (unsigned) pos); float t = p.x; p.x = p.y; p.y = t; return p; } vec2_t least_squares_probe_bottom(image_t *image, unsigned i, vec2_t *centers, unsigned count) { vec2_t min = centers[1]; vec2_t max = centers[3]; float pos = min.x + (max.x - min.x) * (i + 1) / (count + 1); return luminance_probe_bottom(image, (unsigned) pos); } vec2_t least_squares_probe_right(image_t *image, unsigned i, vec2_t *centers, unsigned count) { vec2_t min = centers[0]; vec2_t max = centers[2]; float pos = min.y + (max.y - min.y) * (i + 1) / (count + 1); vec2_t p = luminance_probe_right(image, (unsigned) pos); float t = p.x; p.x = p.y; p.y = t; return p; } ray2_t least_squares_top(image_t *image, vec2_t *centers, unsigned samples) { return least_squares_edge(image, least_squares_probe_top, centers, samples); } ray2_t least_squares_left(image_t *image, vec2_t *centers, unsigned samples) { ray2_t r = least_squares_edge(image, least_squares_probe_left, centers, samples); r.angle = -(r.angle + asinf(1)); return r; } ray2_t least_squares_bottom(image_t *image, vec2_t *centers, unsigned samples) { return least_squares_edge(image, least_squares_probe_bottom, centers, samples); } ray2_t least_squares_right(image_t *image, vec2_t *centers, unsigned samples) { ray2_t r = least_squares_edge(image, least_squares_probe_right, centers, samples); r.angle = -(r.angle + asinf(1)); return r; }
C
#include<stdio.h> #define person 10 void main() { static int overtime[person]; int i,workinghour; for(i=0;i<person;i++) { printf("Enter the %d Working Hour :: ",(i+1)); scanf("%d",&workinghour); if(workinghour>40) overtime[i]=(workinghour-40)*12; printf("Overtime income for %d is RS. %d\n\n",i+1,overtime[i]); } printf("Exit\n"); }