language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/stat.h> //for file stats #include <unistd.h> //for checking file access #include <libgen.h> //for getting file name #include <openssl/sha.h> //for sha1 #include <sys/time.h> #include "Aufgabe2.h" #include "sender_tcp.h" int main (int argc, char *argv[]) { int sockfd, err; //int portno; //socklen_t clilength, length; struct sockaddr_in serv_addr; char buff[BUFFERSIZE]; //buffer for receiving messages (and later for sending as well) unsigned short nlength; //name length char *name; //name of file unsigned int filelength; //actual file size size_t bufferlength; //length of buffer that will be used for sending size_t readbytes; //number of bytes read by fread int fd; //file descriptor for getting length FILE* file; //file stream struct stat filebuf; //file stats unsigned int seqNr; //number of package to be sent //char filedatabuff[BUFFERSIZE-5]; //contains data of file int i; //magic number that makes the program work. char *shaBuffer; //holds the complete file across all data packages char *shaVal; //holds the actual sha1-value char *shaPtr; struct timeval timeout; /****** CHECK INPUT ********/ //check for right number of arguments if (argc != 4) { printf("Illegal Arguments: [RECEIVER_ADDRESS] [RECEIVER_PORT] [FILE PATH]"); exit(1); } //check if file exists and can be read if( access(argv[3], R_OK) == -1 ) { if( access(argv[3], F_OK) ) { printf("File does not exist"); } else { printf("No Read permission on file"); } return 1; } /******* OPEN FILE OPERATIONS *******/ //Open file, handle errors file = fopen(argv[3], "r"); if(!file) { printf("Illegal File"); return 1; } //Get file descriptor fd = fileno(file); if(fd == 0) { printf("File reading error"); return 1; } //Get file stats if(fstat(fd, &filebuf) != 0) { printf("File statistic read error"); return 1; } /**** READ FILE STATS ****/ //get length filelength = filebuf.st_size; //get file name without path name = basename(argv[3]); nlength = strlen(name); /******** SOCKET CREATION ***********/ // AF_INET --> Protocol Family // SOCK_DGRAM --> Socket Type (UDP) // 0 --> Protocol Field of the IP-Header (0, TCP and UDP gets entered automatically) sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { printf("Socket-Error"); exit(1); } // Clearing bzero(buff, BUFFERSIZE); bzero((char*) &serv_addr, sizeof(serv_addr)); //CREATE TARGET ADDRESS // Assign Protocol Family serv_addr.sin_family = AF_INET; // Assign Port serv_addr.sin_port = htons(atoi(argv[2])); // Address of the Receiver (Dotted to Network) serv_addr.sin_addr.s_addr = inet_addr(argv[1]); // Length of the Address Structure //length = sizeof(struct sockaddr_in); if(connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr))<0) { printf(address_error); return 1; } /********* HEADER SENDING *********/ // To satisfy the MTU of a PPPoE-Connection (max package size) if ((bufferlength = nlength + 6) > BUFFERSIZE) { printf("Exceeded maximum package size."); return 1; } prepareHeader(buff, nlength, name, filelength); printf(filename_str, name); printf(filesize_str,filelength); printf("Standby for sending of header...\n"); //send err = write(sockfd, buff, bufferlength); //handle sending errors if (err < 0) { printf("sendto-Error"); exit(1); } printf("Sent %d bytes\n", err); /******* FILE TRANSFER ********/ //reset sequence number seqNr = 0; //prepare Sha shaBuffer = calloc((size_t) filelength, 1); if(!shaBuffer) { printf("Could not allocate shaBuffer\n"); return 1; } shaPtr = shaBuffer; printf("Commencing file transmission\n"); do { //buff[0] = DATA_T; //Yes, we're sending data! //put sequence number into next 4 bytes of buffer /*for(i = 1; i < 5; i++) { buff[i] = (char) ( (seqNr >> ( (i-1)*8) ) & 0xff ); }*/ //check how many files could be read. Is less than BUFFERSIZE-5 when eof is reached readbytes = fread(buff, 1, BUFFERSIZE, file); //transmit if we have any bytes to transmit if(readbytes != 0) { //put filebuffer into real buffer. Can't concat because buff is not really a string and can have null anywhere... for(i = 0; i<readbytes; i++) { *(shaPtr++)=buff[i]; } //Send data. err = write(sockfd, buff, readbytes); if( err != readbytes ) { printf("Sending data package %d failed",seqNr); return 1; } printf("Sent package %d containing %zu bytes\n", seqNr, readbytes); } seqNr++; }while(readbytes == BUFFERSIZE); //once readbytes is less than BUFFERSIZE eof was reached and we're finished. printf("File transmission complete\n"); /******* SHA-1 ********/ //if we don't do this then valgrind on the receiver causes the program to slow down too much to still get this sleep(2); printf("Calculating Sha1...\n"); //calculate sha-1 shaVal = getSha1(shaBuffer, filelength); printf(sender_sha1, shaVal); //prepare transmitting of sha-1 //buff[0] = SHA1_T; for(i = 0; i<SHA_DIGEST_LENGTH*2; i++) { buff[i] = shaVal[i]; } //transmit sha-1 err = write(sockfd, buff, SHA_DIGEST_LENGTH*2); if( err != SHA_DIGEST_LENGTH*2 ) { printf("Error when sending SHA1"); return 1; } printf(SHA1_OK); /****** RECEIVE SHA COMPARE RESULT ******/ timeout.tv_sec = WAIT; timeout.tv_usec = 0; // Set socket options for a possible timeout setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); //receive sha comp result err = read(sockfd, buff, BUFFERSIZE); if (err != 1) { printf(timeout_error); exit(1); } //check header /*if((unsigned char)buff[0] != SHA1_CMP_T) { printf(SHA1_ERROR); }*/ //check actual compare result if( (unsigned char)buff[0] == SHA1_CMP_ERROR) { printf(SHA1_ERROR); } else { printf(SHA1_OK); } /******** CLEAN UP *******/ // Close Socket close(sockfd); fclose(file); free(shaBuffer); free(shaVal); return 0; } void prepareHeader(char *buffer, unsigned short nlength, char *name, unsigned int filelength) { unsigned short i,j; //TYPE-ID //buffer[0] = (char) HEADER_T; //name-length buffer[0] = (char) (nlength & 0xff); buffer[1] = (char) ((nlength >> 8) & 0xff); //name for(i=2; i<nlength+2; i++) { buffer[i] = name[i-2]; } //filesize for(j = 0; j < 4; j++) { buffer[i++] = (char) ( (filelength >> (j*8) ) & 0xff ); } }
C
#include<stdio.h> int main() { int choice,n,i; float a,b, ans=0; printf("**********Simple calculator**********\n"); printf("Make your choice: \n1. press '1' for addition\n2. press '2' for subtraction\n3. press '3' for multiplication\n4. press '4' for division\n"); scanf("%d",&choice); if (choice==3 || choice== 4){ printf("Enter operand 1:"); scanf("%f",&a); printf("Enter operand 2:"); scanf("%f",&b); switch(choice) { case 3: printf("%f",(a*b)); break; case 4: printf("%f",(a/b)); break; } } else if (choice == 1 || choice == 2){ printf("Enter the total number of operands: "); scanf("%d",&n); float arr[n]; for (int i=0; i<n; i++) { printf("Enter operand %d: ",i); scanf("%f",&arr[i]); printf("\n"); } switch(choice) { case 1: for(i=0; i<n; i++){ ans = ans + arr[i]; } printf("Answer: %f",ans); break; case 2: ans = arr[0]; for(i=1; i<=n; i++){ ans = ans - arr[i]; } printf("Answer: %f",ans); break; } } else { printf("Invalid Input"); } }
C
#ifndef projet1c_h #define projet1c_h // Bibliothèques #define MAX_BLOCK 5 #define INJOUABLE -1 #define LIBRE 0 #define OCCUPE 1 #define LIGNE 0 #define COLONNE 1 #include <stdio.h> #include <stdlib.h> #include <time.h> // Fonctions de bases int** create_2D_Array(int nb_lig, int nb_col); void fill_2D_plateau_Carre(int** P, int nb_lig, int nb_col); void fill_Forme_T(int** P, int nb_lig, int nb_col); void display_2D_array(int** P, int nb_lig, int nb_col); void display_ascii(int** P, int nb_lig, int nb_col); void depose_block(int** P, int nb_lig, int nb_col, int** B, int Px, int Py, int size); void getDim2Darray(int *l, int*c); void free_2D_array(int **A, int l, int c); // gestion des blocks typedef struct Block { int appartenance; int** content; int size; }Block; typedef struct Blocks { Block* blocks; int size; }Blocks; Blocks getBlocks(int forAppartenance); Blocks getStandardizedBlocks(int forAppartenance); Block convertBlock(Block block); int getSize(int forAppartenance); void printBlock(Block block); void fillBlock(Block* s1, int content[][5]); void printBlocks(Blocks blocks); void printBlocker(Block block); #endif /* projet1c_h */
C
#include <stdio.h> #include <omp.h> int main() { int read,writ,readcount=0,value=0; printf("Enter the number of readers\n"); scanf("%d",&read); printf("Enter the number of writers\n"); scanf("%d",&writ); omp_set_num_threads(read+writ); omp_lock_t wlock,rlock; omp_init_lock(&wlock); omp_init_lock(&rlock); #pragma omp parallel { if(omp_get_thread_num()<read) { int i = 5; do { omp_set_lock(&rlock); readcount++; if(readcount==0) omp_set_lock(&wlock); printf("Value read by thread %d is %d\n",omp_get_thread_num()+1,value); omp_unset_lock(&rlock); omp_set_lock(&rlock); readcount--; if(readcount==0) omp_unset_lock(&wlock); omp_unset_lock(&rlock); }while(i--); } else { int i = 5; do { omp_set_lock(&wlock); value ++; //printf("Writer %d has written value %d\n",omp_get_thread_num()-read+1,value); omp_unset_lock(&wlock); }while(i--); } } }
C
#include <string.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include "../include/text_buffer.h" #include "../include/utf8.h" #include "../include/utf8_buffer.h" utf8_buffer * utf8_buffer_new(int capacity) { return text_buffer_new(capacity); } void utf8_buffer_destroy(utf8_buffer * buf) { text_buffer_destroy(buf); } utf8_buffer * utf8_buffer_add(utf8_buffer * buf, const char * data, int length) { return text_buffer_add(buf,data,length); } void utf8_buffer_clear(utf8_buffer *buf) { text_buffer_clear(buf); } const char * utf8_buffer_data(const utf8_buffer * buf) { return text_buffer_data(buf); } void utf8_buffer_remove(utf8_buffer * buf, int chars) { const char * data = text_buffer_data(buf); int length = text_buffer_length(buf); int i = length-1; for(; chars > 0; chars--){ for(;i >= 0; i--){ if((data[i] & 0xC0) != 0x80){ i--; break; } } } text_buffer_remove(buf,length - 1 - i); } int utf8_buffer_get(const utf8_buffer * buf, int pos, uint32_t * codepoint) { const char * data = text_buffer_data(buf); return tb_utf8_char_to_unicode(codepoint, &data[pos]); } utf8_iter utf8_iter_new(const char * s){ return (utf8_iter) { .buf = s, .offset = 0 }; } uint32_t utf8_iter_next(utf8_iter * it){ uint32_t res; int off = tb_utf8_char_to_unicode(&res, &it->buf[it->offset]); if(off == TB_EOF) return 0; it->offset += off; return res; }
C
#include <pthread.h> #include <unistd.h> int numero =4; pthread_mutex_t mutex; typedef struct params { int n; }param; void * duplicaN(void *p) { pthread_mutex_lock(&mutex); int i; int temp = numero; for(i =0; i < ((param*)p)->n; i++) { temp *= 2; printf("Duplica %d \n", temp); sleep(5); } numero = temp; pthread_mutex_unlock(&mutex); pthread_exit(NULL); } void * divideN(void *p) { pthread_mutex_lock(&mutex); int i; int temp = numero; for(i = 0; i < ((param *)p)->n; i++) { temp /= 2; printf("Divide %d \n", temp); sleep(5); } numero = temp; pthread_mutex_unlock(&mutex); pthread_exit(NULL); } int main() { pthread_t hilo1; pthread_t hilo2; param p; p.n = 5; pthread_create(&hilo1, NULL, duplicaN, &p); pthread_create(&hilo2, NULL, divideN, &p); pthread_join(hilo1, NULL); pthread_join(hilo2, NULL); }
C
#include <stdio.h> #include <string.h> typedef unsigned char *byte_pointer; void show_bytes(byte_pointer start, size_t len) { int i; for (i = 0; i < len; i++) printf(" %.2x", start[i]); printf("\n"); } int main(int argc, char *argv[]) { const char *m = "mnopqr"; show_bytes((byte_pointer) m, strlen(m)); }
C
#include <stdio.h> int main(void) { int m,i; int a[5]={2,1,2,1,5}; int flag; for(i=0;i<5;i=i+m) { m=a[i]; if(i==4) { flag=0; } } if(flag==0) { printf("true"); } else { printf("false"); } return 0; }
C
/************************************************************************* > File Name: ER-45.c > Author: liqiang > Mail: 1398690148@qq.com > Created Time: 2019年07月29日 星期一 19时02分45秒 ************************************************************************/ #include <stdio.h> #include <inttypes.h> int64_t Triangle(int64_t n) { return n * (n + 1) / 2; } int64_t Pentagonal(int64_t n) { return n * (3 * n - 1) / 2; } int64_t Hexagonal(int64_t n) { return n * (2 * n - 1); } int binary_search(int64_t (*func)(int64_t), int64_t y) { int64_t head = 1, tail = y, mid; while (head <= tail) { mid = (head + tail) >> 1; if (func(mid) == y) return mid; else if (func(mid) < y) head = mid + 1; else tail = mid - 1; } return -1; } int main() { int n = 144; for(;; n++) { if(binary_search(Triangle, Hexagonal(n)) == -1) continue; if(binary_search(Pentagonal, Hexagonal(n)) == -1) continue; printf("%" PRId64 "\n", Hexagonal(n)); break; } return 0; }
C
#include <stdlib.h> #ifndef HASH_TABLE_H #define HASH_TABLE_H #endif #define NO_KEY -1 #define NOT_FOUND -1 /* Intially a hash table is created with a given size. We don't change the size since. In case of collision we simply chain it at the position determined by the hash function. +---------+ | key |---> next | value | +---------+ | key |--> next | value | +---------+ . . "size" elements . . . . +---------+ | key | | Value |---> next +---------+ */ // Each Node in the hash table contains a key, value and pointer to next node. // The next node points to the head of chain (The chain is formed in case of collision). // typedef struct HashNode{ int key; int value; struct HashNode* next; } HashNode; // Hash table which contains a array of hash nodes as depicted above typedef struct HashTable{ HashNode * hashNode; size_t size; int p; // Used in hash computation } HashTable; HashTable* createHashTable(size_t tableSize); void insertHashNode(HashTable* hashTable, int key, int value); int searchHashTable(HashTable* hashTable, int key); void deleteHashNode(HashTable* hashTable, int key); void delsertHashNode(HashTable* hashTable, int oldKey, int newKey, int newValue); HashNode* getHashNode(HashTable* hashTable, int key); size_t hashOfKey(HashTable *hashTable, int key); void destroyHashTable(HashTable* hashTable);
C
#include "polygon.h" Polygon polygon_create(int num_points, Point points[]) { Polygon poly = {num_points, NULL}; if (num_points >= 3) { poly.points = calloc(num_points, sizeof(Point)); int i; for (i = 0 ; i < num_points ; ++i) { poly.points[i] = points[i]; } } return poly; } double polygon_get_minx(Polygon poly) { int i; double minx = poly.points[0].x; for (i = 1 ; i < poly.num_points ; ++i) { if (poly.points[i].x < minx) { minx = poly.points[i].x; } } return minx; } double polygon_get_maxx(Polygon poly) { int i; double maxx = poly.points[0].x; for (i = 1 ; i < poly.num_points ; ++i) { if (poly.points[i].x > maxx) { maxx = poly.points[i].x; } } return maxx; } double polygon_get_miny(Polygon poly) { int i; double miny = poly.points[0].y; for (i = 1 ; i < poly.num_points ; ++i) { if (poly.points[i].y > miny) { miny = poly.points[i].x; } } return miny; } double polygon_get_maxy(Polygon poly) { int i; double maxy = poly.points[0].y; for (i = 1 ; i < poly.num_points ; ++i) { if (poly.points[i].y > maxy) { maxy = poly.points[i].x; } } return maxy; } int polygon_get_line_intersect_count(Polygon poly, Line l) { // construct edges Line *edges = calloc(poly.num_points, sizeof(Line)); int i; for (i = 0 ; i < poly.num_points ; ++i) { if (i != poly.num_points -1) edges[i] = line_create(poly.points[i], poly.points[i+1]); else edges[i] = line_create(poly.points[i], poly.points[0]); } int count = 0; for (i = 0 ; i < poly.num_points ; ++i) { if (line_intersect(edges[i], l)) ++ count; } free(edges); return count; } bool polygon_point_is_in(Polygon poly, Point point) { const double size = (polygon_get_maxx(poly) - polygon_get_minx(poly)) * (polygon_get_maxy(poly) - polygon_get_miny(poly)); const double ray_length = size * size; double theta = 2 * PI * ((rand() % 10000) / 10000); Point p2 = {point.x + ray_length * cos(theta), point.y + ray_length * sin(theta)}; Line ray = line_create(point, p2); int count = polygon_get_line_intersect_count(poly, ray); while (count == 0) { theta = 2 * PI * ((rand() % 10000) / 10000); p2 = point_create(point.x + ray_length * cos(theta), point.y + ray_length * sin(theta)); ray = line_create(point, p2); count = polygon_get_line_intersect_count(poly, ray); } if (count % 2 == 1) return 1; return 0; } void polygon_release(Polygon poly) { if (poly.points) { free(poly.points); } }
C
#ifndef _CLIENT #define _CLIENT #include "functions.h" int main(int argc, char **argv){ launch_serv_if_abs(); int srv_fd = open(MAIN_PIPE, O_WRONLY); exit_if(srv_fd == -1, "Main pipe open"); // Open fifo file in read only #ifdef DEBUG printf("DEBUG : fifo file %s is open for write\n", MAIN_PIPE); #endif send_hello(srv_fd); char path_pid_pipe[100]; sprintf(path_pid_pipe,"%s/%d",PIPE_PATH,getpid()); #ifdef DEBUG printf("DEBUG : FILE PATH = %s\n", path_pid_pipe); #endif exit_if(mkfifo(path_pid_pipe, 0666)==-1,"mkfifo"); // Create pid chat file #ifdef DEBUG printf("DEBUG : fifo file opened\n"); #endif int fork_rtn; switch (fork_rtn = fork()){ case -1: { exit_if(1,"fork"); } break; case 0: { // C'est le fils /!!\ NOUVEAU PID - Reader redirect_ctrl_c(); int my_fd = open(path_pid_pipe, O_RDONLY); exit_if(my_fd == -1, path_pid_pipe); // Open fifo file in read only int rmt_pid = 0; int data_len = 0; char *rec_msg = NULL; char *data_c = NULL; while(1){ data_len = pipe_input(my_fd,&rec_msg); #ifdef DEBUG printf("\nDEBUG : Received %d bytes : \"%s\"\n",data_len ,rec_msg); #endif //// Pid calculation rmt_pid = get_pid(rec_msg); // Pid calculation //// Len & Data calculation data_len = get_data(rec_msg, &data_c); printf("\n\n// Data received ! \\\\\n From pid = %d\n Data_len = %d\n Data = \"%s\"\n\\\\ End of data //\n",rmt_pid, data_len,data_c); printf("%s",prompt); free(rec_msg); free(data_c); fflush(stdout); } } break; default: { // C'est le papa - Sender char buffer_nickname[MAX_NICK_SIZE]; int nick_size = choose_nick(buffer_nickname); while(!nick_size){ printf("Nickname cannot be empty"); nick_size = choose_nick(buffer_nickname); } char buffer_sd_n[100]; int n = snprintf(buffer_sd_n, sizeof(buffer_sd_n),"%d,%d,/nick %s", getpid(), nick_size+6, buffer_nickname); int rtn_val = send_to_server(srv_fd,buffer_sd_n,n); exit_if(rtn_val != 0,"send to server"); char *message = NULL; char *buffer = NULL; int len; while(1){ redirect_ctrl_c_wait(); printf("%s",prompt); fflush(stdout); len = data_input_key(&buffer); // Blocking read function if(len==-1) { printf("Keyboard error\n"); kill(fork_rtn,SIGINT); exit(EXIT_FAILURE); } int msg_size = strlen(buffer)+100; // Will be enough message = malloc(msg_size); if(message==NULL) { printf("malloc failed\n"); kill(fork_rtn,SIGINT); exit(EXIT_FAILURE); } n = snprintf(message, msg_size,"%d,%lu,%s", getpid(), strlen(buffer), buffer); if(len-1){ if(send_to_server(srv_fd, message, n) != 0) { printf("write error\n"); kill(fork_rtn,SIGINT); exit(EXIT_FAILURE); } #ifdef DEBUG printf("DEBUG : %d bytes sent : \"%s\"\n",n,buffer); #endif free(message); free(buffer); } } } break; } return 0; } #endif
C
/* * Command line interface, used under the DADT license */ #ifndef CLI_H #define CLI_H /* * Configuration */ #define configCOMMAND_INT_MAX_OUTPUT_SIZE 255 /* * Port */ #define portBASE_TYPE unsigned #define pdTRUE 1 #define pdFALSE 0 #define pdPASS 1 #define pdFAIL 0 #define pvPortMalloc malloc #define taskENTER_CRITICAL() #define taskEXIT_CRITICAL() /* The prototype to which callback functions used to process command line commands must comply. pcWriteBuffer is a buffer into which the output from executing the command can be written, xWriteBufferLen is the length, in bytes of the pcWriteBuffer buffer, and pcCommandString is the entire string as input by the user (from which parameters can be extracted).*/ typedef portBASE_TYPE (*pdCOMMAND_LINE_CALLBACK)( int8_t *pcWriteBuffer, size_t xWriteBufferLen, const int8_t * pcCommandString ); /* The structure that defines command line commands. A command line command should be defined by declaring a const structure of this type. */ typedef struct xCOMMAND_LINE_INPUT { const int8_t * const pcCommand; /* The command that causes pxCommandInterpreter to be executed. For example "help". Must be all lower case. */ const int8_t * const pcHelpString; /* String that describes how to use the command. Should start with the command itself, and end with "\r\n". For example "help: Returns a list of all the commands\r\n". */ const pdCOMMAND_LINE_CALLBACK pxCommandInterpreter; /* A pointer to the callback function that will return the output generated by the command. */ int8_t cExpectedNumberOfParameters; /* Number of parameters, which may be zero or -1 for variable number of paramter */ } CLI_Command_Definition_t; /* For backward compatibility. */ #define xCommandLineInput CLI_Command_Definition_t /* * Register the command passed in using the pxCommandToRegister parameter. * Registering a command adds the command to the list of commands that are * handled by the command interpreter. Once a command has been registered it * can be executed from the command line. */ portBASE_TYPE CLIRegisterCommand( const CLI_Command_Definition_t * const pxCommandToRegister ); /* * Runs the command interpreter for the command string "pcCommandInput". Any * output generated by running the command will be placed into pcWriteBuffer. * xWriteBufferLen must indicate the size, in bytes, of the buffer pointed to * by pcWriteBuffer. * * CLIProcessCommand should be called repeatedly until it returns pdFALSE. * * pcCmdIntProcessCommand is not reentrant. It must not be called from more * than one task - or at least - by more than one task at a time. */ portBASE_TYPE CLIProcessCommand( const int8_t * const pcCommandInput, int8_t * pcWriteBuffer, size_t xWriteBufferLen ); /*-----------------------------------------------------------*/ /* * A buffer into which command outputs can be written is declared in the * main command interpreter, rather than in the command console implementation, * to allow application that provide access to the command console via multiple * interfaces to share a buffer, and therefore save RAM. Note, however, that * the command interpreter itself is not re-entrant, so only one command * console interface can be used at any one time. For that reason, no attempt * is made to provide any mutual exclusion mechanism on the output buffer. * * CLIGetOutputBuffer() returns the address of the output buffer. */ int8_t *CLIGetOutputBuffer( void ); /* * Return a pointer to the xParameterNumber'th word in pcCommandString. */ const int8_t *CLIGetParameter( const int8_t *pcCommandString, portBASE_TYPE uxWantedParameter, portBASE_TYPE *pxParameterStringLength ); #endif /* CLI_H */
C
#include <stdlib.h> #include "holberton.h" /** * _calloc - character allocate * Description: Allocates memory for an array and sets each element to zero * @nmemb: Number of elements in the array * @size: Size of each element * Return: Pointer to allocated memory, or NULL if unsuccessful. */ void *_calloc(unsigned int nmemb, unsigned int size) { char *pointer; unsigned int index; if (nmemb == 0 || size == 0) return (NULL); pointer = malloc(nmemb * size); if (pointer == NULL) return (NULL); for (index = 0; index < nmemb * size; index++) *(pointer + index) = 0; return ((void *)pointer); }
C
#include<stdio.h> int main(){ int num,i; FILE *fp; fp = fopen("Tables.txt","w"); printf("Enter the number you want table of:"); scanf("%d",&num); fprintf(fp,"Table of %d\n",num); for(i=0;i<10;i++){ fprintf(fp,"%d * %d = %d\n",num,i+1,num * (i+1)); } //fclose(fp); return 0; }
C
// Sum of numbers #include <stdio.h> #include <pthread.h> #include <stdlib.h> struct arg_struct { int a[100]; int n; }; void* child_thread(void *param) { struct arg_struct *args = (struct arg_struct *) param; int sum = 0; for(int i = 0; i < args->n; i++) { if(args->a[i] >= 0) sum += args->a[i]; } return (void *)sum; } int main() { struct arg_struct *args = (struct arg_struct *) malloc(sizeof(struct arg_struct)); printf("n = "); scanf("%d", &args->n); int i = 0; for(; i < args->n; i++) { scanf("%d", &args->a[i]); } int sum; pthread_t thread; pthread_create(&thread, 0, &child_thread, (void *)args); pthread_join(thread, (void **)&sum); printf("The sum is = %d\n", sum); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* actions3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mabuchar <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/13 22:30:55 by mabuchar #+# #+# */ /* Updated: 2021/09/13 22:30:58 by mabuchar ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/push_swap.h" /*----------------------------------------------------------------------*/ t_stack *ft_reverse_rotate_a(t_stack *stack, int index) { int a; if (is_empty_dlist(stack->lia) || stack->lia->end->back == NULL) return (stack); a = stack->lia->end->value; stack->lia = dlist_pop_back(stack->lia); stack->lia = dlist_push_front(stack->lia, a); if (index == 1) ft_putstr_fd("rra\n", 1); return (stack); } /*----------------------------------------------------------------------*/ t_stack *ft_reverse_rotate_b(t_stack *stack, int index) { int b; if (is_empty_dlist(stack->lib) || stack->lib->end->back == NULL) return (stack); b = stack->lib->end->value; stack->lib = dlist_pop_back(stack->lib); stack->lib = dlist_push_front(stack->lib, b); if (index == 1) ft_putstr_fd("rrb\n", 1); return (stack); } /*----------------------------------------------------------------------*/ t_stack *ft_reverse_rotate_rrr(t_stack *stack) { stack = ft_reverse_rotate_a(stack, 0); stack = ft_reverse_rotate_b(stack, 0); ft_putstr_fd("rrr\n", 1); return (stack); }
C
#include<stdio.h> #include<string.h> int main() { char str1[100],str2[100]; int count=0; printf("enter main string:"); scanf("%s",&str1[0]); printf("enter substring:"); scanf("%s",&str2[0]); int len1 = strlen(str1); printf("len1=%d\t",len1); int len2 = strlen(str2); printf("len2:%d\n",len2); for(int i=0;i<=len1-len2;i++) { int j; for(j=0;j<len2;j++) if(str1[i+j] != str2[j]) break; if(j==len2) { count ++; j=0; } } printf("%s occrs %dtimes\n",str2,count); }
C
/* Class: State Member Function: testCheckWhite Checks if the king of current player is in check or not. Return true or false. */ bool State::testCheckWhite(){ // Get the current position of the King pair<int, char> pos = White.getPosFromPiece("K"); int r = pos.first; char c = pos.second; int i = r + 1; char ch = c; while(i <= 8 && colorOfPiece[ make_pair(i, ch) ] == 0) i += 1; if(i <= 8 && colorOfPiece[ make_pair(i, ch) ] == -1){ if(i == r + 1 && chessBoard[ make_pair(i, ch) ] == "K") return 1; if(chessBoard[ make_pair(i, ch) ][0] == 'Q' || chessBoard[ make_pair(i, ch) ][0] == 'R') return 1; } i = r - 1; while(i >= 1 && colorOfPiece[ make_pair(i, ch) ] == 0) i -= 1; if(i >= 1 && colorOfPiece[ make_pair(i, ch) ] == -1){ if(i == r - 1 && chessBoard[ make_pair(i, ch) ] == "K") return 1; if(chessBoard[ make_pair(i, ch) ][0] == 'Q' || chessBoard[ make_pair(i, ch) ][0] == 'R') return 1; } i = r, ch = c + 1; while(ch <= 'h' && colorOfPiece[ make_pair(i, ch) ] == 0) ch += 1; if(ch <= 'h' && colorOfPiece[ make_pair(i, ch) ] == -1){ if(ch == c + 1 && chessBoard[ make_pair(i, ch) ] == "K") return 1; if(chessBoard[ make_pair(i, ch) ][0] == 'Q' || chessBoard[ make_pair(i, ch) ][0] == 'R') return 1; } ch = c - 1; while(ch >= 'a' && colorOfPiece[ make_pair(i, ch) ] == 0) ch -= 1; if(ch >= 'a' && colorOfPiece[ make_pair(i, ch) ] == -1){ if(ch == c - 1 && chessBoard[ make_pair(i, ch) ] == "K") return 1; if(chessBoard[ make_pair(i, ch) ][0] == 'Q' || chessBoard[ make_pair(i, ch) ][0] == 'R') return 1; } i = r + 1, ch = c + 1; while(i <= 8 && ch <= 'h' && colorOfPiece[ make_pair(i, ch) ] == 0) i += 1, ch += 1; if(i <= 8 && ch <= 'h' && colorOfPiece[ make_pair(i, ch) ] == -1){ if(i == r + 1 && ch == c + 1 && (chessBoard[ make_pair(i, ch) ][0] == 'K' || chessBoard[ make_pair(i, ch) ][0] == 'P') ) return 1; if(chessBoard[ make_pair(i, ch) ][0] == 'Q' || chessBoard[ make_pair(i, ch) ][0] == 'B') return 1; } i = r + 1, ch = c - 1; while(i <= 8 && ch >= 'a' && colorOfPiece[ make_pair(i, ch) ] == 0) i += 1, ch -= 1; if(i <= 8 && ch >= 'a' && colorOfPiece[ make_pair(i, ch) ] == -1){ if(i == r + 1 && ch == c - 1 && (chessBoard[ make_pair(i, ch) ][0] == 'K' || chessBoard[ make_pair(i, ch) ][0] == 'P') ) return 1; if(chessBoard[ make_pair(i, ch) ][0] == 'Q' || chessBoard[ make_pair(i, ch) ][0] == 'B') return 1; } i = r - 1, ch = c + 1; while(i >= 1 && ch <= 'h' && colorOfPiece[ make_pair(i, ch) ] == 0) i -= 1, ch += 1; if(i >= 1 && ch <= 'h' && colorOfPiece[ make_pair(i, ch) ] == -1){ if(i == r - 1 && ch == c + 1 && chessBoard[ make_pair(i, ch) ][0] == 'K') return 1; if(chessBoard[ make_pair(i, ch) ][0] == 'Q' || chessBoard[ make_pair(i, ch) ][0] == 'B') return 1; } i = r - 1, ch = c - 1; while(i >= 1 && ch >= 'a' && colorOfPiece[ make_pair(i, ch) ] == 0) i += 1, ch -= 1; if(i >= 1 && ch >= 'a' && colorOfPiece[ make_pair(i, ch) ] == -1){ if(i == r - 1 && ch == c - 1 && chessBoard[ make_pair(i, ch) ][0] == 'K' ) return 1; if(chessBoard[ make_pair(i, ch) ][0] == 'Q' || chessBoard[ make_pair(i, ch) ][0] == 'B') return 1; } int x[] = {-2, -2, -1, -1, 1, 1, 2, 2}; int y[] = {1, -1, -2, 2, -2, 2, 1, -1}; for(int i = 0; i < 8; i++){ if(x[i] + r >= 1 && x[i] + r <= 8 && y[i] + c >= 'a' && y[i] + c <= 'h'){ if(colorOfPiece[ make_pair(x[i] + r, y[i] + c) ] == -1 && chessBoard[ make_pair(x[i] + r, y[i] + ch) ][0] == 'N') return 1; } } return 0; }
C
/****************************************************************************** QUEUE ADT Type definitions and function prototypes for the queue ADT Written by: Iain S. Davis Date: 11 Jun 2013 *******************************************************************************/ #include <stdio.h> #include <stdlib.h> //Global Type Definitions/////////////////////////////////////////////////////// typedef struct queue_node { void *dataPtr; struct queue_node *next; }QUEUE_NODE; typedef struct { QUEUE_NODE *front; QUEUE_NODE *rear; int count; }QUEUE; //Prototype Declarations//////////////////////////////////////////////////////// QUEUE *createQueue (void); QUEUE *destroyQueue (QUEUE *queue); void flushQueue (QUEUE *queue); int dequeue (QUEUE *queue, void **itemPtr); int enqueue (QUEUE *queue, void *itemPtr); int queueFront (QUEUE *queue, void **itemPtr); int queueRear (QUEUE *queue, void **itemPtr); int queueCount (QUEUE *queue); int emptyQueue (QUEUE *queue); int fullQueue (QUEUE *queue);
C
// Author: Anthony Huynh // Class: CS 344 // Project: Program 2 - adventure // Date Due: 11/1/2019 //outline from https://oregonstate.instructure.com/courses/1738958/pages/2-dot-2-program-outlining-in-program-2 was used #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <fcntl.h> //constant definitions #define LONGEST_ROOM_NAME_LENGTH 9 //will allow 8 characters plus null #define MAX_CONNECTIONS 6 #define MIN_CONNECTIONS 3 #define TOTAL_ROOMS 10 #define ROOMS_TO_CREATE 7 #define FILE_SUFFIX "_room" #define LONGEST_DIRECTORY_NAME_LENGTH 100 enum bool {false = 0, true = 1}; struct Room { char name[LONGEST_ROOM_NAME_LENGTH]; char type[11]; struct Room *connections[MAX_CONNECTIONS]; int numConnections; }; void createRoom(struct Room*, char[TOTAL_ROOMS][LONGEST_ROOM_NAME_LENGTH], char*, int*); void createFile(struct Room*); enum bool isGraphFull(struct Room**); void addRandomConnection(struct Room**); struct Room* getRandomRoom(struct Room**); enum bool canAddConnectionFrom(struct Room*); enum bool connectionAlreadyExists(struct Room*, struct Room*); void connectRoom(struct Room*, struct Room*); enum bool isSameRoom(struct Room*, struct Room*); int main(int argc, char* argv[]) { srand(time(0)); //list of possible room names char roomNames[TOTAL_ROOMS][LONGEST_ROOM_NAME_LENGTH] = { "UnderSea", "Lava", "Darkness", "WanoKuni", "Galar", "Hyrule", "Magnolia", "Wakanda", "Tropical", "Yorknew" }; //array to hold pointers to each room and allocates memory struct Room *roomsToTraverse[ROOMS_TO_CREATE]; int i; for (i = 0; i < ROOMS_TO_CREATE; i++) { roomsToTraverse[i] = malloc(sizeof(struct Room)); } //array used to keep track of which room name was already used, initializes to 0 int roomsCreated[TOTAL_ROOMS]; for (i = 0; i < TOTAL_ROOMS; i++) { roomsCreated[i] = 0; } //creates all the rooms createRoom(roomsToTraverse[0], roomNames, "START_ROOM", roomsCreated); for (i = 1; i < ROOMS_TO_CREATE - 1; i++) { createRoom(roomsToTraverse[i], roomNames, "MID_ROOM", roomsCreated); } createRoom(roomsToTraverse[ROOMS_TO_CREATE - 1], roomNames, "END_ROOM", roomsCreated); // Create all connections in graph while (isGraphFull(roomsToTraverse) == false){ addRandomConnection(roomsToTraverse); } //gets current process id pid_t processId; processId = getpid(); //creates array of characters and initializes to null char directoryName[LONGEST_DIRECTORY_NAME_LENGTH]; memset(directoryName, '\0', sizeof(directoryName)); //fills array with name of directory and process id snprintf(directoryName, sizeof(directoryName), "huynhant.rooms.%d", processId); //makes directory mkdir(directoryName, 0700); //moves to new directory chdir(directoryName); //creates new file for each room for (i = 0; i < ROOMS_TO_CREATE; i++) { createFile(roomsToTraverse[i]); } //frees memory used by rooms array i = 0; for (i; i < ROOMS_TO_CREATE; i++) { free(roomsToTraverse[i]); } return 0; } //creates a room void createRoom(struct Room* roomPtr, char roomNames[TOTAL_ROOMS][LONGEST_ROOM_NAME_LENGTH], char* roomType, int* roomsCreated) { int roomNumber; roomNumber = rand() % TOTAL_ROOMS; //will keep randomizing until a new number appears while (roomsCreated[roomNumber] != 0) { roomNumber = rand() % TOTAL_ROOMS; } roomsCreated[roomNumber] = 1; //will set the room name and type strcpy(roomPtr->name, roomNames[roomNumber]); strcpy(roomPtr->type, roomType); } //creates each file, requires a pointer to the room to be passed in void createFile(struct Room* roomPtr) { //will initialize fileName to all \0 char fileName[14]; memset(fileName, '\0', sizeof(fileName)); //copies room's name into fileName strcpy(fileName, roomPtr->name); //concatenates FILE_SUFFIX(_room) to end of fileName strcat(fileName, FILE_SUFFIX); //opens the file with the appropriate name FILE * filePointer; filePointer = fopen(fileName, "w+"); //writes room description to file fprintf(filePointer, "ROOM NAME: %s\n", roomPtr->name); int i; for (i = 0; i < roomPtr->numConnections; i++) { fprintf(filePointer, "CONNECTION %d: %s\n", i + 1, roomPtr->connections[i]->name); } fprintf(filePointer, "ROOM TYPE: %s\n", roomPtr->type); //closes the file fclose(filePointer); } //will return false if all rooms in graph have greater than 2 and less than 7 rooms(3-6) enum bool isGraphFull(struct Room** roomsToTraverse) { int i; for (i = 0; i < ROOMS_TO_CREATE; i++) { if ((roomsToTraverse[i]->numConnections < MIN_CONNECTIONS) || (roomsToTraverse[i]->numConnections > MAX_CONNECTIONS)) return false; } return true; } // Adds a random, valid outbound connection from a Room to another Room void addRandomConnection(struct Room** roomsToTraverse){ struct Room* A; struct Room* B; while (true) { A = getRandomRoom(roomsToTraverse); if (canAddConnectionFrom(A) == true) break; } do { B = getRandomRoom(roomsToTraverse); } while (canAddConnectionFrom(B) == false || isSameRoom(A, B) == true || connectionAlreadyExists(A, B) == true); connectRoom(A, B); } // Returns a random Room, does NOT validate if connection can be added struct Room* getRandomRoom(struct Room** roomsToTraverse){ int randomNumber; randomNumber = rand() % ROOMS_TO_CREATE; return roomsToTraverse[randomNumber]; } // Returns true if a connection can be added from Room x (< 6 outbound connections), false otherwise enum bool canAddConnectionFrom(struct Room* roomPtr) { if (roomPtr->numConnections < MAX_CONNECTIONS){ return true; } return false; } // Returns true if a connection from Room x to Room y already exists, false otherwise enum bool connectionAlreadyExists(struct Room* roomPtr1, struct Room* roomPtr2){ int i; int strCompareResults; for (i = 0; i < roomPtr1->numConnections; i++) { strCompareResults = strcmp(roomPtr1->connections[i]->name, roomPtr2->name); if (strCompareResults == 0) { return true; } } return false; } // Connects Rooms x and y together, does not check if this connection is valid, connects both ways void connectRoom(struct Room* roomPtr1, struct Room* roomPtr2){ roomPtr1->connections[roomPtr1->numConnections] = roomPtr2; roomPtr1->numConnections++; roomPtr2->connections[roomPtr2->numConnections] = roomPtr1; roomPtr2->numConnections++; } // Returns true if Rooms x and y are the same Room, false otherwise enum bool isSameRoom(struct Room* roomPtr1, struct Room* roomPtr2){ int strCompareResults; strCompareResults = strcmp(roomPtr1->name, roomPtr2->name); if (strCompareResults == 0) { return true; } return false; }
C
#include <stdio.h> int fib (int n) { if (n < 2 ) return n; return fib(n-1) + fib(n-2); //O(k^n) } int main(void) { int n = fib(42); printf("%d\n",n); return 0; }
C
#include <stdio.h> #include <stdlib.h> int employee; struct Employee_details { char* name; char* company; }*emp; void Display(char *,char *); int main() { int n, m; char choice; printf("*****Welcome to ABC pvt. limited *****\n"); printf("*****Here you can enter your employee id details*****\n\nHow many Empolyee are there\n"); scanf("%d",&employee); emp = (struct Employee_details *) calloc (employee,sizeof(struct Employee_details)); do { printf("Enter the character size of your employee ID\n"); scanf("%d", &n); emp->name = (char *) malloc ((n+1)*sizeof(char)); printf("Enter your name :"); scanf("%s",emp->name); printf("Enter the character size of your company name\n"); scanf("%d",&m); emp->company = (char *) malloc ((m+1)* sizeof(char)); printf("Enter the name of your company\n"); scanf("%s",emp->company); Display(emp->name,emp->company); printf("If you don't want to add more employee details PRESS n\n"); //scanf("%c",&choice); choice = getchar(); } while ((choice != 'n')); return 0; } void Display(char *name,char *company) { for (int i = 0; i < employee; i++) { printf("The %d employee name is :%s\n",i+1,(char)*(emp + i)->name); printf("The company name of %d employee is :%s\n",i+1,(char)*(emp + i)->company); } }
C
#include <stdio.h> #include <stdlib.h> #include "hashtable.h" /* * HashTable è una struttura dati che mappa una chiave in un valore * il caso peggiore di ricerca è di O(1+a) se m < n dove a = n/m. * m = numero di slot della tabella, cioè quante chiavi differenti possiamo salvare nella * tabella. Mentre n è il dominio delle chiavi. * Per mappare una chiave in un indice di una tabella e' necessaria una hashFunction * che prende in input la chiave e restituisce un indice tra 0 e m. * Non è possibile un hash function iniettiva poichè il dominio delle chiavi >> del numero di slot della tabella * pertanto si verificano delle collisioni. Per bypassare le collisioni si può associare ad ogni indice una linked * list di valori e non solo un unico valore. Oppure si può utilizzare il probing o il double hashing * * Dunque hashtable sara una struct che contiene un vettore di hashitem il quale è una struct che conterrà * la chiave e il bucket che non è altro che la lista collegata che contiene i valori che fan riferimento * alla stessa chiave. * * La LEN(il numero di slot) dell hashtable NON VARIA a runtime * OVVIAMENTE hashfunction ritorna un interno compreso tra 0-m-1 poichè ci sono solo m slot differenti nella * hashtable * * The hash table should be an array with length about 1.3 times the maximum * number of keys that will actually be in the table, and * * Size of hash table array should be a prime number (especially with the * simple hash function we looked at) * */ int main(int argc, char ** argv){ hashTable_t * h = initHashTable(19); add2Table(1, 1, h); add2Table(2, 2, h); add2Table(239, 239, h); bucket_t *val = lookupValue(239, h); if (val != NULL){ printf("value: %d at key 239\n", val->value); } removeValue(239, h); destroyTable(h); return 0; } hashTable_t* initHashTable(int size){ int i = 0; hashTable_t * table = (hashTable_t *)malloc(sizeof(hashTable_t)); table->size = size; table->table = (hashItem_t *) malloc(size*sizeof(hashItem_t *)); for (i = 0; i < size; i ++){ table->table[i].key = 0; table->table[i].values = NULL; } return table; } int hashFunction(int key, hashTable_t *h){ int index = key % h->size; printf("key: %d ==== index: %d\n", key, index); return index; } void add2Table(int key, int value, hashTable_t *h){ int index = hashFunction(key, h); bucket_t *tmp = h->table[index].values; bucket_t *toadd = (bucket_t *)malloc(sizeof(bucket_t)); toadd->value = value; toadd->next = NULL; if(tmp == NULL){ tmp = toadd; } else{ while(tmp->next != NULL){ tmp = tmp->next; } tmp->next = toadd; } return ; } bucket_t* lookupValue(int key, hashTable_t * h){ int index = hashFunction(key, h); bucket_t * tmp = h->table[index].values; return tmp; } void removeValue(int key, hashTable_t * h){ int index = hashFunction(key, h); bucket_t * bucket = h->table[index].values; bucket_t * tmp; h->table[index].key = 0; while(bucket != NULL){ tmp = bucket->next; free(bucket); bucket = tmp; } return; } void destroyTable(hashTable_t *h){ bucket_t * tmp; for(int i = 0; i < h->size; i ++){ bucket_t * bucket = h->table[i].values; while(bucket != NULL){ tmp = bucket->next; free(bucket); bucket = tmp; } } free(h->table); free(h); }
C
#include "barrier.h" #include <pthread.h> #include <sys/mman.h> /* * 1) Wpuść N - 1 * 2) Wpuść N, zamknij A, otwórz B * 3) Wywal N - 1 * 4) Otwórz A, zamknij B * * \ / * \_____________/ * A| N miejsc |B * |_____________| * / \ * / \ */ /* * Zaimplementowałem dwie wersje bariery, jednak * żadna z nich zdaje się nie działać, mimo że * nie byłem w stanie znaleźć do nich kontprzykładu. * ( w szczególności zakomentowana wersja zdaje się być * dość naturalną implementacją ) */ barrier_t * bar_init( int num ) { barrier_t * b = mmap( NULL, sizeof( barrier_t ), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0 ); b -> num = num; b -> counter = 0; sem_init( & b -> critsec, 1, 1 ); sem_init( & b -> entry, 1, num ); // sem_init( & b -> entry, 1, 1 ); sem_init( & b -> exit, 1, 0 ); return b; } void bar_wait( barrier_t * b ) { sem_wait( & b -> entry ); sem_wait( & b -> critsec ); b -> counter ++; if( b -> counter == b -> num ) { for( int i = 0; i < b -> num; ++ i ) { sem_post( & b -> exit ); } } sem_post( & b -> critsec ); sem_wait( & b -> exit ); sem_wait( & b -> critsec ); b -> counter --; if( b -> counter == 0 ) { for( int i = 0; i < b -> num; ++ i ) { sem_post( & b -> entry ); } } sem_post( & b -> critsec ); } //// Ta werja wymaga dodatkowo odkomentowania sem_init dla entry // void // bar_wait( barrier_t * b ) { // sem_wait( & b -> entry ); // sem_wait( & b -> critsec ); // // b -> counter ++; // if( b -> counter == b -> num ) { // sem_post( & b -> exit ); // } else { // sem_post( & b -> entry ); // } // // sem_post( & b -> critsec ); // // sem_wait( & b -> exit ); // sem_wait( & b -> critsec ); // // b -> counter --; // if( b -> counter == 0 ) { // sem_post( & b -> entry ); // } else { // sem_post( & b -> exit ); // } // // sem_post( & b -> critsec ); // } void bar_destroy( barrier_t * b ) { sem_destroy( & b -> entry ); sem_destroy( & b -> exit ); sem_destroy( & b -> critsec ); munmap( b, sizeof( barrier_t ) ); }
C
#include <stdio.h> #include <stdlib.h> #define INSERT 1 #define DELETE 2 #define PRINT 3 #define EXIT 0 #define TRUE 1 #define FALSE 0 struct node{ struct node *_next; int value; }; typedef struct node *_PtrNode; typedef struct node NODE; void menu(void); void insert(_PtrNode*,int); void print(_PtrNode*); int isEmpty(_PtrNode*); void delete(_PtrNode*); int main() { int choice, value; _PtrNode root; do{ menu(); printf("Scelta: "); scanf("%d", &choice); switch (choice){ case INSERT: printf("Inserisci un valore: "); scanf("%d", &value); insert(&root,value); break; case DELETE: if(isEmpty(&root)){ printf("Lista vuota!\n"); } else { delete(&root); } break; case PRINT: if(isEmpty(&root)) { printf("Lista vuota!\n"); } else { print(&root); } break; case EXIT: printf("Ciao!\n"); break; default:printf("Scelta non valida!\n"); } } while(choice != 0); return 0; } void menu(void){ printf("1.Inserisci un nuovo nodo\n"); printf("2.Elimina il primo nodo\n"); printf("3.Stampa la coda\n"); printf("0.Esci dal programma\n"); } void insert(_PtrNode *_root, int value){ _PtrNode new_node, index; new_node = malloc(sizeof(NODE)); if(new_node != NULL){ new_node->_next = NULL; new_node->value = value; if(*_root == NULL){ *_root = new_node; } else { index = *_root; while(index->_next != NULL){ index = index->_next; } index->_next = new_node; } } else { printf("Memoria insufficiente!\n"); } } void print(_PtrNode *_root){ _PtrNode index; index = *_root; while(index->_next != NULL){ printf("%d -> ", index->value); index = index->_next; } printf("%d -> NULL\n", index->value); } int isEmpty(_PtrNode *_root){ if(*_root == NULL) return TRUE; return FALSE; } void delete(_PtrNode *_root){ _PtrNode index, previous; index = *_root; if((*_root)->_next == NULL){ *_root = NULL; free(index); } else { while(index->_next != NULL){ previous = index; index = index->_next; } previous->_next = NULL; free(index); } }
C
#include <stdio.h> /* printf */ #include <stdlib.h> #include <time.h> /* We want a BOARD_SIZExBOARD_SIZE board game by default */ #define BOARD_SIZE 5 char board[BOARD_SIZE * BOARD_SIZE] = { 0 }; // Filled with zeros char get_cell(int x, int y) { return board[y * BOARD_SIZE + x]; } void set_cell(int x, int y, char color) { board[y * BOARD_SIZE + x] = color; } void init_board(void) { srand((int)time(NULL)); // initialisation of rand int i, j; for (i = 0; i < BOARD_SIZE; i++) { for (j = 0; j < BOARD_SIZE; j++) { int rd_number = rand()%7; if(i==0 & j==BOARD_SIZE-1){ set_cell(i, j, '^'); } else if(i==BOARD_SIZE-1 & j==0){ set_cell(i, j, 'v'); } else{ switch(rd_number){ case 0: set_cell(i, j, 'A'); break; case 1: set_cell(i, j, 'B'); break; case 2: set_cell(i, j, 'C'); break; case 3: set_cell(i, j, 'D'); break; case 4: set_cell(i, j, 'E'); break; case 5: set_cell(i, j, 'F'); break; case 6: set_cell(i, j, 'G'); break; } } } } } void print_board(void) { int i, j; for (i = 0; i < BOARD_SIZE; i++) { for (j = 0; j < BOARD_SIZE; j++) { printf("%c", get_cell(i, j)); } printf("\n"); } } // old update_board (too many calculus) //void update_board(char player, char chosen_color) //{ // int c = 0; // do{ // c = 0; // int i, j; // for (i = 0; i < BOARD_SIZE; i++) { // for (j = 0; j < BOARD_SIZE; j++) { // if(get_cell(i, j) == chosen_color){ // if((get_cell(i-1, j) == player & i > 0) | (get_cell(i, j+1) == player & j < BOARD_SIZE - 1) | (get_cell(i+1, j) == player & i < BOARD_SIZE - 1) | (get_cell(i, j-1) == player & j > 0)){ // set_cell(i, j, player); // c++; // } // } // } // } // } while(!c); //} void update_board(char player, char chosen_color) { int board_positions[BOARD_SIZE * BOARD_SIZE * 2] = { 0 }; int c_tot = 0; int i, j; for (i = 0; i < BOARD_SIZE; i++) { for (j = 0; j < BOARD_SIZE; j++) { if(get_cell(i, j) == player){ board_positions[c_tot * 2] = i; board_positions[c_tot * 2 + 1] = j; c_tot++; } } } int c; for (c = 0; c < c_tot; c++){ i = board_positions[c * 2]; j = board_positions[c * 2 + 1]; if(get_cell(i-1, j) == chosen_color & i > 0){ board_positions[c_tot * 2] = i - 1; board_positions[c_tot * 2 + 1] = j; set_cell(board_positions[c_tot * 2], board_positions[c_tot * 2 + 1], player); c_tot++; } if(get_cell(i, j+1) == chosen_color & j < BOARD_SIZE - 1){ board_positions[c_tot * 2] = i; board_positions[c_tot * 2 + 1] = j + 1; set_cell(board_positions[c_tot * 2], board_positions[c_tot * 2 + 1], player); c_tot++; } if(get_cell(i+1, j) == chosen_color & i < BOARD_SIZE - 1){ board_positions[c_tot * 2] = i + 1; board_positions[c_tot * 2 + 1] = j; set_cell(board_positions[c_tot * 2], board_positions[c_tot * 2 + 1], player); c_tot++; } if(get_cell(i, j-1) == chosen_color & j > 0){ board_positions[c_tot * 2] = i; board_positions[c_tot * 2 + 1] = j - 1; set_cell(board_positions[c_tot * 2], board_positions[c_tot * 2 + 1], player); c_tot++; } } } void possession(double *result_up, double *result_down) { int i, j; double c_down = 0; double c_up = 0; for (i = 0; i < BOARD_SIZE; i++) { for (j = 0; j < BOARD_SIZE; j++) { if(get_cell(i, j) == 'v'){ c_down++; } else if(get_cell(i, j) == '^'){ c_up++; } } } double perc_up = 100*c_up/(BOARD_SIZE*BOARD_SIZE); double perc_down = 100*c_down/(BOARD_SIZE*BOARD_SIZE); printf("Possession\n"); printf("Player ^: %f\n", perc_up); printf("Player v: %f\n\n", perc_down); // utilisation de pointeurs pour récuperer les deux valeurs *result_up = perc_up; *result_down = perc_down; } void switch_letters_near(char *letters_near, int i, int j){ switch(get_cell(i, j)){ case 'A': letters_near[0] = 'A'; break; case 'B': letters_near[1] = 'B'; break; case 'C': letters_near[2] = 'C'; break; case 'D': letters_near[3] = 'D'; break; case 'E': letters_near[4] = 'E'; break; case 'F': letters_near[5] = 'F'; break; case 'G': letters_near[6] = 'G'; break; case '^': break; case 'v': break; } } char rd_player(char player){ char letters_near[7] = { '0' }; int i; for (i = 0; i < 7; i++){ letters_near[i] = '0'; } int board_positions[BOARD_SIZE * BOARD_SIZE * 2] = { 0 }; int c_tot = 0; int j; for (i = 0; i < BOARD_SIZE; i++) { for (j = 0; j < BOARD_SIZE; j++) { if(get_cell(i, j) == player){ board_positions[c_tot * 2] = i; board_positions[c_tot * 2 + 1] = j; c_tot++; } } } int c; for (c = 0; c < c_tot; c++){ i = board_positions[c * 2]; j = board_positions[c * 2 + 1]; if(i > 0){ switch_letters_near(letters_near, i-1, j); } if(j < BOARD_SIZE - 1){ switch_letters_near(letters_near, i, j+1); } if(i < BOARD_SIZE - 1){ switch_letters_near(letters_near, i+1, j); } if(j > 0){ switch_letters_near(letters_near, i, j-1); } } int rd_number = rand()%7; while (letters_near[rd_number] == '0'){ rd_number = rand()%7; } return letters_near[rd_number]; } int main(void) { int game_mode = 0; printf("\nSelect game mode\n"); printf("1: Player vs Player\n"); printf("2: Player vs AI\n"); scanf("%d", &game_mode); init_board(); printf("\n\nWelcome to the 7 wonders of the world of the 7 colors\n" "*****************************************************\n\n" "Current board state:\n"); print_board(); // update_board('v','A'); // // printf("Current board state:\n"); // print_board(); char user_input = 0; int c = 0; char player; double val_up = 0, val_down = 0; while(val_up<=50.0 & val_down<=50.0){ user_input = 0; c++; switch(game_mode){ case 1: if(c%2 == 0){ player = '^'; } else{ player = 'v'; } scanf(" %c", &user_input); while (user_input == '^' | user_input == 'v'){ scanf(" %c", &user_input); } update_board(player, user_input); printf("\n"); break; case 2: if(c%2 == 0){ char rd_letter = rd_player('^'); printf("rd %c", rd_letter); update_board('^', rd_letter); printf("\n"); } else{ printf("Player v must input letter\n"); scanf(" %c", &user_input); while (user_input == '^' | user_input == 'v'){ scanf(" %c", &user_input); } update_board('v', user_input); printf("\n"); } break; } printf("Current board state:\n"); print_board(); printf("\n"); possession(&val_up, &val_down); // val_up et val_down contiennent les résultats voulus } if(val_up>val_down){ printf("****** Player ^ won! ******\n"); } else if(val_down>val_up){ printf("****** Player v won! ******\n"); } else{ printf("****** Draw ******\n"); } return 0; // Everything went well }
C
/* * @Copyright(C): 信念D力量 (freerealmshn@163.com) * All Rights Reserved. * ********************************************** * @FilePath: /CExample/lists-demo/loop-list.c * @Author: 信念D力量 * @Github: https://www.github.com/fy2008 * @Date: 2020-09-05 21:49:48 * @LastEditTime: 2020-09-09 22:25:16 * @Description: 循环单链表例子 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define LINE printf("-----------------------------------------------\n"); typedef enum { OK, ERROR } State; typedef struct { char name[25]; int age; } Student_t; typedef struct List { Student_t Stu; struct List *Next; } List_t; List_t* list_init(void); State list_empty(List_t *list); State list_append(List_t *list, Student_t stu); State list_insert(List_t *list, int pos, Student_t stu); void list_ForEach(List_t *list); int main(void) { List_t *list_head; Student_t stu; list_head = list_init(); printf("--------------- 菜单栏 ---------------\n"); printf("(1) 尾部追加 || (2)遍历输出 || (3) 退出\n"); for(;;) { int s; scanf("%d", &s); switch (s) { case 1: printf("请输入学生姓名:"); scanf("%s", &stu.name); printf("请输入学生年龄:"); scanf("%d", &stu.age); list_append(list_head, stu); break; case 2: list_ForEach(list_head); break; case 3: goto quit; break; default: break; } printf("(1) 尾部追加 || (2)遍历输出 || (3) 退出\n"); } quit: return 0; } /** * @description: 初始化链表,返回一个头结点 * @param {None} * @return {List_t} */ List_t* list_init(void) { List_t *list = (List_t *)malloc(sizeof(List_t)); list->Next = NULL; return list; } State list_empty(List_t *list) { if(list->Next == NULL) { return OK; } else { return ERROR; } } State list_append(List_t *list, Student_t stu) { List_t *list_new = (List_t *)malloc(sizeof(List_t)); strcpy(list_new->Stu.name, stu.name); list_new->Stu.age = stu.age; list_new->Next = NULL; if (OK == list_empty(list)) { list->Next = list_new; } else { list = list->Next; while( list->Next != NULL) { list = list->Next; } list->Next = list_new; } return OK; } State list_insert(List_t *list, int pos, Student_t stu) { return OK; } /** * @description: 遍历链表 * @param {type} * @return {void} */ void list_ForEach(List_t *list) { if (OK == list_empty(list)) { printf("链表为空!\n"); } else { list = list->Next; while( list != NULL) { printf("Name: %s | ", list->Stu.name); printf("Age: %d\n", list->Stu.age); LINE list = list->Next; } } }
C
/* Transliterates every byte from STDIN if it matches * a character in the first string to the respective * character in the second string */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> /* Checks for errors in processing STDIN or printing to STDOUT */ void checkInput() { if (ferror(stdin) != 0) { fprintf(stderr, "ERROR: Unable to process STDIN\n"); exit(1); } } void checkOutput() { if (ferror(stdin) != 0) { fprintf(stderr, "ERROR: Unable to print to STDOUT\n"); exit(1); } } int main (int argc, char *argv[]) { /* Check for proper number of operands */ if (argc != 3) { printf("ERROR: Wrong number of operands\n"); exit(1); } char* fromString = argv[1]; char* toString = argv[2]; /* Check fromString for repeats */ long current, next; for (current = 0; fromString[current] != '\0'; ++current) for (next = current + 1; fromString[next] != '\0'; ++next) if (fromString[current] == fromString[next]) { printf("ERROR: Repeating charactres in from operand\n"); exit(1); } /* Compare lengths */ long toLength; for (toLength = 0; toString[toLength] != '\0'; ++toLength); if (current != toLength) { printf("ERROR: Operands are not of same length\n"); exit(1); } /* Process through all of STDIN */ char currentChar = getchar(); checkInput(); while (currentChar != EOF) { /* If match, transliterate byte */ bool noMatch = true; for (current = 0; fromString[current] != '\0'; ++current) if (fromString[current] == currentChar) { putc(toString[current], stdout); checkOutput(); noMatch = false; } /* Otherwise simply print */ if (noMatch) { putc(currentChar, stdout); checkOutput(); } /* Get next char */ currentChar = getchar(); checkInput(); } }
C
#ifndef __SKIP__ #define __SKIP__ //FOR VACCINATED SKIPLIST struct VacSkipRecord{ //the info we want to keep at the list char* name; char* date; }; struct VacPtrNodes{ //nodes to represent the element in each level struct VacSkipRecord* elem; //pointer to the node with the element it represents struct VacPtrNodes* down; struct VacPtrNodes* next; }; struct VacPath{ //list to maintain the path struct VacPtrNodes* ptr; struct VacPath* next; }; typedef struct VacPtrNodes* VacSkipList; int addVacSkipList(VacSkipList *list, struct VacSkipRecord* element, int *num_of_levels); int removeVacSkipList(VacSkipList *list, char* id, int *num_of_levels); int searchVacSkipList(VacSkipList list, char* id); char* getDate_VacSkipList(VacSkipList list, char* id); void printVacSkipList(VacSkipList list); void freeVacSkipList(VacSkipList *list, int *num_of_levels); //FOR NOT VACCINATED SKIPLIST struct NotVacSkipRecord{ //the info we want to keep at the list char* name; }; struct NotVacPtrNodes{ //nodes to represent the element in each level struct NotVacSkipRecord* elem; //pointer to the node with the element it represents struct NotVacPtrNodes* down; struct NotVacPtrNodes* next; }; struct NotVacPath{ //list to maintain the path struct NotVacPtrNodes* ptr; struct NotVacPath* next; }; typedef struct NotVacPtrNodes* NotVacSkipList; int addNotVacSkipList(NotVacSkipList *list, struct NotVacSkipRecord* element, int *num_of_levels); int removeNotVacSkipList(NotVacSkipList *list, char* id, int *num_of_levels); int searchNotVacSkipList(NotVacSkipList list, char* id); void printNotVacSkipList(NotVacSkipList list); void freeNotVacSkipList(NotVacSkipList *list, int *num_of_levels); #endif
C
#include <stdio.h> #include "list.h" #include "listmenu.h" void printMenu(MenuItems *menuitems, struct List* list){ printf("MAIN MENU\tC:%d\tH:%p\tT:%p\n", Count(list), list->head, list->tail); int i = 0; for(i; i < menuitems->count; i++){ printf("[%d]\t%s\n", i, menuitems->items[i].name); } printf("\n\nEnter number of menu list and press ENTER, ENTER -1 for escape\n"); } void MenuItemAll(struct List* list){ PrintList(list); } void MenuItemAdd(struct List* list){ int value = 0; printf("Enter value to add in list\n"); scanf("%d", &value); Add(factoryItem(value), list); } void MenuItemRem(struct List* list){ int pos = 0; printf("Enter pos which you want remove\n"); scanf("%d", &pos); RemoveItem(pos, list); } void MenuItemDel(struct List* list){ int pos = 0; printf("Enter pos which you want delete\n"); scanf("%d", &pos); DelItem(pos, list); } void MenuItemIns(struct List* list){ int pos, value; printf("Enter pos and value which you want insert to list\n"); scanf("%d %d", &pos, &value); Insert(pos, factoryItem(value), list); } void MenuItemCount(struct List* list){ printf("COUNT: %d\n", Count(list)); } void MenuItemGet(struct List* list){ int pos = 0; printf("Enter pos which you want get\n"); scanf("%d", &pos); PrintItem(Get(pos, list), list); } void MenuItemClear(struct List* list){ Clear(list); printf("List cleared!\n"); } void MenuItemGetIndex(struct List* list){ struct Item* item; printf("Enter address item\n"); scanf("%p", &item); printf("INDEX OF %p : %d", item, GetIndex(item, list)); }
C
#include <stdio.h> #include "irgenerator.h" static void printFunction (const Function*); static void printOp (const IROp*); static void printSymbol (const Symbol*); static void printImport (const Import*); static void printConstants (const Constants*); void irgen_print(IRGenerator* p) { printf(".MODULE\n"); for( LListNode* n=p->module.imports.set.first ; n ; n=n->next ) printImport((Import*)n); for( LListNode* n=p->module.symtab.symbols.first ; n ; n=n->next ) printSymbol((Symbol*)n); printConstants(&p->module.constants); printf("\n"); for( LListNode* n=p->module.functions.first ; n ; n=n->next ) printFunction((Function*)n); printf(".MODULE-END\n"); } void printConstants(const Constants* p) { for( LListNode* n=p->set.first ; n ; n=n->next ) { Constant* k = (Constant*)n; printf(" .const %i: [%s]\n", k->index, k->value.buffer); } } void printImport(const Import* p) { if( string_is_empty(&p->as) ) printf(" .imp %s\n", p->name.buffer); else printf(" .imp %s -> %s\n", p->name.buffer, p->as.buffer); } void printFunction(const Function* fn) { printf ( "\n%s:\n", string_is_empty(&fn->name) ? "_entry" : fn->name.buffer ); for( LListNode* n=fn->ops.first ; n ; n=n->next ) printOp((IROp*)n); } void printOp(const IROp* op) { switch( op->op ) { case NOP: printf(" NOP\n"); break; case PUSH: printf(" PUSH $%i\n", op->A); break; case DISCARD: printf(" DISCARD %i\n", op->A); break; case MOV: printf(" MOV $%i, $%i\n", op->A, op->B); break; case SMOV: printf(" SMOV %i, $%i\n", op->A, op->B); break; case LOADK: printf(" LOADK $%i, K%i\n", op->A, op->B); break; case CALL: printf(" CALL $%i, %i\n", op->A, op->B); break; case JMP: printf(" JMP $%i\n", op->A); break; case JMPF: printf(" JMPF $%i <$%i>\n", op->A, op->B); case GET: printf(" GET $%i, $%i, $%i\n", op->A, op->B, op->C); break; case ADD: printf(" ADD $%i, $%i, $%i\n", op->A, op->B, op->C); break; case SUB: printf(" SUB $%i, $%i, $%i\n", op->A, op->B, op->C); break; case MUL: printf(" MUL $%i, $%i, $%i\n", op->A, op->B, op->C); break; case DIV: printf(" DIV $%i, $%i, $%i\n", op->A, op->B, op->C); break; case RET: if( op->A ) printf(" RET %i\n", op->A); else printf(" RET\n"); break; case LABEL: printf("L%i:\n", op->A); break; default: printf(" (%02X)\n", op->op); break; } } void printSymbol(const Symbol* s) { printf ( " .sym %c%c[%s]:%i\n", s->flags&F_PUBLIC ? 'P' : ' ', s->flags&F_FUNCTION ? 'F' : ' ', s->name.buffer, s->vindex ); }
C
#include"/Users/amuthanmannan/Documents/collection/Collection-API-in-C copy/collection.h" LinkedList* linkedlist(){ LinkedList* list; list=(LinkedList*)malloc(sizeof(LinkedList)); list->head=NULL; list->tail=NULL; list->size=0; return list; } Node* init_node(void* data){ Node* n; n=(Node*)malloc(sizeof(Node)); n->data=(void*)(data); n->next=NULL; n->prev=NULL; return n; } void llist_add(LinkedList* list,void* newData){ Node *newNode; newNode=init_node(newData); LLaddNode(list,newNode); } int llist_insertAfter(LinkedList* list,void* nextTo,void* newData){ Node *curr,*newNode; curr=LLgetObj(list,nextTo); if(curr==NULL){ return 0; } newNode=init_node(newData); newNode->next=curr->next; curr->next=newNode; list->size=(list->size)+1; return 1; } int llist_insertFirst(LinkedList* list,void* newData){ Node *head,*node; node=init_node(newData); head=list->head; if(head==NULL){ list->head=node; return 1; } node->next=head; list->head=node; list->size=(list->size)+1; return 1; } void* llist_tail(LinkedList* list){ Node* temp; temp=(Node*)list->head; while(1){ if(temp->next==NULL){ return (void*)temp; } temp=temp->next; } return NULL; } void* llist_get(LinkedList* list,int pos){ Node* temp; temp=(Node*)list->head; int i=0; while(temp!=NULL){ if(i==pos){ return temp->data; } temp=temp->next; i++; } return NULL; } int llist_indexof(LinkedList* list,void* data){ Node *curr,*n; n=LLgetObj(list,data); curr=list->head; int i=0; while(1){ if(curr==n){ return i; } curr=curr->next; if(curr==NULL){ return -1; } i++; } return i; } int llist_size(LinkedList* list){ return list->size; } void llist_removeAt(LinkedList* list,int pos){ Node *temp,*prev,*toReturn; temp=(Node*)list->head; prev=temp; int i=1; if(pos==0){ list->head=list->head->next; list->size=(list->size)-1; } else{ while(1){ temp=temp->next; if(i==list->size-1&&i==pos){ prev->next=NULL; break; } else{ if(temp==NULL){break;} if(i==pos){ prev->next=temp->next; break; } prev=temp; } i++; } list->size=(list->size)-1; } } void LLaddNode(LinkedList* list,Node* newNode){ Node *head; head=list->head; if(head==NULL){ list->head=newNode; } else{ Node* lastEle; lastEle=LLget(list,list->size-1); lastEle->next=newNode; } list->size=(list->size)+1; } Node* LLgetObj(LinkedList* list,void* data){ Node* head; head=list->head; while(head!=NULL){ if(head->data==data){ return head; } head=head->next; } return NULL; } Node* LLget(LinkedList* list,int pos){ Node* temp; temp=(Node*)list->head; int i=0; while(temp!=NULL){ if(i==pos){ return temp; } temp=temp->next; i++; } return NULL; }
C
#include <stdio.h> #include <string.h> int main() { int c; char s[100],*p; scanf("%s",s); c = strlen(s); p = &s[c-1]; while(p!=s) { printf("%c", *p--); } printf("%c\n", *p); return 0; }
C
/** * A small module for testing powerfulness of numbers. * * References on powerful numbers: * http://en.wikipedia.org/wiki/Powerful_number * http://oeis.org/A001694 * http://mathworld.wolfram.com/PowerfulNumber.html * * Author: Vasilis Poulimenos * Date: 3/1/2015 * Version: 1.0.0 */ #ifndef ISPOWERFUL_H_ #define ISPOWERFUL_H_ /** * Checks if the number specified is powerful. * * This function uses a naive algorithm based on trivial division to test * for powerfulness. As a result, it will be slow for very large numbers. * * Returns 1 if the number is powerful or 0 otherwise. * Raises an error (by returning -1) in case of invalid input (i.e. 0 (zero)). */ int ispowerful(unsigned long int); #endif /* ISPOWERFUL_H_ */
C
#include<stdio.h> void main() { int n,i,sum=0; printf("Enter any digit: "); scanf("%d",&n); while(n>0) { i=n%10;//Remainder if(i%2==0) { sum=sum+i; } n=n/10; } printf("Sum=%d\n",sum); }
C
#include "uart.h" #include "allocater.h" #include "tools.h" #include "exception.h" static int time = 0; char *entry_error_messages[] = { "SYNC_INVALID_EL1t", "IRQ_INVALID_EL1t", "FIQ_INVALID_EL1t", "ERROR_INVALID_EL1T", "SYNC_INVALID_EL1h", "IRQ_INVALID_EL1h", "FIQ_INVALID_EL1h", "ERROR_INVALID_EL1h", "SYNC_INVALID_EL0_64", "IRQ_INVALID_EL0_64", "FIQ_INVALID_EL0_64", "ERROR_INVALID_EL0_64", "SYNC_INVALID_EL0_32", "IRQ_INVALID_EL0_32", "FIQ_INVALID_EL0_32", "ERROR_INVALID_EL0_32", "SYNC_ERROR" , "SYSCALL_ERROR" }; void timer_init() { unsigned long int count,freq; asm volatile ("mrs %0, cntpct_el0" :"=r" (count)); asm volatile ("mrs %0, cntfrq_el0" :"=r" (freq)); //cntpct_el0,cntfrq_el0 //print_int(count); //uart_puts("\n"); //print_int(freq); //uart_puts("\n"); time = count / freq; } void irq_router(void) { //spsr_el1 : 0x0000000060000000 //elr_el1 : 0x0000000000081640 //esr_el1 : 0x0000000000000000 uart_puts("core time : "); print_int(time); uart_puts("\n"); time = time + 2; core_timer_handler(); } void exception_handler (void) { //spsr_el1, elr_el1, and esr_el1 unsigned long int spsr,elr,esr; asm volatile ("mrs %0, spsr_el1\n" :"=r" (spsr));//200003C0 --> 2 is C bit asm volatile ("mrs %0, elr_el1\n" :"=r" (elr)); asm volatile ("mrs %0, esr_el1\n" :"=r" (esr)); int iss = esr & 0x01ffffff; if(iss == 1) { timer_init(); core_timer_enable(); } if(iss == 0) { uart_puts("exception handler!!!\n"); uart_puts(" spsr_el1 : "); print_mem((void*)spsr); uart_puts("\n"); uart_puts(" elr_el1 : "); print_mem((void*)elr); uart_puts("\n"); uart_puts(" esr_el1 : "); print_mem((void*)esr); uart_puts("\n"); } } void not_implemented () { uart_puts ("function not implemented!\n"); while (1); } void show_invalid_entry_message(int type, unsigned long esr, unsigned long address) { uart_puts (entry_error_messages[type]); uart_puts ("\n ESR: "); print_mem((void*)esr); uart_puts ("\n address: "); print_mem((void*)address); uart_puts ("\n "); }
C
//factorial using recursion #include<stdio.h> int fact(int x) { int f; if(x==0) { return(1); } else{ f=x*fact(x-1); return(f); } } int main() { int no,ans; scanf("%d",&no); ans=fact(no); printf("the answer is %d",ans); }
C
#include <stdio.h> #include <stdlib.h> int main() { int d, m, nm, dem; scanf("%d %d %d", &d, &m, &nm); if((d<=7) && (d>=2) && (m>=1) && (m<=12) && (nm>=28) && (nm <=31)) { printf("Thang %d\n", m); printf("Thu Hai Thu Ba Thu Tu Thu Nam Thu Sau Thu Bay Chu Nhat \n"); dem=1; for(int i=1; i<=7; i++) { for(int q=1; q<=7; q++) { if(i==1) { if(q<d-1) printf(" "); else { printf("%d ", dem); dem++; } } else if(dem>nm) break; else { if(dem<10) printf("%d ", dem); else printf("%d ", dem); dem++; } } printf("\n"); } } return 0; }
C
#include<iostream> int main() { using namespace std; cout.setf(ios_base::fixed, ios_base::floatfield); cout << "Interger division: 9/5 = " << 9/5 << endl << "Floating-point division : 9.0/5.0 = " << 9.0/5.0 <<endl << "Mixed division: 9.0/5 = " << 9.0/5 << endl << "double constants: 1e7/9.0 = " << 1e7/9.0 <<endl << "float constants: 1e7f/9.0f = " << 1e7f/7.0f << endl ; cin.get (); cin.get (); return 0; }
C
#include <stdio.h> int newton(int n,int k) { if(k==0 || k==n) { return 1; } if(n>k && k>0) { return newton(n-1,k-1)+newton(n-1,k); } } int main() { int x,y; scanf("%d %d",&x,&y); printf("%d\n",newton(x,y)); }
C
#include <stdio.h> #include <stdlib.h> int main() { int vertex=0; int node=0; int orientation=0; int weightiness=0; int c; char input[20]; printf("Type name of input file:\n"); scanf("%s", input); FILE *MatrixFile=fopen(input, "r"); if (MatrixFile == NULL) { printf("No such File"); exit(2); } while (!feof(MatrixFile)) { // Считаем кол-во вершин if ((fgetc(MatrixFile)) == ';') { vertex++; } } fseek(MatrixFile, 0, SEEK_SET); while ((c = fgetc(MatrixFile)) != ';'){ // Кол-во узлов(связей) if (c == ',') node++; } node++; int Arr[vertex][node]; // Создание таблицы в виде двумерного массива fseek(MatrixFile, 0, SEEK_SET); for (int i=0; i < vertex; i++){ int j=0; while ((fgetc(MatrixFile))!=';') fscanf(MatrixFile,"%d",&Arr[i][j++]); } fclose(MatrixFile); for (int i = 0; i < vertex; i++) { // Проверка каждой колонки на взвешенность и ориентированность графа for (int j = 0; j < node; j++) { if (Arr[i][j]>1) weightiness=1; if (Arr[i][j]<0) orientation=1; } } int *weight[node]; // Если граф взвешен if (weightiness) { for (int j = 0; j < node; j++) { for (int i = 0; i < node; i++) { if (Arr[i][j]>0) weight[j]= &Arr[i][j]; } } } char VertNames[vertex]; // Установка имен for (int i = 0; i < vertex; i++){ VertNames[i]= 'a' + i; } char Connect[node][2]; // Установка связей между вершинами for (int j = 0; j < node; j++) { int k = 0; for (int i = 0; i < vertex; i++) { if (Arr[i][j]<0) Connect[j][1] = VertNames[i]; if (Arr[i][j]>0) Connect[j][k++] = VertNames[i]; } } FILE *GraphFile = fopen("graph.dot", "w"); // Создание dot-файла и преобразование его в png if (GraphFile == NULL) { printf("Problem with making a file"); exit(2); } if (orientation) fprintf(GraphFile,"di"); fprintf(GraphFile,"graph Test {\n"); for (int i = 0; i < node; i++){ if (!orientation) fprintf(GraphFile,"%c -- %c ",Connect[i][0],Connect[i][1]); else { fprintf(GraphFile,"%c -> %c ",Connect[i][0],Connect[i][1]); } if (weightiness) fprintf(GraphFile,"[label = %d] \n",*weight[i]); } fprintf(GraphFile,"}\n"); fclose(GraphFile); system("dot -Tpng graph.dot -o graph.png"); printf("\nGraph is created\n"); if (node>(((vertex-1)*(vertex-2))/2)) { // Проверка связанности графа printf("\nThis graph is connected\n"); } else { printf("\nThis graph is not connected\n"); } printf("\nPlease check graph.dot and graph.png "); return 0; }
C
/********************************* * Class: MAGSHIMIM C2 * * Week 3 * * HW solution * **********************************/ #include <stdio.h> #include <string.h> void printArray(char* p, int len) { char* ogp = p; // the original p for (p; p < ogp + len; p++) { printf("%c", *p); } printf("\n"); } /* . \ ( ) sigal (I used the last question, the was 2...) */ int main(void) { char* msg = "hi jyegq meet me at 2 :)"; printArray(msg, strlen(msg)); (void)getchar(); return 0; }
C
//Meeting of old friends #include<stdio.h> int main() { long long int l1,l2,r1,r2,i,j,cnt; while(scanf("%lld %lld %lld %lld %lld",&l1,&r1,&l2,&r2,&k)==5) { cnt=0; for(i=l1;i<=r1;i++) { for(j=l2;j<=r2;j++) if(i==j && i!=k) cnt++; if(i==j && i==k) i++; } printf("%lld\n",cnt); } return 0; }
C
#include "task.h" #include <stdio.h> int main(){ int a; int b; printf("Write two numbers:\n"); scanf("%u%u", &a, &b); swap(&a,&b); printf("The answer is %d", gcdCyc(a, b)); }
C
#include<stdio.h> void PrencheVect(); void Menu(); int vect[5]; int tam = sizeof(vect) / sizeof(int); int main() { Menu(); //CHAMA O MENU GERAL return 0; } void PrencheVect() { int elemento=0; for (int i = 0; i < tam; i++) { printf("== DIGITE O %d ELEMENTO DO VETOR :",(i+1)); scanf_s("%d", &elemento); } } void Menu() { int opcoes = 0; printf("==================== MENU =====================\n"); printf(""); PrencheVect(); printf(""); do { printf("===============================================\n"); printf("================== OPES =====================\n"); printf("===============================================\n"); printf(""); printf("( 1 ) ========== ORDERNAR POR \"BUBBLE SORT\"==\n"); printf("( 2 ) ========== ORDERNAR POR \"INSERTION SORT\"\n"); printf("( 3 ) ========== ORDERNAR POR \"SELECTION SORT\"\n"); printf("( 4 ) ========== ORDERNAR POR \"QUICK SORT\"===\n"); printf("( 5 ) ========== BUSCAR VETOR \"SEQUENCIAL\"===\n"); printf("( 6 ) ========== ORDERNAR POR \"EXAUSTIVA\"====\n"); printf("( 7 ) ========== ORDERNAR POR \"BINRIA\"======\n"); printf("( 8 ) ========== SAIR==========================\n"); printf(""); printf("===============================================\n"); } while (opcoes>0&&opcoes<8); }
C
/* ** EPITECH PROJECT, 2020 ** tools.c ** File description: ** all the usefull functions */ #include "../include/rpg.h" void my_putchar(char c) { write(1, &c, 1); } void my_putstr(char *str) { for (; *str != '\0'; str++) my_putchar(*str); } void my_puterr(char d) { write(2, &d, 1); } void my_putstrerr(char *str) { for (; *str != '\0'; str++) my_puterr(*str); } int my_strcmp(char const *s1, char const *s2) { int i = 0; for (; s1[i] != '\0';) { if (s1[i] < s2[i]) return (-1); else if (s1[i] == s2[i]) i++; else if (s1[i] > s2[i]) return (1); } return (0); }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> int primeCheck(int num) { for(int i=2;i<num/2;i++) { if(num%i==0) return 0; } return 1; } int rotRight(int num, int size) { int digits[size]; int temp = num; for(int i=size-1;i>=0;i--) { digits[i]=temp%10; temp /= 10; } int newDigits[size]; int newInt = 0; for(int i=0;i<size;i++) { newDigits[i]=digits[(i+1)%size]; int pos = (int)pow(10,size-i-1); newInt += newDigits[i]*pos; } return newInt; } int main(int argc, char** argv) { char* inp = argv[1]; double x = atof(inp); double size = log10(x); int sizeR = ceil(size); int intX =(int)x; for(int i=0;i<sizeR;i++) { if(primeCheck(intX)==1) intX = rotRight(intX,sizeR); else { printf("Not circular prime \n"); return 0; } } printf("Circular prime \n"); return 1; }
C
//#HW09 //ALP EMİR BİLEK //161044049 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> int main() { //ARRAY'A RASTGELE SAYILAR ATIYORUZ. srand(time(NULL)); //20'LİK ÜÇ ARRAY TANIMLIYORUZ. int array2[20]; int array3[20]; int array1[20]; // DEĞİŞKENLERİMİZİ TANIMLIYORUZ. int counter1,counter2,i; double cosine_similarity,square_root,toplam1,toplam2,sonuc2,total,dot,sonuc1; counter1=0; counter2=0; dot=0; toplam1=0; sonuc1=0; square_root=0; cosine_similarity=0; toplam2=0; total=0; sonuc2=0; //ARRAYLARA RANDOM DEĞERLER ATIYORUZ. for(i=0;i<20;i++) { array1[i] = rand() % 10; array2[i] = rand() % 10; } //ARRAY1 'İ PRİNT EDİYORUZ. printf("VEKTOR 1="); for(i =0 ; i<20 ; i++) { printf("%d,",array1[i]); } //ARRAY2'Yİ PRİNT EDİYORUZ. printf("\nVEKTOR 2="); for(int i =0 ; i<20 ; i++) { printf("%d,", array2[i]); } //ARRAY1 DEKİ SAYILARIN NORMUNU ALIYORUZ. for(int k=0;k<=19;k++){ //ARRAY1 DEKİ 0 LARI ALMAMAK İÇİN BİR COUNTER TUTUYORUZ. if(array1[k]!=0){ counter1++; } } //ARRAY1 İN NORMUNU PRİNT EDİYORUZ. printf("\nVEKTOR 1 L0 NORM:"); printf("%d",counter1); //ARRAY2 DEKİ SAYILARIN NORMUNU ALIYORUZ. for(int k=0;k<=19;k++){ //ARRAY2 DEKİ 0 LARI ALMAMAK İÇİN BİR COUNTER TUTUYORUZ. if(array2[k]!=0){ counter2++; } } //ARRAY2 İN NORMUNU PRİNT EDİYORUZ. printf("\nVEKTOR 2 L0 NORM:"); printf("%d",counter2); printf("\nVEKTOR 1+ VEKTOR 2="); //ARRAY3'E ARRAY1 VE ARRAY2 NİN TOPLAMLARINI ATIYORUZ. for(i=0;i<20;i++){ array3[i]=array1[i]+array2[i]; //VEKTÖR1 VE VEKTÖR 2 Yİ PRİNT EDİYORUZ. printf("%d,", array3[i]); } for(i=0;i<20;i++){ //COSİNE SİMİLARTY 'İ HESAPLAMAK İÇİN ARRAYLARIN KARELERİNİ ALIYORUZ. toplam1+=pow(array1[i],2); toplam2+=pow(array2[i],2); sonuc1=sonuc1+toplam1; sonuc2=sonuc2+toplam2; } for(i=0;i<20;i++){ //VEKTÖRLERİN İÇ ÇARPIMINI BULMAK İÇİN ARRAYLARIN İNDEXLERİNİ ÇARPIP TOPLUYORUZ. total= array1[i] * array2[i]; dot=total+dot; } //KARELERİNİ ALDIĞIMIZ ARRAYLARIN KAREKÖKLERİNİ ALIP TOPLUYORUZ. square_root= sqrt(sonuc1)*sqrt(sonuc2); //COSİNE SİMİLARTY İ HESAPLAMAK İÇİN İÇ ÇARPIMI BULDUĞUMUZ KAREKÖKE BÖLÜYORUZ. cosine_similarity=1-dot/square_root; //COSİNE SİMİLARİTY İ PRİNT EDİYORUZ. printf("\nsim(VEKTOR1,VEKTOR2)=%f",cosine_similarity); return 0; }
C
//Isso é um comentário de uma linha. ///Isso é um comentário de documentação de varias linhas, vou usar esse pois é mais legivel que o cinza. /* Isso é um comentário de várias linhas. */ /** Isso é um comentário de documentação de várias linhas. */ #include <stdio.h> ///Essa é a bliblioteca que contém as declarações de printf() e scanf(). ///stdio.h é o nome em si do arquivo. Veremos a razão do < > nas próximas aulas. int main() ///Essa é a principal função do programa, o ponto de inicio da execução do programa. Até a aula de funções isso é macaco. { ///Essa é a chave que inicia o bloco de execução da função main. /** Tipos básicos de variável: int, float, double, char. * Podem ser declaradas várias variáveis de um mesmo tipo em uma mesma linha. * É opcional inicializar as variáveis com um valor inicial. */ int i1, i2 = 18, i3 = 70; float f1 = 10.3, f2; double d1 = 42.12, d2 = 50.7234; char c1 = 'k'; i1 = 15; ///As variáveis também podem ser atribuídas um valor em linhas após sua declaração /** * No C, o operador '=' não denota igualdade e sim atribuição. O que está do lado esquerdo recebe o valor do lado direito. * logo 30 = i1 está errado, pois 30 não é uma variável e não pode receber outro valor. */ ///Operadores matemáticos do C: + - * / % (modulo, e apenas pode ser usado para operandos inteiros) f1 = i2 * d2 + 3; ///f1 recebe o valor 916,0212 i1 = i3 / 2; ///i1 recebe o valor 7, pois, como é uma divisão entre inteiros, o resultado é inteiro f2 = f1 / i1; ///Numa divisão entre um float e um int, a divisão é tratada como divisão entre floats, e o resultado é um float. i1 = f2 * f1; ///Acontece um truncamento, por tentar colocar um float em um inteiro. i1 = 3 * 5; // i1 = i2 / 0; ///Não fazer divisões por 0, pois crasha o programa /** Uso do prinf(): * printf() é uma função que imprime texto na tela. */ printf("Exemplos de printf():\n"); printf("Hello World!\n"); /** O caractere \n significa quebra de linha. (O printf() imprime Hello World! e pula uma linha). * O printf também pode imprimir o valor de variáveis na tela: * Associação entre tipos de variável e especificadores de formatação: * * int : %d (escreve inteiros na base decimal, para a base octal se usa %o e hexadecimal %x) * float : %f (escreve números em ponto flutuante, para escrever em notação científica se usa %e) * double : %f (na hora da impressão somente, para a leitura pelo scanf se usaria %lf) * char : %c * * ex: printf("O valor de i2 na base decimal e: %d\nE o valor de i2 na base hexadecimal e: %x\n", i2, i2); * imprime: * O valor de i2 na base decimal e: 18 * E o valor de i2 na base hexadecimal e: 12 */ printf("O valor de i2 na base decimal e: %d\nE o valor de i2 na base hexadecimal e: %x\n", i2, i2); printf("%d %f %f %c\n", i1, f1, d1, c1); printf("O valor do produto de i1 e i2 e %d", i1 * i2); printf("\n"); // printf('Um exemplo de erro, usei aspas simples'); // print("Outro exemplo de erro, equeci o f no printf"); // printf("Um exemplo de erro em que eu esqueço de fechar as aspas); // Printf("Um exemplo de erro em que o printf começa com P maiusculo"); /** Uso do scanf(): * scanf() é uma função que lê dados do teclado e armazena-os em variaveis daquele tipo. * * Ex: scanf("%d", &i3); * lê um inteiro do teclado e salva ele em i3. Logo i3 passa a ter aquele valor. * O & denota "Endereço de" e será visto com mais detalhes na aula de ponteiros, * é necessário colocá-lo para que scanf consiga modificar o valor de i3, * porem veremos isso com mais detalhes apenas na aula de ponteiros. * * Associação entre tipos de variável e especificadores de formatação: * * int : %d (lê inteiros na base decimal, para a base octal se usa %o e hexadecimal %x) * float : %f * double : %lf (na hora da leitura somente, para a impressão pelo printf se usaria %f) * char : %c */ scanf("%c", &c1); scanf("%f %lf", &f1, &d2); /** * Boa prática para scanf: somente colocar %algo ou espaços dentro dos "" do scanf(), * pois pode bugar o funcionamento correto caso contrário. */ /** * Uso do if: * * if(condição) { * comandos; * } * * Ou, caso só haja um comando, pode-se omitir as chaves {} * * if(condição) comando; * * se a condição for verdadeira, executam-se os comandos dentro do bloco {} imediatamente após o if. * se a condição for falsa, ignoram-se os comandos do bloco {} * * a condição pode ser um numero (ex: 34) ou uma expressão condicional (ex: i1 > 1) * caso seja um numero, a condição será verdadeira se o numero for diferente de 0 e falsa se for igual a 0. * * ex: * if(-9) { * ... * } * esse exemplo sempre entra no if * * if(0) { * ... * } * esse exemplo nunca entra no if * * no caso de uma expressão condicional, a expressão é evaluada e se transforma em um dos numeros 0 ou 1, * que, então, é usado para entrar ou não no if. * * ex: * if(30 > 2) { * ... * } * nesse exemplo, o 30 > 2 se transforma em 1, logo o exemplo vira: * if(1) { * ... * } * que sempre entra no if. * * operadores comparativos: * > (maior que) * < (menor que) * >= (maior ou igual que) * <= (menor ou igual que) * == (igual à) * != (diferente de) */ if(i1 > i2) { printf("i1:%d é maior que i2:%d\n", i1, i2); } printf("O valor de 4800 > 700 eh %d\n", 4800 > 700); ///Imprime '1' na tela, demonstrando assim que realmente (4800 > 700) vira (1) /** * Uso do else: * * if(condição) { * comandosDoIf; * } * else { * comandosDoElse; * } * * Ou, caso so haja um comando no bloco do else, as chaves podem ser omitidas: * * else comandoDoElse; * * O else deve ser sempre precedido por um if. * O bloco do else só é executado caso a condição do if seja falsa. * * ex: * if(1 > 2) printf("1 é maior que 2\n"); * else printf("1 não é maior que 2\n"); * * o programa imprime a segunda mensagem na tela. */ ///Outro Exemplo: int a = 5, b = 5; if(a < b) { printf("%d < %d\n", a, b); } else { printf("%d >= %d\n", a, b); } /** * uso do else if: * o else if é apenas a junção do else com outro if. ex: * if(a < b) { * printf("a eh menor que b\n"); * } * else if(a > b) { * printf("a eh maior que b\n"); * } * else { * printf("a eh igual a b\n"); * } * * varios if else podem ser encadeados */ /** * mais detalhes sobre expressões condicionais: * pode-se encadear expressões condicionais com o uso dos operadores lógicos: * * && :AND * || :OR * ! :NOT * * o and verifica se as duas condições são verdadeiras, e, no caso, retorna verdadeiro. ex: * (2 > 1) && (7 >= -9) é uma expressão verdadeira, já * (1 != 1) && (9 > 0) é uma expressão falsa, pois 1 != 1 é falso. * * o or verifica se alguma das condições é verdadeira, e, no caso, retorna verdadeiro. ex: * (10 > -100) || (1 == 1000) é verdadeiro, pois a condição da esquerda é verdadeira, já * (0 > 1 || 10000 == 100) é falso, pois as duas condições são falsas. * * o not nega uma expressão à sua direita. ex: * !(10 != 10) é uma expressão verdadeira, pois 10 != 10 é falsa. * * pode-se encadear várias condições desse modo. */ ///Ex: if(100 > 20 && !(7 > 8 || 9 == 1)){ ///por incrivel que pareça, da verdadeiro. printf("Entrou no if\n"); } else { printf("Entrou no else\n"); } return 0; }
C
/** * @fichier main.c * @titre Convolution 2D * @description Convolution 2D avec la programmation concurrente * @auteurs Kevin Estalella & Federico Lerda * @date 21 Octobre 2015 * @version 1.0 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include "time.h" //librarie utilisée pour calculer le temps total de la convolution #include "convolution.h" #include "filtre.h" /** * Point d'entrée du programmae * @param argc nombre d'arguments * @param argv tableau de string qui stock les arguments * @return code de fin d'execution du programme */ int main(int argc, char **argv) { if (argc != 5) { fprintf(stderr, "usage: %s input output filter nb_threads\n"\ "where input and output are PPM files\n", argv[0]); return EXIT_FAILURE; } char *input = argv[1]; char *output = argv[2]; char *filtre = argv[3]; int nb_threads = atoi(argv[4]); img_t *img = load_ppm(input); //charge l'image source if (img == NULL) { fprintf(stderr, "Failed loading %s!\n", input); return EXIT_FAILURE; } img_t *img2 = alloc_img(img->width, img->height); //alloue la mémoire pour l'image de destination //départ du temps d'exécution struct timespec start, finish; clock_gettime(CLOCK_MONOTONIC, &start); //déclaration des variables utilisées pour l'appel des différents threads pthread_t threads[nb_threads]; convolution_params_t tab[nb_threads]; //calcule une portion de l'image pour la convolution avec les threads int taille_portion_image = (img->height * img->width) / nb_threads; //on fait une boucle pour chaque thread for(int i = 0; i < nb_threads; i++) { //nous remplissons la structure que l'on passe au thread tab[i].source = img; tab[i].destination = img2; tab[i].filtre = filtre; tab[i].debut = taille_portion_image * i; //calcul de la position initial if (i == (nb_threads-1)) { tab[i].fin = img->width * img->height; //calcul de la position final } else { //on prend la valeur maximal pour le dernier élement afin de ne pas perdre des pixels tab[i].fin = taille_portion_image * (i+1); //calcul de la position final } //on crée le thread et on test qu'il ne crash pas if (pthread_create(&threads[i], NULL, thread, &tab[i]) != 0) { fprintf(stderr, "pthread_create failed!\n"); free_all_img(img,img2); //libère la mémoire de l'image source et destination return EXIT_FAILURE; } } for(int i = 0; i < nb_threads; i++) { //permet d'attendre que chaque thread se termine if (pthread_join(threads[i], NULL) != 0) { fprintf(stderr, "pthread_join failed!\n"); free_all_img(img,img2); //libère la mémoire de l'image source et destination return EXIT_FAILURE; } } //nous affichons le temps après la convolution clock_gettime(CLOCK_MONOTONIC, &finish); double elapsed_ms = 1000 * (finish.tv_sec - start.tv_sec); elapsed_ms += (finish.tv_nsec - start.tv_nsec) / 1000000.0; printf("Temps d'execution pour calculer la convolution : %f \n", elapsed_ms); //enregistre l'image de fin modifiée grâce à la convolution 2d if (!write_ppm(argv[2], img2)) { fprintf(stderr, "Failed writing %s!\n", output); free_all_img(img,img2); //libère la mémoire de l'image source et destination return EXIT_FAILURE; } free_all_img(img,img2); //libère la mémoire de l'image source et destination return EXIT_SUCCESS; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define OUTPUT_NAME "output.c" #define LUT_SIZE 0xFF #define AVAILABLE_MEMORY "1024" #if defined(__clang__) #define COMPILER "clang" #else #define COMPILER "gcc" #endif int main(int argc, char **argv) { if (argc < 2) { printf("Not enough arguments\n"); return 1; } char *input_name = argv[1]; char *commands[LUT_SIZE]; memset(commands, 0, LUT_SIZE * sizeof(char *)); commands['>'] = "++p;"; commands['<'] = "--p;"; commands['+'] = "++*p;"; commands['-'] = "--*p;"; commands['.'] = "putchar(*p);"; commands[','] = "*p=getchar();"; commands['['] = "while(*p){"; commands[']'] = "}"; FILE *output = fopen(OUTPUT_NAME, "w"); FILE *input = fopen(input_name, "r"); if (output == NULL || input == NULL) { printf("File error\n"); return 1; } fseek(input, 0, SEEK_END); int size = ftell(input); fseek(input, 0, SEEK_SET); char *brainfuck_code = calloc(size + 1, sizeof(char)); fread(brainfuck_code, 1, size, input); fclose(input); char program_template[] = "#include <stdio.h>\n" "char m[" AVAILABLE_MEMORY "];\n" "char *p = m;\n" "int main(void) {%s return 0;}"; char *code = NULL; int code_size = 0; for (int i = 0; brainfuck_code[i] != 0; i++) { if (commands[brainfuck_code[i]] == NULL) { continue; } int length = strlen(commands[brainfuck_code[i]]); code = realloc(code, code_size + length + 1); strcpy(code + code_size, commands[brainfuck_code[i]]); code_size += length; } int output_length = strlen(code) + strlen(program_template); char *final_output = calloc(output_length + 1, sizeof(char)); sprintf(final_output, program_template, code); fputs(final_output, output); fclose(output); free(code); free(final_output); char template[] = COMPILER " -o %s " OUTPUT_NAME; char *selected_name = argc > 2 ? argv[2] : "brainfart"; int mem = strlen(template) + strlen(selected_name) + 1; char *system_command = calloc(mem, sizeof(char)); sprintf(system_command, template, selected_name); system(system_command); free(system_command); remove(OUTPUT_NAME); printf("Done\n"); return 0; }
C
#pragma once struct VoxelInfo { float4 min; // float4 float4 size; // float4 uint4 voxels_per_tile; // uint4 uint4 voxel_tiles_count; // uint4 float4 GetMin() { return min; } float4 GetSize() { return size; } uint4 GetVoxels_per_tile() { return voxels_per_tile; } uint4 GetVoxel_tiles_count() { return voxel_tiles_count; } };
C
/* ** minishell.c for minishell in /home/macmil_r/rendu/PSU_2013_minishell1 ** ** Made by a ** Login <macmil_r@epitech.net> ** ** Started on Fri Dec 13 16:45:11 2013 a ** Last update Sat Mar 8 21:47:15 2014 a */ #include <unistd.h> #include <stdlib.h> #include "minishell.h" char **path(char **tab, char **env) { int i; char *str; char **str1; i = 0; while (env[i] != '\0') { if (my_strncmp("PATH=", env[i], 5) == 0) str = env[i]; i = i + 1; } while (*str != '=') str = str + 1; str = str + 1; str1 = my_str_to_wordtab(str, ':'); return (str1); } char pid(char **tab, char **env, char **mypath) { int i; char *str; pid_t pid; int ret; ret = other_function(tab, env); if ((pid = fork()) == -1) exit(my_putstr("Fork problem")); i = 0; if (pid == 0) { while (mypath[i] != '\0') { str = my_strcat(mypath[i], "/"); str = my_strcat(str, tab[0]); execve(str, tab, env); i = i + 1; } if (ret == 0) my_putstr("Shell did not recognize your comand\n"); } else wait(0); } char *my_copy(char buff[50000]) { int i; char *str; i = 0; str = malloc(sizeof(char) * 50000); while (buff[i] != '\0') { str[i] = buff[i]; i = i + 1; } str[i] = '\0'; return (str); } char *my_read(int fd, int size) { int ret; int i; char buff[50000]; char *str; i = 0; ret = read(fd, buff, size); if (ret == 0 || ret == -1) exit(0); if (buff == NULL) exit(my_putstr("read not executable")); if (ret < 2) return (NULL); if (ret > 1) { while (buff[i] != '\0') { if (buff[i] == '\n') buff[i] = '\0'; i = i + 1; } } str = my_copy(buff); return (str); } int minishell(char **env) { char *buff; char **tab; char **mypath; int ret; char op; my_putstr("$>"); my_signal(); while (buff = my_read(0, 49999)) { if (buff != NULL) { op = operation(buff); tab = my_str_to_wordtab(buff, op); mypath = path(tab, env); if (op == ';') point(tab, env, mypath); else if (op == '|' && tab[1] != '\0') my_pipe(tab, env, mypath); else if (op == ' ') pid(tab, env, mypath); } my_putstr("$>"); } }
C
// 2.3#include <stdio.h> // int main() // { // int i ; // for ( i = 1; i <= 100; i++) // { // if (i%2==0) // { // printf("%d\n ", i); // } // } // return 0; // } // 2.8#include <stdio.h> // int main() // { // float x, y; // scanf("%f%f", &x, &y); // int z = x + y; // printf("%.2f\n", x); // printf("%.2f\n", y); // printf("%d", z); // return 0; // } //2.7 #include <stdio.h> //problem // int main() // { // int x= 123456, y= 123456; // short int z = x + y; // printf("%hd", z); // return 0; // } //2.5 #include <stdio.h> // int main() // { // float r, s; // scanf("%f%f", &r, &s); // printf("***LIST OF ITEMS***\n"); // printf("Item price\n"); // printf("Rice Rs %.2f\n", r); // printf("Suger Rs %.2f", s); // return 0; // } // 2.4#include <stdio.h> // int main() // { // float x, y; // scanf("%f%f", &x, &y); // float z = x / y; // printf("%f\n",x); // printf("%f\n",y); // printf("%.2f",z); // return 0; // } // #include <stdio.h> // int main() // { // float f_number = 15.95; // int i_number = f_number * 100; // printf("%d", i_number); // return 0; // } // 2.1#include <stdio.h> // double sum(int n) // { // double sum = 0.0, i; // for (i = 1; i <= n; i++) // { // sum += 1 / i; // } // return sum; // } // int main() // { // int n; // scanf("%d", &n); // printf("%f\n", sum(n)); // return 0; // } 2.6// #include <stdio.h> // int main() // { // float numbers[5]; // int j, p = 0, n = 0; // printf("\nInput the number: "); // scanf("%f%f%f%f%f", &numbers[0], &numbers[1], &numbers[2], &numbers[3], &numbers[4]); // for (j = 0; j < 5; j++) // { // if (numbers[j] > 0) // { // p++; // } // else if (numbers[j] < 0) // { // n++; // } // else if (numbers[j] = 0) // { // break; // } // } // printf("\nNumber of positive numbers: %d", p); // printf("\nNumber of negative numbers: %d", n); // printf("\n"); // return 0; // } 2.10// #include<stdio.h> // #define TRUE 1 // #define PI 3.141593 // void main() // { // float a; // float b; // float c; // float d = PI; // if (TRUE) // { // a = 100; // b = a * 10; // c = b - a; // } // printf("\na=%f\nb=%f\nc=%f\nPI=%f", a, b, c, d); // } 2.9// #include <stdio.h> // int main() // { // typedef unsigned int unit; // unit i,j; // i = 10; // j=20; // printf("value of i = %d\n",i); // printf("value of j = %d\n",j); // return 0; // }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strchr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dgonor <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/10 13:55:10 by dgonor #+# #+# */ /* Updated: 2017/11/10 13:55:19 by dgonor ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strchr(const char *s, int c) { while (*s != (char)c && *s != '\0') { s++; } if (*s == (char)c) return ((char *)s); return (NULL); } /* **The strchr() function locates the first occurrence of **c (converted to a char) in the string **pointed to by s. The terminating null character is **considered to be part of the string; **therefore if c is `\0', the functions locate the terminating `\0'. **The strrchr() function is identical to strchr(), **except it locates the last occurrence of c. **RETURN VALUES **The functions strchr() and strrchr() return **a pointer to the located character, or NULL if **the character does not appear in the string. */
C
#include<stdio.h> #include<unistd.h> #include<sys/shm.h> #include<string.h> main(int argc, char** argv) { int i,k=1; key_t key= ftok("shmfile",65); int shmid =shmget(key,1024,0666|IPC_CREAT); char *str =(char*) shmat(shmid,(void*)0,0); for(i=0;i<argc;i++) { strcpy(str,argv[i]); } printf("Address is %d",&str); printf("Data written in memory:%s\n",str); shmdt(str); }
C
#include "TDA_lista.h" bool_t TDA_Lista_vacios(lista_t lista) { return lista==NULL; } status_t TDA_Lista_crear(lista_t * plista) { if(plista == NULL) return ST_ERROR_PUNTERO_NULO; *plista = NULL; return ST_OK; } status_t TDA_Lista_crear_nodo(nodo_t ** pnodo, void * dato) { if(pnodo == NULL) return ST_ERROR_PUNTERO_NULO; if((*pnodo= (nodo_t *) calloc(1, sizeof(nodo_t)))==NULL) return ST_ERROR_MEMORIA_INSUFICIENTE; (* pnodo)-> sig = NULL; (* pnodo)-> dato = dato; return ST_OK; } status_t TDA_Lista_destruir_nodo(nodo_t **pnodo, status_t (*destructor)(void *)) { if(pnodo == NULL) return ST_ERROR_PUNTERO_NULO; if(destructor != NULL) (*destructor)((*pnodo)->dato); (*pnodo)-> dato = NULL; (*pnodo)-> sig = NULL; free(*pnodo); *pnodo=NULL; return ST_OK; } status_t TDA_Lista_destruir(lista_t * plista, status_t (*destructor)(void *)) { nodo_t * primero; if(plista==NULL) return ST_ERROR_PUNTERO_NULO; while(*plista!=NULL) { primero=*plista; *plista=(*plista)->sig; TDA_Lista_destruir_nodo(&primero,destructor); } return ST_OK; } status_t TDA_Lista_insertar_ppio(lista_t * plista, void * dato) { status_t st; nodo_t *nodo; if(plista==NULL) return ST_ERROR_PUNTERO_NULO; if((st=TDA_Lista_crear_nodo(&nodo,dato))!=ST_OK) return st; nodo->sig=*plista; *plista=nodo; return ST_OK; } status_t TDA_Lista_insertar_final(lista_t * plista, void * dato) { status_t st; nodo_t *nodo,*aux; if(plista==NULL) return ST_ERROR_PUNTERO_NULO; if((st=TDA_Lista_crear_nodo(&nodo,dato))!=ST_OK) return st; if(*plista == NULL) { if((st=TDA_Lista_crear_nodo(&nodo,dato))!=ST_OK) return st; *plista=nodo; return ST_OK; } aux = *plista; while(aux->sig != NULL) aux = aux->sig; aux->sig = nodo; return ST_OK; } void * lista_buscar(lista_t plista, void *t, int(*cmp)(void*,void*)) { lista_t aux_recorrer; if(plista==NULL||cmp==NULL) return NULL; aux_recorrer = plista; while(aux_recorrer!=NULL && (*cmp)(t,aux_recorrer->dato)) aux_recorrer=aux_recorrer->sig; return (aux_recorrer==NULL)?NULL: aux_recorrer->dato; } /* int comparar_usuarios_por_id(void *dato1,void *dato2) { usuario_t *usr1,*usr2; usr1 =(usuario_t *)dato1; usr2 =(usuario_t *)dato2; if(usr1->id == usr2->id) si los id son iguales devuelve 0 return 0; return 1; si los id son diferentes devuelve 1 } */ status_t TDA_Lista_recorrer(lista_t lista, void(*pf)(void*,void*),void*arg) { if(lista==NULL||pf==NULL) return ST_ERROR_PUNTERO_NULO; while(lista!=NULL) { (*pf)(lista->dato,arg); lista=lista->sig; } return ST_OK; } status_t TDA_Lista_recorrer2(lista_t lista, void(*pf)(void*)) { if(lista==NULL||pf==NULL) return ST_ERROR_PUNTERO_NULO; while(lista!=NULL) { (*pf)(lista->dato); lista=lista->sig; } return ST_OK; } nodo_t * TDA_Lista_siguiente(nodo_t * nodo) { return nodo->sig; } void imprimir(void *dato) { usuario_t* aux; int i; aux = (usuario_t *)dato; printf("ID: %d\n",aux->id); printf("Nombre: %s\n",aux->nombre); printf("Username: %s\n",aux->usuario); printf("Amigos:\n"); for (i=0;i<(aux->amigos->used_size);i++) printf("%d\n",aux->amigos->amigos[i]); TDA_Lista_recorrer2(aux->mensajes, &imprimir_mensajes); } void imprimir_mensajes(void *dato) { mensaje_t* aux; aux = (mensaje_t *)dato; printf("Mensaje_t\n"); printf("Id mensaje: %d\n",aux->id_mensaje ); printf("Fecha: %s\n",aux->str_time ); printf("Id usuario: %d\n",aux->id_usuario ); printf("Mensaje util: %s\n",aux->str_mensaje ); } void destruir_cadena (void *dato) { char *cadena; cadena =(char *)dato; free(cadena); cadena = NULL; } status_t destruir_struct_mensaje(void *dato) { mensaje_t* mensaje; mensaje = (mensaje_t *)dato; if(!mensaje) return ST_ERROR_PUNTERO_NULO; free(mensaje); mensaje = NULL; return ST_OK; } status_t destruir_usuario(void *dato) { usuario_t* usr; usr = (usuario_t *)dato; if(!usr) return ST_ERROR_PUNTERO_NULO; if((usr)->usuario) { free((usr)->usuario); (usr)->usuario = NULL; } if((usr)->nombre) { free((usr)->nombre); (usr)->nombre = NULL; } TDA_Vector_amigos_destruir(&(usr->amigos)); TDA_Lista_destruir(&(usr->mensajes),&destruir_struct_mensaje); free(usr); usr = NULL; return ST_OK; }
C
#include <stdio.h> #include <string.h> #include "dataio.h" int modify_credit(name, price) const char* name; int price; { char filename[20]; int i; int credit; FILE* person_data; strcpy(filename, "DATA\\"); i = 5; strncpy(&filename[i], name, 8); if (strlen(name) > 8) { i += 8; } else { i += strlen(name); } strcpy(&filename[i], ".txt"); person_data = fopen(filename, "r"); if (person_data == NULL) { // printf("Warning: Filename %s does not exist!\n", filename); credit = 0; } else { fscanf(person_data, "%i", &credit); fclose(person_data); } // Write only if the price would change credit if (price != 0) { credit += price; person_data = fopen(filename, "w"); if (person_data == NULL) { // printf("ERROR: Filename %s could not be created or overwritten!\nCheck system integrity!\n", filename); } else { fprintf(person_data, "%i", credit); fclose(person_data); } } return credit; }
C
// test_search_functions.c // <Teng-Ju Yang tyang28> #include <stdio.h> #include <assert.h> #include "search_functions.h" #include <stdlib.h> #include <string.h> #include <ctype.h> /* * Declarations for tester functions whose definitions appear below. * (You will need to fill in the function definition details, at the * end of this file, and add comments to each one.) * Additionally, for each helper function you elect to add to the * provided search_functions.h, you will need to supply a corresponding * tester function in this file. Add a declaration for it here, its * definition below, and a call to it where indicated in main. */ void test_file_eq(); // This one is already fully defined below. void test_populate_grid(); void test_find_right(); void test_find_left(); void test_find_down(); void test_find_up(); void test_find_all(); /* * Main method which calls all test functions. */ int main() { printf("Testing file_eq...\n"); test_file_eq(); printf("Passed file_eq test.\n\n"); printf("Running search_functions tests...\n"); test_populate_grid(); test_find_right(); test_find_left(); test_find_down(); test_find_up(); test_find_all(); /* You may add calls to additional test functions here. */ printf("Passed search_functions tests!!!\n"); } /* * Test file_eq on same file, files with same contents, files with * different contents and a file that doesn't exist. * Relies on files test1.txt, test2.txt, test3.txt being present. */ void test_file_eq() { FILE* fptr = fopen("test1.txt", "w"); fprintf(fptr, "this\nis\na test\n"); fclose(fptr); fptr = fopen("test2.txt", "w"); fprintf(fptr, "this\nis\na different test\n"); fclose(fptr); fptr = fopen("test3.txt", "w"); fprintf(fptr, "this\nis\na test\n"); fclose(fptr); assert( file_eq("test1.txt", "test1.txt")); assert( file_eq("test2.txt", "test2.txt")); assert(!file_eq("test2.txt", "test1.txt")); assert(!file_eq("test1.txt", "test2.txt")); assert( file_eq("test3.txt", "test3.txt")); assert( file_eq("test1.txt", "test3.txt")); assert( file_eq("test3.txt", "test1.txt")); assert(!file_eq("test2.txt", "test3.txt")); assert(!file_eq("test3.txt", "test2.txt")); assert(!file_eq("", "")); // can't open file } void test_populate_grid(){ char grid[10][10]; assert(populate_grid(grid, "grid.txt") == 4); } void test_find_right(){ char grid[10][10]; int n = populate_grid(grid, "grid.txt"); assert(find_right(grid, n, "key", stdout) == 1); } void test_find_left(){ char grid[10][10]; int n = populate_grid(grid, "grid.txt"); assert(find_right(grid, n, "tip", stdout) == 1); } void test_find_down(){ char grid[10][10]; int n = populate_grid(grid, "grid.txt"); assert(find_down(grid, n, "pop", stdout) == 1); } void test_find_up(){ char grid[10][10]; int n = populate_grid(grid, "grid.txt"); assert(find_up(grid, n, "pop", stdout) == 1); } void test_find_all(){ char grid[10][10]; int n = populate_grid(grid, "grid.txt"); assert(find_all(grid, n, "tip", stdout) == 1); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <errno.h> double f(double x); double Lagrange(double (*f)(),double *p, int order, double x); int main() { double p[5] = { 1, 1.1, 1.2, 1.3, 1.4 }; /* Store polynomial factors here:*/ puts("Will approximate f(x) = e^2x -1 with 4th order lagrange polynomial"); printf("f(1.25) = %.4f\n", Lagrange(&f, p, 5, 1.25)); return 0; } double f(double x) { return exp(2*x) -1; } double Lagrange(double (*f)(),double *p, int order, double x) { int j,m; double prod, L=0; for(j=0;j<order;++j) { prod=1; for(m=0;m<order;++m) if(m!=j) prod *= ((x - p[m])/(p[j]-p[m])); L += f(p[j])*prod; } return L; }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* simplesort.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: srepelli <marvin@le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2018/04/04 15:21:55 by srepelli #+# ## ## #+# */ /* Updated: 2018/07/17 16:37:01 by srepelli ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "../push_swap.h" int is_min(int *a, int len, int k) { int i; i = 0; while (i < len) { if (k > a[i]) return (0); i++; } return (1); } int whereismin(int *tab, size_t len) { int mil; int i; i = 0; mil = len / 2; while (i <= mil) { if (is_min(tab, len, tab[i])) return (1); i++; } return (0); } void simplesort(t_piles *p) { while (!issort(p)) { if ((p->lena > 2 && p->a[0] > p->a[1] && checksort(p) != 1) || is_min(p->a, p->lena, p->a[1])) sapr(p); while (p->lena > 2 && checksort(p) != 1) { if (is_min(p->a, p->lena, p->a[0])) pbpr(p); else { if (!whereismin(p->a, p->lena)) rrapr(p); else rapr(p); } } if (!issort(p) && !ft_arrayissort(p->a, p->lena) && !whereismin(p->a, p->lena)) rrapr(p); else if (!issort(p) && !ft_arrayissort(p->a, p->lena)) rapr(p); if (p->lenb) papr(p); } }
C
/* * Author: manuel * E-mail Manuel_Angel99@outlook.com * Created: 2016-08-30 16:44:00 * * File: getchar.c * Description: Implements the C standard getchar function wich returns the first character in the wrote line and prints the input */ #include <stdio.h> int getchar(void) { char buffer[1]; size_t lenght = 1; getline(buffer, &lenght); return buffer[0]; }
C
#include <stdio.h> int main() { int v = 1 == 1; printf("1: %d\n", v); v = 1 != 1; printf("2: %d\n", v); v = (3*3.2) < (4*2.3); printf("3: %d\n", v); float f1 = 2.781; float f2 = 3.14156; v = (f2 >= f1); printf("4: %d\n", v); double f3 = 3.1415600000000000001; v = (f3 == f2); printf("5: %d\n", v); f3 = 3.14156; v = (f3 == f2); printf("6: %d\n", v); /* * Woah!? What happened with this last one? * * Try to avoid using == when checking for equality of two floating point numbers. * * More on why this is later on in the course, but for a quick fix to this problem see if2.c */ return 0; }
C
#include<stdio.h> int main() { char c[] = "#Amit"; char *p =c; printf("%s %d",p,'aa'); }
C
#include "mylist.h" struct s_node *node_at(struct s_node *head, int n) { assert(n >= 0); assert(head != NULL); if (head != NULL) { struct s_node *temp; if (n <= 0) { return head; } temp = head; while (n > 0) /* loop through list */ { if (temp -> next == NULL) /*if we reach end of list, return last node */ { return temp; } temp = temp -> next; n--; } return temp; /* else return node at index n */ } else { return NULL; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int compareFiles(FILE *fp1, FILE *fp2) { char ch1 = getc(fp1); char ch2 = getc(fp2); int error = 0; while (ch1 != EOF && ch2 != EOF) { if (ch1 != ch2) { error++; } ch1 = getc(fp1); ch2 = getc(fp2); } return error; } void printquestion() { printf("\n\t1. Write a Program to Find factorial of a number.\n "); } int menu(){ printf("\n\n\t\t Welcome Student\n\n "); printquestion(); printf(" press 0 to exit.\n\nChoose Question Number: \n"); int q; scanf("%d", &q); return q; } int main(){ int q; q = menu(); while(q != 0){ int COUNT = q; // Input of the Code file system("del file.c"); system("del output.txt"); system("del prog.exe"); char sentence[1000]; FILE *fptr; fptr = fopen("program.txt", "w"); if(fptr == NULL) { printf("Error! File not Found!"); } char s[] ="end123"; printf("Enter a sentence , enter end123 to end:\n"); for(int i = 0;;i++) { gets(sentence); if (strcmp(sentence,s) == 0) { break; } fprintf(fptr,"%s\n", sentence); } fclose(fptr); // End Input of code file // Rename the Input code system("RENAME program.txt file.c"); // Comparing the output system("gcc -o prog file.c"); char Execute[50] = "prog < DATA/input"; char count[5]; itoa(COUNT, count, 10); strcat(Execute, count); strcat(Execute, ".txt > output.txt "); // Getting the output const char *EXECUTE = Execute; system(EXECUTE); char Checkfile[20] = "DATA/check"; strcat(Checkfile, count); strcat(Checkfile, ".txt"); // Name of Check Output file const char *CHECKFILE = Checkfile; FILE *fp1 = fopen("output.txt", "r"); FILE *fp2 = fopen(CHECKFILE, "r"); if (fp1 == NULL || fp2 == NULL) { printf("Error : Files not present"); exit(0); } if(compareFiles(fp1,fp2) == 0){ printf("Correct Answer!"); } else{ printf("Your output have mistakes.Try adding a new line at the end. "); } fclose(fp1); fclose(fp2); q = menu(); }; return 0; }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> void display() { extern int x; //we cannot use the global declared variable unless we use the keyword extern datatype variable printf("%d",x); } int main(){ extern int x; printf("%d\n",x); display(); getch(); return 0; } int x = 152; //we can declare the values where we want if we use the extern keyword
C
#include "apue.h" int main(void) { struct stat statbuf; /* git foo's file info */ if(stat("foo",&statbuf) < 0){ err_sys("stat error for foo"); } /* turn on set-group-ID and turn off group-execute */ if(chmod("foo",statbuf.st_mode & ~S_IXGRP | S_ISGID) < 0){ err_sys("chmod error for foo"); } /* set absoulte mode to "rw-r--r--" */ if(chmod("bar",S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0){ err_sys("chmod bar error"); } exit(0); }
C
#include<stdio.h> #include<stdlib.h> /** * @struct QueueNode * @desc Contains item and pointer to next QueueNode. */ struct QueueNode { int item; struct QueueNode* next; }; /** * @struct Queue * @desc Contains pointers to first node and last node, the size of the Queue. */ struct Queue { struct QueueNode* head; struct QueueNode* tail; int size; }; /** * @desc Creates the Queue by allocating space and initializing the pointers * @return pointer to the Queue structure */ struct Queue* createQueue () { struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue)); queue->size = 0; queue->head = NULL; queue->tail = NULL; return queue; } /** * @brief Adds an item at the end of the queue * @desc If it is the first item, both head and tail will point to it, * else tail->next and tail will point to the item. */ void Enqueue (struct Queue* queue, int item) { struct QueueNode* n = (struct QueueNode*) malloc (sizeof(struct QueueNode)); n->item = item; n->next = NULL; if (queue->head == NULL) { // no head queue->head = n; } else{ queue->tail->next = n; } queue->tail = n; queue->size++; } /** * @brief Returns and removes the first item from the queue */ int Dequeue (struct Queue* queue) { struct QueueNode* head = queue->head; int item = head->item; queue->head = head->next; queue->size--; free(head); return item; }
C
#include <stdio.h> #include <signal.h> int main(int argc, char **argv) { int sig, i; pid_t pid; pid = atoi(argv[1]); for (i = 2; i < argc; i++) { sig = atoi(argv[i]); kill(pid, sig); } }
C
#include<stdio.h> //function:input a decimal and output its binary form void to_bin(int n){ int r=n%2; if(n>=2) to_bin(n/2); putchar(r?'1':'0'); } int main(){ int n; scanf("%d",&n); to_bin(n); return 0; }
C
#include<stdio.h> #include<stdlib.h> struct node{ struct node *prev; int data; struct node *next; }*head=NULL; int count=0; void count_length() { struct node *temp=head; int c=0; while(temp!=NULL) { c++; temp=temp->next; } count=c; } void Insertion_At_front(int data) { struct node *newNode=NULL; newNode=malloc(sizeof(struct node)); newNode->prev=NULL; newNode->data=data; newNode->next=NULL; if(head==NULL) { head=newNode; } else { head->prev=newNode; newNode->next=head; head=newNode; } } void Insertion_At_end(int data) { struct node *newNode=NULL,*temp=head; newNode=malloc(sizeof(struct node)); newNode->prev=NULL; newNode->data=data; newNode->next=NULL; if(head==NULL) { head=newNode; } else { while(temp->next!=NULL) { temp=temp->next; } temp->next=newNode; newNode->prev=temp; } } void Insertion_At_Specific_location(int data,int loc) { struct node *newNode=NULL,*temp; int c=1; newNode=(struct node *)malloc(sizeof(struct node)); newNode->prev=NULL; newNode->data=data; newNode->next=NULL; temp=head; count_length(); if(loc>count) { printf("\nIndex out of range (0 to %d)\n",count); return; } while(c!=loc) { temp=temp->next; c++; } newNode->next=temp->next; newNode->prev=temp; temp->next=newNode; } void Deletion_at_front() { struct node *temp=NULL; temp=head; if(temp==NULL) { puts("List is already Empty"); } else { temp=temp->next; } head=temp; temp=NULL; free(temp); } void Deletion_at_end() { struct node *temp=NULL,*prev=NULL; temp=head; if(temp==NULL) { puts("List is Already Empty"); } else if(temp->next==NULL) { head=temp->next; free(temp); temp=NULL; } else { while(temp->next!=NULL) { prev=temp; temp=temp->next; } prev->next=temp->next; free(temp); temp=NULL; } } void Deletion_at_specific_location(int loc) { int c=0; struct node *temp=NULL,*temp2=NULL,*temp3=NULL; temp=head; if(temp==NULL) { puts("List is already Empty"); } elseif { temp=temp->next; } head=temp; temp=NULL; free(temp); while(c!=loc) { temp2=temp; temp=temp->next; c++; } if(temp->next==NULL) { puts("true"); temp2=temp->prev; temp->prev=NULL; temp2->next=NULL; } else{ temp->next->prev=temp2; temp2->next=temp->next; free(temp); } // temp2->next=temp->next->next; // temp->next=NULL; // temp2->prev=temp2; // temp->prev=NULL; // temp=NULL; // free(temp); } void display() { struct node *temp=head; if(temp==NULL) { puts("List is Empty"); } else { while(temp!=NULL) { printf("%d\t",temp->data); temp=temp->next; } printf("\n"); } } int main() { int n,val,loc; while(1) { puts("1.Insertion"); puts("2.Deletion"); puts("3.Display"); puts("4.Exit"); scanf("%d",&n); switch(n) { case 1: puts("-----Insertion Operation-----------"); puts("1.At front"); puts("2.At End"); puts("3.at any location"); scanf("%d",&n); switch(n) { case 1: puts("Enter a data (Integer type only)"); scanf("%d",&val); Insertion_At_front(val); break; case 2: puts("Enter a data (Integer type only)"); scanf("%d",&val); Insertion_At_end(val); break; case 3: puts("------Location by Index/postion----"); puts("Enter a data (Integer type only)"); scanf("%d",&val); puts("Enter the location"); scanf("%d",&loc); Insertion_At_Specific_location(val,loc); break; default: puts("Invalid Input"); break; } break; case 2: puts("---------- Deletion Operation --------------"); puts("1.Deletion at Front"); puts("2.Deletion at End"); puts("3.Deletion at Specific Location"); scanf("%d",&n); switch(n) { case 1: Deletion_at_front(); break; case 2: Deletion_at_end(); break; case 3: count_length(); printf("Enter the location (start index 0 to %d)\n",count); scanf("%d",&loc); if(count-1<loc) { printf("\nIndex out of range (0 to %d)\n",count); } else if(loc < 0) { printf("\nIndex out of range (0 to %d)\n",count); } else { Deletion_at_specific_location(loc); } break; default: puts("Invalid Option"); break; } break; case 3: display(); break; case 4: exit(1); default: puts("Invalid input"); } } display(); return 0; }
C
unsigned udb_int (unsigned n, unsigned * keys) { ght_hash_table_t * ht = ght_create (n); unsigned i; unsigned count; for (i = 0; i < n; i ++) { if (ght_get (ht, sizeof (keys [i]), & keys [i])) ght_remove (ht, sizeof (keys [i]), & keys [i]); else ght_insert (ht, (void *) & keys [i], sizeof (keys [i]), & keys [i]); } count = ght_count (ht); ght_finalize (ht); return count; } unsigned udb_str (unsigned n, char ** keys) { ght_hash_table_t * ht = ght_create (n); unsigned i; unsigned count; for (i = 0; i < n; i ++) { if (ght_get (ht, strlen (keys [i]), keys [i])) ght_remove (ht, strlen (keys [i]), keys [i]); else ght_insert (ht, (void *) keys [i], strlen (keys [i]), keys [i]); } count = ght_count (ht); ght_finalize (ht); return count; }
C
/* * Program name --- crosscompo.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include "crossmatch.h" #define BUFFER 100 #define FUNCTION 1 // 0: L1 distance, 1: euclid distance extern double epsilon; extern struct SeqList *list; extern int listnum; /* * Allocate memory for data sequence */ void malloc_double (struct DataElement *array) { int len; len = array->length; array->value = (double *)malloc(sizeof(double) * len); if (array->value == NULL) { printf ("array->value malloc error\n"); exit(1); } } /* * Read data sequence */ void read_file( char *filename, double *seq, int len ) { int j; char read_buf[BUFFER]; FILE *fp; if ( ( fp = fopen ( filename , "r" ) ) == NULL ){ printf( " %s can not open\n" , filename); exit(1); } j = 0; while (fgets(read_buf,BUFFER,fp) != NULL ){ seq[j] = atof(read_buf); j++; if (j >= len) break; } if (j < len) printf("Warning: sequence is short. length=%d\n", j); fclose(fp); } /* * Compute distance between elements */ double element_dist (double *x, double *y) { double dist; #if FUNCTION /* square of euclid distance */ dist = (*x - *y) * (*x - *y); #else double abs; /* L1 distance */ abs = *x - *y; if (abs < 0) { abs = -1 * abs; } dist = abs; #endif return (dist); } /* * Compute elapsed time (micro seconds) */ long long int get_time_usec (struct timeval start, struct timeval end) { long long sec, usec; if (start.tv_usec <= end.tv_usec) { sec = end.tv_sec - start.tv_sec; usec = end.tv_usec - start.tv_usec; } else { sec = end.tv_sec - start.tv_sec - 1; usec = end.tv_usec - start.tv_usec + 1000000; } return sec * 1000000 + usec; } /* * Compute maximum value */ double max (double *a, double *b, double *c) { double maximum; if (*a >= *b) { maximum = *a; } else { maximum = *b; } if (*c > maximum) { maximum = *c; } return (maximum); } /* * Compute minimum value */ double min (double *a, double *b, double *c) { double minmum; if (*a <= *b) { minmum = *a; } else { minmum = *b; } if (*c < minmum) { minmum = *c; } return (minmum); }
C
#include "stdio.h" #include "cmap.h" #define NVAL (1024 * 1024) int main() { CMap *map = cmap_init(); int a[1024 * 1024]; char **s; s = (char**)malloc(sizeof(char*) * NVAL); int i; printf("Populating arrays ...\n"); for (i = 0; i < NVAL; ++i) { a[i] = i; s[i] = (char*)malloc(sizeof(char) * 32); sprintf(s[i], "%d", i); } printf("done.\n"); printf("Adding %d values to the map ...\n", NVAL); for (i = 0; i < NVAL; ++i) cmap_add(map, s[i], &(a[i])); printf("done.\n"); printf("Checking map ...\n"); unsigned int collisions = 0; for (i = 0; i < NVAL; ++i) { int val = *(int*)cmap_get(map, s[i]); if (val != a[i]) { printf("collision: map[\"%s\"] = %d (expected %d)\n", s[i], val, a[i]); collisions++; } } printf("done.\n"); printf("Collisions: %f%\n", (float)collisions * 100. / NVAL); cmap_free(map); }
C
/* Header files stdio.h - for printf stdlib.h - for exit function */ #include <stdio.h> #include <stdlib.h> /* Help function */ void help_function() { /* Print help details and exit */ printf("Usage: cfs <URL>\n"); printf("<URL>\t\t Support http, https, port, path \n"); printf("If no arguments, print help\n"); /* Exit safely */ exit(0); }
C
#include "apue.h" int main(int argc, char *argv[]) { int bytes; int a, b; char line[MAXLINE]; while ( (bytes = read(STDIN_FILENO, line, MAXLINE)) > 0) { /* null terminate */ line[bytes] = 0; if (sscanf(line, "%d%d", &a, &b) == 2) { sprintf(line, "%d\n", a + b); bytes = strlen(line); write(STDOUT_FILENO, line, bytes); } } exit(0); }
C
/** ** main.c ** spor command line **/ /* TODO * - an optional outfd for a passthru hash? * - use varargs in macros */ #include <string.h> #include <stdlib.h> #include <unistd.h> #include "spor.h" #include "spor_ltc.h" #include "util.h" #define EXE "spor" #define PWPROMPT "Password: " #define PWCONFIRM "Confirm Password: " #define USAGE() \ fprintf(stderr, "Usage: " EXE " cmdstring\n"\ " [0,1,3-9]: set active file descriptor\n"\ " P,p: read password from (the terminal,input descriptor) and generate symmetric key\n"\ " i,o: set (input, output) to active file descriptor\n"\ " e,d: symmetric (encrypt,decrypt) input to output\n"\ " E,D: asymmetric (encrypt,decrypt) input to output\n"\ " g,f: asymmetric (sign,verify) input, signature to active descriptor\n"\ " b,v: asymmetric key type is (public,private)\n"\ " m,x: assymetric key (import from, export to) active descriptor\n"\ " k: generate new asymmetric key\n"\ "spaces are ignored, active descriptor is reset to stdin/out when accessed.\n"\ "passwords are are reset when used (i.e with e,d,vm, or vx).\n"\ "PP forces password confirmation prompt\n"\ "Examples:\n"\ " " EXE " 'k b3x PPvx 4g' 3>publickey >privatekey <file 4>file.sig\n"\ " " EXE " 'Pvm 3i 4f' <privatekey 3<file 4<file.sig\n"\ " " EXE " 'Pvm PPvx' <privatekey >privatekey.newpassphrase\n"\ " cat pwdfile | " EXE " 'p 3i 4o e' 3<clear 4>cipher\n"\ ),exit(1) /* global password buffers */ unsigned char pwbuf[BUFSZ], pwbuf2[BUFSZ]; struct asymkey akey; void cleanup_atexit(void) { /* overwrite our stack memory with zeros * size to burn is discovered experimentally * with stack_test.sh: increase the value until * the minimum stack size jumps * explicitly zero our password buffers */ s0_teardown(); zeromem(pwbuf, sizeof(pwbuf)); zeromem(pwbuf2, sizeof(pwbuf2)); zeromem(&akey, sizeof(akey)); burn_stack(1024*4); } /* manage input, output, active file descriptors */ #define GET(src, default) ((src<0) ? default : src) #define NEXTIN() (infd=GET(nextfd, 0),(nextfd=-1, infd)) #define NEXTOUT() (outfd=GET(nextfd, 1), (nextfd=-1, outfd)) #define CLOSEIN() (close(infd),infd=0) #define CLOSEOUT() (close(outfd), outfd=1) int main(int argc, char **argv) { int infd = 0, outfd = 1, nextfd = -1, savfd; char *cmd; unsigned char *pwptr = NULL; char *pwprompt = PWPROMPT; unsigned pwsz = 0, pwsz2 = 0; if (argc != 2 ) USAGE(); cmd = argv[1]; s0_setup(); s0_asym_setup(&akey); atexit(cleanup_atexit); for (int i=0; cmd[i]; i++) { switch ( cmd[i] ) { case ' ': /* ignored for input readability */ break; case 'p': /* get passphrase from a file descriptor */ pwsz = read_or_die(NEXTIN(), pwbuf, sizeof(pwbuf), "reading passphrase"); CLOSEIN(); break; case 'P': /* get a passphrase from the terminal */ if ( pwsz ) { /* this is a confirmation read */ memcpy(pwbuf2, pwbuf, pwsz); pwsz2 = pwsz; pwprompt = PWCONFIRM; } pwsz = readpass(pwprompt, pwbuf, sizeof(pwbuf)); if ( pwsz2 ) { if ( pwsz != pwsz2 ) DIE("password mismatch"); if ( memcmp(pwbuf, pwbuf2, pwsz) ) DIE("password mismatch"); } zeromem(pwbuf2, pwsz2); break; case 'i': /* (re)set active input descriptor */ infd=NEXTIN(); break; case 'o': /*(re)set active output descriptor */ outfd=NEXTOUT(); break; case 'e': /* encrypt */ s0_encrypt_stream(infd, outfd, pwbuf, pwsz); zeromem(pwbuf, pwsz); pwsz=0; CLOSEIN(); CLOSEOUT(); break; case 'd': /* decrypt */ s0_decrypt_stream(infd, outfd, pwbuf, pwsz); zeromem(pwbuf, pwsz); pwsz=0; CLOSEIN(); CLOSEOUT(); break; case 'E': s0_asym_encrypt_stream(&akey, infd, outfd); CLOSEIN(); CLOSEOUT(); break; case 'D': s0_asym_decrypt_stream(&akey, infd, outfd); CLOSEIN(); CLOSEOUT(); break; case 'g': /* sign stream on infd, write sig to nextfd*/ fprintf(stderr, "infd=%d, outfd=%d, nextfd=%d\n", infd, outfd, nextfd); s0_sign_stream(&akey, infd, NEXTOUT()); CLOSEIN(); CLOSEOUT(); break; case 'f': /* verify stream on input with sig on next descriptor*/ /* to keep the api consistent with other functions, * read the stream to be signed on infd * and force the caller to specify the fd of the sig */ savfd = infd; s0_verify_stream(&akey, savfd, NEXTIN()); CLOSEIN(); break; case 'b': pwptr=NULL; break; case 'v': pwptr=pwbuf; break; case 'm': /* mport asymmetric key */ s0_import_key(&akey, NEXTIN(), pwptr, pwsz); if ( pwptr ) { zeromem(pwbuf, pwsz); pwsz=0; } CLOSEIN(); break; case 'x': /* xport asymmetric key */ s0_export_key(&akey, NEXTOUT(), pwptr, pwsz); if ( pwptr ) { zeromem(pwbuf, pwsz); pwsz=0; } CLOSEOUT(); break; case 'k': /* generate asymmetric key */ s0_create_key(&akey); break; case '0': case '1': /* don't smash stderr */ case '3': case '4': case '5': case '6': case '7': case '8': case '9': nextfd = atoi(cmd+i); break; default: fprintf(stderr, "bad cmd: %c\n", cmd[i]); USAGE(); } } exit(0); }
C
#include "queue.h" #include "robio.h" void Queue_Initialize(Queue * queue) { queue->start = 0; queue->end = 0; queue->current_count = 0; } int Queue_PushEnd(Queue * queue, QUEUE_ITEM_TYPE item) { if ((queue->end + 1) % QUEUE_SIZE == queue->start) { return ERR_QUEUE_FULL; } assert((int)item, "Queue_PushEnd: item=0"); queue->items[queue->end].item = item; queue->end = (queue->end + 1) % QUEUE_SIZE; queue->current_count += 1; return 0; } QUEUE_ITEM_TYPE Queue_PopStart(Queue * queue) { if (queue->start == queue->end) { return 0; } QUEUE_ITEM_TYPE item = queue->items[queue->start].item; assert((int)item, "Queue_PopStart: item=0"); queue->start = (queue->start + 1) % QUEUE_SIZE; queue->current_count -= 1; return item; } int Queue_CurrentCount(Queue * queue) { return queue->current_count; } void PriorityQueue_Initialize(PriorityQueue * queue) { int i; for (i = 0; i < NUM_PRIORITIES; i++) { Queue_Initialize(&(queue->queues[i])); } queue->queues_with_items = 0; } int PriorityQueue_Put(PriorityQueue * queue, QUEUE_ITEM_TYPE item, QueuePriority priority) { if (!Queue_IsValidPriority(priority)) { assertf(0, "PriorityQueue_Put: Unknown priority %d", priority); return ERR_QUEUE_PRIORITY; } //robprintfbusy((const unsigned char *)"PQ: put %d at %d\n", item, priority); queue->queues_with_items |= 1 << (NUM_PRIORITIES - 1 - priority); //PriorityQueue_PrintItems(queue); return Queue_PushEnd(&(queue->queues[priority]), item); } QUEUE_ITEM_TYPE PriorityQueue_Get(PriorityQueue * queue) { return PriorityQueue_GetLower(queue, HIGHEST, 0); } QUEUE_ITEM_TYPE PriorityQueue_GetLower(PriorityQueue * queue, QueuePriority min_priority, QueuePriority * next_min_priority) { if (!Queue_IsValidPriority(min_priority)) { assertf(0, "PriorityQueue_GetLower: Unknown min_priority %d", min_priority); return (QUEUE_ITEM_TYPE) ERR_QUEUE_PRIORITY; } int queues_with_items = queue->queues_with_items; // Make leading bits zeros for higher priorities we don't want to check queues_with_items &= (1 << (NUM_PRIORITIES - min_priority)) - 1; int priority = __builtin_clz(queues_with_items); if (next_min_priority) { *next_min_priority = priority; } if (priority == NUM_PRIORITIES) { // No items in any queue return 0; } assertf(Queue_IsValidPriority(priority), "PriorityQueue_GetLower: Got bad priority %d from CLZ", priority); assertf(priority >= min_priority, "PriorityQueue_GetLower: Got bad priority %d from CLZ -- b", priority); QUEUE_ITEM_TYPE item = Queue_PopStart(&(queue->queues[priority])); if (item) { return item; } else { //robprintfbusy((const unsigned char *)"PQ: empty %d at %d\n", item, priority); queue->queues_with_items ^= 1 << (NUM_PRIORITIES - 1 - priority); //PriorityQueue_PrintItems(queue); return 0; } } int Queue_IsValidPriority(QueuePriority priority) { if (priority >= 0 && priority <= NUM_PRIORITIES - 1) { return 1; } else { return 0; } } void PriorityQueue_PrintItems(PriorityQueue * queue) { int i; int has_item; robprintfbusy((const unsigned char *)"PQ=%d ", queue); for (i = 0; i < NUM_PRIORITIES; i++) { has_item = queue->queues_with_items & 1 << (NUM_PRIORITIES - 1 - i); robprintfbusy((const unsigned char *)"%d=%d ", i, has_item); } robprintfbusy((const unsigned char *)"\n", queue); }
C
#include <stdio.h> // Call back function void funcA(); void funcB(void(*pFunc())); int main(int argc, char const *argv[]) { printf("Lets start...\n"); void (*pFunc)() = &funcA; // Calling a function with callback funktion as argument funcB(pFunc); return 0; } void funcA() { printf("This is function A"); } void funcB(void(*pFunc())) { printf("B is calling .....\n"); (*pFunc)(); // callback to A }
C
/* HEADER: CUG205.00; TITLE: WORDS for Microsoft; DATE: 09/24/86; DESCRIPTION: "Places words on individual lines."; KEYWORDS: Software tools, Text filters, words, make words; SYSTEM: MS-DOS; FILENAME: WORDS.C; WARNINGS: "The author claims copyrights and authorizes non-commercial use only."; AUTHORS: Michael M. Yokoyama; COMPILERS: Microsoft; */ #include <stdio.h> #include <ctype.h> main() { int ch; int col; col = 1; while ((ch = getchar()) != EOF) if (isalpha(ch)) { putchar(ch); col ++; } else if (col != 1) { putchar('\n'); col = 1; } } 
C
#include <string.h> class N { char _str[64]; int _nb; public: N(int nb) { _nb = nb; } void *setAnnotation(char *str) { int len = strlen(str); return (memcpy(this->_str, str, len)) } virtual void operator+(N *n) { return(this->_nb + n->_nb); } virtual void operator-(N *n) { return(n->_nb -this->_nb); } } int main(int ac, char ** av) { if (ac < 2) _exit(1); N *tmp1 = new N(5); N *tmp2 = new N(6); tmp1->setAnnotation(av[1]); tmp2->operator+(tmp1); // -> mov (%eax),%eax .. mov (%eax),%edx return (0); }
C
#include <stdio.h> int main() { int n=50, i, x; int vet[n]; // DETERMINANDO VALORES AO VETOR for(i=0; i<n; i++){ vet[i] = 1; } i=0; // ALTERAR OS VALORES DO VETOR ATE UM VALOR SER 0 do{ scanf("%d", &vet[i]); if(vet[i] != 0){ i++; } }while(vet[i] != 0); i=0; // MOSTRANDO NA TELA SE O NUMERO É POSITIVO OU NEGATIVO do{ if(vet[i] > 0){ printf("POSITIVO\n"); } else{ printf("NEGATIVO\n"); } i++; }while(vet[i] != 0); return 0; }
C
#include "stdio.h"; signed int factorial (signed int x,) { signed int output = 1; signed int i = 0; while (i < x) { output = output * i; i = i + 1; } return output; } void main () { signed int x = 10; signed int y = 10; signed int z = x + y; if (x + y == z) { z = z + z; } else { z = z - z; } }
C
/*========================================================= 第3-6節 ListConcate() ========================================================= */ #include <stdio.h> #include <stdlib.h> typedef struct tagListNode { int data; struct tagListNode* next; } ListNode; int InsertTail(ListNode*, int); int ListLength(ListNode*); void ListTraverse(ListNode*); void ListConcate(ListNode*, ListNode*); void FreeAllNode(ListNode*); void main(void) { ListNode* listA, *listB; FILE* fin; int insertdata; if ((fin = fopen("List.in", "r")) == NULL) { printf("File can not be opened, program terminate."); exit(1); } listA = (ListNode*)malloc(sizeof(ListNode)); listA->next = NULL; listB = (ListNode*)malloc(sizeof(ListNode)); listB->next = NULL; fscanf(fin, "%d", &insertdata); while (!feof(fin)) { InsertTail(listA, insertdata); InsertTail(listB, insertdata); fscanf(fin, "%d", &insertdata); } fclose(fin); printf("\n The elements of the listA are : \n"); ListTraverse(listA); printf("\n "); printf("\n The elements of the listB are : \n"); ListTraverse(listB); printf("\n "); ListConcate(listA, listB); printf("\n The elements of the listA ( after concatenation ) are : \n"); ListTraverse(listA); printf("\n "); FreeAllNode(listA); /*釋放所有節點*/ FreeAllNode(listB); /*釋放所有節點*/ exit(0); /*結束程式*/ } void ListTraverse(ListNode* head) { ListNode* p = head; p = p->next ; while (p) { printf("\t%d", p->data); p = p->next ; } } void ListConcate(ListNode* listA, ListNode* listB) { ListNode* p = listA ; while (p->next != NULL) { p = p->next ; } p->next = listB->next ; listB->next = NULL ; } int InsertTail(ListNode* head, int value) { ListNode* new_node, *p = head; if ((new_node = (ListNode*)malloc(sizeof(ListNode))) == NULL) { return (0); } new_node->data = value; new_node->next = NULL; while (p->next != NULL) { p = p->next; } p->next = new_node; return (1); } void FreeAllNode(ListNode* head) { ListNode* next_node; while (head != NULL) { next_node = head->next; free(head); head = next_node; } } 
C
#include <stdio.h> #include <fcntl.h> int main(void) { int intvar; FILE *fp; char stringvar[80]; float floatvar; ///char ready[80]; fp = fopen("/home/bheckel/junk2.txt", "r"); ///char *mystr = "5 words 6.0"; fscanf(fp, "%d %s %f", &intvar, stringvar, &floatvar); ///sscanf(mystr, "%d %s %f", &intvar, stringvar, &floatvar); printf("here %s and %f and %d\n", stringvar, floatvar, intvar); ///sprintf(ready, "TESTING %d", 5); ///printf("now here: %s\n", ready); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> int main(int argc, char **argv) { FILE *ifh; size_t rb; char *buf; int ret; const size_t bufsize = 257; if (argc < 2) { fprintf(stderr, "Need command-line arg.\n"); exit(EXIT_FAILURE); } for (int i = 1; i < argc; i++) { ifh = fopen(argv[i], "r"); if (ifh == NULL) { perror("fopen"); exit(EXIT_FAILURE); } printf("contents of %s:\n\n", argv[i]); buf = (char *)calloc(bufsize, 1); if (!buf) { fprintf(stderr, "Unable to allocate memory.\n\n"); exit(EXIT_FAILURE); } while ((rb = fread(buf, 1, bufsize - 1, ifh))) { printf("%s", buf); memset(buf, 0, bufsize); if (feof(ifh)) { break; } } free(buf); ret = fclose(ifh); if (ret == EOF) { perror("fclose"); exit(EXIT_FAILURE); } } return EXIT_SUCCESS; }
C
#include <stdio.h> int main() { int p; register int i = 5; // Note: if the register request is not honored the auto sc will be used. printf("i = %d\n", i); printf("%u\n", &p); // printf("%u\n", &i); // Note: you cannot find the address of a register variable return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_memory.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: afarapon <afarapon@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/04 21:34:28 by afarapon #+# #+# */ /* Updated: 2018/01/08 12:36:01 by afarapon ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static char *ft_help_one(char *src, t_all_flags all, char *sign) { char *temp; if (all.f_minus || !all.f_zero) { temp = src; src = ft_strjoin(sign, src); src = ft_make_width(src, all); } else { all.width = all.width - 2; src = ft_make_width(src, all); temp = src; src = ft_strjoin(sign, src); } free(temp); free(sign); return (src); } static char *ft_help_two(char *src, t_all_flags all, char *sign, int cmp) { char *temp; src = ft_make_precision(src, all); if (!cmp && sign && !all.dot && ((int)(ft_strlen(src) + 2) >= all.width || !all.f_zero)) { temp = src; src = ft_strjoin(sign, src); free(temp); } else if (!cmp && all.dot) { free(src); src = ft_strjoin(sign, ""); } else if (!cmp && sign && !all.dot && all.width) { src = ft_make_width(src, all); src[1] = 'x'; } if (sign) free(sign); src = ft_make_width(src, all); return (src); } static char *ft_memory_make(char *src, t_all_flags all, int cmp) { char *sign; sign = ft_get_hex_sign(all); if (sign && cmp) src = ft_help_one(src, all, sign); else if (!cmp && all.dot && !all.f_sharp) { free(src); src = ft_strdup(""); src = ft_make_width(src, all); } else src = ft_help_two(src, all, sign, cmp); return (src); } char *ft_print_memory(char **f, t_all_flags all_flags, va_list list) { char *res; unsigned long int ptr; (*f)++; all_flags.f_sharp = 1; all_flags.large = 0; ptr = va_arg(list, unsigned long int); res = ft_itoa_base(ptr, 16, all_flags); res = ft_make_precision(res, all_flags); res = ft_memory_make(res, all_flags, ft_strcmp("0", res)); return (res); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> void calculate_bribe(int *q, int qcount){ int bribe_cnt = 0, max; bool found_chaotic = false; for (int j = qcount - 1; j >= 0; j--){ // Calculate if chaotic queue found and break if necessary if(q[j] - (j + 1) > 2){ found_chaotic = true; break; } max = 0; if(q[j] - 2 > max){ max = q[j] - 2;} for(int i = max; i < j; i++){ bribe_cnt = (q[i] > q[j]) ? bribe_cnt + 1 : bribe_cnt; } } if(found_chaotic){ printf("%s\n", "Too chaotic"); } else{ printf("%d\n", bribe_cnt); } } int main(){ int n, T; int* q; scanf("%d", &T); for(int i = 0; i < T; i++){ // Input t-th test case scanf("%d", &n); // Allocate memory for the final q q = (int *)malloc((sizeof(int) * n)); // Get q entries for (int j = 0; j < n; j++){ scanf("%d", (q + j)); } calculate_bribe(q, n); free(q); } return 0; }
C
#include<stdio.h> int main() { int X,P; //X is price of coffee and P is discount rate int total_amount=0; //entire amount to pay in order to get it as FREE scanf("%d%d",&X,&P); P=100-P; while(X>0) { total_amount= total_amount + X; X = (P*X)/100; } printf("%d\n",total_amount); return 0; }
C
/*īI * MicroSDTFSPIģʽʵַ * http://www.cnblogs.com/einstein-2014731/p/4885382.html * * nios ii֮Micro SDTFspia * https://blog.csdn.net/ming1006/article/details/7283689# */ #include "include.h" #define MICROSD_CS PTB20_OUT //CS #define MICROSD_DI PTB21_OUT //DI #define MICROSD_CLK PTB22_OUT //CLK #define MICROSD_DO GPIO_Get(PTB23) //DO u32 spi_speed = 30;//the spi speed(0-255),0 is fastest //delay 1usactually notit maybe is several usI don't test it void usleep(u32 i){ while(i --); } //set CS low void CS_Enable(){ //set CS low MICROSD_CS = 0; } //set CS high and send 8 clocks void CS_Disable(){ //set CS high MICROSD_CS = 1; //send 8 clocks SDWriteByte(0xff); } //write a byte void SDWriteByte(u8 data){ u8 i; //write 8 bits(MSB) for(i = 0; i < 8; i++){ MICROSD_CLK = 0; usleep(spi_speed); if (data & 0x80) MICROSD_DI = 1; else MICROSD_DI = 0; data <<= 1; MICROSD_CLK = 1; usleep(spi_speed); } //when DI is free,it should be set high MICROSD_DI = 1; } //read a byte u8 SDReadByte(){ u8 data = 0x00, i; //read 8 bit(MSB) for (i = 0; i < 8; i++){ MICROSD_CLK = 0; usleep(spi_speed); MICROSD_CLK = 1; data <<= 1; if (MICROSD_DO == 1) data |= 0x01; usleep(spi_speed); } return data; } //send a command and send back the response u8 SDSendCmd(u8 cmd, u32 arg, u8 crc){ u8 r1, time = 0; //send the command,arguments and CRC SDWriteByte((cmd & 0x3f) | 0x40); SDWriteByte(arg >> 24); SDWriteByte(arg >> 16); SDWriteByte(arg >> 8); SDWriteByte(arg); SDWriteByte(crc); //read the respond until responds is not '0xff' or timeout do { r1 = SDReadByte(); time++; //if time out,return if (time > 254) break; } while (r1 == 0xff); return r1; } //reset SD card u8 SDReset(){ u8 i, r1, time = 0; //set CS high CS_Disable(); //send 128 clocks for (i = 0; i < 16; i++){ SDWriteByte(0xff); } //set CS low CS_Enable(); //send CMD0 till the response is 0x01 do{ r1 = SDSendCmd(CMD0, 0, 0x95); time++;//if time out,set CS high and return r1 if (time > 254){ //set CS high and send 8 clocks CS_Disable(); return r1; } } while (r1 != 0x01); //set CS high and send 8 clocks CS_Disable(); return 0; } //initial SD card(send CMD55+ACMD41 or CMD1) u8 SDInit() { u8 r1, time = 0; //set CS low GPIO_Init(GPIOB,20,GPO,1); GPIO_Init(GPIOB,21,GPO,1); GPIO_Init(GPIOB,22,GPO,1); GPIO_Init(GPIOB,23,GPI,0); SDReset(); CS_Enable(); //check interface operating condition r1 = SDSendCmd(CMD8, 0x000001aa, 0x87); //if support Ver1.x,but do not support Ver2.0,set CS high and return r1 if (r1 == 0x05) { //set CS high and send 8 clocks CS_Disable(); return r1; } //read the other 4 bytes of response(the response of CMD8 is 5 bytes) r1 = SDReadByte(); r1 = SDReadByte(); r1 = SDReadByte(); r1 = SDReadByte(); do{ //send CMD55+ACMD41 to initial SD card do{ r1 = SDSendCmd(CMD55, 0, 0xff); time++; //if time out,set CS high and return r1 if (time > 254){ //set CS high and send 8 clocks CS_Disable(); LCD_P8x16Str(0, 2, "ERROE"); return r1; } } while (r1 != 0x01); r1 = SDSendCmd(ACMD41, 0x40000000, 0xff); //send CMD1 to initial SD card //r1 = SDSendCmd(CMD1,0x00ffc000,0xff); time++; //if time out,set CS high and return r1 if (time > 254){ //set CS high and send 8 clocks CS_Disable(); return r1; } } while (r1 != 0x00); LCD_P8x16Str(0, 4, "succed"); //set CS high and send 8 clocks CS_Disable(); return 0; } //read a single sector u8 SDReadSector(u32 addr, u8 * buffer) { u8 r1; u8 i, time = 0; //set CS low CS_Enable(); //send CMD17 for single block read r1 = SDSendCmd(CMD17, addr << 9, 0x55); //if CMD17 fail,return if (r1 != 0x00){ //set CS high and send 8 clocks CS_Disable(); return r1; } //continually read till get the start byte 0xfe do{ r1 = SDReadByte(); time++; //if time out,set CS high and return r1 if (time > 30000){ //set CS high and send 8 clocks CS_Disable(); return r1; } } while (r1 != 0xfe); //read 512 Bits of data for (i = 0; i < 512; i++){ buffer[i] = SDReadByte(); } //read two bits of CRC SDReadByte(); SDReadByte(); //set CS high and send 8 clocks CS_Disable(); return 0; } //read multiple sectors u8 SDReadMultiSector(u32 addr, u8 sector_num, u8 * buffer) { u16 i, time = 0; u8 r1; //set CS low CS_Enable(); //send CMD18 for multiple blocks read r1 = SDSendCmd(CMD18, addr << 9, 0xff); //if CMD18 fail,return if (r1 != 0x00) { //set CS high and send 8 clocks CS_Disable(); return r1; } //read sector_num sector do { //continually read till get start byte do { r1 = SDReadByte(); time++; //if time out,set CS high and return r1 if (time > 30000 || ((r1 & 0xf0) == 0x00 && (r1 & 0x0f))) { //set CS high and send 8 clocks CS_Disable(); return r1; } } while (r1 != 0xfe); time = 0; //read 512 Bits of data for (i = 0; i < 512; i++) { *buffer++ = SDReadByte(); } //read two bits of CRC SDReadByte(); SDReadByte(); } while (--sector_num); time = 0; //stop multiple reading r1 = SDSendCmd(CMD12, 0, 0xff); //set CS high and send 8 clocks CS_Disable(); return 0; } //write a single sector u8 SDWriteSector(u32 addr, u8 * buffer) { u16 i, time = 0; u8 r1; u8 txt[16]; //set CS low CS_Enable(); do { do { //send CMD24 for single block write r1 = SDSendCmd(CMD24, addr << 9, 0xff); time++; //if time out,set CS high and return r1 if (time > 254){ //set CS high and send 8 clocks CS_Disable(); LCD_P8x16Str(10, 6, "ERRor"); sprintf(txt, "add:%04d", r1); LCD_P8x16Str(0, 0, (u8*) txt); return r1; } } while (r1 != 0x00); time = 0; //send some dummy clocks for (i = 0; i < 5; i++){ SDWriteByte(0xff); } //write start byte SDWriteByte(0xfe); //write 512 bytes of data for (i = 0; i < 512; i++){ SDWriteByte(buffer[i]); } //write 2 bytes of CRC SDWriteByte(0xff); SDWriteByte(0xff); //read response r1 = SDReadByte(); time++; //if time out,set CS high and return r1 if (time > 254){ //set CS high and send 8 clocks CS_Disable(); LCD_P8x16Str(10, 6, "ERR0"); return r1; } } while ((r1 & 0x1f) != 0x05); time = 0; //check busy do { r1 = SDReadByte(); time++; //if time out,set CS high and return r1 if (time > 60000){ //set CS high and send 8 clocks CS_Disable(); LCD_P8x16Str(10, 6, "ERR"); return r1; } } while (r1 != 0xff); //set CS high and send 8 clocks CS_Disable(); return 0; } //write several blocks u8 SDWriteMultiSector(u32 addr, u8 sector_num, u8 * buffer){ u16 i, time = 0; u8 r1; //set CS low CS_Enable(); //send CMD25 for multiple block read r1 = SDSendCmd(CMD25, addr << 9, 0xff); //if CMD25 fail,return if (r1 != 0x00){ //set CS high and send 8 clocks CS_Disable(); return r1; } do { do { //send several dummy clocks for (i = 0; i < 5; i++){ SDWriteByte(0xff); } //write start byte SDWriteByte(0xfc); //write 512 byte of data for (i = 0; i < 512; i++){ SDWriteByte(*buffer++); } //write 2 byte of CRC SDWriteByte(0xff); SDWriteByte(0xff); //read response r1 = SDReadByte(); time++; //if time out,set CS high and return r1 if (time > 254){ //set CS high and send 8 clocks CS_Disable(); return r1; } } while ((r1 & 0x1f) != 0x05); time = 0; //check busy do{ r1 = SDReadByte(); printf("n%d", r1); time++; //if time out,set CS high and return r1 if (time > 30000){ //set CS high and send 8 clocks CS_Disable(); return r1; } } while (r1 != 0xff); time = 0; } while (--sector_num); //send stop byte SDWriteByte(0xfd); //check busy do{ r1 = SDReadByte(); time++; //if time out,set CS high and return r1 if (time > 30000){ //set CS high and send 8 clocks CS_Disable(); return r1; } } while (r1 != 0xff); //set CS high and send 8 clocks CS_Disable(); return 0; } //get CID or CSD u8 SDGetCIDCSD(u8 cid_csd, u8 * buffer){ u8 r1; u16 i, time = 0; //set CS low CS_Enable(); //send CMD10 for CID read or CMD9 for CSD do { if (cid_csd == CID) r1 = SDSendCmd(CMD10, 0, 0xff); else r1 = SDSendCmd(CMD9, 0, 0xff); time++; //if time out,set CS high and return r1 if (time > 254) { //set CS high and send 8 clocks CS_Disable(); return r1; } } while (r1 != 0x00); time = 0; //continually read till get 0xfe do { r1 = SDReadByte(); time++; //if time out,set CS high and return r1 if (time > 30000){ //set CS high and send 8 clocks CS_Disable(); return r1; } } while (r1 != 0xfe); //read 512 Bits of data for (i = 0; i < 16; i++){ *buffer++ = SDReadByte(); } //read two bits of CRC SDReadByte(); SDReadByte(); //set CS high and send 8 clocks CS_Disable(); return 0; }
C
#include <stdio.h> //int main() { // int a = 10; // int *pi; // int **ppi; // // pi = &a; // ppi = &pi; // // printf("--------------------------------------------------\n"); // printf(" & * **\n"); // printf("--------------------------------------------------\n"); // printf("a%10d%10u\n", a, &a); // printf("pi%10u%10u%10d\n", pi, &pi, *pi); // printf("ppi%10u%10u%10u%10u\n", ppi, &ppi, *ppi, **ppi); // printf("--------------------------------------------------\n"); // // return 0; //} void swap_ptr(char **ppa, char **ppb); int main() { char *pa = "SSSS"; char *pb = "FFFF"; printf("pa -> %s, pb -> %s\n", pa, pb); swap_ptr(&pa, &pb); printf("pa -> %s, pb -> %s\n", pa, pb); return 0; } void swap_ptr(char **ppa, char **ppb) { char *pt; pt = *ppa; *ppa = *ppb; *ppb = pt; } //int main() { // int ary[5]; // // printf("ary : %u\t", ary); // printf(" ary ּ : %u\n", &ary); // printf("ary + 1 : %u\t", ary + 1); // printf(" &ary + 1 : %u\n", &ary + 1); // // return 0; //} //int main() { // int ary[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; // int(*pa)[4]; // int i, j; // // pa = ary; // for (i = 0; i < 3; i++) { // for (j = 0; j < 4; j++) { // printf("%5d", pa[i][j]); // } // printf("\n"); // } //} // //void swap(int *pa, int *pb); // //int main() { // int a = 10; // int b = 20; // // printf("a : %d\n", a); // printf("b : %d\n", b); // // swap(&a, &b); // // printf("a : %d\n", a); // printf("b : %d\n", b); // // return 0; //} // //void swap(int *pa, int *pb) { // int temp = *pa; // // *pa = *pb; // *pb = temp; //} //int main() { // int ary[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; // int(*pa)[4]; // int i, j; // // pa = ary; // for (i = 0; i < 3; i++) { // for (j = 0; j < 4; j++) { // printf("%5d", *(*(ary + i) + j)); // } // printf("\n"); // } //} //#define INF 999999999 // //void MaxAndMin(int *MPtr, int *mPtr, int *arr); // //int main() { // int *maxPtr = NULL; // int *minPtr = NULL; // int arr[5]; // // printf("迭 Է\n"); // for (int i = 0; i < 5; i++) { // scanf("%d", arr + i); // } // // MaxAndMin(&maxPtr, &minPtr, arr); // // printf("迭 ּ : %p\n", arr); // printf("ִ ּ : %p\n", maxPtr); // printf("ּڰ ּ : %p\n", minPtr); // // return 0; //} // //void MaxAndMin(int **MPtr, int **mPtr, int *arr) { // int max = 0; // int maxidx = 0; // int min = INF; // int minidx = 0; // // //ִ ã // for (int i = 0; i < 5; i++) { // if (*(arr + i) > max) { // max = *(arr + i); // maxidx = i; // } // } // // *MPtr = arr + maxidx; // // //ּڰ ã // for (int i = 0; i < 5; i++) { // if (*(arr + i) < min) { // min = *(arr + i); // minidx = i; // } // } // // *mPtr = arr + minidx; //}
C
/* Title : 9_median.c Author : Sandeep Date : 12 June 2019 Description : Reading two different unsorted arrays, finding median for those two arrays and finally finding the average of two medians Input : Two arrays, Number of terms in first and second array output : Sorted arrays, Medians for two arrays and average of two medians of the given arrays */ #include <stdio.h> #include <stdlib.h> //declare the functions float median( int *, int); void print(int *, int); void sorting(int *, int); void populate(int *, int); int main() { //declaring the variables char option; int num1, num2, status; float average, median1, median2; do { //clear the screen system("clear"); //enter the number of terms for two arrays and store them in the variables printf("enter the number of terms for 1st and 2nd array : "); status = scanf("%d%d", &num1, &num2); //validating input if (status != 2 || num1 <= 0 || num2 <= 0) { printf("invalid number of terms\n"); return 0; } //declaring 1st array int a[num1]; printf("enter the 1st array values\n"); //calling populate function to store values in the 1st array populate(a, num1); //declaring 2nd array int b[num2]; printf("enter the 2nd array values\n"); //calling populate function to store values in the 2nd array populate(b, num2); //sorting 1st array printf("\nfirst array after sorting\n"); sorting(a, num1); print(a, num1); //sorting 2nd array printf("\n2nd array after sorting\n"); sorting(b, num2); print(b, num2); //calling median function for 1st array median1 = median(a, num1); printf("\nmedian of 1st array = %f\n", median1); //calling median function for 2nd array median2 = median(b, num2); printf("\nmedian of 2nd array = %f\n", median2); //finding the average of two medians average = (median1 + median2) / 2.0f; printf("\naverage of two medians = %f\n", average); printf("want to continue...[Yy || Nn] : "); scanf("\n%c", &option); }while (option == 'Y' || option == 'y'); return 0; } //defining populate function void populate(int *p, int num) { int i; for (i = 0; i < num; i++) { scanf("%d", p++); } } //defining sorting function void sorting(int *p, int num) { int i, j, temp; for(i = 0; i < num; i++) { for(j = i; j < num; j++) { if ( *(p+i) > *(p+j)) { temp = *(p+i); *(p+i) = *(p+j); *(p+j) = temp; } } } } //defining print function to print values in the array void print(int *p, int num) { int i; for(i = 0; i < num; i++) { printf("%d\t", *(p + i)); } printf("\n"); } //defining median function to find median of an array float median( int *p, int num) { float median; if ( num % 2) { median = *(p+(num/2)); } else { median = ((*(p+num/2)) + (*(p+(num/2) -1)) ) / 2.0f ; } return median; }
C
/** ** Copyright 2017-2018 Lu <miroox@outlook.com> ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. **/ #include"lcd.h" static void LcdWrite(bit op,unsigned char dat) //写入命令/数据 { LCD1602_E = 0; //使能清零 LCD1602_RS = op; //选择发送命令|数据 LCD1602_RW = 0; //选择写入 #ifndef LCD1602_4PINS LCD1602_DATAPINS = dat; //放入命令/数据 Delay1ms(1); //等待数据稳定 LCD1602_E = 1; //写入时序 Delay1ms(5); //保持时间 LCD1602_E = 0; #else LCD1602_DATAPINS &= 0x0f; LCD1602_DATAPINS = HI4BITS(dat); //发送高四位 Delay1ms(1); LCD1602_E = 1; //写入时序 Delay1ms(5); //保持时间 LCD1602_E = 0; LCD1602_DATAPINS = LO4BITS(dat); //发送低四位 Delay1ms(1); LCD1602_E = 1; //写入时序 Delay1ms(5); //保持时间 LCD1602_E = 0; #endif } static char LcdRead(bit op) //读入状态/数据(好像并没什么用) { char dat; #ifndef LCD1602_4PINS LCD1602_DATAPINS=0xff; //其实我也不知道为什么要全部置一 LCD1602_E = 0; Delay1ms(3); LCD1602_RS = op; //选择发送命令|数据 LCD1602_RW = 0; //选择读出 LCD1602_E = 1; dat = LCD1602_DATAPINS; Delay1ms(1); LCD1602_E = 0; #else char buf; LCD1602_DATAPINS |= 0xf0; //高四位置一 LCD1602_E = 0; Delay1ms(3); LCD1602_RS = op; //选择发送命令|数据 LCD1602_RW = 0; //选择读出 LCD1602_E = 1; dat = LCD1602_DATAPINS; Delay1ms(1); LCD1602_E = 0; //EN脉冲宽度大于150ns Delay1ms(1); dat &= 0xf0; //取高位 LCD1602_DATAPINS |= 0xf0; //高四位置一 Delay1ms(1); LCD1602_E = 1; //之前至少延时大于30ns buf = LCD1602_DATAPINS; Delay1ms(1); LCD1602_E = 0; //EN脉冲宽度大于150ns Delay1ms(1); dat |= (buf>>4); //得到低位 #endif return(dat); } void LcdInit() //LCD初始化 { #ifndef LCD1602_4PINS #ifndef LCD1602_10ROWS LcdWrite(OP_COMD,CMD_8PINS|CMD_2LINE); #else LcdWrite(OP_COMD,CMD_8PINS|CMD_10ROW); #endif LcdWrite(OP_COMD,CMD_NOCUR); //开显示不显示光标 //LcdWrite(OP_COMD,CMD_CURRT); //写一个指针加1,这个好像是自动的 LcdWrite(OP_COMD,CMD_CLS); LcdWrite(OP_COMD,DDRAMADD(0x00)); //设置数据指针起点 #else LcdWrite(OP_COMD,0x32); //据说是将8位总线转为4位总线,咱也不懂 #ifndef LCD1602_10ROWS LcdWrite(OP_COMD,CMD_2LINE); #else LcdWrite(OP_COMD,CMD_10ROW); #endif LcdWrite(OP_COMD,CMD_NOCUR); //开显示不显示光标 //LcdWrite(OP_COMD,CMD_CURRT); //写一个指针加1,这个好像是自动的 LcdWrite(OP_COMD,CMD_CLS); LcdWrite(OP_COMD,DDRAMADD(0x00)); //设置数据指针起点 #endif lcd.ac=0; lcd.base=buffer; } #ifndef LCD1602_10ROWS #define is_lcdprint(x) (((x)>=32&&(x)<=127)||((x)>=160&&(x)<=223)) #else #define is_lcdprint(x) (((x)>=32&&(x)<=127)||((x)>=160&&(x)<=255)) #endif void LcdCls(void) { LcdWrite(OP_COMD,CMD_CLS); lcd.ac=0; memset(lcd.base,0,CHCOL*CHROW); } void LcdCursorShow(bit set) { if(set){ LcdWrite(OP_COMD,CMD_CURFLS); } else { LcdWrite(OP_COMD,CMD_NOCUR); } } void LcdLineFeed(void) { #ifndef LCD1602_10ROWS if(lcd.ac<SCDLINE){ LcdWrite(OP_COMD,CMD_CURES); LcdWrite(OP_COMD,DDRAMADD(SCDLINE)); lcd.ac=SCDLINE; } #else LcdCls(); #endif } void LcdBackspace(void) { if((lcd.ac&~SCDLINE)>0){ LcdWrite(OP_COMD,CMD_CRLMV); if(lcd.ac&~SCDLINE>SCCOL){ LcdWrite(OP_COMD,CMD_SCLMV); } LcdWrite(OP_DATA,' '); LcdWrite(OP_COMD,CMD_CRLMV); lcd.base[lcd.ac--]=0; } } void LcdDelete(void) { if(lcd.base[lcd.ac]){ LcdWrite(OP_DATA,0); LcdWrite(OP_COMD,CMD_CRLMV); lcd.base[lcd.ac]=0; } else { LcdBackspace(); } } void LcdPutchar(char c) { if(is_lcdprint(c) && (lcd.ac<(SCDLINE+40))){ if((lcd.ac&~SCDLINE)<CHCOL-1){ LcdWrite(OP_DATA,c); lcd.base[lcd.ac&~SCDLINE]=c; if((lcd.ac&~SCDLINE)>=SCCOL){ LcdWrite(OP_COMD,CMD_SCLMV); } lcd.ac++; } else { LcdWrite(OP_DATA,c); lcd.base[lcd.ac]=c; LcdLineFeed(); } } } void LcdCursorMov(bit drc) { if(drc==DRC_LEFT){ if((lcd.ac&~SCDLINE)>0 && lcd.base[lcd.ac-1] ){ LcdWrite(OP_COMD,CMD_CRLMV); if(lcd.ac&~SCDLINE>SCCOL){ LcdWrite(OP_COMD,CMD_SCLMV); } lcd.ac--; } } else { if((lcd.ac&~SCDLINE)!=(CHCOL-1) && lcd.base[lcd.ac+2] ){ LcdWrite(OP_COMD,CMD_CRRMV); if(lcd.ac&~SCDLINE>=SCCOL){ LcdWrite(OP_COMD,CMD_SCRMV); } lcd.ac++; } } }
C
#include "hashTable.h" #include "io.h" void initializeHT(int N) { //! initialize hash table with length "INITIAL_HT_SIZE_FACTOR" of N (1/4 of N) size = INITIAL_HT_SIZE_FACTOR * N; hT = (char **) malloc(sizeof(char *) * size); for (int i = 0; i < size; ++i) { hT[i] = NULL; } } float getFillFactor() { //! return the fill factor of the hash table float fillFactor = -1; int fillCount = 0; for (int i = 0; i < size; ++i) { if (hT[i] != NULL) fillCount++; } fillFactor = fillCount / (float) size; return fillFactor; } void resizeHT() { //! reconstruct the hash table by (usually) doubling its size //! only call this when the current fill factor of your hash table > MAX_FILL_FACTOR //! careful, when resizing, the 'size' variable should be changed as well such that the 'hashFunction's distribution will work //! be double careful! all the elements which are already in the hash table have to be RE-hashed! (explanation @ lab) int newSize = size * 2; char **newHT = (char **) malloc(sizeof(char *) * newSize); for (int i = 0; i < newSize; ++i) { newHT[i] = NULL; } char **oldHT = hT; hT = newHT; for (int i = 0; i < size; ++i) { if (oldHT[i]) { insert(oldHT[i]); } } size = newSize; } int insert(char *element) { //! insert an element //! returns the number of collisions which occurred before the element was inserted int collisionCount = 0; int i = 0; int pos = hashFunction(element, i); while (hT[pos] != NULL) { collisionCount++; i++; pos = hashFunction(element, i); } hT[pos] = (char *) malloc(sizeof(char) * MAX_STRING_LENGTH); strcpy(hT[pos], element); return collisionCount; } int hashFunction(char *content, int i) { int length = strlen(content); int k, sum; for (sum = 0, k = 0; k < length; k++) { sum += content[k]; } return (sum + i * i) % size; }
C
#include <stdio.h> int main() { long long int i,num,sum=0,sump=0; printf("Enter No "); scanf("%lld",&num); int temp = num; while(num>0) { i = num % 10; sum = sum + i; num /=10; } printf("Sum of All Digit %lld\n",sum); return 0; }
C
/* Pippolo - a nosql distributed database. Copyright (C) 2012 Andrea Nardinocchi (nardinocchi@psychogames.net) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "memory.h" struct str_pointer_node *memory = NULL; size_t filled_memory = 0; pthread_mutex_t mutex_memory; void p_memory_clean (void) { pthread_mutex_init(&mutex_memory, NULL); } void *_p_malloc (size_t size, const char *file, unsigned int line) { struct str_pointer_coords *coords = NULL; struct str_pointer_node *singleton = NULL; void *result = NULL; unsigned char *checksum = NULL; size_t length = (size+sizeof(str_pointer_coords))+pippolo_overflow; if ((result = malloc(length))) { checksum = (unsigned char *)((char *)result+size); coords = (str_pointer_coords *)(checksum+pippolo_overflow); coords->file = file; coords->line = line; memset(result, 0, size); *((unsigned int *)checksum) = pippolo_checksum; if ((singleton = (struct str_pointer_node *) malloc(sizeof(str_pointer_node)))) { singleton->pointer = result; singleton->size = size; pippolo_lock(mutex_memory); singleton->next = memory; memory = singleton; filled_memory += length; pippolo_unlock(mutex_memory); } else pippolo_log(ELOG_DEBUGGING, "memory in overallocation at %s (line %d)\n", file, line); } else pippolo_log(ELOG_DEBUGGING, "memory in overallocation at %s (line %d)\n", file, line); return result; } void *_p_realloc (void *pointer, size_t size, const char *file, unsigned int line) { struct str_pointer_node *singleton = memory; void *result = NULL; if ((result = _p_malloc(size, file, line))) { pippolo_lock(mutex_memory); singleton = memory; while (singleton) { if (singleton->pointer == pointer) { memcpy(result, pointer, p_min(singleton->size, size)); pippolo_unlock(mutex_memory); _p_free(pointer, file, line); pippolo_lock(mutex_memory); break; } singleton = singleton->next; } pippolo_unlock(mutex_memory); } return result; } void _p_free (void *pointer, const char *file, unsigned int line) { struct str_pointer_node *singleton = memory, *backup; pippolo_bool done; done.value = pippolo_false; pippolo_lock(mutex_memory); if (memory) { if (singleton->pointer == pointer) { memory = singleton->next; _p_free_check(singleton, file, line); done.value = pippolo_true; } else { while (singleton->next) { backup = singleton->next; if (backup->pointer == pointer) { singleton->next = backup->next; _p_free_check(backup, file, line); done.value = pippolo_true; break; } singleton = singleton->next; } } } pippolo_unlock(mutex_memory); if (!done.value) pippolo_log(ELOG_DEBUGGING, "suspicious of double pippolo_free called at %s (line %d)\n", file, line); free(pointer); } void _p_free_check (struct str_pointer_node *singleton, const char *file, unsigned int line) { struct str_pointer_coords *coords = NULL; size_t length = (singleton->size+sizeof(str_pointer_coords))+pippolo_overflow; unsigned char *checksum = NULL; checksum = (unsigned char *)(((char *)singleton->pointer)+singleton->size); if (*((unsigned int *)checksum) != pippolo_checksum) { coords = (struct str_pointer_coords *)(checksum+pippolo_overflow); pippolo_log(ELOG_DEBUGGING, "mistaken pointer allocated at %s (line %d) and pippolo_free'd at %s (line %d)\n", coords->file, coords->line, file, line); } filled_memory -= length; free(singleton); }
C
/* ** my_aff_comb2.c for my_aff_comb2 in /home/wuilla_j/rendu/Piscine_C_J03 ** ** Made by Julien Wuillaume ** Login <wuilla_j@epitech.net> ** ** Started on Wed Sep 30 11:33:29 2015 Julien Wuillaume ** Last update Wed Sep 30 20:13:04 2015 Julien Wuillaume */ int my_putchar(char c) { write(1, &c, 1); } int number_to_char(int n) { my_putchar(n/10 + 48); my_putchar(n%10 + 48); } int my_aff_comb2() { int number_1; int number_2; number_1 = 0; number_2 = 1; while (number_1 <= 99) { while (number_2 <= 99 && number_2 > number_1) { number_to_char(number_1); my_putchar(32); number_to_char(number_2); number_2 = number_2 + 1; if (number_1 != 98 && number_2 != 99) { my_putchar(44); } } number_1 = number_1 + 1; number_2 = number_1 + 1; } } int main() { my_aff_comb2(); }