language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <fcntl.h> #include <malloc.h> #define MAX_COM 8 #define MAX_COM_LEN 64 char **_getline(int *com_count, char **args) { int arg = 0; char **com = malloc(MAX_COM * sizeof(char*)); for (int i = 0; i < MAX_COM; ++i) { com[i] = malloc(MAX_COM_LEN); } for (int i = 0; i < MAX_COM; ++i) { *com_count = i + 1; arg = 0; for (int j = 0; j < MAX_COM_LEN; ++j) { read(STDOUT_FILENO, &com[i][j], 1); /* Разделение команд */ if (com[i][j] == '|') { com[i][j] = 0; args[i][arg] = 0; break; } /* Конец ввода строки */ if (com[i][j] == '\n') { com[i][j] = 0; args[i][arg] = 0; i = MAX_COM; break; } /* Разделение команды и аргументов */ if ( !arg && j > 1 && com[i][j] == '-' && com[i][j-1] == ' ') { args[i][arg++] = com[i][j]; --j; } else if (arg) { args[i][arg++] = com[i][j]; --j; } } } /* Удаление проделов в конце команд */ for (int i = 0; i < *com_count; ++i) { for(int j = 0; j < strlen(com[i]); ++j) if (com[i][j] == ' ') { com[i][j] = 0; break; } } return com; } void _free(char **buf, int row_count) { for (int i = 0; i < row_count; ++i) { free(buf[i]); } free(buf); } void _pipeline(char **com, char **args, int com_count) { int fd[2]; pid_t pid; for (int i = 0; i < com_count; ++i) { pipe(fd); pid = fork(); if (pid == 0) { /* Замена стандартного дескриптока и закрытие не используемых */ if (i != com_count -1) { dup2(fd[1], 1); close(fd[0]); } else { close(fd[0]); close(fd[1]); } /* Вызов команды с агрументами и без */ if (args[i][0] == 0) execlp(com[i], com[i], NULL); else execlp(com[i], com[i], args[i], NULL); } else { wait(NULL); /* Замена стандартного дескриптока и закрытие не используемых */ if(i != com_count - 1) { dup2(fd[0], 0); close(fd[1]); } else { close(fd[1]); close(fd[0]); } } } } int main() { pid_t pid; int fd_out[2]; int fd_in[2]; int com_count; char **com; char **args = malloc(MAX_COM * sizeof(char*)); for (int i = 0; i < MAX_COM; ++i) { args[i] = malloc(MAX_COM_LEN); } while(1) { /* Формирование массива команд и аргументов */ com = _getline(&com_count, args); if(!strcmp(com[0], "quit")) break; /* Конвеерное выполнение команд */ _pipeline(com, args, com_count); _free(com, MAX_COM); } _free(com, MAX_COM); _free(args, MAX_COM); return 0; }
C
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <err.h> #include "bus.h" void callback(void* _ctx, void* _msg) { int msg = *(int*) _msg; int ctx = *(int*) _ctx; printf("Callback for client %d received: 0x%x\n", ctx, msg); } int main() { Bus* bus; int msg0, msg1, ctx0, ctx1; ctx0 = 0; ctx1 = 1; msg0 = 0xdead; msg1 = 0xbeef; /* Create a new bus */ if (!bus_new(&bus, 0)) errx(EXIT_FAILURE, "error @ %s:%d: bus_new", __FILE__, __LINE__); /* Register clients with IDs 0 and 1 */ if (!bus_register(bus, 0, &callback, &ctx0) || !bus_register(bus, 1, &callback, &ctx1)) { bus_free(bus); errx(EXIT_FAILURE, "error @ %s:%d: bus_register", __FILE__, __LINE__); } /* Send the message to all registered clients (0 and 1) */ if (!bus_send(bus, 0, &msg0, BUS_BROADCAST)) { bus_free(bus); errx(EXIT_FAILURE, "error @ %s:%d: bus_send", __FILE__, __LINE__); } /* Unregister client with ID = 1 */ if (!bus_unregister(bus, 1)) { bus_free(bus); errx(EXIT_FAILURE, "error @ %s:%d: bus_unregister", __FILE__, __LINE__); } /* Send the message to all registered clients (just client 0) */ if (!bus_send(bus, 0, &msg1, BUS_BROADCAST)) { bus_free(bus); errx(EXIT_FAILURE, "error @ %s:%d: bus_send", __FILE__, __LINE__); } /* Delete the bus */ bus_free(bus); return 0; }
C
#include <stdio.h> #include <stdlib.h> struct Date { int day; int month; int year; }; struct person { char *name; int age; struct Date *dob; }; void display(struct person** details, int size) { int i; for (i = 0; i < size; i++) { printf("Name = %s\n", details[i] -> name); printf("Age = %d\n", details[i] -> age); printf("Date of birth in day/month/year = %d/%d/%d\n", details[i] -> dob -> day, details[i] -> dob -> month, details[i] -> dob -> year); } } int main() { int i; struct person **details = (struct person**) malloc(sizeof(struct person*) * 10); for (i = 0; i < 10; i++) { details[i] = (struct person*) malloc(sizeof(struct person)); details[i] -> dob = (struct Date*) malloc (sizeof(struct Date)); details[i] -> name = (char*) malloc (sizeof(char) * 20); } printf("Enter the details of 10 persons\n"); for (i = 0; i < 3; i++) { printf("Enter the name, age, DOB with day month and year in order\n"); scanf("%s", details[i] -> name); scanf("%d", &details[i] -> age); scanf("%d", &details[i] -> dob -> day); scanf("%d", &details[i] -> dob -> month); scanf("%d", &details[i] -> dob -> year); } display(details, 3); return 0; }
C
/* Programa de estilo primitivo */ #include <stdio.h> #define MX 1000 int main(void) { void Generar(int, double []); void Alterar(int, double []); void Imprimir(int, double []); int n; double v[MX]; n ++; LeeNComponentes: printf("\n Introduce el numero de componentes: "); scanf("%d", &n); if (n < 1 || n > MX) goto LeeNComponentes; Generar(n, v); Alterar(n, v); Imprimir(n, v); fflush(stdin); getchar(); return(0); }
C
/************************************************************************** AstronomicalAlgorithms A portable ANSI C implementation of some of the algorithms published in Astronomical Algorithms by Jean Meeus 2nd edition (December 1998) Willmann-Bell ISBN: 0943396638 by Christophe DAVID ([email protected]) You may use parts of this source code as long as - you mention clearly that its latest version can be obtained free of charge at http://www.christophedavid.org/ AND - you send me a free copy of whatever you make using this code. Comments and suggestions welcome. **************************************************************************/ /*! @file @brief calculates the Greenwich Mean Sideral Time @author Christophe DAVID \n [email protected] \n http://www.christophedavid.org @since 01/07/1999 @version 1.0 @date 05/04/2001 @bug no known bug @param double *GreenwichSideralTime @param short Year @param short Month @param short Day @param short Hours @param short Minutes @param short Seconds @param short Calendar @param short Mode @return - 0 : completed successfully - 1 : error in parameter 1 - 2 : error in parameter 2 - 3 : error in parameter 3 - 4 : error in parameter 4 - 5 : error in parameter 5 - 6 : error in parameter 6 - 7 : error in parameter 7 - 8 : error in parameter 8 - 9 : error in parameter 9 @if logger @image html http://www.mot.be/cgi-bin/logger.cgi?GreenwichSideralTime.c @endif */ /* see page 87 */ #ifdef ASTROALGO #include <math.h> #include <stdio.h> #include "AstroAlgo.h" __declspec(dllexport) short __stdcall #else short #endif ShGreenwichMeanSideralTime(double *pdoGreenwichSideralTime, short shY, short shM, short shD, short shH, short shm, short shS, short shCalendar, short shMode) /* shCalendar JULIAN for julian, GREGORIAN for gregorian */ /* shMode 1 gives the result in seconds */ /* shMode 2 gives the result in degrees */ { short shReturnValue = (short) 0; short shIsLeap = (short) 0; double ashDaysInMonth[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; double doInputJulianDate = (double) 0; if (pdoGreenwichSideralTime != NULL) { *pdoGreenwichSideralTime = (double) 0; } if (pdoGreenwichSideralTime == NULL) { shReturnValue = (short) 1; } else if ((shM < 1) || (shM > 12)) { shReturnValue = (short) 3; } else if ((shD < 1) || (shD > ashDaysInMonth[(int) shM - 1])) { shReturnValue = (short) 4; } else if ( (shH < 0) || (shH > 23) ) { shReturnValue = (short) 5; } else if ( (shm < 0) || (shm > 59) ) { shReturnValue = (short) 6; } else if ( (shS < 0) || (shS > 59) ) { shReturnValue = (short) 7; } else if ( (shCalendar != (short) JULIAN) && (shCalendar != (short) GREGORIAN) ) { shReturnValue = (short) 8; } else if ( (shMode != (short) 1) && (shMode != (short) 2) ) { shReturnValue = (short) 9; } /* leap year validation */ else if (ShIsLeapYear(&shIsLeap, (short) shY, shCalendar) != 0) { shReturnValue = (short) 901; } else if ((shM == 2) && (shD == 29) && (shIsLeap != 1)) { shReturnValue = (short) 101; } else if (ShJulianDay(&doInputJulianDate, shY, shM, shD, shCalendar) != 0) { shReturnValue = (short) 102; } else if (doInputJulianDate - floor(doInputJulianDate) != (double) 0.5) { shReturnValue = (short) 103; } else { double doT = (double) ((doInputJulianDate - (double) 2451545) / (double) 36525); if (shMode == 1) { *pdoGreenwichSideralTime = ( ( ((double) 6 * (double) 3600) + ((double) 41 * (double) 60) + (double) 50.54841 ) + ((double) 8640184.812866 * doT) + ((double) 0.093104 * doT * doT) - ((double) 0.0000062 * doT * doT * doT) ); *pdoGreenwichSideralTime += (double) 1.00273790935 * ( ((double) shH * (double) 3600) + ((double) shm * (double) 60) + ((double) shS) ); } else if (shMode == 2) { *pdoGreenwichSideralTime = ( (double) 100.46061837 + ((double) 36000.770053608 * doT) + ((double) 0.000387933 * doT * doT) - ((doT * doT * doT) / (double) 38710000) ); /* add H m S to InputJulianDate, see page 88 */ } } return shReturnValue; }
C
/* ============================================================================ Name : three_stacks_one_array_trial.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #define ARR_SIZE 30 #define NUM_OF_ARRAY 3 int array[ARR_SIZE]; int start = 0; int end = ARR_SIZE - 1; int middle = ARR_SIZE/2; void push(int value, int stack_no) { if (stack_no == 1) { if (start == ARR_SIZE/2 -1) { printf("Stack 1 limit exceeded"); } array[start++] = value; } else if (stack_no == 2) { if (end == middle) { printf("Stack 2 limit exceeded"); } array[end--] = value; } else if (stack_no == 3) { if (end == middle) { printf("Stack 3 limit exceeded"); } array[middle++] = value; } } int pop(int stack_no) { if (stack_no ==1) { if (start <= 0) { printf("Stack is empty. Cannot pop"); return 0; } return array[start--]; } else if (stack_no ==2) { if (end >= ARR_SIZE -1) { printf("Stack is empty. Cannot pop"); return 0; } return array[end++]; } else if(stack_no == 3) { if (middle <= ARR_SIZE /2) { printf("Stack is empty. Cannot pop"); return 0; } return array[middle--]; } return 0; } int main(void) { push(0, 1); push(1, 1); push(2, 1); push(3, 1); push(4, 2); push(5, 2); push(6, 3); push(7, 3 ); push(8, 1); push(9, 1); push(10, 1); push(11, 1); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); printf("%d\n", pop(1)); return 0; }
C
#include <assert.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <math.h> #include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include <unistd.h> // #define VERBOSE enum color { black, blue, red, purple, green, teal, yellow, white }; // SYSTEM void printLog(char* message, ...) { struct timeval currentTime; gettimeofday(&currentTime, NULL); char timestamp[27]; // enough for "-2147483648:00:00 00:00:00" + null strftime(timestamp, 27, "%Y:%m:%d %H:%M:%S", localtime(&currentTime.tv_sec)); printf("%s.%03d cloudbit: ", timestamp, currentTime.tv_usec / 1000); va_list args; va_start(args, message); vprintf(message, args); puts(""); va_end(args); } void printError(char* message) { printLog("%s: %s", message, strerror(errno)); } void fillTimeSpec(struct timespec* ts, double seconds) { double integral, fraction; fraction = modf(seconds, &integral); ts->tv_sec = (int)trunc(integral); ts->tv_nsec = (int)trunc(fraction * 1000000000); } void delay(double seconds) { struct timespec ts; fillTimeSpec(&ts, seconds); nanosleep(&ts, NULL); } bool socketHasMessage(uint32_t socket, double seconds) { struct timespec ts; fillTimeSpec(&ts, seconds); fd_set descriptors; FD_ZERO(&descriptors); FD_SET(socket, &descriptors); int result = pselect(socket + 1, &descriptors, NULL, NULL, &ts, NULL); return FD_ISSET(socket, &descriptors); } bool readFile(char* filename, uint8_t** buffer, uint32_t* size, bool nullTerminate) { FILE* file = fopen(filename, "rb"); if (file == NULL) { printError("Failed to read file during fopen"); *size = 0; *buffer = NULL; return false; } if (fseek(file, 0, SEEK_END) != 0) { printError("Failed to read file during fseek to end"); fclose(file); *size = 0; *buffer = NULL; return false; } uint32_t length = ftell(file); if (fseek(file, 0, SEEK_SET) != 0) { printError("Failed to read file during fseek to start"); fclose(file); *size = 0; *buffer = NULL; return false; } if (*size == 0) { *size = length; } else if (*size > length) { printLog("Failed to read file: insufficient data in file (file is %d bytes, need %d bytes)", length, *size); fclose(file); *size = 0; *buffer = NULL; return false; } uint32_t bufferSize = *size + (nullTerminate ? 1 : 0); *buffer = malloc(bufferSize); length = fread(*buffer, 1, *size, file); if (length != *size) { printError("Failed to read file during fread"); free(*buffer); *buffer = NULL; *size = 0; fclose(file); return false; } if (fclose(file) != 0) { printError("Failed to read file during fclose"); free(*buffer); *buffer = NULL; *size = 0; return false; } if (nullTerminate) *(*buffer + length) = 0; return true; } // The length is in bytes. The textBuffer must have length*2 characters. // No attempt is made to check for a null terminator in textBuffer. // If textBuffer contains any bytes that are not ASCII 0-9 a-f A-F, then // the method returns false, and byteBuffer will be in a corrupted state. // Otherwise, it returns true. bool decodeHexBytes(char* textBuffer, uint8_t* byteBuffer, uint32_t length) { uint32_t index; for (index = 0; index < length; index += 1) { uint8_t byteValue = 0; bool highByte = false; do { char digit = textBuffer[index * 2 + (highByte ? 0 : 1)]; uint8_t value; switch (digit) { case '0': value = 0; break; case '1': value = 1; break; case '2': value = 2; break; case '3': value = 3; break; case '4': value = 4; break; case '5': value = 5; break; case '6': value = 6; break; case '7': value = 7; break; case '8': value = 8; break; case '9': value = 9; break; case 'A': case 'a': value = 10; break; case 'B': case 'b': value = 11; break; case 'C': case 'c': value = 12; break; case 'D': case 'd': value = 13; break; case 'E': case 'e': value = 14; break; case 'F': case 'f': value = 15; break; default: return false; } if (highByte) value <<= 4; byteValue += value; highByte = !highByte; } while (highByte); byteBuffer[index] = byteValue; } } // NETWORK #define macAddressSize 6 struct network_t { struct sockaddr* serverAddress; uint32_t serverAddressLength; struct sockaddr* localAddress; uint32_t localAddressLength; uint32_t sendSocket; uint32_t receiveSocket; uint8_t localMacAddress[macAddressSize]; }; void initNetwork(char* serverName, uint16_t sendPort, uint16_t receivePort, uint8_t localMacAddress[macAddressSize], struct network_t* network) { // Resolve the server name. struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED; hints.ai_socktype = SOCK_DGRAM; struct addrinfo* serverAddresses; uint32_t result = getaddrinfo(serverName, NULL, &hints, &serverAddresses); if (result != 0) { printLog("Failed to resolve server address \"%s\": %s", serverName, gai_strerror(result)); exit(1); } // Configure the sending socket. assert(serverAddresses != NULL); network->serverAddressLength = serverAddresses->ai_addrlen; network->serverAddress = malloc(network->serverAddressLength); memcpy(network->serverAddress, serverAddresses->ai_addr, network->serverAddressLength); freeaddrinfo(serverAddresses); switch (network->serverAddress->sa_family) { case AF_INET: ((struct sockaddr_in*)(network->serverAddress))->sin_port = htons(sendPort); uint8_t* ip = (uint8_t*)&(((struct sockaddr_in*)(network->serverAddress))->sin_addr.s_addr); printLog("Using IPv4; server %s is at: %hhd.%hhd.%hhd.%hhd", serverName, *ip, *(ip + 1), *(ip + 2), *(ip + 3)); break; case AF_INET6: ((struct sockaddr_in6*)(network->serverAddress))->sin6_port = htons(sendPort); printLog("Using IPv6."); break; default: assert(0); } network->sendSocket = socket(network->serverAddress->sa_family, SOCK_DGRAM, 0); if (network->sendSocket < 0) { printError("Failed to open UDP socket for sending"); exit(1); } // Configure the receiving socket. network->receiveSocket = socket(AF_INET6, SOCK_DGRAM, 0); if (network->receiveSocket < 0) { printError("Failed to open UDP socket for receiving"); exit(1); } socklen_t one = 1; if (setsockopt(network->receiveSocket, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { printError("Failed to open UDP socket for receiving"); exit(1); } network->localAddressLength = sizeof(struct sockaddr_in6); network->localAddress = malloc(network->localAddressLength); memset(network->localAddress, 0, network->localAddressLength); ((struct sockaddr_in6*)(network->localAddress))->sin6_family = AF_INET6; ((struct sockaddr_in6*)(network->localAddress))->sin6_port = htons(receivePort); ((struct sockaddr_in6*)(network->localAddress))->sin6_addr = in6addr_any; if (bind(network->receiveSocket, network->localAddress, network->localAddressLength) < 0) { printError("Failed to bind UDP socket for receiving"); exit(1); } // Configure MAC address. memcpy(network->localMacAddress, localMacAddress, macAddressSize); } void doneNetwork(struct network_t* network) { free(network->serverAddress); network->serverAddress = NULL; network->serverAddressLength = 0; close(network->sendSocket); network->sendSocket = 0; free(network->localAddress); network->localAddress = NULL; network->localAddressLength = 0; close(network->receiveSocket); network->receiveSocket = 0; } uint32_t packetSize = macAddressSize + 1 + 1 + 2; uint32_t macAddressOffset = 0; uint32_t padding1Offset = macAddressSize + 0; uint32_t flagsOffset = macAddressSize + 1; uint32_t valueOffset = macAddressSize + 2; void sendToNetwork(struct network_t* network, uint16_t value, bool button) { uint8_t buffer[packetSize]; memcpy(&buffer[macAddressOffset], network->localMacAddress, macAddressSize); buffer[padding1Offset] = 0x00; buffer[flagsOffset] = 0x00; if (button) buffer[flagsOffset] |= 0x01; buffer[valueOffset + 0] = (uint8_t)((value >> 8) & 0xFF); buffer[valueOffset + 1] = (uint8_t)(value & 0xFF); uint32_t sentBytes = sendto(network->sendSocket, &buffer, sizeof(buffer), 0, network->serverAddress, network->serverAddressLength); if (sentBytes < 0) { printLog("Failed to send to UDP socket: %m"); return; } } struct packet_t { bool setLed; enum color color; bool setOutput; uint16_t value; }; #define bufferSize 10 bool receiveFromNetwork(struct network_t* network, struct packet_t* result) { uint8_t buffer[bufferSize]; uint32_t bytes = recv(network->receiveSocket, buffer, bufferSize, MSG_DONTWAIT | MSG_TRUNC); if (bytes < 0) { printLog("Failed to receive from UDP socket: %m"); return false; } if (bytes < bufferSize) { printLog("Received malformed packet on UDP socket: %m"); return false; } if (buffer[0] != network->localMacAddress[0] || buffer[1] != network->localMacAddress[1] || buffer[2] != network->localMacAddress[2] || buffer[3] != network->localMacAddress[3] || buffer[4] != network->localMacAddress[4] || buffer[5] != network->localMacAddress[5]) { printLog("Received packet on UDP socket intended for another cloudbit"); return false; } result->setLed = (buffer[6] & 0x80) > 0; result->color = result->setLed ? buffer[6] & 0x07 : 0x00; result->setOutput = (buffer[7] & 0x80) > 0; result->value = result->setOutput ? (buffer[8] << 8) + buffer[9] : 0xFFFF; return true; } // LOW-LEVEL HARDWARE ACCESS void poke(uint32_t* page, uint32_t offset, uint32_t value) { #ifdef VERBOSE printLog("poke 0x%08x + 0x%04x : %8x", page, offset, value); #endif *(volatile uint32_t*)((uint32_t)page + offset) = value; } uint32_t peek(uint32_t* page, uint32_t offset) { uint32_t result = *(volatile uint32_t*)((uint32_t)page + offset); #ifdef VERBOSE printLog("peek 0x%08x + 0x%04x : %8x", page, offset, result); #endif return result; } // HIGH-LEVEL HARDWARE ACCESS // - ADC uint16_t readInput(uint32_t* page) { const uint32_t atTriggerBefore = 0x0004; const uint32_t atTriggerAfter = 0x0018; const uint32_t atValue = 0x0050; uint32_t newValue; bool wasHighBitSet = (newValue = peek(page, atValue)) >= 0x80000000; poke(page, atTriggerBefore, 0x00000001); while (wasHighBitSet == ((newValue = peek(page, atValue)) >= 0x80000000)) { } poke(page, atTriggerAfter, 0x00000001); newValue = newValue &~ 0x80000000; if (newValue < 200) newValue = 200; if (newValue > 1700) newValue = 1700; newValue = ((newValue - 200) * 0xFFFF) / 1500; assert((newValue & 0xFFFF) == newValue); return (uint16_t)newValue; } // - BUTTON bool readButton(uint32_t* page) { const uint32_t buttonOffset = 0x0610; uint32_t value = peek(page, buttonOffset); return (value & 0x00000080) == 0; } // - DAC uint32_t lastDacReadyFlag; void writeOutput(uint32_t* page, uint32_t value) { uint32_t counter = 0; do { uint32_t readyFlag; while (((readyFlag = peek(page, 0x0040) & 0x00000002) == lastDacReadyFlag) && counter < 100) { delay(0.0000000001); counter += 1; } // if we wait more than 100ns, just stop waiting and write the value regardless poke(page, 0x00F0, (value + 0x8000) % 0x10000); lastDacReadyFlag = readyFlag; } while (counter < 20); // try to write the value up to 20 times } // - LED void setColor(uint32_t* page, enum color value) { // green channel if ((value & 0b100) > 0) { poke(page, 0x0508, 0x40000000); } else { poke(page, 0x0504, 0x40000000); } // red channel if ((value & 0b010) > 0) { poke(page, 0x0508, 0x80000000); } else { poke(page, 0x0504, 0x80000000); } // blue channel if ((value & 0b001) > 0) { poke(page, 0x0518, 0x10000000); } else { poke(page, 0x0514, 0x10000000); } } // MAIN void main(int argc, char** argv) { printLog("initializing..."); // HARDWARE int32_t fd = open("/dev/mem", O_RDWR); if (fd < 0) { printError("Failed to open /dev/mem"); exit(1); } // Map the 8KB page around the GPIO hardware memory. uint32_t* gpioPage = mmap(NULL, 0x1fff, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x80018000); if (gpioPage == MAP_FAILED) { printError("Failed to mmap /dev/mem for LED hardware"); exit(1); } // Initialize the LED hardware. // This sequence based on LEDcolor.d and button.d. poke(gpioPage, 0x0114, 0xF0000000); // LED poke(gpioPage, 0x0124, 0x0000C000); // button poke(gpioPage, 0x0134, 0x03000000); // LED poke(gpioPage, 0x0704, 0x40000000); // LED poke(gpioPage, 0x0714, 0x10000000); // LED poke(gpioPage, 0x0718, 0x00000080); // button // Map the 8KB page around the DAC hardware memory. uint32_t* dacPage = mmap(NULL, 0x1fff, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x80048000); if (dacPage == MAP_FAILED) { printError("Failed to mmap /dev/mem for DAC hardware"); exit(1); } // The DAC hardware is initialized by DAC_init. lastDacReadyFlag = ~peek(dacPage, 0x0040) & 0x00000002; // assume it's ready // Map the 8KB page around the ADC hardware memory. uint32_t* adcPage = mmap(NULL, 0x1fff, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x80050000); if (adcPage == MAP_FAILED) { printError("Failed to mmap /dev/mem for ADC hardware"); exit(1); } // Initialize the ADC hardware. // This sequence based on ADC.d. poke(adcPage, 0x0008, 0x40000000); poke(adcPage, 0x0004, 0x00000001); poke(adcPage, 0x0028, 0x01000000); poke(adcPage, 0x0014, 0x00010000); poke(adcPage, 0x0034, 0x00000001); poke(adcPage, 0x0024, 0x01000000); poke(adcPage, 0x0144, 0x00000000); if (close(fd) < 0) { printError("Failed to close /dev/mem"); exit(1); } // NETWORK char* serverName; uint32_t serverNameLength = 0; if (!readFile("/root/localbit_server.cfg", (uint8_t**)&serverName, &serverNameLength, true)) { printLog("Failed to open server configuration file."); exit(1); } *(char*)(strchrnul(serverName, 0x0A)) = '\0'; printLog("Configured localbit server hostname is \"%s\"", serverName); char* localMacAddressString; uint32_t localMacAddressStringLength = 12; if (!readFile("/root/mac_address.cfg", (uint8_t**)&localMacAddressString, &localMacAddressStringLength, false)) { printLog("Failed to open MAC address file."); exit(1); } uint8_t localMacAddress[macAddressSize]; decodeHexBytes(localMacAddressString, localMacAddress, macAddressSize); printLog("Configured cloudbit device identity is \"%02x:%02x:%02x:%02x:%02x:%02x\"", *(localMacAddress+0), *(localMacAddress+1), *(localMacAddress+2), *(localMacAddress+3), *(localMacAddress+4), *(localMacAddress+5) ); struct network_t network; initNetwork(serverName, 2020, 2021, localMacAddress, &network); free(serverName); free(localMacAddressString); // PROGRAM LOOP setColor(gpioPage, black); writeOutput(dacPage, 0x0000); printLog("ready"); uint32_t lastValue = 0; double pause = 0.0; while (true) { if (socketHasMessage(network.receiveSocket, pause)) { struct packet_t packet; if (receiveFromNetwork(&network, &packet)) { printLog("received message: setLed=%02x color=%02x setOutput=%02x value=%04x", packet.setLed, packet.color, packet.setOutput, packet.value); if (packet.setLed) setColor(gpioPage, packet.color); if (packet.setOutput) writeOutput(dacPage, packet.value); } } bool button = readButton(gpioPage); uint16_t value = readInput(adcPage); printLog("input: %04x button: %02x", value, button); sendToNetwork(&network, value, button); int delta = abs(lastValue - value); lastValue = value; if (delta > 0x500 || button) { pause = 0.00; } else if (delta > 0x200) { pause -= 0.01; } else { pause += 0.01; } if (pause < 0.0) pause = 0.0; if (pause > 2.0) pause = 2.0; delay(0.01); } doneNetwork(&network); }
C
#include <stdio.h> #include <stdlib.h> typedef struct dummy_Cell { int data; struct dummy_Cell *next; } Cell; int main(){ Cell *c2; c2 = (Cell *)malloc(sizeof(Cell)); c2->data = 100; c2->next = NULL; Cell *c1; c1 = (Cell *)malloc(sizeof(Cell)); c1->data = 200; c1->next = NULL; c1->next = c2; printf("First cell %d, Next cell %d \n",c1->data,c2->data); printf("First cell %d, Next cell %d \n",c1->data,c1->next->data); free(c1); free(c2); return 0; } /**************answer********************** q238059h@iav059:~/program/network/1006$ ex4 First cell 200, Next cell 100 First cell 200, Next cell 100 ********************************************/
C
/*You will be given 3 integers as input. The inputs may or may not be different from each other. You have to output 1 if all three inputs are different from each other, and 0 if any input is repeated more than once. Input ----- Three integers on three lines. Output ------ 1 if the three inputs are different from each other , 0 if some input is repeated more than once SAMPLE TEST CASES : Test Case 1 Input: 3 2 1 Output: 1 Test Case 2 Input: 3 1 3 Output: 0 */ #include <stdio.h> void main() { int a, b, c; scanf("%d%d%d",&a,&b,&c); if(a != b && a != c && b != c) printf("\n1"); else printf("\n0"); }
C
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //4. Write a program which creates two thread, and by using appropriate synchronization technique avoid the scheduling problem. //Date : 15-10-2020 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h> int counter=0; pthread_mutex_t lock; //function to be considerd as thread void *ThreadProc(void *p) { pthread_mutex_lock(&lock); //lock lavlyamule serialy exicution hotay thread ch mhanjech at a time one thread only //cretical section part stats from hear unsigned long i=0; counter ++; printf("Task %d started succesfully\n", counter); for(i=0;i<0xffffffff;i++); //Execution bloking loop printf("Task %d finished succesfully\n", counter); //cretical section parts ends hear pthread_mutex_unlock(&lock); pthread_exit(NULL); } int main(int argc, char * argv[]) { pthread_t thread1, thread2; int ret =0; if(pthread_mutex_init(&lock,NULL) !=0) { printf("Error: Unable to create mutex\n"); } printf("Inside Main thread\n"); ret = pthread_create( &thread1, NULL, ThreadProc, NULL ); if(ret !=0) { printf("Error: Unable to create thread1\n"); } ret = pthread_create( &thread2, NULL, ThreadProc, NULL ); if(ret !=0) { printf("Error: Unable to create thread2\n"); } pthread_join(thread1,NULL); pthread_join(thread2,NULL); printf("Terminating Main thread\n"); pthread_exit(NULL); pthread_mutex_destroy(&lock); return 0; }
C
// Write a C Program to sort elements in Lexicographical Order (Dictionary Order) #include<stdio.h> #include<string.h> int main() { int n; printf("Enter number of words\n"); scanf("%d",&n); char a[n][50]; printf("Enter %d words\n",n); gets(a[0]); for(int i=0;i<n;i++) gets(a[i]); for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) if(strcmp(a[i],a[j])>0) { char temp[50]; strcpy(temp,a[i]); strcpy(a[i],a[j]); strcpy(a[j],temp); } printf("Entered words in lexicographical order are\n"); for(int i=0;i<n;i++) puts(a[i]); } /*Output: Enter number of words 3 Enter 3 words dictionary encyclopedia book Entered words in lexicographical order are book dictionary encyclopedia*/
C
#include <stdio.h> #include <stdlib.h> #include "file.h" file* creerFile (int taille){ file* f = (file*)malloc(sizeof(file)); f->t = (sommetParcours**)malloc(sizeof(sommetParcours*)*taille); f->taille = taille; f->tete = 0; f->queue = 0; return f; } void detruireFile (file* f){ free(f->t); } int fileVide (file* f){ int vide = 1; if(f->queue == f->tete){ vide =0; } return vide; } void enfiler (file* f, sommetParcours* sp){ (f->t)[f->queue] = sp; f->queue = (f->queue + 1)%(f->taille); } sommetParcours* defiler (file* f){ sommetParcours* s = (f->t)[(f->tete)]; f->tete = (f->tete + 1)%(f->taille); return(s); }
C
/*$ -fno-inline $*/ #include <stdio.h> int cse1(int a) { int x = a * 3; int y = 3 * a; return x + y; } int cse2(int a, int b) { int x = a * b; int y = b * a; return x - y; } int main() { printf("cse1(3) = %d (should be 18)\n", cse1(3)); printf("cse2(3,4) = %d (should be 0)\n", cse2(3,4)); return 0; }
C
#include <stdio.h> int main(void) { float a,b,c; printf("请输入实数a:");scanf("%f",&a); printf("请输入实数b:");scanf("%f",&b); printf("请输入实数c:");scanf("%f",&c); if (a==b && a==c) printf("1\n"); else if(a==b || a==c || b==c) printf("2\n"); else if (a+b>c && a+c>b && b+c>a ) printf("3\n"); else printf("0\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printxX.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hmoumani <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/23 21:23:26 by hmoumani #+# #+# */ /* Updated: 2020/01/19 23:48:31 by hmoumani ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" void ft_print_precx(int len, char *s) { int i; int width; width = (flags.prec > len) ? ft_absolute_val(flags.width) - (ft_absolute_val(flags.width) - flags.prec) - 1 : ft_absolute_val(flags.width) - len + 1; (flags.prec > 0 && ft_absolute_val(flags.prec) <= len && flags.width > len && flags.fill == '0') ? flags.fill = ' ' : 1; i = 0; (s[0] == '-') ? width++ : 1; if (flags.prec > len && width > 0) while (++width < flags.width) g_size += write(1, " ", 1); else if (flags.width > len) { if (s[0] == '-' && flags.width > len && ft_absolute_val(flags.prec) && flags.fill == '0') { s++; ft_putchar_fd('-', 1); width--; } while (i++ < flags.width - len) g_size += write(1, &flags.fill, 1); } i = 0; if (s[0] == '-') { s++; ft_putchar_fd('-', 1); width--; i--; } while (++i < flags.prec - len + 1) g_size += write(1, "0", 1); ft_putstr_fd(s, 1); if (flags.width * -1 > len + i) while (--width > 0 && flags.width < 0) g_size += write(1, " ", 1); } int ft_printd_x(int size, int num, char *s, int len) { int i; i = 0; if (flags.haspoint) flags.fill = (flags.fill == '0' && flags.prec > len) ? '0' : ' '; if (size > 0 && flags.width) { if (num < 0 && flags.fill == '0' && !flags.haspoint) { g_size += write(1, "-", 1); num *= -1; s++; } while (++i < size && !flags.haspoint) g_size += write(1, &(flags.fill), 1); while (++i <= size && flags.haspoint && flags.width > 0) g_size += write(1, " ", 1); } if (num == 0 && flags.prec == 0 && flags.haspoint && flags.width) ft_putchar_fd(' ', 1); else if (num == 0 && flags.prec == 0 && flags.haspoint && !flags.width) return (1); else ft_putstr_fd(s, 1); if (size < 0 && flags.width && ft_absolute_val(flags.width) > len) while (++size < 0) g_size += write(1, &(flags.fill), 1); return (1); } void ft_width_x(char *s, int num) { int size; size_t len; size = 0; len = ft_strlen(s); if (!flags.prec) { size = (flags.width > 0) ? flags.width - len + 1 \ : flags.width + len - 1; ft_printd_x(size, num, s, len); } else { ft_print_precx((int)len, s); } } static void ft_strrev(char *s) { char temp; int i; int len; i = 0; len = ft_strlen(s) - 1; while (i <= len / 2) { temp = s[i]; s[i] = s[len - i]; s[len - i] = temp; i++; } } static char *ft_dectohexax(unsigned int n) { char *hexadecinum; unsigned int i; unsigned int temp; i = 0; if (!(hexadecinum = ft_calloc(100, sizeof(char)))) return (NULL); hexadecinum[0] = '0'; while(n != 0) { temp = n % 16; if (temp < 10) hexadecinum[i] = temp + 48; else hexadecinum[i] = temp + 55; n = n / 16; if (flags.conv == 'x' || flags.conv == 'p') hexadecinum[i] = ft_tolower(hexadecinum[i]); i++; } ft_strrev(hexadecinum); return (hexadecinum); } void ft_printxX(va_list *args) { size_t n; char *s; n = va_arg(*args, size_t); s = ft_dectohexax(n); ft_width_x(s, n); }
C
/*==========================================================================*/ /* SEED reader | find_type43 | station header */ /*==========================================================================*/ /* Name: find_type43 Purpose: print channel poles and zeroes response table to standard output Usage: void find_type43 (); find_type43 (); Input: none - uses information in globally-available structure Output: none Externals: type43_head - 1st entry in table; defined in structures.h, allocated in globals.h Warnings: none Errors: none Called by: print_response Calls to: none Algorithm: print the contents of the structure to the standard output. Notes: The structure is a linked list; type43_head is the first member of the list Problems: none known References: Halbert et al, 1988; see main routine Language: C, hopefully ANSI standard Author: Dennis O'Neill Revisions: 02/16/94 CL changed string formated output to protect against null pointers */ #include "rdseed.h" #include "resp_defs.h" int find_type43(fp, code) FILE *fp; int code; { struct type43 *type43; /* looping vbl */ int i; /* counter */ char *blkt_id="B043"; /* blockette id string */ for (type43 = type43_head; type43 != NULL; type43 = type43->next) { if (type43->response_code == code) { if (fp == NULL) break; fprintf (fp,"%s+ +-----------------------",com_strt); fprintf (fp,"---------------------+ +\n"); fprintf (fp,"%s+ | Response (Poles & Zeros), %5s ch %3s",com_strt, current_station->station, current_channel->channel); fprintf (fp," | +\n"); fprintf (fp,"%s+ +-----------------------",com_strt); fprintf (fp,"---------------------+ +\n"); fprintf (fp,"%s\n",com_strt); fprintf (fp,"%s%s%2.2d Response type: ",blkt_id,fld_pref,5); switch (type43->response_type) { case 'A' : fprintf(fp," A [Laplace Transform (Rad/sec)]\n"); break; case 'B' : fprintf(fp," B [Analog (Hz)]\n"); break; case 'C' : fprintf(fp," C [Composite]\n"); break; case 'D' : fprintf(fp," D [Digital (Z-transform)]\n"); break; default : fprintf(fp," %c\n",type43->response_type ? type43->response_type : ' '); break; } fprintf (fp,"%s%s%2.2d Response in units lookup: ", blkt_id,fld_pref,6); find_type34(fp,type43->input_units_code); fprintf (fp,"%s%s%2.2d Response out units lookup: ", blkt_id,fld_pref,7); find_type34(fp,type43->output_units_code); fprintf (fp,"%s%s%2.2d A0 normalization factor: %G\n", blkt_id,fld_pref,8,type43->ao_norm); fprintf (fp,"%s%s%2.2d Normalization frequency: %G\n", blkt_id,fld_pref,9,type43->norm_freq); fprintf (fp,"%s%s%2.2d Number of zeroes: %d\n", blkt_id,fld_pref,10,type43->number_zeroes); fprintf (fp,"%s%s%2.2d Number of poles: %d\n", blkt_id,fld_pref,15,type43->number_poles); fprintf (fp,"%sComplex zeroes:\n",com_strt); fprintf (fp,"%s i real imag real_error imag_error\n", com_strt); for (i = 0; i < type43->number_zeroes; i++) fprintf (fp,"%s%s%2.2d-%2.2d %3d % E % E % E % E\n", blkt_id,fld_pref,11,14,i, type43->zero[i].real, type43->zero[i].imag, type43->zero[i].real_error, type43->zero[i].imag_error); fprintf (fp,"%sComplex poles:\n",com_strt); fprintf (fp,"%s i real imag real_error imag_error\n", com_strt); for (i = 0; i < type43->number_poles; i++) fprintf (fp,"%s%s%2.2d-%2.2d %3d % E % E % E % E\n", blkt_id,fld_pref,16,19,i, type43->pole[i].real, type43->pole[i].imag, type43->pole[i].real_error, type43->pole[i].imag_error); fprintf (fp,"%s\n",com_strt); break; } } if (type43 == NULL) return(0); else return(1); } int old_find_type43(fp, code) FILE *fp; int code; { struct type43 *type43; /* looping vbl */ int i; /* counter */ for (type43 = type43_head; type43 != NULL; type43 = type43->next) { if (type43->response_code == code) { if (fp == NULL) break; fprintf (fp,"B043\n"); fprintf (fp,"Response lookup code: %d\n", type43->response_code); fprintf (fp,"Response name: %s\n", type43->name ? type43->name : "(null)"); fprintf (fp,"Response type: %c\n", type43->response_type); fprintf (fp,"Response in units lookup: %4d ", type43->input_units_code); find_type34(fp,type43->input_units_code); fprintf (fp,"Response out units lookup: %4d ", type43->output_units_code); find_type34(fp,type43->output_units_code); fprintf (fp,"AO normalization factor: %G\n", type43->ao_norm); fprintf (fp,"Normalization frequency: %G\n", type43->norm_freq); fprintf (fp,"Number of zeroes: %d\n", type43->number_zeroes); fprintf (fp,"Number of poles: %d\n", type43->number_poles); fprintf (fp,"Complex zeroes:\n"); fprintf (fp," i real imag real_error imag_error\n"); for (i = 0; i < type43->number_zeroes; i++) fprintf (fp,"%3d % E % E % E % E\n", i, type43->zero[i].real, type43->zero[i].imag, type43->zero[i].real_error, type43->zero[i].imag_error); fprintf (fp,"Complex poles:\n"); fprintf (fp," i real imag real_error imag_error\n"); for (i = 0; i < type43->number_poles; i++) fprintf (fp,"%3d % E % E % E % E\n", i, type43->pole[i].real, type43->pole[i].imag, type43->pole[i].real_error, type43->pole[i].imag_error); fprintf (fp,"\n"); break; } } if (type43 == NULL) return(0); else return(1); }
C
#include <stdio.h> int main() { int lines_counter, character = 0; lines_counter = 0; while ((character = getchar()) != EOF) { if (character == '\n') { ++lines_counter; } } printf ("%ld\n", lines_counter); return 0; }
C
#include "ctrlmgr_loop.h" FILE *fp; void ctrl_loop_run(SharedStatus *status){ int running = 1; OperationStatus stat; fp = fopen("test.txt", "w"); while(running){ stat = dispatch_cmd(status); pthread_mutex_lock(status->lock); if(status->state->run_status != RUNNING){ running = 0; } pthread_mutex_unlock(status->lock); } fclose(fp); } OperationStatus dispatch_cmd(SharedStatus *status){ Command *cur_cmd; CommandStatus stat; int keep_running = 1; //Issue: command status set back to EXECUTING before cmdmgr thread starts again pthread_mutex_lock(status->lock); cur_cmd = status->state->current_cmd; // If the current command has been set to finished, and another command // is available (via next_cmd), then start executing the next command. if (status->state->current_cmd->status == STATUS_FINISHED && status->state->next_cmd != NULL){ cur_cmd = status->state->next_cmd; LOG_CTRL("Next command was available, using that one!\n"); LOG_CTRL("\tcounter: %d\n", cur_cmd->counter); LOG_CTRL("\tmode: %s\n", get_cmd_mode_name(cur_cmd->mode)); LOG_CTRL("\tstatus: %s\n\n", get_cmd_status_name(cur_cmd->status)); }else if(status->state->current_cmd->status == STATUS_FINISHED){ //LOG_CTRL("Current command is set to finished, but no next_cmd available.\n"); }else{ //LOG_CTRL("State not finished, next cmd may be available.\n"); } cur_cmd->status = STATUS_EXECUTING; pthread_mutex_unlock(status->lock); switch(cur_cmd->mode){ case NO_OP: stat = STATUS_FINISHED; break; case IDLE: stat = exc_idle(&(status->state->command_info), cur_cmd->params); break; case TAKE_OFF: stat = exc_takeoff(cur_cmd->params); break; case LAND: stat = exc_landing(cur_cmd->params); keep_running = 0; break; case HOVER: stat = exc_hover(&(status->state->command_info), cur_cmd->params); break; case PATROL: stat = exc_patrol(cur_cmd->params); break; } pthread_mutex_lock(status->lock); cur_cmd->status = stat; if(status->state->cmdmgr_status != RUNNING){ keep_running = 0; } //LOG_CTRL("ctrl loop: cmd status updated to %d\n", stat); if(!keep_running){ status->state->run_status = STOP; handle_shutdown(); LOG_CTRL("Ctrl loop service has stopped.\n"); // Signal buffer just in case cmd handler is waiting on empty buf pthread_cond_signal(status->buffer_cond); } pthread_cond_signal(status->command_cond); pthread_mutex_unlock(status->lock); return (stat == STATUS_FINISHED) ? STATUS_OK : STATUS_FAIL; } CommandStatus exc_idle(_Atomic(CommandInfo) *cmd_info, Parameters params){ fprintf(fp, "EXECUTING COMMAND: Idle\n"); idle(cmd_info); return STATUS_FINISHED; } CommandStatus exc_takeoff(Parameters params){ fprintf(fp, "EXECUTING COMMAND: TakeOff\n"); fprintf(fp, "\tRequested altitude: %d inches.\n", params.TakeOff.altitude); LOG_CTRL("EXECUTING COMMAND: TakeOff\n"); LOG_CTRL("\tRequested altitude: %d inches.\n", params.TakeOff.altitude); enable_leds(); //sleep(2); return STATUS_FINISHED; } CommandStatus exc_landing(Parameters params){ fprintf(fp, "EXECUTING COMMAND: Landing\n"); fprintf(fp, "\tRequested location: %d\tEmergency flag: %d.\n", params.Land.location, params.Land.emergency); LOG_CTRL("EXECUTING COMMAND: Landing\n"); LOG_CTRL("\tRequested location: %d\tEmergency flag: %d.\n", params.Land.location, params.Land.emergency); //sleep(2); return STATUS_FINISHED; } CommandStatus exc_hover(_Atomic(CommandInfo) *cmd_info, Parameters params){ fprintf(fp, "EXECUTING COMMAND: Hover\n"); fprintf(fp, "\tRequested pos: %d\tMaintain flag: %d.\n", params.Hover.location, params.Hover.maintain); LOG_CTRL("EXECUTING COMMAND: Hover\n"); LOG_CTRL("\tRequested pos: %d\tMaintain flag: %d.\n", params.Hover.location, params.Hover.maintain); hover(cmd_info); //sleep(2); return STATUS_FINISHED; } CommandStatus exc_patrol(Parameters params){ return STATUS_FINISHED; }
C
#include<stdio.h> #include<conio.h> int ITEM,FRONT,REAR,QUEUE[10]; void insert(int ITEM) { if(FRONT==1 && REAR==10 || FRONT==REAR+1) { printf("OverFlow Condition"); } if(FRONT==NULL) { FRONT=1; REAR=1; } else { REAR=REAR+1; } QUEUE[REAR]=ITEM; } void delet() { if(FRONT==NULL) { printf("UnderFlow Condition"); } QUEUE[FRONT]=ITEM; if(FRONT==REAR) { FRONT=NULL; REAR=NULL; } else if(FRONT==10) { FRONT=1; } else { FRONT=FRONT+1; } } void main() { int i; clrscr(); insert(2); insert(4); insert(7); delet(); insert(10); insert(1); printf("Elements of queue\n"); for(i=1;i<=REAR;i++) { printf("%d\n",QUEUE[i]); } delet(); printf("Elements of QUEUE\n"); for(i=1;i<=REAR;i++) { printf("%d\n",QUEUE[i]); } getch(); }
C
/* Copyright (c) 1986 AT&T */ /* All Rights Reserved */ /* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T */ /* The copyright notice above does not evidence any */ /* actual or intended publication of such source code. */ /* This module is created for NLS on Sep.03.86 */ #ident "@(#)wsncat.c 1.6 93/12/02 SMI" /* from JAE2.0 1.0 */ /* * Concatenate s2 on the end of s1. S1's space must be large enough. * At most n characters are moved. * return s1. */ #include <stdlib.h> #include <wchar.h> #pragma weak wcsncat = _wcsncat #pragma weak wsncat = _wsncat wchar_t * _wcsncat(wchar_t *s1, const wchar_t *s2, size_t n) { register wchar_t *os1 = s1; while (*s1++) /* find end of s1 */ ; ++n; --s1; while (*s1++ = *s2++) /* copy s2 to s1 */ if (--n == 0) { /* at most n chars */ *--s1 = 0; break; } return (os1); } wchar_t * _wsncat(wchar_t *s1, const wchar_t *s2, size_t n) { return (wcsncat(s1, s2, n)); }
C
double x = 1.23456; /* 預設顯示 6 位 */ printf("x = %lf\n", x); /* 整體寬度佔 10 個長度 (含 "點" 與 "小數") */ printf("x = %10lf\n", x); /* 顯示小數點 2 位 */ printf(" x = %.2lf\n", x); /* 整體寬度佔 10 個長度 顯示小數點 2 位*/ printf(" x = %10.2lf\n", x); /* 寬度、小數位數由變數控制 */ int width = 10; int precision = 2; printf(" x = %*lf\n", width, x); /* 由變數指定寬度 */ printf(" x = %.*lf\n", precision, x); /* 由變數指定顯示位數 */ printf(" x = %*.*lf\n", width, precision, x); /* 由變數指定寬度與顯示位數 */
C
/*Given a number N. Write a program to check whether every bit in the binary representation of the given number is set or not. Input: First line of input contains a single integer T which denotes the number of test cases. T test cases follows. First line of each test case contains a single integer N which denotes the number to be checked. Output: For each test case, print "YES" without quotes if all bits of N are set otherwise print "NO". Constraints: 1<=T<=1000 0<=N<=1000 Example: Input: 3 7 14 4 Output: YES NO NO */ #include<stdio.h> #include<stdlib.h> int main() { int t, i; scanf("%d", &t); for ( i = 0 ; i < t; i++ ) { int n; scanf("%d", &n); int x = binary(n); int ch = check(x); if( ch == 1) printf("YES\n"); else printf("NO\n"); } return 1; } int binary( int n) { int remainder = 0, i = 1, binary = 0; while( n!=0) { remainder = n%2; n = n/2; binary = binary + (remainder*i); i = i * 10; } return binary; } int check(int binary) { while(binary != 0) { int r = binary % 10; binary = binary / 10; if( r == 0) return 0; } return 1; }
C
#include <stdio.h> #include <stdarg.h> void GhiVaoTep(FILE* file, const char type, size_t size, ...); void thongBao(char* argc, ...); int main() { int a, b, c; FILE* file = fopen("input.txt", "r"); GhiVaoTep(file, 'd', 3, &a, &b, &c); fclose(file); thongBao("abc", a, b, c); } void GhiVaoTep(FILE* file, const char type, size_t size, ...) { va_list argv; va_start(argv, size); char format[] = "%x"; format[1] = type; for (; 0ull < size; size--) fscanf(file, format, va_arg(argv, size_t)); va_end(argv); } void thongBao(char* argc, ...) { va_list argv; va_start(argv, argc); do printf("%c : %d\n", *argc, va_arg(argv, int)); while (*(++argc)); va_end(argv); }
C
/***************************User's declarations********************************/ #include <stdio.h> /* printf */ #include <assert.h> /* assert */ #include "bst.h" /**********************assistance functions declarations***********************/ int IntCompare(const void *data1, const void *data2, void *param); int AddOne(void *data, void *param); void PrintList(const bst_t *bst); /************************Test function declarations****************************/ void BSTIsEmptyTest(const bst_t *bst); void BSTBeginTest(const bst_t *bst); void BSTEndTest(const bst_t *bst); void BSTGetDataTest(bst_iter_t iter); void BSTIterIsEqualTest(bst_iter_t iter1, bst_iter_t iter2); bst_iter_t BSTInsertTest(bst_t *bst, void *data); void BSTSizeTest(const bst_t *bst); void BSTDestroyTest(bst_t *bst); void BSTPrevTest(bst_iter_t iter); void BSTNextTest(bst_iter_t iter); void BSTRemoveTest(bst_iter_t iter); void BSTFindTest(const bst_t *bst, const void *data); void BSTForEachTest(bst_iter_t from, bst_iter_t to, bst_do_action_func_t do_action, void *param); /**********************Test case function declarations*************************/ void TestCase(void); /**********************************main****************************************/ int main(void) { printf("---------------------------------------\n"); TestCase(); printf("---------------------------------------\n"); return (0); } /************************Test function implemintations*************************/ void BSTIsEmptyTest(const bst_t *bst) { assert(bst); printf("\nIs Empty:\nThe list is"); BSTIsEmpty(bst) ? printf(" ") : printf(" not "); printf("empty.\n"); } /**********************************************************************/ void BSTBeginTest(const bst_t *bst) { bst_iter_t iter = {0}; int *num = NULL; printf("The first iterator to the smallest element is: "); iter = BSTBegin(bst); num = (int *)BSTGetData(iter); if(NULL == num) { printf("The list is empty\n\n"); } else { printf("%d\n", *num); } } /**********************************************************************/ void BSTEndTest(const bst_t *bst) { bst_iter_t iter = {0}; printf("\nBST End:\n"); if(BSTIsEmpty(bst)) { printf("The list is empty\n\n"); } else { iter = BSTEnd(bst); if (BSTGetData(iter) == NULL) { printf("You have received the end of the list.\n"); } } } /**********************************************************************/ void BSTGetDataTest(bst_iter_t iter) { printf("The integer stored in the given iter is: %d\n", *(int *)BSTGetData(iter)); } /**********************************************************************/ void BSTIterIsEqualTest(bst_iter_t iter1, bst_iter_t iter2) { printf("**Is Equal:**\nThe both iters are"); BSTIterIsEqual(iter1, iter2) ? printf(" ") : printf(" not "); printf("The same.\n"); } /**********************************************************************/ bst_iter_t BSTInsertTest(bst_t *bst, void *data) { bst_iter_t iter = {0}; iter = BSTInsert(bst, data); if(BSTIterIsEqual(iter ,BSTEnd(bst))) { printf("Insertion has been failed\n"); } else { printf("Insertion of element %d has been successful\n", *(int *)BSTGetData(iter)); } return (iter); } /**********************************************************************/ void BSTSizeTest(const bst_t *bst) { printf("\nYou have %ld elements in your list.\n\n", BSTSize(bst)); } /**********************************************************************/ void BSTDestroyTest(bst_t *bst) { BSTDestroy(bst); printf("\nThe list has been destroyed.\n"); } /**********************************************************************/ void BSTPrevTest(bst_iter_t iter) { bst_iter_t temp = {0}; temp = BSTPrev(iter); printf("\nPrev Test:\nYour iter is: %d\n", *(int *)BSTGetData(iter)); if(BSTGetData(temp)) { printf("The prev iter is: %d\n", *(int *)BSTGetData(temp)); } else { printf("You have entered an invalid iter\n"); } } /**********************************************************************/ void BSTNextTest(bst_iter_t iter) { bst_iter_t temp = {0}; temp = BSTNext(iter); printf("\nNext Test:\nYour iter is: %d\n", *(int *)BSTGetData(iter)); if(BSTGetData(temp)) { printf("The next iter is: %d\n", *(int *)BSTGetData(temp)); } else { printf("You have entered an invalid iter\n"); } } /**********************************************************************/ void BSTRemoveTest(bst_iter_t iter) { printf("\nRemove:\n%d has been removed from the list.\n", *(int *)BSTGetData(iter)); BSTRemove(iter); } /**********************************************************************/ void BSTFindTest(const bst_t *bst, const void *data) { bst_iter_t temp = {0}; printf("Find Test:\n"); temp = BSTFind(bst, data); if(BSTIterIsEqual(temp, BSTEnd(bst))) { printf("The wanted data %d was not found\n", *(int *)data); } else { printf("%d was found in the list.\n", *(int *)BSTGetData(temp)); } } /**********************************************************************/ void BSTForEachTest(bst_iter_t from, bst_iter_t to, bst_do_action_func_t do_action, void *param) { if(BSTForEach(from, to, do_action, param) == 0) { printf("\nThe action was successful for all the elements\n"); } else { printf("\nThe action was NOT successful for all the elements\n"); } } /**********************assistance functions Implementations********************/ int IntCompare(const void *data1, const void *data2, void *param) { assert(data1); assert(data2); (void)param; if(*(int *)data1 < *(int *)data2) { return (1); } if(*(int *)data1 == *(int *)data2) { return (0); } return (-1); } /**********************************************************************/ int AddOne(void *data, void *param) { (void)param; if(data == NULL) { return (0); } *(int *)data += 1; return (1); } /**********************************************************************/ void PrintList(const bst_t *bst) { bst_iter_t temp = {0}; bst_iter_t end = {0}; assert(bst); temp = BSTBegin(bst); end = BSTEnd(bst); while(!BSTIterIsEqual(temp, end)) { printf("%d, ", *(int *)BSTGetData(temp)); temp = BSTNext(temp); } printf("\n\n"); } /********************Test case function Implementations************************/ void TestCase(void) { /*variable declarations*/ bst_t *bst = NULL; int num3 = 3; int num5 = 5; int num7 = 7; int num1 = 1; int num4 = 4; int num2 = 2; int *num3_ptr = &num3; int *num5_ptr = &num5; int *num7_ptr = &num7; int *num1_ptr = &num1; int *num4_ptr = &num4; int *num2_ptr = &num2; bst_iter_t iter3 = {0}; bst_iter_t iter5 = {0}; bst_iter_t iter7 = {0}; bst_iter_t iter1 = {0}; bst_iter_t iter4 = {0}; bst_iter_t iter2 = {0}; /*create the list*/ bst = BSTtCreate(IntCompare, NULL); BSTIsEmptyTest(bst); /*insert the elements*/ iter3 = BSTInsertTest(bst, num3_ptr); iter5 = BSTInsertTest(bst, num5_ptr); iter7 = BSTInsertTest(bst, num7_ptr); iter1 = BSTInsertTest(bst, num1_ptr); iter4 = BSTInsertTest(bst, num4_ptr); iter2 = BSTInsertTest(bst, num2_ptr); BSTIsEmptyTest(bst); BSTSizeTest(bst); /*prints the list*/ PrintList(bst); /*finding an element*/ BSTFindTest(bst, num4_ptr); /*removes an element*/ BSTRemoveTest(iter7); BSTSizeTest(bst); /*prints the list*/ PrintList(bst); /*finding an element*/ BSTFindTest(bst, num4_ptr); /*Add one to each of the elements*/ BSTForEachTest(BSTBegin(bst), BSTEnd(bst), AddOne, NULL); /*prints the list*/ PrintList(bst); BSTPrevTest(iter3); BSTPrevTest(iter1); BSTNextTest(iter5); BSTPrevTest(iter7); BSTBeginTest(bst); BSTEndTest(bst); BSTDestroyTest(bst); } /******************************************************************************/
C
#include<stdio.h> #include<stdlib.h> void BST_insert(); void BST_delete(); void infixorder(); void levelorder(); void menu(); void addq(); void deleteq(); void infixorder(); void levelorder(); typedef struct node { int val; struct node* left; struct node* right; struct node* parent; } node; typedef struct queue { struct queue* next; node* element; } queue; //a factory to create a node node* get_a_node(int x, node* parent) { node* nd = malloc(sizeof(node)); nd->val = x; nd->left = NULL; nd->right = NULL; nd->parent = parent; return nd; } //a factory to create a queue element queue* get_a_queue(node* element) { queue* q = malloc(sizeof(queue)); q->next = NULL; q->element = element; return q; } //function to free queue's memory void free_queue(queue** q) { queue* current_q = *q; while(current_q != NULL) { *q = current_q->next; free(current_q); current_q = *q; } } //put nodes into q void queue_put(node* n, queue** last) { if(n->left != NULL) { (*last)->next = get_a_queue(n->left); (*last) = (*last)->next; } if(n->right != NULL) { (*last)->next = get_a_queue(n->right); (*last) = (*last)->next; } } //insert a node into a heap void heap_insert(node** root, int x) { //insert new node if the heap is empty if(*root == NULL) { *root = get_a_node(x, NULL); } //serach for a proper insert point else { queue* q = get_a_queue(*root); queue* current_q = q; queue* last_q = q; node* current_node; while(current_q != NULL) { //get one node out of queue current_node = current_q->element; if(current_node->left == NULL) { current_node->left = get_a_node(x, current_node); current_node = current_node->left; } else if(current_node->right == NULL) { current_node->right = get_a_node(x, current_node); current_node = current_node->right; } else { queue_put(current_node, &last_q); //increment the current pointer current_q = current_q->next; continue; } //put the node to proper point while(current_node->parent != NULL && current_node->parent->val < current_node->val) { //swap the value int temp = current_node->parent->val; current_node->parent->val = current_node->val; current_node->val = temp; current_node = current_node->parent; } break; } free_queue(&q); } return; } int search_heap(node** root, int key) { if(*root != NULL) { queue* q = get_a_queue(*root); queue* current_q = q; queue* last_q = q; node* test; while(current_q != NULL) { test = current_q->element; queue_put(test, &last_q); if(test->val == key) return 1; else current_q = current_q->next; } free_queue(&q); printf("\n"); return 0; } } //print the heap with levelorder void levelorder_heap(node** root) { if(*root != NULL) { queue* q = get_a_queue(*root); queue* current_q = q; queue* last_q = q; node* test; while(current_q != NULL) { test = current_q->element; queue_put(test, &last_q); printf("%d, ",test->val); current_q = current_q->next; } free_queue(&q); printf("\n"); return 0; } } typedef struct node2 *treenode; typedef struct node2 { int data; treenode left; treenode right; }; treenode SearchTree = NULL, queue2[100], heap = NULL; int BST_search(); int Heap_search(); int main() { node *root = NULL; int choose1, choose2, key; int insert_data, have; printf("choose which tree you want\n"); printf("1.Binary search tree\n"); printf("2.Max heap\n"); scanf("%d",&choose1); if(choose1 == 1) { while(1) { menu(); scanf("%d",&choose2); printf("\n"); switch(choose2) { case 1: printf("Input insert data.\n"); scanf("%d",&insert_data); have = BST_search(&insert_data); if(have != 0) printf("This data already exist.\n"); else BST_insert(&insert_data); break; case 2: printf("Input the data you want to delete.\n"); scanf("%d",&insert_data); have = BST_search(&insert_data); if(have == 0) printf("Doesn't have this data.\n"); else BST_delete(&insert_data); break; case 3: printf("Which one you want to find?\n"); scanf("%d",&key); have = BST_search(&key); if(have == 0) printf("Doesn't have this data.\n"); else printf("The tree has this data.\n"); break; case 4: infixorder(SearchTree); printf("\n"); break; case 5: levelorder(SearchTree); printf("\n"); break; } } } if(choose1 == 2) { while(1) { menu(); scanf("%d",&choose2); printf("\n"); switch(choose2) { case 1: printf("Input the insert data.\n"); scanf("%d",&key); have = search_heap(&root, key); if(have == 1) printf("This data already exist.\n"); else heap_insert(&root, key); break; case 2: printf("Didn't do this.\n"); break; case 3: printf("Which one you want to find?\n"); scanf("%d",&key); have = search_heap(&root, key); if(have == 0) printf("Doesn't have this data.\n"); else printf("Having this data.\n"); break; case 4: printf("Didn't do this.\n"); break; case 5: levelorder_heap(&root); break; } } } } void menu() { printf("1. Insert\n"); printf("2. Delete\n"); printf("3. Search\n"); printf("4. Print Infix order\n"); printf("5. Print Level order\n"); } //addq and delete use to perform levelorder void addq(int *rear,treenode now) { *rear = *rear + 1; queue2[*rear] = now; } treenode delete(int *front) { *front = *front + 1; return queue2[*front]; } int BST_search(int *key) { //use new to begin the tree treenode new = SearchTree; while(new != NULL) { if(*key == new->data) return 1; //if smaller then go to left, or go to right. if(*key < new->data) new = new->left; else new = new->right; } return 0; } void BST_insert(int *key) { int data; int insert = 0; treenode ptr, now; //Use ptr as a node to store the insert data. //And use now to record the current node. ptr = malloc(sizeof(*ptr)); ptr->data = *key; ptr->left = ptr->right = NULL; if(SearchTree == NULL) SearchTree = ptr; else { now = SearchTree; //Use insert to record whether insert the data. while(!insert) { if(now->data > ptr->data) { if(now->left == NULL) { now->left = ptr; insert = 1; } else now = now->left; } else { if(now->right == NULL) { now->right = ptr; insert =1; } else now = now->right; } } } } void BST_delete(int *key) { treenode new2, new, father; int find = 0; //Use father to store the previous node. new = father = SearchTree; while(new != NULL && !find) { //Use new to record the node want to delete. if(new->data == *key) find = 1; else { father = new; if(new->data > *key) new = new->left; else new = new->right; } } if(new == NULL) printf("This tree doesn't have this data."); //it is a root. else if(new->left == NULL && new->right == NULL && new == SearchTree) { SearchTree = NULL; new = NULL; } //it is a last node, doesn't link other, so use father to record NULL. else if(new->left == NULL && new->right == NULL) { if(father->left == new) father->left = NULL; else father->right = NULL; new = NULL; } //left is NULL, so we just need to link it's right sub tree. else if(new->left == NULL) { if(father != new) { if(father->left == new) father->left = new->right; else father->right = new->right; } //it is root, so just turn to next. else SearchTree = SearchTree->right; new = NULL; } else if(new->right == NULL) { if(father != new) { if(father->left == new) father->left = new->left; else father->right = new->left; } else SearchTree = SearchTree->left; new = NULL; } else { // father = new; new2 = new->left; //turn to left, then go to right until NULL. while(new2->right != NULL) { father = new2; new2 = new2->right; } //Replace the data at the delete node. new->data = new2->data; if(father->left == new2) father->left = new2->left; else father->right = new2->left; new2 = NULL; } } void infixorder(treenode new) { if(new != NULL) { infixorder(new->left); printf("%d, ",new->data); infixorder(new->right); } } void levelorder(treenode new) { int front =0, rear = 0; if(!new) printf("ERROR!!"); else { addq(&rear, new); for(;;) { new = delete(&front); if(new) { printf("%d, ",new->data); if(new->left) addq(&rear, new->left); if(new->right) addq(&rear, new->right); } else break; } } }
C
#include <stdio.h> int main() { FILE *file = fopen("/home/malah/Code/IMIE/CPP/filemake/tocopie", "r"); int c; while ((c = getc(file)) != EOF) { putchar(c); } fclose(file); return 0; }
C
#include <stdio.h> #include <stdlib.h> void merge (int *left, int *right, int n, int m); void mergesort (int *arr, int n); long long swaps; void merge (int *left, int *right, int n, int m) { if (n > 1) mergesort (left, n); if (m > 1) mergesort (right, m); int i = 0, j = 0, size = n + m, *arr = (int *) malloc (sizeof (int) * size), dex = 0; while (i < n && j < m) { if (left[i] <= right[j]) { arr[dex++] = left[i++]; } else { arr[dex++] = right[j++]; swaps += n - i; } } while (i < n) arr[dex++] = left[i++]; while (j < m) arr[dex++] = right[j++]; for (i = 0; i < size; i++) left[i] = arr[i]; free (arr); } void mergesort (int *arr, int n) { int x = n / 2; int y = n - x; merge (arr, arr + x, x, y); } int main () { int n, i; while (1) { scanf ("%d", &n); if (n == 0) break; int *arr = (int *) malloc (sizeof (int) * n); for (i = 0; i < n; i++) { scanf ("%d", arr + i); } swaps = 0; mergesort (arr, n); printf ("%lld\n", swaps); free (arr); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: acolin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/20 10:19:46 by acolin #+# #+# */ /* Updated: 2021/10/22 17:05:48 by acolin ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" size_t ft_strlen(const char *s) { size_t i; i = 0; while (s[i] != '\0') i++; return (i); } char *ft_strdup(const char *s) { char *str; size_t i; str = (char *)malloc(sizeof(char) * ft_strlen(s) + 1); if (!str) return (NULL); i = 0; while (s[i] != '\0') { str[i] = s[i]; i++; } str[i] = '\0'; return (str); } size_t ft_strlcat(char *dst, const char *src, size_t size) { size_t size_src; size_t size_dst; size_t i; size_src = ft_strlen(src); size_dst = ft_strlen(dst); i = 0; while (size--) { dst[i + size_dst] = src[i]; i++; } dst[i + size_dst] = '\0'; return (size_dst + size_src); } size_t ft_strlcpy(char *dst, const char *src, size_t size) { size_t i; i = 0; if (size > 0) { while (--size && src[i]) { dst[i] = src[i]; i++; } dst[i] = '\0'; } while (src[i]) i++; return (i); } char *check_buffer(char *buffer, size_t size) { size_t i; if (buffer[size] != '\0') { free(buffer); return (NULL); } i = 0; while (i < size) i++; while (buffer[i] != '\0') { buffer[i] = '\0'; i++; } buffer[i] = '\0'; return (buffer); }
C
/* 8. Accept character from user. If it is capital then display all the characters from the input characters till Z. If input character is small then print all the characters in reverse order till a. In other cases return directly. Input : Q Output : Q R S T U V W X Y Z Input : m Output : m l k j i h g f e d c b a */ void Display(char);
C
//WAP to enter the two numbers and perform all arithmetic operators #include<stdio.h> #include<math.h> int main(){ int a ,b; printf("Enter the 1st number:\n"); scanf("%d\n",&a); printf("Enter the 2nd number:\n"); scanf("%d\n",&b); int z=a*b; printf("The value of z is %d\n ",z); printf("The value of a+b is %d\n ",a+b); printf("The value of a-b is %d\n ",a-b); printf("The value of a*b is %d\n ",a*b); printf("The value of a/b is %f\n ",(double)a/b); printf("The value of a^b is %f\n ",pow(a,b)); return 0; }
C
/* * Week_4 This program opens and reads a file of integer into an array and places * the values into a binary tree structure. Walks the tree "inorder" and prints * the values to the screen. */ #include <stdio.h> #include <stdlib.h> typedef struct intNumber { int data; struct intNumber * left; struct intNumber * right; }intNumber; //Read number of Elements from the file void getNumOfElements(FILE * ifp, int * numOfElements) { if(ifp == NULL) { printf("Error opening file\n"); exit(1); } if(fscanf(ifp, "%d", numOfElements) != EOF) printf("Number of Elements: %d\n", *numOfElements); } //Read the integers from the file void readInts(FILE * ifp, int * nums, int size) { int i=0, j=0; while (fscanf(ifp, "%d", &nums[i]) !=EOF && i<size) i++; for(j=0; j<size; j++ ) printf("%d ", nums[j]); printf("\n\n"); } //Create and insert a new element void insert(intNumber** head, int data) { intNumber* newEl = (intNumber*) malloc(sizeof(intNumber)); newEl->data = data; newEl->left = NULL; newEl->right = NULL; intNumber* i; if(*head == NULL) { *head = newEl; return; } for(i= *head; i!=NULL;) { //printf("left %p , right %p \n", i->left, i->right ); if(newEl->data > i->data) { if(i->right == NULL) { i->right = newEl; return; } else i = i->right; } else { if(i->left == NULL) { i->left = newEl; return; } else i= i->left; } } } //Print elements from the binary tree structure void printInOrder(intNumber* head) { if(head == NULL) return; if(head->left != NULL) { printInOrder(head->left); printf("%d ", head->data); printInOrder(head->right); } else { printf("%d ", head->data); printInOrder(head->right); } } int main() { FILE *ifp; int numOfElements=0, i; intNumber* head = NULL; ifp = fopen("listOfInts.txt", "r"); getNumOfElements(ifp, &numOfElements); int nums[numOfElements]; readInts(ifp, nums, numOfElements); //create new elements for(i=0; i<numOfElements; i++) { insert(&head, nums[i]); } printf("Print in order: \n"); printInOrder(head); return 0; }
C
#include<stdio.h> main() { int a=0x12131415; short int *sh=(short int *)&a; int i=0,n=2; for(i=0;i<n;i++) { printf("%x",*sh); sh++; } }
C
#ifndef __WMWM__LIST_H__ #define __WMWM__LIST_H__ typedef struct list_item list_t; struct list_item { void *data; list_t *prev; list_t *next; }; /* * Move element in item to the head of list mainlist. */ void list_to_head(list_t **mainlist, list_t *item); /* * Create space for a new item and add it to the head of mainlist. * * Returns item or NULL if out of memory. */ list_t *list_add(list_t **mainlist); /* * Remove item from list mainlist. */ void list_remove(list_t **mainlist, list_t *item); /* * Free any data in current item and then delete item. Optionally * update number of items in list if stored != NULL. */ void list_erase(list_t **list, int *stored, list_t *item); /* * Delete all items in list. Optionally update number of items in list * if stored != NULL. */ void list_erase_all(list_t **list, int *stored); /* * Print all items in mainlist on stdout. */ void list_print(list_t *mainlist); #endif /* __WMWM__LIST_H__ */
C
// Mutual exclusion lock. #define _check_lock(lock, massage) do{\ if(!holding(lock)) \ panic(massage);\ }while(0)\ struct spinlock { uint locked; // Is the lock held? // For debugging: char *name; // Name of lock. int cpu; // The number of the cpu holding the lock. uint pcs[10]; // The call stack (an array of program counters) // that locked the lock. };
C
// Author: Benjamin Mayes #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> // the type of element that the heart consists of typedef struct _heart_entry heart_entry; struct _heart_entry { unsigned int h; int paths; }; // the adjacency matrix unsigned int** adjacency_matrix; //adds an edge to the adjacency matrix void new_edge( int u, int v, int w ) { adjacency_matrix[u][v] = w; } int main() { // read in the number of vertices and edges int n, m; scanf("%d %d", &n, &m ); //create the adjacency matrix adjacency_matrix = (unsigned int**)malloc((n+1)*sizeof(unsigned int*)); for( int i = 0; i <= n; ++i ) { adjacency_matrix[i] = (unsigned int*)calloc((n+1),sizeof(unsigned int)); } int u,v,w; for( int i = 0; i < m; ++i ) { scanf( "%d %d %d", &u, &v, &w ); new_edge( u, v, w ); } // fill in the remaining parts of the adjacency matrix with // a value meanining "INFINITY" for( int i = 1; i <= n; ++i ) { for( int j = 1; j <= n; ++j ) { if( !adjacency_matrix[i][j] ) { adjacency_matrix[i][j] = INT_MAX; } } } // create the 3d heart heart_entry*** heart = (heart_entry***)calloc((n+1),sizeof(heart_entry**)); for( int i = 0; i <= n; ++i ) { heart[i] = (heart_entry**)calloc((n+1),sizeof(heart_entry*)); for( int j = 0; j <= n; ++j ) { heart[i][j] = (heart_entry*)calloc((n+1),sizeof(heart_entry)); } } // fill in the first level of the heart for( int i = 1; i <= n; ++i ) { for( int j = 1; j <= n; ++j ) { heart[i][j][0].h = adjacency_matrix[i][j]; if( heart[i][j][0].h < INT_MAX ){ heart[i][j][0].paths = 1; } } } // The modified Floyd-Warshall for( int k = 1; k <= n; ++k ) { for( int i = 1; i <= n; ++i ) { for( int j = 1; j <= n; ++j ) { if( i != j ) { unsigned int if_not_k = heart[i][j][k-1].h; // the number of paths if k is not chosen does not change unsigned int if_not_k_path = heart[i][j][k-1].paths; unsigned int if_k = heart[i][k][k-1].h + heart[k][j][k-1].h; // choosing k means we want to multiply the number of // paths of the two subpaths unsigned int if_k_path = heart[i][k][k-1].paths * heart[k][j][k-1].paths; // handle infinity cases if( if_not_k > INT_MAX ) { if_not_k = INT_MAX; if_not_k_path = 0; } if ( if_k > INT_MAX ) { if_k = INT_MAX; if_k_path = 0; } // when equal, we want to add the number of paths if( if_k == if_not_k ) { heart[i][j][k].h = if_k; // we want to combine the number of paths heart[i][j][k].paths = if_not_k_path + if_k_path; // choosing k is better than not choosing k } else if( if_k < if_not_k ) { heart[i][j][k].h = if_k; heart[i][j][k].paths = if_k_path; // it is better to not choose k } else { heart[i][j][k].h = if_not_k; heart[i][j][k].paths = if_not_k_path; } } } } } // print out the table of distances and path counts for( int i = 1; i <= n; ++i ) { for( int j = 1; j <= n; ++j ) { if( heart[i][j][n].h < INT_MAX ) { if( i != j ) { printf( "%d/%d ", heart[i][j][n].h, heart[i][j][n].paths ); } else { printf( "0/1 " ); } } else { printf( "inf/0 "); } } printf( "\n" ); } //cleanup memory for( int i = 0; i <= n; ++i ) { for( int j = 0; j <= n; ++j ) { free(heart[i][j]); } free(heart[i]); free(adjacency_matrix[i]); } free(heart); free(adjacency_matrix); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int n; float* a = NULL; printf("Enter array size: "); scanf("%d", &n); if (n < 1) { printf("Invalid size!"); return 1; } a = (float*)malloc(n*sizeof(float)); if (a == NULL) { printf("Mem error!"); return 1; } int i; for (i = 0; i < n; i++) { printf("a[%d] = ", i); scanf("%f", &a[i]); } printf("Data: "); for (i = 0; i < n; i++) { printf("%f ", a[i]); } printf("\n"); // do some other things ... // Finally freeing memory free(a); return 0; }
C
#include "MyString.h" #include <stdio.h> #include <assert.h> #define ZERO 0 unsigned int countSubStr(const char* str1, const char* str2, int isCyclic); int length (const char* string); unsigned int check(const char* str1, const char* str2, int forSize); /** * * @param str1 the first string we compare with * @param str2 teh second string we want to find * @param forSize how many times we need to run depends of if cyclic or of str 2 bigger or smaller that str1 * @return how many times it was found */ unsigned int check(const char* str1, const char* str2, int forSize) { // const char *p = str1; int i = 0; int firstInMatch = 0; unsigned int reps = 0; int len2 = length(str2); int len1 = length(str1); int j = 0 ; while ( i < forSize) { ++i; if (*(str1 + i % len1) == *(str2 + j)) { if (!firstInMatch) { firstInMatch = i; } ++j; } else { i = firstInMatch + 1; firstInMatch = 0 ; j = 0; } if (j == len2-1) { i = firstInMatch + 1; firstInMatch = 0 ; j = 0; ++reps; } } return reps; } /** * * @param str1 the first string we compare with * @param str2 teh second string we want to find * @param isCyclic >0 if yes < 0 if no * @return how many times it was found */ unsigned int countSubStr(const char* str1, const char* str2, int isCyclic) { int i = 0; unsigned int reps = 0; int lenS2 = length(str2); int lenS1 = length(str1); if ((str2 == NULL) || (str1 == NULL)) { return 0; } if ( lenS2 == lenS1) // checkes if is teh same string wouldnt matter if cyclic or not { assert(i = 0); while (i == lenS1) { if (*(str2 + i) != *(str1 + i)) { return 0; } ++i; } assert(i == lenS1); return 1; } if (isCyclic) { if (lenS1 > lenS2) { reps = check(str1, str2, lenS1 + lenS2 -1); } else { int len = 0 ; while( len < lenS2 ) { len = len + lenS1; } reps = check(str1, str2, len); } } else { if( lenS2 > lenS1) { return ZERO; } else { reps = check(str1, str2, lenS1); } } return reps; } /** * * @param string * @return teh lingth of teh string */ int length(const char *string) { int len = 0 ; while ( *(string + len) != '\0') { ++len; } return len; }
C
/** @file source_untrusted.h * * @brief Helper utilities for validate and get data from untrusted source * * All function inside is non-thread safe nor interrupt safe. Generally the * caller use memlock to protect thread safeness, while avoid calling it inside * interrupt handler to allow interrupt unsafeness. * * @author Leiyu Zhao */ #ifndef SOURCE_UNTRUSTED_H #define SOURCE_UNTRUSTED_H // Verify a user space range, with given previlage. // Returns false if and only if there's any address in the range [start, end] // that: 1. fall in kernel memory 2. is not writable while mustWritable=true bool verifyUserSpaceAddr( uint32_t startAddr, uint32_t endAddr, bool mustWritable); // get an integer from addr to target. return true if success bool sGetInt(uint32_t addr, int* target); // get a NUL-terminated string from addr to target, return its size // return -1 on failure // return non-neg value indicating the number of chars get (exclude the // terminating zero). Must <= size // if return < size, there must be a terminating zero at target[return] int sGetString(uint32_t addr, char* target, int size); // get a NUL-terminated uint array from addr to target, return its size // return -1 on failure // return non-neg value indicating the number of uint get (exclude the // terminating zero). Must <= size // if return < size, there must be a terminating zero at target[return] int sGeUIntArray(uint32_t addr, uint32_t* target, int size); #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char string1[] = "napis1"; char string2[] = "napis2"; char *result; printf("%s", &string1); printf("%s", &string2); result=strcatt(string1,string2); printf("%s", &result); return 0; } char *strcatt(char *str1, char *str2){ char *result; int i=0,j=0,s; s=strlen(str1)+strlen(str2)+1; result=(char *)malloc(s*siezeof(char)); for(i;str1[i]!='\n',i++) result[i]=str1[i]; for(j;str2!='\n';j++) result[i+j]=str2[j]; return result; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <ctype.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #include <sys/select.h> #include <errno.h> #include <time.h> #define MAX_DATA 1025 #define MAX_NAME 100 #define BUFFER 2000 #define MAXSIZE 20 #define MAXBUFLEN 2000 //Max clients that the server will listen too #define MAXCLIENTS 10 //Used for text conferencing where the value of 0 corresponds to an unconnected conference session #define NOSESSION 0 //Max number of sessions that can be present at once #define MAXCONFERENCESESSIONS 100 //Defining the types used to communicate between server/client #define LOGIN 0 #define LO_ACK 1 #define LO_NACK 2 #define EXIT 3 #define JOIN 4 #define JN_ACK 5 #define JN_NACK 6 #define LEAVE_SESS 7 #define NEW_SESS 8 #define NS_ACK 9 #define MESSAGE 10 #define QUERY 11 //A request from the client of a list of online users and available sessions #define QU_ACK 12 //List of users online and their session IDS #define STDIN 0 struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; socklen_t ai_addrlen; struct sockaddr *ai_addr; char *ai_canonname; struct addrinfo *ai_next; }; //credentials stored in file "Server LoginInformation.txt" //global variables used for preserving server data between function calls //these are initialized in login int sockfd; struct addrinfo hints, *servinfo, *p; int rv; int loggedin = 0; /*used to indicate that client is sucessfully logged into the server*/ int inSession = 0; /*used to indicate that client is currently in a session*/ int hostSize = 0; /*used to keep track of length of currently logged in username*/ char username[MAXBUFLEN]; /*used to keep track of the currently logged in user*/ char curSesh[MAXBUFLEN]; /*used to keep track of the currently joined session*/ int wantQuit = 0; /*used to keep track of whether or not the user issued the quit command*/ int wantLeave = 0; /*used to keep track of whether or not the user issued leavesession*/ //function to tie all the information into correct packet form char* packetize(int type, int size, char* source, char* data, int packetSize) { char buf[MAXBUFLEN]; char intermediate[MAXBUFLEN]; char* result; result = (char*) malloc(packetSize * sizeof (char)); sprintf(buf, "%d", type); strcpy(intermediate, buf); strcat(intermediate, ":"); sprintf(buf, "%d", size); strcat(intermediate, buf); strcat(intermediate, ":"); strcat(intermediate, source); strcat(intermediate, ":"); strcat(intermediate, data); result = intermediate; return result; } //function to connect to server using login credentials //argv[0] = id, argv[1] = password, argv[2] = server ip, argv[3] = server port int login(char** argv) { int numbytes; char buf[MAXBUFLEN]; char result[MAXBUFLEN]; //connection initialization memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[2], argv[3], &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and make a socket for (p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to create socket\n"); return 2; } int error; error = connect(sockfd, p->ai_addr, p->ai_addrlen); if (error) { printf("client: failed to connect to server \n"); return -1; } //at this point we are connected to the server in the given port number //create a packet using appropriate info and sent it to server int type = LOGIN; int size = strlen(argv[1]); hostSize = strlen(argv[0]); //determine the packet size //4 colons (4 bytes) + data size + size of source + 1 type (1 byte) + size of the variable "size" sprintf(buf, "%d", size); int packetSize = 4 + size + 1 + strlen(buf) + strlen(argv[0]); char* packet = packetize(type, size, argv[0], argv[1], packetSize); if ((numbytes = send(sockfd, packet, packetSize, 0)) == -1) { perror("client: send"); exit(1); } //receive acknowledgment from server if ((numbytes = recv(sockfd, result, MAXBUFLEN, 0)) == -1) { perror("client: recv"); exit(1); } //parse the packet to get the data char* garbage1; char* garbage2; char* garbage3; char* reason; garbage1 = strtok(result, ":"); garbage2 = strtok(NULL, ":"); garbage3 = strtok(NULL, ":"); reason = strtok(NULL, ":"); //if reason is not empty, server indicates that login was not successful if (reason != NULL) { printf("%s\n", reason); return -1; } return 0; } int join_session(char* sessionID) { int numbytes; char result[MAXBUFLEN]; int packetSize = hostSize + 4 + 1 + strlen(sessionID) + 1; char* packet = packetize(JOIN, strlen(sessionID), username, sessionID, packetSize); if ((numbytes = send(sockfd, packet, packetSize, 0)) == -1) { perror("client: send"); exit(1); } //printf("sent %d to server \n", numbytes); //receive acknowledgment from server if ((numbytes = recv(sockfd, result, MAXBUFLEN, 0)) == -1) { perror("client: recv"); exit(1); } //printf("received packet is %s\n", result); //parse the packet to get the data char* garbage1; char* garbage2; char* garbage3; char* error; garbage1 = strtok(result, ":"); garbage2 = strtok(NULL, ":"); garbage3 = strtok(NULL, ":"); error = strtok(NULL, "\0"); /*if(error != NULL){ printf("%s\n"); return -1; }*/ strcpy(curSesh, sessionID); return 0; } int create_session() { int numbytes; char result[MAXBUFLEN]; int packetSize = hostSize + 4 + 1 + 1; char* packet = packetize(NEW_SESS, 0, username, "", packetSize); //printf("%s userame\n", username); //printf("packet to send: %s\n", packet); if ((numbytes = send(sockfd, packet, packetSize, 0)) == -1) { perror("client: send"); exit(1); } //printf("sent %d to server \n", numbytes); if ((numbytes = recv(sockfd, result, MAXBUFLEN, 0)) == -1) { perror("client: recv"); exit(1); } //printf("packet is: %s\n", result); //printf("received %d from server\n", numbytes); //parse the packet to get the data char* garbage1; char* garbage2; char* garbage3; char* response; garbage1 = strtok(result, ":"); garbage2 = strtok(NULL, ":"); garbage3 = strtok(NULL, ":"); response = strtok(NULL, ":"); if (response != NULL) { printf("%s \n", response); return -1; } return 0; } int quit() { wantQuit = 1; return 0; } int logout() { int numbytes; int packetSize = hostSize + 4 + 1 + 1; char* packet = packetize(EXIT, 0, username, "", packetSize); //printf("packet to send: %s\n", packet); if ((numbytes = send(sockfd, packet, packetSize, 0)) == -1) { perror("client: send"); exit(1); } loggedin = 0; //printf("sent %d to server \n", numbytes); return 0; } int leave_session() { int numbytes; int packetSize = hostSize + 4 + 1 + 1; char* packet = packetize(LEAVE_SESS, 0, username, "", packetSize); //printf("packet to send: %s\n", packet); if ((numbytes = send(sockfd, packet, packetSize, 0)) == -1) { perror("client: send"); exit(1); } //printf("sent %d to server \n", numbytes); wantLeave = 1; return 0; } int list() { int numbytes; int packetSize = hostSize + 4 + 2 + 1; char* packet = packetize(QUERY, 0, username, "", packetSize); char result[MAXBUFLEN]; // printf("packet to send: %s\n", packet); if ((numbytes = send(sockfd, packet, packetSize, 0)) == -1) { perror("client: send"); exit(1); } // printf("sent %d to server \n", numbytes); //while (1) { //} if ((numbytes = recv(sockfd, result, MAXBUFLEN, 0)) == -1) { perror("client: recv"); exit(1); } //parse the packet to get the data char* garbage1; char* garbage2; char* garbage3; char* response; garbage1 = strtok(result, ":"); garbage2 = strtok(NULL, ":"); garbage3 = strtok(NULL, ":"); response = strtok(NULL, ":"); printf("%s\n", response); return 0; } int userHandler() { int numbytes; char userInput[MAXBUFLEN]; char command[MAXBUFLEN]; fgets(userInput, sizeof (userInput), stdin); int i = 0; while (userInput[i] != '\0') { if (userInput[i] == '\n') userInput[i] = '\0'; i++; } strcpy(command, userInput); char* yes = strtok(command, " "); if (strcmp(yes, "/leavesession") == 0) { leave_session(); return 0; } if (strcmp(yes, "/quit") == 0) { quit(); return 0; } if (strcmp(yes, "/list") == 0) { list(); return 0; } if (strcmp(yes, "/logout") == 0) { logout(); return 0; } int packetSize = hostSize + 4 + 2 + strlen(userInput) + 1; char* packet = packetize(MESSAGE, strlen(userInput), username, userInput, packetSize); // printf("packet to send: %s\n", packet); if ((numbytes = send(sockfd, packet, packetSize, 0)) == -1) { perror("client: send"); exit(1); } // printf("sent %d to server \n", numbytes); } int receiveHandler() { int numbytes; char result[MAXBUFLEN]; if ((numbytes = recv(sockfd, result, MAXBUFLEN, 0)) == -1) { perror("client: recv"); exit(1); } char* garbage1; char* garbage2; char* garbage3; char* response; garbage1 = strtok(result, ":"); garbage2 = strtok(NULL, ":"); garbage3 = strtok(NULL, ":"); response = strtok(NULL, ":"); printf("%s\n", response); return 0; } int main(int argc, char *argv[]) { //parameters for parser char userInput[BUFFER]; char* command; int uargc = 0; //dynamic string array that holds user inputs char** uargv; uargv = (char**) malloc(sizeof (char**)); if (argc != 1) { fprintf(stderr, "usage: server\n"); exit(1); } loopOne: //parse user input while (1) { printf("please enter one of the following commands:\n/login\n/logout\n/register\n/quit\n"); fgets(userInput, sizeof (userInput), stdin); uargc = 0; //removing the trailing newline character int i = 0; while (userInput[i] != '\0') { if (userInput[i] == '\n') userInput[i] = '\0'; i++; } char* incr = userInput; while ((incr = strchr(incr, ' ')) != NULL) { uargc++; incr++; } command = strtok(userInput, " "); if (command == NULL) { printf("error: empty input, please try again\n"); continue; } if (strcmp(command, "/login") == 0) { if (uargc != 4) { printf("login: required parameters <clientID> <password> <server-IP> <server-port> \n"); continue; } //read in the parameters uargv = (char**) malloc(sizeof (char**)); for (i = 0; i < uargc; i++) { uargv[i] = (char*) malloc(sizeof (char*)); uargv[i] = strtok(NULL, " "); //printf("argv is %s \n", uargv[i]); } int error = login(uargv); if (!error) { loggedin = 1; strcpy(username, uargv[0]); printf("login successful, hello %s \n", uargv[0]); break; } else printf("login failed, please try again \n"); continue; } if (strcmp(command, "/logout") == 0) { if (uargc != 0) { printf("logout: required parameters NONE\n"); continue; } break; } if (strcmp(command, "/quit") == 0) { if (uargc != 0) { printf("quit: required parameters NONE\n"); continue; } break; } printf("error: invalid command \n"); } loopTwo: while (1) { printf("please enter one of the following commands:\n/joinsession\n/createsession\n/quit\n"); fgets(userInput, sizeof (userInput), stdin); uargc = 0; //removing the trailing newline character int i = 0; while (userInput[i] != '\0') { if (userInput[i] == '\n') userInput[i] = '\0'; i++; } //figure out how many arguments were passed in by the user char* incr = userInput; while ((incr = strchr(incr, ' ')) != NULL) { uargc++; incr++; } command = strtok(userInput, " "); if (command == NULL) { printf("error: empty input, please try again\n"); continue; } if (strcmp(command, "/joinsession") == 0) { if (uargc != 1) { printf("joinsession: required parameters <sessionID>\n"); continue; } uargv[0] = strtok(NULL, " "); // printf("argv is %s \n", uargv[0]); int error = join_session(uargv[0]); if (error) { printf("joining session failed, please try again\n"); continue; } printf("successfully joined sesesion %s\n", argv[0]); inSession = 1; break; } if (strcmp(command, "/createsession") == 0) { if (uargc != 0) { printf("createsession: required parameters <sessionID> \n"); continue; } create_session(); inSession = 1; printf("successfully created and joined session\n"); break; } if (strcmp(command, "/list") == 0) { if (uargc != 0) { printf("list: required parameters NONE\n"); continue; } break; } //not implemented yet if (strcmp(command, "/register") == 0) { if (uargc != 2) { printf("register: required parameters <clientID> <password>\n"); continue; } break; } if (strcmp(command, "/quit") == 0) { if (uargc != 0) { printf("quit: required parameters NONE\n"); continue; } quit(); return 0; } } printf("Commands: \n/leavesession\n/list\n/quit\n/logout\n"); //user is in the session at this point fd_set readfds; while (1) { //actively poll both the socket connected with the server and STDIN //if STDIN is flagged, receive user input then send it //if the input is a command, handle accordingly //if socfd is flagged, receive packet from server FD_ZERO(&readfds); FD_SET(STDIN, &readfds); FD_SET(sockfd, &readfds); struct timeval tv; tv.tv_sec = 10; tv.tv_usec = 0; select(sockfd + 1, &readfds, NULL, NULL, &tv); if (FD_ISSET(sockfd, &readfds)) { receiveHandler(); continue; } if (FD_ISSET(STDIN, &readfds)) { userHandler(); continue; } if (wantQuit) { printf("bye bye\n"); return 0; } if (wantLeave) { printf("left session\n"); wantLeave = 0; goto loopTwo; } if (loggedin == 0) { printf("logged out\n"); goto loopOne; } } freeaddrinfo(servinfo); close(sockfd); free(uargv[0]); free(uargv[1]); free(uargv[2]); free(uargv[3]); free(uargv); }
C
#include <omp.h> #include <stdio.h> static long num_steps = 10000000; double step; void main () { int i; double x, pi, sum = 0.0; double start_time = omp_get_wtime(); step = 1.0/(double) num_steps; #pragma omp parallel num_threads(2) private(i,x) { #pragma omp for reduction(+:sum) schedule(static) for (i=0; i< num_steps; i++) { x = (i+0.5)*step; sum = sum + 4.0/(1.0+x*x); } } pi = step * sum; printf("pi: %f\n", pi); printf("elapsed time: %f\n", omp_get_wtime() - start_time); }
C
/*WAP to insert item in unsorted array*/ #include<stdio.h> #define size 20 main(){ int a[size],i,n,item; printf("enter num. of element: "); scanf("%d",&n); /*creat array*/ for(i=0;i<n;i++){ printf("enter number %d: ",i+1); /*index of array starts with 0 and user knows start as 1*/ scanf("%d",&a[i]); } printf("enter element to store: "); scanf("%d",&item); /*shifting*/ for(i=n-1;i>=0 && a[i]>item ;i--){ a[i+1]=a[i]; } /*insert*/ a[i+1]=item; /*a[pos]=item*/ n++; /*now array has one element extra */ /*output*/ for(i=0;i<n;i++) printf("%d\t",a[i]); return 0; }
C
// RLG20141229 #include <avr/io.h> #include <util/delay.h> int main(void) { DDRB |= 0b00100110; // leave all the other bits alone, just set bit 1 (PB1), 2 (PB2), & 5 (PB5) by or'ing with 00100110 DDRC &= 0b11111011; // leave all the other bits alone, just clear bit 2 (PC2) by anding with 1111 1011 // PORTC |= (1 << PC2); // set pull up resistor on PC2 PORTC |= 0b00000100; // set pull up resistor on PC2 by or'ing with 00000100 while (1) { if (PINC & (1 << PC2)) { // pinc & 1 only until the button is pressed // PORTB &= ~(1 << PB5); PORTB &= 0b11011111; // if the button is not pressed then PB5 = 0 } else { // PORTB |= (1 << B5); // if the button is pressed then PB5 = 1 PORTB |= 0b00100000; // if the button is pressed then PB5 = 1 } } return(0); }
C
#include "defs.h" int init(SDL_Window **g_Window,SDL_Renderer **renderer) { SDL_Surface *icon=NULL; if(0 != SDL_Init(SDL_INIT_VIDEO)) { printf("Erreur SDL_Init : %s\n", SDL_GetError()); return -1; } if(0 != TTF_Init()) { printf("Erreur TTF_Init : %s\n", SDL_GetError()); return -1; } if(0!=SDL_CreateWindowAndRenderer(WINDOW_WIDTH,WINDOW_HEIGHT,SDL_WINDOW_SHOWN,g_Window,renderer)) { printf("Erreur SDL_CreateWindowAndRenderer : %s\n", SDL_GetError()); return -1; } SDL_SetWindowTitle(*g_Window,"Chess Royal Alpha"); icon=IMG_Load("sprites/ico.png"); SDL_SetWindowIcon(*g_Window,icon); return 0; } SDL_Texture *loadIMG(char path[], SDL_Renderer *renderer) { SDL_Surface *surface = NULL; SDL_Texture *texture=NULL; surface = IMG_Load(path); if(surface==NULL) { printf("Erreur IMG_Load : %s\n", IMG_GetError()); return NULL; } texture = SDL_CreateTextureFromSurface(renderer,surface); SDL_FreeSurface(surface); if(texture==NULL) { printf("Erreur SDL_CreateTextureFromSurface : %s\n",SDL_GetError()); return NULL; } return texture; } SDL_Texture *loadFont_Blended(SDL_Renderer *renderer, TTF_Font *police, char texte[], int red, int green, int blue) { SDL_Surface *surface=NULL; SDL_Texture *texture=NULL; SDL_Color couleur={red, green, blue, 255}; surface = TTF_RenderText_Blended(police, texte, couleur); texture = SDL_CreateTextureFromSurface(renderer,surface); SDL_FreeSurface(surface); if(texture==NULL) { printf("Erreur SDL_CreateTextureFromSurface : %s\n",SDL_GetError()); return NULL; } return texture; } int RendTex(SDL_Texture *texture, SDL_Renderer *renderer, int x, int y) { SDL_Rect rect; rect.x=x; rect.y=y; if(0!=SDL_QueryTexture(texture,NULL,NULL,&rect.w,&rect.h)) { printf("Erreur SDL_QueryTexture : %s\n",SDL_GetError()); return -1; } if(0!=SDL_RenderCopy(renderer,texture,NULL,&rect)) { printf("Erreur SDL_RenderCopy : %s\n",SDL_GetError()); return -1; } return 0; } void render_button(SDL_Renderer *renderer, char text[], SDL_Rect button) { SDL_Rect button_outline = {0, 0, 0, 0}; int outline = 1; SDL_Texture *button_text = NULL; SDL_Rect font_rect; TTF_Font *font_OpenSans = NULL; SDL_SetRenderDrawColor(renderer, 52, 152, 219, 255);//Couleur des boutons (intrieur) SDL_RenderFillRect(renderer, &button); SDL_SetRenderDrawColor(renderer, 41, 128, 185, 255);//Couleur des boutons (contour) while(outline < BUTTON_OUTLINE) { button_outline.w = button.w + 2 * outline; button_outline.h = button.h + 2 * outline; button_outline.x = button.x - outline; button_outline.y = button.y - outline; SDL_RenderDrawRect(renderer, &button_outline); outline++; } SDL_RenderPresent(renderer); font_OpenSans = TTF_OpenFont("ttf/OpenSans-Regular.ttf", 40); button_text = loadFont_Blended(renderer, font_OpenSans, text, 236, 240, 241); SDL_QueryTexture(button_text, NULL, NULL, &font_rect.w, &font_rect.h); RendTex(button_text, renderer, button.x + (button.w-font_rect.w) / 2, button.y + (button.h-font_rect.h) / 2); SDL_RenderPresent(renderer); } int isCursorOnButton(SDL_Rect button) { int isInside=0; int cursorX, cursorY; SDL_GetMouseState(&cursorX, &cursorY); if((cursorX>button.x) &&(cursorX<button.x+button.w) &&(cursorY>button.y) &&(cursorY<button.y+button.h)) { isInside=1; } return isInside; } void renderFillRect(SDL_Renderer *renderer,SDL_Rect rect,int r,int g,int b,int a) { SDL_SetRenderDrawBlendMode(renderer,SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor(renderer,r,g,b,a); SDL_RenderFillRect(renderer,&rect); SDL_RenderPresent(renderer); } void renderTextInRect(SDL_Renderer *renderer, char text[], SDL_Rect rect) { TTF_Font *font_OpenSans = TTF_OpenFont("ttf/OpenSans-Regular.ttf", 40); SDL_Texture *TextTexture; SDL_Rect font_rect; TextTexture = loadFont_Blended(renderer, font_OpenSans, text, 0, 0, 0); SDL_QueryTexture(TextTexture, NULL, NULL, &font_rect.w, &font_rect.h); RendTex(TextTexture, renderer, rect.x+(rect.w-font_rect.w)/2, rect.y+(rect.h-font_rect.h)/2); SDL_RenderPresent(renderer); } void renderCenteredText(SDL_Renderer *renderer, char text[], int x, int y, int r, int g, int b, int size) { TTF_Font *font_OpenSans = TTF_OpenFont("ttf/OpenSans-Regular.ttf", size); SDL_Texture *TextTexture; SDL_Rect font_rect; TextTexture = loadFont_Blended(renderer, font_OpenSans, text, r, g, b); SDL_QueryTexture(TextTexture, NULL, NULL, &font_rect.w, &font_rect.h); RendTex(TextTexture, renderer, x-font_rect.w/2, y-font_rect.h/2); SDL_RenderPresent(renderer); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* choose_flag.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mazoukni <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/24 04:40:23 by mazoukni #+# #+# */ /* Updated: 2020/02/12 05:33:06 by mazoukni ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" t_flag ft_asso(t_flag flag, int b) { flag.value = b; flag.state = 1; return (flag); } t_flags ft_reshape(t_flags wpz) { t_flags shape; shape.width.state = 0; shape.zero.state = 0; shape.prec.state = 0; if (wpz.prec.state) shape.prec = ft_asso(shape.prec, wpz.prec.value); if (wpz.prec.state && wpz.prec.value > -1) { shape.prec = ft_asso(shape.prec, wpz.prec.value); shape.zero = ft_asso(shape.zero, wpz.prec.value); if (wpz.zero.state) shape.width = ft_asso(shape.width, wpz.zero.value); else if (wpz.width.state) shape.width = ft_asso(shape.width, wpz.width.value); } else if (wpz.prec.state && wpz.prec.value < 0 && wpz.zero.state && wpz.zero.value < 0) shape.width = ft_asso(shape.width, wpz.zero.value); else if (wpz.zero.state) shape.zero = ft_asso(shape.zero, wpz.zero.value); else if (wpz.width.state) shape.width = ft_asso(shape.width, wpz.width.value); return (shape); } char const *choose_flag(char *format, va_list argp, int *a) { t_flags wpz; wpz.width = fetch_width(format, argp); wpz.zero = fetch_zero(format, argp); wpz.prec = fetch_prec(format, argp); while (!ft_isalpha(*format) && *format != '%') format++; if (*format == 'd' || *format == 'i' || *format == 'c') print_decint((char*)format, argp, ft_reshape(wpz), a); else if (*format == 'X' || *format == 'x' || *format == 'u') print_hex(format, argp, ft_reshape(wpz), a); else if (*format == 'p') print_pointer(argp, wpz, a); else if (*format == 's') print_string(argp, wpz, a); else print_prec(wpz, a); format++; return (format); }
C
// this is a merge sorting algorithm // time complexity: O(n*Log n) #include<stdio.h> #include<stdlib.h> void merge(int A[],int l,int m,int r) { int i,j,k; int n1=(m-l)+1; int n2=r-m; int L[n1],R[n2]; for(i=0;i<n1;i++) L[i]=A[l+i]; for(j=0;j<n2;j++) R[j]=A[m+1+j]; i=0; j=0; k=l; while(i<n1&&j<n2) { if(L[i]<=R[j]) { A[k]=L[i]; i++; } else { A[k]=R[j]; j++; } k++; } while(i<n1) { A[k]=L[i]; i++; k++; } while(j<n2) { A[k]=R[j]; j++; k++; } } void merge_sort(int A[],int left,int right) { int middle; if(left<right){ middle=left+(right-left)/2; merge_sort(A,left,middle); merge_sort(A,middle+1,right); merge(A,left,middle,right); } } int main() { int *A,size,i; printf("enter size"); scanf("%d",&size); A=(int*)malloc(sizeof(int)*size); for(i=0;i<size;i++) scanf("%d",&A[i]); merge_sort(A,0,size-1); for(i=0;i<size;i++) printf("%d\t",A[i]); return 0; } // Input: Size: 7 // 10 7 2 54 32 1 4 // Output: 1 2 4 7 10 32 54
C
/***********************************************************************/ /* Anyone is free to copy, modify, publish, use, compile, sell, */ /* dismantle, dismember or distribute this software, either in source */ /* code form or as object code or assembly code, for any purpose, */ /* commercial or non-commercial, and by any means. */ /***********************************************************************/ #include <stdio.h> #include <stdlib.h> #include "btree.h" /***********************************************************************/ /* CreateBtree: Create binary tree from an integer array */ /* */ /***********************************************************************/ struct TreeNode *CreateBtree(int *arr, int s, int e) { struct TreeNode *root; int mid = s + (e - s) / 2; /* We are the leaf nodes */ if (e < s) return NULL; /* Allocate the node */ root = malloc(sizeof(struct TreeNode )); if (!root) return NULL; /* Assign the value and recursively generate left and right sub-trees */ root->val = arr[mid]; root->left = CreateBtree(arr, s, mid - 1); root->right = CreateBtree(arr, mid + 1, e); return root; } /***********************************************************************/ /* CreateBLtree: Create binary linked tree from an integer array */ /* */ /***********************************************************************/ struct TreeLinkNode *CreateBLTree(int *arr, int s, int e) { struct TreeLinkNode *root; int mid = s + ((e - s + 1) / 2); /* Array is empty */ if (s > e) return NULL; root = malloc(sizeof(struct TreeLinkNode)); if (!root) return NULL; root->val = arr[mid]; root->next = NULL; root->left = CreateBLTree(arr, s, mid - 1); root->right = CreateBLTree(arr, mid + 1, e); return root; } /***********************************************************************/ /* FreeBtree: Free binary tree */ /* */ /***********************************************************************/ void FreeBtree(struct TreeNode *root) { if (!root) return; FreeBtree(root->left); root->left = NULL; FreeBtree(root->right); root->left = root->right = NULL; free(root); } /***********************************************************************/ /* InorderBtree: Inorder print of Btree */ /* */ /***********************************************************************/ void InorderBtree(struct TreeNode *root) { if (!root) return; InorderBtree(root->left); printf("%d ", root->val); InorderBtree(root->right); } /***********************************************************************/ /* InorderBLtree: Inorder print of BLtree */ /* */ /***********************************************************************/ void InorderBLTree(struct TreeLinkNode *root) { /* Validate the node */ if (!root) return; InorderBLTree(root->left); printf("%d ", root->val); InorderBLTree(root->right); } /***********************************************************************/ /* PreorderBtree: Preorder print of Btree */ /* */ /***********************************************************************/ void PreorderBtree(struct TreeNode *root) { if (!root) return; printf("%d ", root->val); PreorderBtree(root->left); PreorderBtree(root->right); } /***********************************************************************/ /* PostorderBtree: Postorder print of Btree */ /* */ /***********************************************************************/ void PostorderBtree(struct TreeNode *root) { if (!root) return; PostorderBtree(root->left); PostorderBtree(root->right); printf("%d ", root->val); } /***********************************************************************/ /* InorderBtreeArr: Inorder storing of Btree into an array */ /* */ /***********************************************************************/ void InorderBtreeArr(struct TreeNode *root, int **arr) { if (!root) return; InorderBtreeArr(root->left, arr); **arr = root->val; (*arr) += 1; InorderBtreeArr(root->right, arr); } /***********************************************************************/ /* PreorderBtreeArr: Preorder storing of Btree into an array */ /* */ /***********************************************************************/ void PreorderBtreeArr(struct TreeNode *root, int **arr) { if (!root) return; **arr = root->val; (*arr) += 1; PreorderBtreeArr(root->left, arr); PreorderBtreeArr(root->right, arr); } /***********************************************************************/ /* PreorderBtreeBArr: Preorder storing of Btree nodes into an array */ /* */ /***********************************************************************/ void PreorderBtreeBArr(struct TreeNode *root, struct TreeNode ***arr) { if (!root) return; **arr = root; (*arr) += 1; PreorderBtreeBArr(root->left, arr); PreorderBtreeBArr(root->right, arr); } /***********************************************************************/ /* PostorderBtreeArr: Postorder storing of Btree into an array */ /* */ /***********************************************************************/ void PostorderBtreeArr(struct TreeNode *root, int **arr) { if (!root) return; PostorderBtreeArr(root->left, arr); PostorderBtreeArr(root->right, arr); **arr = root->val; (*arr) += 1; } /***********************************************************************/ /* LevelTraversalBLtree: Level traversal of BLtree */ /* */ /***********************************************************************/ void LevelTraversalBLtree(struct TreeLinkNode *root) { struct TreeLinkNode *tnode; /* Validate the input */ if (!root) return; /* Save pointer to the next level, print the present level */ tnode = root->left ? root->left : root->right; do printf("%d ", root->val); while ((root = root->next)); printf("\n"); /* Move to the next level */ LevelTraversalBLtree(tnode); } /***********************************************************************/ /* FreeBLtree: Free binary linked tree */ /* */ /***********************************************************************/ void FreeBLtree(struct TreeLinkNode *root) { if (!root) return; FreeBLtree(root->left); root->left = NULL; FreeBLtree(root->right); root->right = NULL; free(root); }
C
/* ID: ronak.b1 LANG: C TASK: crypt1 */ #include <assert.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define i64 long long #define uint unsigned int #define MAX(a, b) ( a > b ? a : b ) #define MIN(a, b) ( a < b ? a : b ) char numset[10]; int numarr[10]; char num_is_in_set( int num ); int compare_int( const void *a, const void *b ) { return *(int*) a - *(int*) b; } char is_valid( int a, int b, int c, int d, int e ) { int numtop = a*100 + b*10 + c; int p1 = numtop * e, p2 = numtop * d; int p = p1 + p2*10; return p <= 9999 && p1 <= 999 && p2 <= 999 && num_is_in_set(p1) && num_is_in_set(p2) && num_is_in_set(p); } char num_is_in_set( int num ) { char buff[50]; sprintf( buff, "%d", num ); for ( char *c = buff; *c != '\0'; ++c ) if ( !numset[*c-'0'] ) return 0; return 1; } int main() { FILE *fin = fopen( "crypt1.in", "r" ); FILE *fout = fopen( "crypt1.out", "w+" ); int N, numsolutions; fscanf( fin, "%d", &N ); for ( int i = 0; i < N; ++i ) { int num; fscanf( fin, "%d", &num ); numset[num] = 1; numarr[i] = num; } numsolutions = 0; for ( int a = 0; a < N; ++a ) { for ( int b = 0; b < N; ++b ) { for ( int c = 0; c < N; ++c ) { for ( int d = 0; d < N; ++d ) { for ( int e = 0; e < N; ++e ) { if ( is_valid( numarr[a], numarr[b], numarr[c], numarr[d], numarr[e] ) ) { numsolutions++; } } } } } } fprintf( fout, "%d\n", numsolutions ); fclose( fin ); fclose( fout ); return 0; }
C
// CODE: DMS Assignment Problem-35 #include <stdio.h> int main() { int C; printf("\nGiven the Truth values of P and Q:\n\n"); printf(" P | Q\n"); printf("-------\n"); printf(" T | T\n T | F\n F | T\n F | F\n"); printf("\n INSTRUCTIONS: Enter a correct choice\n"); printf("\t1. Conjuntion\n\t2. Disjunction\n\t3. Exclusive or\n\t4. Conditional Statement\n\t5. Biconditional Statement\n\t6. Exit\n"); do { printf("\nEnter the choice: "); scanf("%d", &C); switch(C) { case 1: printf("\nThe Conjunction of P and Q Propositions:\n"); printf(" P | Q | P ^ Q\n"); printf("---|---|-------\n"); printf(" T | T | T\n T | F | F\n F | T | F\n F | F | F\n"); break; case 2: printf("\nThe Disjunction of P and Q Propositions:\n"); printf(" P | Q | P V Q\n"); printf("---|---|-------\n"); printf(" T | T | T\n T | F | T\n F | T | T\n F | F | F\n"); break; case 3: printf("\nThe Exclusive OR of P and Q Propositions:\n"); printf(" P | Q | P (+) Q\n"); printf("---|---|-------\n"); printf(" T | T | F\n T | F | T\n F | T | T\n F | F | F\n"); break; case 4: printf("\nThe Conditional Statement of P and Q Propositions:\n"); printf(" P | Q | P --> Q\n"); printf("---|---|-------\n"); printf(" T | T | T\n T | F | F\n F | T | T\n F | F | T\n"); break; case 5: printf("\nThe Biconditonal Statement of P and Q Propositions:\n"); printf(" P | Q | P <--> Q\n"); printf("---|---|-------\n"); printf(" T | T | T\n T | F | F\n F | T | F\n F | F | T\n"); break; case 6: printf("\nYou Exited\n"); break; default: printf("\n---/** ENTER A CORRECT CHOICE **/---\n"); } } while (C != 6); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include "stdio.h" #include "graph.h" #define ERROR_WRONG_VERTEX_NUM 1 #define ERROR_WRONG_EDGE_NUM 2 #define ERROR_WRONG_LINES_NUM 3 int checkInput(FILE * fout, int vert, int edge); int main() { int vert_num = -1, edge_num = -1; int i, ver1, ver2; FILE * fin = fopen("in.txt", "r"); FILE * fout = fopen("out.txt", "w"); if (!fscanf(fin, "%d" ,&vert_num)){ printf("bad number of lines"); return 0; } if (!fscanf(fin, "%d", &edge_num)){ printf("bad number of lines"); return 0; } if (checkInput(fout, vert_num, edge_num)) return 0; Vertex ** vert_array = constructVertex(vert_num); for (i = 0; i < edge_num; i++) { if (fscanf(fin, "%d", &ver1) == -1 || fscanf(fin, "%d", &ver2) == -1) { fprintf(fout, "bad number of lines"); return 0; } if (ver1 > vert_num || ver1 < 0 || ver2 < 0 || ver2 > vert_num) { fprintf(fout, "bad vertex"); return 0; } vert_array[ver1-1]->list_to = push(vert_array[ver2-1], vert_array[ver1-1]->list_to); } writeSortedGraph(fout, vert_array, vert_num); return 0; } int checkInput(FILE * fout, int vert, int edge) { if (vert == -1 || edge == -1){ fprintf(fout, "bad number of lines"); return ERROR_WRONG_LINES_NUM; } if (vert < 0 || vert > 1000){ fprintf(fout, "bad number of vertices"); return ERROR_WRONG_VERTEX_NUM; } if (edge < 0 || edge > vert*(vert + 1) / 2){ fprintf(fout, "bad number of edges"); return ERROR_WRONG_EDGE_NUM; } return 0; }
C
#include <stdio.h> #define VALUE_BITS 8*sizeof(int) bitPrint(int n, unsigned m) { if (0==m) return; bitPrint(n,m<<1); printf("%d",0!=(n&m)); } int bitRev(int value) { int result = 0; for(int i = 0; i < VALUE_BITS; i++) { result = (result << 1) | (value & 1); value >>= 1; } return result; } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int value, revValue; scanf("%d", &value); bitPrint(value, 1); printf("\n"); revValue = bitRev(value); printf("%d \n", revValue); bitPrint(revValue, 1); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> FILE *out; int main () { int Ssocket = socket (AF_INET, SOCK_STREAM, 0); struct sockaddr_in myaddr, clientaddr; myaddr.sin_family = AF_INET; myaddr.sin_port = htons(4000); myaddr.sin_addr.s_addr = INADDR_ANY; bind(Ssocket, (struct sockaddr*)&myaddr, sizeof ( struct sockaddr_in)); listen(Ssocket, 20); int nSock; char buff[1000]; int rsize = 0; int nfd; while ( nfd = accept(Ssocket, (struct sockaddr*) &clientaddr, &nSock) ) { if (nfd == -1) { printf("Fatal Error, Please Shut Down Your Computer"); return 1; } rsize = recv(nfd, buff, 200, 0); printf("%s",buff); } close(nSock); return 0; }
C
#include<stdio.h> int main(){ for(int i=0; i<128; i++){ printf("DECIMAL = %d : ASCII = %c\n",i,i); } return 0; }
C
/* * Exam 2 Program 2 * Written by: Tyler Duong, Nikki Abedi, Jasmine Sourinthone * CS36 9/5/19 */ #include <stdio.h> #include <stdlib.h> #include <time.h> int roll( int min, int max ) //return a random number between 1 and 6 { return (rand() / ((double)RAND_MAX+1)) * (max-min+1) + min; } int main() { int i_user_num, //Purpose: hold the user's input for number bet on i, //Purpose: act as an iterator for all for loops r, //Purpose: hold each roll's result for printing i_win_ct; //Purpose: hold the number of times the user matched their number float f_bet, //Purpose: hold the user's input for amount bet f_res; //Purpose: hold the result winnings of the user printf("How lucky are you feeling: $"); scanf("%f", &f_bet); if ( f_bet < 0 ) // f_bet <= 0 { printf("You can't bet negative money\n"); return 3; } printf("What number are you betting on (1-6): "); scanf("%d", &i_user_num); if ( i_user_num < 1 || i_user_num > 6 ) { printf(" You're stupid that number is invalid\n"); return 8; } srand(time(NULL)); //generate a pseudo-random seed based on the time f_res = 0; //init result as 0 i_win_ct = 0; printf("Roll: "); for ( i = 0; i < 5; i++ ) //roll 5 times { r = roll(1,6); //generate the roll printf("%d ", r); //print each value so the user can verify that this rigged game is rigged if ( i_user_num == r ) { f_res += f_bet; //for each correct roll, add the amount i_win_ct++; } } printf("\n"); //if the count is not 0, you win (i_win_ct)? printf("You matched %d time(s)!\n", i_win_ct) : printf("You didn't match anything\n"); if (f_res) printf("You won $%.02f\n", f_res); //if is a non-zero value else printf("You sorta suck at this game...\n"); //else you lost //operators // x++ - increment x by one after // ++x - increment x by one before // x-- - decrease x by one after // --x - decrease x by one before // x+=5 - increase x by 5 return 0; } /* OUTPUT: $ ./main How lucky are you feeling: $6000 What number are you betting on (1-6): 5 Roll: 5 2 1 6 3 You matched 1 time(s)! You won $6000.00 $ ./main How lucky are you feeling: $2 What number are you betting on (1-6): 2 Roll: 5 2 4 2 2 You matched 3 time(s)! You won $6.00 $ ./main How lucky are you feeling: $-100 You can't bet negative money $ ./main How lucky are you feeling: $1 What number are you betting on (1-6): -2 You're stupid that number is invalid */ //Pick a random number and a range ( the computer) //Srand and rand only //2000 to 8000 //srand((unsigned)time(&t)); //Num = rand()%6001 + 2000; //Num = rand()%(max-min+1) + min; //printf("Enter the score "); // scanf("%d", &score); // if (score < 0 || score > 100) // > greater than if ( 2 > 1 ) ... // >= gt or eq to if ( 2 >= 2 ) ... if ( x >= 100 ) ... // < less than // <= lt or eq to // == equal to // && and if (true && true) ... if ( x >= 100 && y >= 100 ) ... // || or if (true || false) ... if (1 > 0 || 1 > 4) // ( 2 > 1 ) == true
C
// // Created by shhan on 12/26/16. // #include "sh_list.h" SH_LinkedList_t *SH_LinkedListNew(void) { SH_LinkedList_t *l = NULL; l = (SH_LinkedList_t *)malloc(sizeof(SH_LinkedList_t)); if (l) { memset(l, 0, sizeof(*l)); } return l; } RETCODE SH_LinkedListAdd(SH_LinkedList_t *list, void *data) { if (list) { if (list->head == NULL) { // Head list->head = (SH_ListData_t *)malloc(sizeof(SH_ListData_t)); list->head->next = NULL; list->head->data = data; list->cur = list->head; list->prev = list->head; } else { SH_ListData_t *p; // Tail //list->cur = list->head; while(list->cur->next) { list->cur = list->cur->next; } p = (SH_ListData_t *)malloc(sizeof(SH_ListData_t)); p->data = data; p->next = NULL; list->cur->next = p; list->prev = list->cur; list->cur = list->cur->next; } return SH_SUCCESS; } return SH_FAIL; } void SH_LinkedListFree(SH_LinkedList_t *list, void(*free_data_callback)(void *)) { SH_ListData_t *temp = NULL; SH_ListData_t *head = list->head; while(head) { if (head->data) { free_data_callback(head->data); temp = head->next; free(head); head = temp; } } free(list); } /* SH_LinkedList* SH_NewList() { SH_LinkedList *l = (SH_LinkedList *)malloc(sizeof(SH_LinkedList)); memset(l, 0, sizeof(*l)); return l; } SH_LinkedList* SH_AddList(SH_LinkedList *l, void *data, int len) { SH_LinkedList *p = NULL; if (data && len > 0) { if (l->data) free(l->data); l->data = malloc(len); if (l->data) { memcpy(l->data, data, len); p = (SH_LinkedList *)malloc(sizeof(SH_LinkedList)); memset(p, 0, sizeof(SH_LinkedList)); l->next = p; l = l->next; } } return p; } void SH_RemoveAllList(SH_LinkedList *head, void (*free_data_callback)(void *)) { while (head->data) { SH_LinkedList *temp; free_data_callback(head->data); temp = head->next; free(head); head = temp; } if (head) free(head); }*/
C
#include "usart.h" void Uart1_Init(u32 bound) { RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1); GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;// GPIO_Init(GPIOA, &GPIO_InitStructure); RCC_APB2PeriphClockCmd(RCC_APB2Periph_UART1, ENABLE); UART_InitTypeDef UART_InitStructure; UART_InitStructure.UART_BaudRate = bound;// UART_InitStructure.UART_WordLength = UART_WordLength_8b; UART_InitStructure.UART_StopBits = UART_StopBits_1; UART_InitStructure.UART_Parity = UART_Parity_No; UART_InitStructure.UART_HardwareFlowControl = UART_HardwareFlowControl_None; UART_InitStructure.UART_Mode = UART_Mode_Rx | UART_Mode_Tx; UART_Init(UART1, &UART_InitStructure); UART_ITConfig(UART1, UART_IT_RXIEN, ENABLE); UART_Cmd(UART1, ENABLE); } void NVIC_Uart1_Init(void) { NVIC_InitTypeDef NVIC_InitStruct; NVIC_InitStruct.NVIC_IRQChannel = UART1_IRQn; NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStruct.NVIC_IRQChannelPriority = 0; NVIC_Init(& NVIC_InitStruct); } /******************************************************************************* * @name : UartSendByte() * @brief : UART1 send byte * @param : void * @retval : void *******************************************************************************/ void UartSendByte(u8 dat) { UART_SendData(UART1, dat); while(!UART_GetFlagStatus(UART1, UART_FLAG_TXEPT)); } /******************************************************************************* * @name : UartSendGroup() * @brief : UART1 send byte * @param : u8* buf:buffer address u16 len:data length * @retval : void *******************************************************************************/ void UartSendGroup(u8* buf, u16 len) { while(len--) UartSendByte(*buf++); } /******************************************************************************* * @name : UartSendAscii() * @brief : UART1 send ASCII * @param : char *str * @retval : void *******************************************************************************/ void UartSendAscii(char *str) { while(*str) UartSendByte(*str++); } ///ضc⺯printfڣضʹprintf int fputc(int ch, FILE *f) { //һֽݵ UartSendByte((uint8_t) ch); //ȴ while (UART_GetFlagStatus(UART1, UART_FLAG_TXEPT) == RESET); return (ch); } ///ضc⺯scanfڣдʹscanfgetcharȺ int fgetc(FILE *f) { //ȴ while (UART_GetFlagStatus(UART1, UART_FLAG_RXAVL) == RESET); return (int)UART_ReceiveData(UART1); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> static const int blsize = 100; static unsigned char byte = 0; static unsigned char offset = 1; static const unsigned char max_offset = (1 << 7); static int ch_pid; static unsigned char buf [100]; static int i = 0; void CrashOnError(int err, char* descr) { if(err){ perror(descr); exit(1); } } void PrintToStdout() { int n = write(STDOUT_FILENO, buf, i); CrashOnError(n < 0, "Error writing to stdout"); fflush(stdout); } void RememberByte() { buf[i++] = byte; byte = 0; if(i == blsize) { PrintToStdout(); i = 0; } } void GotOne(int signumber) { byte += offset; offset = (offset << 1); int err = kill(ch_pid, SIGUSR1); CrashOnError(err < 0, "Error telling child OK"); } void GotZero(int signumber) { offset = (offset << 1); int err = kill(ch_pid, SIGUSR1); CrashOnError(err < 0, "Error telling child OK"); } void GotChildIsDead (int signumber) { if(i > 0) { i--; } PrintToStdout(); exit(0); } void GotParentIsDead(int signumber) { printf("Error: PARENT IS DEAD\n"); exit(1); } void GotParentIsAlive(int signumber) { alarm(0); } int main(int argc, char** argv) { if (argc != 2) { printf("Error: invalid number of arguments\nUsage %s file\n", argv[0]); exit(1); } int err; sigset_t empty_set; err = sigemptyset(&empty_set); CrashOnError(err, "Error creating empty set"); sigset_t block_set; err = sigemptyset(&block_set); CrashOnError(err < 0, "Error initializing block_set in parent"); err = sigaddset(&block_set, SIGUSR1); CrashOnError(err < 0, "Error adding SIGUSR1 to block_set"); err = sigaddset(&block_set, SIGUSR2); CrashOnError(err < 0, "Error adding SIGUSR2 to block_set"); err = sigaddset(&block_set, SIGCHLD); CrashOnError(err < 0, "Error adding SIGCHILD to block_set"); err = sigaddset(&block_set, SIGALRM); CrashOnError(err <0, "Error adding SIGALRM to child set"); err = sigprocmask(SIG_BLOCK, &block_set, NULL); CrashOnError(err < 0, "Error changing signal mask of parent"); ch_pid = fork(); //CHILD if(ch_pid == 0) { int fd_in = open(argv[1], O_RDONLY); CrashOnError(fd_in < 0, "Error opening file"); int par_pid = getppid(); struct sigaction pdead_act; pdead_act.sa_handler = GotParentIsDead; pdead_act.sa_flags = 0; err = sigfillset(&pdead_act.sa_mask); CrashOnError(err, "Error filling set for sigaction pdead_act"); err = sigaction(SIGALRM, &pdead_act, NULL); CrashOnError(err < 0, "Error setting action GotParentIsDead"); struct sigaction palive_act; palive_act.sa_handler = GotParentIsAlive; palive_act.sa_flags = 0; err = sigfillset(&palive_act.sa_mask); CrashOnError(err, "Error filling set for sigaction palive_act"); err = sigaction(SIGUSR1, &palive_act, NULL); CrashOnError(err < 0, "Error setting action GotParentIsAlive"); int n = 1; while (n > 0) { n = read(fd_in, &byte, 1); CrashOnError(n < 0, "Error reading from file"); for (offset = 1; offset > 0; offset = (offset << 1)) { if (offset & byte) { err = kill(par_pid, SIGUSR1); CrashOnError(err < 0, "Error sending one(SIGUSR1) to parent"); } else { err = kill(par_pid, SIGUSR2); CrashOnError(err < 0, "Error sending zero (SIGUSR2) to parent"); } alarm(1); sigsuspend(&empty_set); } //printf("send %c\n", byte); } err = close(fd_in); CrashOnError(err != 0, "Error closing file"); exit(0); } //PARENT struct sigaction one_act; one_act.sa_handler = GotOne; one_act.sa_flags = 0; err = sigfillset(&one_act.sa_mask); CrashOnError(err, "Error filling set for sigaction one_act"); err = sigaction(SIGUSR1, &one_act, NULL); CrashOnError(err < 0, "Error setting action GotOne"); struct sigaction zero_act; zero_act.sa_handler = GotZero; zero_act.sa_flags = 0; err = sigfillset(&zero_act.sa_mask); CrashOnError(err, "Error filling set for sigaction zero_act"); err = sigaction(SIGUSR2, &zero_act, NULL); CrashOnError(err < 0, "Error setting action GotZero"); struct sigaction chdead_act; chdead_act.sa_handler = GotChildIsDead; chdead_act.sa_flags = 0; err = sigfillset(&chdead_act.sa_mask); CrashOnError(err, "Error filling set for sigaction chdead_act"); err = sigaction(SIGCHLD, &chdead_act, NULL); CrashOnError(err < 0, "Error setting action GotChildIsDead"); while(1) { sigsuspend(&empty_set); if (offset == 0){ offset = 1; RememberByte(); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <ctype.h> /** * main - Entry point and execute the ramdon number * * Return: 0 */ int main(void) { char l; char u; for (l = 'a'; l <= 'z'; ++l) putchar(l); for (u = 'A'; u <= 'Z'; ++u) putchar(u); putchar('\n'); return (0); }
C
/** * hilo.c, by Lawrence Buckingham on 08 March 2020. * (C) 2020 Queensland University of Technology. */ #include <stdio.h> #include <time.h> #include <stdlib.h> int main () { // Think of a number srand(time(NULL)); int secret = 1 + rand() % 100; int guess; // Forever... while (1) { printf("I'm thinking of a number between 1 and 100. Can you guess what it is?\n"); int conversions = scanf("%d", &guess); if ( conversions < 0 ) { // Out of data printf( "End of input reached, bye.\n" ); break; } else if ( conversions == 0 ){ // Data, but not numeric - throw away the rest of the line. printf( "You need to enter a whole number!\nTry again.\n" ); char discardChar; do { conversions = scanf( "%c", &discardChar ); } while ( conversions == 1 && discardChar != '\n' ); } else { // printf( "conversions = %d\n", conversions ); // printf( "guess = %d\n", guess ); if ( guess > secret ) { printf("Your guess is too high.\n"); } else if ( guess < secret ) { printf("Your guess is too low.\n"); } else { printf("You. Are. A. Genius.\nWell done for guessing the answer.\n"); break; } } } printf( "Goodbye. Please play again some day.\n" ); return 0; }
C
#ifndef NO_IDENT static char *Id = "$Id: putraw.c,v 1.4 1995/06/04 17:08:54 tom Exp $"; #endif /* * Title: putraw.c * Author: Thomas E. Dickey * Created: 12 Nov 1984 * Last update: * 03 Jun 1995, prototyped * * Function: Print a null-ended string on the terminal. Unlike 'printf', * this VMS function will not be confused by backspaces. (The * problem with 'printf' is that it does not track backspaces * when determining the wraparound column.) */ #include <descrip.h> #include <string.h> #include "crt.h" extern void lib$put_screen(struct dsc$descriptor_s *p); void putraw (char *s_) { static $DESCRIPTOR(DSC_bell," "); DSC_bell.dsc$a_pointer = s_; DSC_bell.dsc$w_length = strlen(s_); lib$put_screen (&DSC_bell); }
C
/* - STRCSPN.C - The ANSI "strcspn" function. $Revision: 328482 $ Copyright 1986 - 1999 IAR Systems. All rights reserved. */ #include "string.h" size_t strcspn(const char *s1, const char *s2) { #ifdef _INTRINSIC return strcspn(s1, s2); #else char *v; size_t n = 0; while (*s1) { v = (char *)s2; while (*v) { if (*v++ == *s1) return n; } s1++; n++; } return n; #endif }
C
/*! @file * * @brief Routines for controlling the Real Time Clock (RTC) on the TWR-K70F120M. * * Implementation of functions for operating the real time clock (RTC). * * @author Mohammad Yasin Azimi, Scott Williams * @date 2016-10-31 */ /*! * @addtogroup RTC_module RTC module documentation * @{ */ #include "RTC.h" #include "LEDs.h" #include "types.h" #include "MK70F12.h" /*! @brief Initializes the RTC before first use. * * Sets up the control register for the RTC and locks it. * Enables the RTC and sets an interrupt every second. * @param userFunction is a pointer to a user callback function. * @param userArguments is a pointer to the user arguments to use with the user callback function. * @return bool - TRUE if the RTC was successfully initialized. */ BOOL RTC_Init() { RTCSemaphore = OS_SemaphoreCreate(0); // Enable clock gate RTC SIM_SCGC6 |= SIM_SCGC6_RTC_MASK; // Enables oscillator for external signal RTC_CR |= RTC_CR_OSCE_MASK; // Enable 18pF load as per lab note hint RTC_CR = RTC_CR | RTC_CR_SC16P_MASK | RTC_CR_SC2P_MASK; // RTC Interrupt Enable Register // Enables seconds enable interrupt (on by default) RTC_IER |= RTC_IER_TSIE_MASK; // Disables Time Alarm Interrupt RTC_IER &= ~RTC_IER_TAIE_MASK; // Disables Overflow Interrupt RTC_IER &= ~RTC_IER_TOIE_MASK; // Disables Time Invalid Interrupt RTC_IER &= ~RTC_IER_TIIE_MASK; // Locks the control register RTC_LR &= ~RTC_LR_CRL_MASK; // Initialises the timer control RTC_SR |= RTC_SR_TCE_MASK; // NVIC Register Masks (RM: Page 95 - 98) // Clear any pending 'seconds' interrupts on RTC using IRQ value NVICICPR2 = (1<<(67 % 32)); // Enable 'seconds' interrupts on RTC NVICISER2 = (1<<(67 % 32)); // RTC successfully initialised return bTRUE; } /*! @brief Sets the value of the real time clock. * * @param hours The desired value of the real time clock hours (0-23). * @param minutes The desired value of the real time clock minutes (0-59). * @param seconds The desired value of the real time clock seconds (0-59). * @note Assumes that the RTC module has been initialized and all input parameters are in range. */ void RTC_Set(const uint8_t hours, const uint8_t minutes, const uint8_t seconds) { // Intermediate value recording day count of TSR uint32_t daysTSR, TSRregOut, TSRregIn, hoursGMTtime; // GMT delay for Australia noted uint8_t GMTchangeHours = 10; // Disables the time counter RTC_SR &= ~RTC_SR_TCE_MASK; // Calculates the value of real time clock with imperfect error handling uint32_t timeSeconds = ((hours % 24) * 3600) + ((minutes % 60) * 60) + (seconds % 60); // Note TSR value at start of function TSRregIn = RTC_TSR; // Hours since 1/1/70 0:00 as a remainder of 24 hoursGMTtime = (RTC_TSR / 3600) % 24; if(hoursGMTtime + GMTchangeHours > 23) { // Because Setting time in location on other side of GMT dateline daysTSR= (RTC_TSR / (24*60*60)) + 1; } else { // Because setting time in location at time where date is shared with date of GMT time daysTSR= (RTC_TSR / (24*60*60)); } // Resets Time Seconds Register UNIX time RTC_TSR = timeSeconds + (daysTSR * 24 * 60 * 60) - (GMTchangeHours*60*60); TSRregOut = RTC_TSR; // Re-enables the time counter RTC_SR |= RTC_SR_TCE_MASK; } /*! @brief Gets the value of the real time clock. * * @param hours The address of a variable to store the real time clock hours. * @param minutes The address of a variable to store the real time clock minutes. * @param seconds The address of a variable to store the real time clock seconds. * @note Assumes that the RTC module has been initialized. */ void RTC_Get(uint8_t* const hours, uint8_t* const minutes, uint8_t* const seconds) { uint32_t UNIXtime; // AEST time is GMT + 10 hours uint8_t GMT = 10; // Un-required variable, declared for interpretation purposes only UNIXtime = RTC_TSR; // Updates the current time value of hours for Sydney (GMT+10) *hours = ((UNIXtime / 3600) + GMT) % 24; // Updates the current time value of minutes *minutes = (UNIXtime / 60) % 60; // Updates the current time value of seconds *seconds = UNIXtime % 60; } /*! @brief Interrupt service routine for the RTC. * * The RTC has incremented one second. * The semaphore signal will be called * @note Assumes the RTC has been initialized. */ void __attribute__ ((interrupt)) RTC_ISR(void) { OS_ISREnter(); // Semaphore signals RTC semaphore OS_SemaphoreSignal(RTCSemaphore); OS_ISRExit(); } /*! * @} */
C
/* ============================================================================ Name : server.c Author : TM Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> //dołączanie bibliotek #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include "library.h" // dołączanie pliku nagłówkowego library.h int main(int argc , char *argv[]) { char buf[50]; //deklaracja bufora int port = 8883; // port domyślny if(argc == 2) { port = atoi(argv[1]); //konwersja string na int printf("Port Introduced %d\n", port); if(port == 0) port = 8883; //ustawienie portu domyślnego } int socket_desc , client_sock , c , read_size; //definicja zmiennych typu int struct sockaddr_in server , client; //definicja struktur dla klienta i serwera char message[100]; //definicja zmiennej char przechowywującej wiadomość od klienta socket_desc = socket(AF_INET , SOCK_STREAM , 0); //stworzenie gniazda if (socket_desc == -1) { printf("Cannot create a socket"); } puts("Socket created"); //gniazdo poprawni utworzone server.sin_family = AF_INET; //ipv4 server.sin_addr.s_addr = INADDR_ANY; //bindowanie do wszystkich dostępnych interfejsów serwera server.sin_port = htons( port ); //host to network short if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) //bindowanie połączenia { perror("Bind failed. Error"); //bindowanie nieudane return 1; } puts("Bind successfull"); //bindowanie udane listen(socket_desc , 3); //oczekiwanie na połączenie puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in); client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c); if (client_sock < 0) { perror("Accept failed"); //połączenie nieudane return 1; } puts("Connected"); while( (read_size = recv(client_sock , message , 100 , 0)) > 0 ) { //odebranie wiadomości function(message, buf); write(client_sock , buf , strlen(buf)); } if(read_size == 0) { puts("Client disconnected"); //rozłączenie klienta fflush(stdout); } else if(read_size == -1) { perror("Receivinng failed"); //odbiór nieudany } if(!close(client_sock)) puts("Client socket closed"); //zamknięcie gniazda if(!close(socket_desc)) puts("socket desc closed"); return EXIT_SUCCESS; }
C
/* ============================================================================ ANEXO 5-1: Armar un Men de Opciones con las siguientes opciones: 1-Inicializar 2-Cargar 3-Mostrar 4-Calcular Promedio 5-Ordenar Al ingresar a cada opcin del men deber imprimir en pantalla el nombre del mismo. Ej: Si se presiona la opcin 1 mostrar por pantalla Ud. ha seleccionado lo opcin 1-Inicializar ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include "funciones.h" int main(void) { setbuf(stdout, NULL); return 0; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> enum{MAX=81,LINE=5}; typedef struct dt {char model[50],phangiai[10];float store,gia;}dt; void conv_dat(FILE *f1,FILE *f2) { float store,gia; char ten[50],pg[50]; dt a; while(fscanf(f1,"%s",ten)!=EOF) { strcpy(a.model,ten); fscanf(f1,"%f",&store); a.store=store; fscanf(f1,"%s",pg); strcpy(a.phangiai,pg); fscanf(f1,"%f",&gia); a.gia=gia; fwrite(&a,sizeof(dt),1,f2); } } void in(dt *a) { printf("Model:%s\nThong tin:\nBo nho:%g\nDo phan giai:%s\nGia:%g\n***\n",a->model,a->store,a->phangiai,a->gia); } void show(FILE *f) { char buff[81]; int dem=0; dt *a; a=(dt *)malloc(sizeof(dt)); rewind(f); while(fread(a,sizeof(dt),1,f)!=0) { dem++; if(dem%LINE==0) {printf("press any key to continue\n");getchar();} in(a); } free(a); } void search(FILE *f) { char model[50]; dt *a; printf("Nhap model dien thoai ban muon tim kiem:"); scanf("%s",model); rewind(f); a=(dt *)malloc(sizeof(dt)); while(fread(a,sizeof(dt),1,f)!=0) if(strcmp(a->model,model)==0) {in(a);break;} free(a); } int main(int argc,char* argv[]) { FILE *f,*f1; int chon; if(argc!=2) {printf("Cu phap: %s <file data.txt>\n",argv[0]);exit(1);} else if((f=fopen(argv[1],"r"))==NULL) {printf("Cant open file %s\n",argv[1]);exit(0);} else { printf("Cua hang di dong NO-store\n"); printf("Menu\n1.Chuyen du lieu tu file .txt sang .doc\n"); printf("2.Hien danh sach dien thoai cua cua hang\n"); printf("3.Tim kiem mau dien thoai theo model\n"); printf("4.Exit\n"); if((f1=fopen("dt.dat","w+b"))==NULL) {printf("Cant open file dt.dat\n");exit(1);} else do{ printf("Chon:"); scanf("%d",&chon); switch(chon) { case 1:conv_dat(f,f1);break; case 2:show(f1);break; case 3:search(f1);break; } }while(chon!=4); fclose(f);fclose(f1); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> #define n_of_n 50 unsigned long long gen_random() { unsigned long long n=0; int ten=1; //srand(time(NULL)); for(int i=0;i<20;i++) { n=n+abs(ten*(rand()%9+1)); ten*=10; } return (n); } //function to generate prime numbers------------------------------------------------------- int* prime_generate(int *n) { int a[9000]; for(int i=0;i<9000;i++) a[i]=i+1000; for(int i=2;i<=5000;i++) { for(int j=2;i*j<10000;j++) { //if(i*j<5000) // printf("%d\t%d\t%d\n",i*j,i,j); if(i*j>=1000) a[i*j-1000]=0; } } int *p; p=(int*) malloc(1500*sizeof(int)); int index=0; for(int i=0;i<9000;i++) if(a[i]!=0) { p[index]=a[i]; index++; } *n=index; return p; } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> int main() { int n; int *p=prime_generate(&n); srand(time(0)); int t=3; while(t--) { int prime_index=rand()%n; printf("The prime number is : %d\n\n",p[prime_index]); printf("random large number\tremainder\n------------------------------------\n"); int num[n_of_n]; for(int i=0;i<n_of_n;i++) { num[i]=gen_random(); unsigned long long mod=num[i]%(unsigned long long)(p[prime_index]); printf("%lld\t\t%d\n",num[i],mod); } printf("=========================================================\n\n"); } return 0; }
C
#include "Array.h" /* Perform an element by element subtraction of one vector from another, where v3[i] = v1[i] - v2[i] and return the resulting vector. */ Vector sub(Vector v1, Vector v2){ int count = v2.count; Vector negV2; negV2 = create_vector(count); int x; for(x = 0; x < count; x++) { double neg = v2.vector[x] * (-1.0); insert(&negV2, neg); } Vector v3; v3 = add(v1, negV2); return v3; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int zufallszahlen(int max, int min) { int rz; rz = (rand() % (max - min + 1) + min); return rz; } void ziehung(int f[], int anzahl, int max, int min) { for(int i = 0; i < anzahl; i++) { f[i] = zufallszahlen(max, min); } for(int j = 0; j < anzahl; j++) { for(int k = 0; k < anzahl; k++) { if(j == k){ break; } if(f[j] == f[k]) { f[k] = zufallszahlen(max, min); } continue; } } } int eingabe(int f[], int max, int min, int anzahl, char *txt) { char s[100]; int n = 0; printf("%s", txt); int merker; for(int i = 0; i < anzahl; i++) { do{ merker = 0; printf("Ihre %d Eingabe: ", i + 1); fgets(s, 100, stdin); n = sscanf(s, "%d", &f[i]); if(f[i] > max || f[i] < min ) { printf("Falsche Eingabe \n"); merker++; break; } for(int j = 0; j < i; j++) { if (f[i] == f[j]) { merker++; } } continue; } while (n != 1 || merker == 1); } } void vergleiche(int f[], int f1[], int anzahl) { int tips = 0; for(int i = 0; i < anzahl; i++ ) { for(int j = 0; j < anzahl; j++) { if(f[j] == f1[i]){ tips++; } } } printf("\n\tDu hast %d mal Richtig getippt", tips); } void bubblesort(int f[], int anzahl){ int t = 0; int merker = 0; for(int i = 0; i < anzahl; i++ ) { for(int j = 0; j < anzahl - 1 - i; j++) { if(f[j] > f[j + 1]) { t = f[j]; f[j] = f[j + 1]; f[j + 1] = t; merker++; } if (merker == 0) { return; } } } } int ausgabe(int f[], int anzahl, char *txt) { printf("%s", txt); for(int i = 0; i < anzahl; i++) { printf("%d ", f[i]); } } int main () { int f[10], f1[10]; srand(time(NULL)); eingabe(f, 45, 1, 6, "\n\tIhre Tipps\n"); bubblesort(f, 6); ziehung(f1, 6, 45, 1); bubblesort(f1, 6); ausgabe(f, 6, "\n\tIhre Tipps"); ausgabe(f1, 6, "\n\tGezogene Tipps"); vergleiche( f, f1, 6); return 0; }
C
/* Escreva duas funções para ordenar um vetor de números de forma crescente. Escreva uma função recebendo um arranjo e outra recebendo um ponteiro. Em seguida, chame estes módulos a partir de um módulo main para testar seu programa. */ #include <stdio.h> #include <stdlib.h> void escreverVetor(int v[], int colunas) { for(int i = 0; i < colunas; i++) printf("[%d]", v[i]); printf("\n"); } void vetorOrdemCrescente(int v[], int colunas) { int aux, i, j; for(i = 0;i < colunas - 1; i++) { for(j = 0; j < colunas - 1 - i; j++) { if(v[j] > v[j + 1]){ aux = v[j]; v[j] = v[j + 1]; v[j + 1] = aux; } } } } void vetorOrdemDecrescente(int v[], int colunas) { int aux, i, j; for(i = 0;i < colunas - 1; i++) { for(j = 0; j < colunas - 1 - i; j++) { if(v[j] < v[j + 1]){ aux = v[j]; v[j] = v[j + 1]; v[j + 1] = aux; } } } } void vetorOrdemCrescentePonteiro(int *vP, int colunas) { int aux, i, j; for(i = 0;i < colunas - 1; i++) { for(j = 0; j < colunas - 1 - i; j++) { if(vP[j] > vP[j + 1]){ aux = vP[j]; vP[j] = vP[j + 1]; vP[j + 1] = aux; } } } } void vetorOrdemDecrescentePonteiro(int *vP, int colunas) { int aux, i, j; for(i = 0;i < colunas - 1; i++) { for(j = 0; j < colunas - 1 - i; j++) { if(vP[j] < vP[j + 1]){ aux = vP[j]; vP[j] = vP[j + 1]; vP[j + 1] = aux; } } } } main() { int colunas = 5; int v[] = {3, 5, 1, 2, 4}; int *vP = (int *)malloc(sizeof(int[colunas])); vP[0] = 10; vP[1] = 6; vP[2] = 9; vP[3] = 8; vP[4] = 7; printf("Vetor v:"); escreverVetor(v, colunas); printf("Vetor v ordem crescente: \n"); vetorOrdemCrescente(v, colunas); escreverVetor(v, colunas); printf("Vetor v ordem decrescente: \n"); vetorOrdemDecrescente(v, colunas); escreverVetor(v, colunas); printf("\n\nVetor vP:"); escreverVetor(vP, colunas); printf("Vetor vP ordem crescente: \n"); vetorOrdemCrescentePonteiro(vP, colunas); escreverVetor(vP, colunas); printf("Vetor vP ordem decrescente: \n"); vetorOrdemDecrescentePonteiro(vP, colunas); escreverVetor(vP, colunas); free(vP); }
C
#include<stdio.h> int main(int argc, char const *argv[]) { if (argc==2) { printf("You suck you have only one argument\n"); }else if(argc>2 || argc<4){ printf("Here are your arguments\n"); for (int i = 0; i < argc; ++i) { printf("%s\n",argv[i] ); } }else if(argc>10){ printf("You have too many arguments\n"); } return 0; }
C
const int GAMEBOARD_SIZE = 3; int *ptrToRow; int *ptrToCol; void PrintBoard(char board[GAMEBOARD_SIZE][GAMEBOARD_SIZE]) { char newBoard[GAMEBOARD_SIZE][GAMEBOARD_SIZE] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; for (int row = 0; row < GAMEBOARD_SIZE; row++) { for (int col = 0; col < GAMEBOARD_SIZE; col++) { if (board[row][col] == 1) { newBoard[row][col] = 'X'; } if (board[row][col] == -1) { newBoard[row][col] = 'O'; } if (board[row][col] == 0) { newBoard[row][col] = '.'; } } } cout << "- " << "0 " << "1 " << "2 " << endl; cout << "0 " << newBoard[0][0] << " " << newBoard[0][1] << " " << newBoard[0][2] << " " << endl; cout << "1 " << newBoard[1][0] << " " << newBoard[1][1] << " " << newBoard[1][2] << " " << endl; cout << "2 " << newBoard[2][0] << " " << newBoard[2][1] << " " << newBoard[2][2] << " " << endl; } void GetMove(int *row, int *col) { char comma = 'a'; cin >> *row >> comma >> *col; } bool MoveIsValid(char board[GAMEBOARD_SIZE][GAMEBOARD_SIZE], int row, int col) { if (board[row][col] == 0) { return true; } else { return false; } }
C
#ifndef ERRORS_H #define ERRORS_H #include <stdlib.h> #include <stdio.h> typedef const char* strings[]; static inline void errorArray(int count, const char* strs[]) { for (int i = 0; i < count; i++) fputs(strs[i], stderr); } static inline void error(const char* type, const char* message) { errorArray(3, (strings){type, " error: ", message}); exit(1); } #endif
C
#include<stdio.h> main() { int num,i; for(num=10;num<=15;num++) { for(i=1;i<=10;i++) { printf("%d * %d = %d\n",num,i,num*i); } } printf("\n"); }
C
#include<stdio.h> #include<math.h> /* This file initially contained a piece of code that checks is a number is prime or not Added a function that checks if a number is even or odd as well */ char* getResultStringValue(int num) { if(num==0) { return "its even"; } else { /* code */ return "its odd"; } } int EvenOrOdd(int num) { return num%2; } int main() { int num,i; printf("Enter a number?\n"); scanf("%d",&num); printf("EvenOrOdd : %s\n",getResultStringValue(EvenOrOdd(num))); for(i=2;i<=sqrt(num);i++) { if (num%i==0) { printf("the number must not be a prime\n"); return 1; } } printf("The number you entered is probably a prime number\n"); return 0; }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <sys/resource.h> #include <wait.h> #include <errno.h> #include <signal.h> #include <setjmp.h> #include <time.h> #include <stropts.h> #include <sys/mman.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/sem.h> #include <sys/shm.h> #include <limits.h> #include <semaphore.h> // -lpthread #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <poll.h> int main(int argc, char* args[]) { /* unix׽(δ): ȫ˫ܵؽͨ/߳ͨ AF_UNIX(unix׽) SOCK_STREAM(ֽ)/SOCK_DGRAM(ݱ) socketpair unix׽(δ): ȫ˫ܵ s[0]д/ <<==>> s[1]д/ ע: 1ֻждݺ󱾶˲ܶ 2: ʹs[0]д/, ӽʹs[1]д/, ֮ 3ͬһҲԣֻ1Ҫ https://blog.csdn.net/weixin_40039738/article/details/81095013 */ pid_t pid; int sockfd[2]; /* socketpair unix׽(δ): ȫ˫ܵ */ if (socketpair(AF_UNIX, SOCK_STREAM/*SOCK_DGRAM*/, 0, sockfd) < 0) perror("socketpair"); pid = fork(); if (pid > 0) { /* parent process */ char buf[128]; struct pollfd pfd; int fd = sockfd[0]; // ֻʹsockfd[0]/д close(sockfd[1]); snprintf(buf, sizeof(buf), "%s", "123"); write(fd, buf, strlen(buf)+1); printf("A write: %s\n", buf); /* ȴɶ */ pfd.fd = fd; pfd.events = POLLIN; /* fdݿɶ */ pfd.revents = -1; poll(&pfd, sizeof(pfd)/sizeof(struct pollfd), -1); /* -1ȴ(ʱ) */ if (pfd.revents = POLLIN) { read(pfd.fd, buf, sizeof(buf)); buf[sizeof(buf)-1] = '\0'; printf("A read: %s\n", buf); } close(sockfd[0]); waitpid(pid, 0, 0); } else if (pid == 0) { /* child process */ char buf[128]; struct pollfd pfd; int fd = sockfd[1]; // ֻʹsockfd[1]/д close(sockfd[0]); snprintf(buf, sizeof(buf), "%s", "456"); write(fd, buf, strlen(buf)+1); printf("B write: %s\n", buf); /* ȴɶ */ pfd.fd = fd; pfd.events = POLLIN; /* fdݿɶ */ pfd.revents = -1; poll(&pfd, sizeof(pfd)/sizeof(struct pollfd), -1); /* -1ȴ(ʱ) */ if (pfd.revents = POLLIN) { read(pfd.fd, buf, sizeof(buf)); buf[sizeof(buf)-1] = '\0'; printf("B read: %s\n", buf); } } return 0; }
C
// C program to store, count, detect lengths of words in an array #include <stdio.h> #include <string.h> #include <cs50.h> int main() { // Enter nonsentence words into array // (with space added for further code applying reasons in file findwordintext.c) char words_array[][10] = { "Mr. ", "Mrs. ", "MR. ", "MRS. "}; // Count the quantity of words in array int words_array_count = sizeof(words_array) / 10; printf("Elements in the array: %i\n", words_array_count); // Detect the length of words in words_array and put lengths into new array int k = 0; long words_array_length[words_array_count]; for (k=0; k<words_array_count; k++) { words_array_length[k] = strlen(words_array[k]); printf("Length of %i word %s in array is %lu letters\n", k, words_array[k], words_array_length[k]); } }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <pthread.h> int SharedVariable = 0; pthread_mutex_t lock; pthread_barrier_t barrier; void SimpleThread(int which) { int num, val; for (num = 0; num < 20; num++) { if (random() > RAND_MAX/2) { usleep(10); } pthread_mutex_lock(&lock); val = SharedVariable; printf("*** thread %d sees value %d\n", which, val); SharedVariable = val + 1; pthread_mutex_unlock(&lock); } pthread_barrier_wait(&barrier); val = SharedVariable; printf("Thread %d sees final value %d\n", which, val); } void *SimpleThreadStart(void *id_ptr) { int *id_ptr_local = (int *)id_ptr; SimpleThread(*id_ptr_local); } int main(int argc, char** argv) { if (argc <= 1) { printf("Thread count command line parameter required!\n"); exit(0); } if (!isdigit((unsigned char)*argv[1])) { printf("Thread count must be number!\n"); exit(0); } int thread_count = atoi(argv[1]); if (thread_count < 0) { printf("Thread count must be a postive integer!\n"); exit(0); } int i; int ids[thread_count]; pthread_t tid[thread_count]; pthread_barrier_init(&barrier, NULL, thread_count); for (i = 0; i < thread_count; i++) { ids[i] = i; pthread_create(&tid[i], NULL, SimpleThreadStart, (void *)&ids[i]); } for (i = 0; i < thread_count; i++) { pthread_join(tid[i], NULL); } pthread_barrier_destroy(&barrier); exit(0); }
C
char chrtobyte(char); void include(unsigned *, char); void exclude(unsigned *, char); unsigned substr(unsigned, unsigned); unsigned intersection(unsigned, unsigned); unsigned getunion(unsigned, unsigned); unsigned difference(unsigned, unsigned); char in(char, unsigned); char chrtobyte(char c){ c-=48; return c; } void include(unsigned *s, char c){ *s |= (1<<c); } void exclude(unsigned *s, char c){ *s &= ~(1<<c); } unsigned substr(unsigned s1, unsigned s2){ return (s1 & ~s2); } unsigned intersection(unsigned s1, unsigned s2){ return (s1 & s2); } unsigned getunion(unsigned s1, unsigned s2){ return (s1 | s2); } unsigned difference(unsigned s1, unsigned s2){ return (s1 ^ s2); } char in(char c, unsigned s){ if (1<<c & s) return 255; else return 0; }
C
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <winsock2.h> #include <conio.h> #define MAX 5000 #define PORT 12345 #define SA struct sockaddr int client_socket, server_socket,menustate; char javabserver[1000],authtoken[32]; void makesocket(); void registeruser(); void loginuser(); void logout(); void joinchannel(); void createchannel(); void leavechannel(); void channelmembers(); void sendmessage(); void refresh(); void searchmember(); void searchmessage(); void menu1(); void menu2(); void menu3(); int main() { system("color F2"); menu1(); int n; while(1) { scanf("%d%*c",&n); if ((menustate==1)&&(n==1)) { registeruser(); continue; } if ((menustate==1)&&(n==2)) { loginuser(); continue; } if ((menustate==2)&&(n==1)) { createchannel(); continue; } if ((menustate==2)&&(n==2)) { joinchannel(); continue; } if ((menustate==2)&&(n==3)) { logout(); continue; } if ((menustate==3)&&(n==1)) { sendmessage(); continue; } if ((menustate==3)&&(n==2)) { refresh(); continue; } if ((menustate==3)&&(n==3)) { channelmembers(); continue; } if ((menustate==3)&&(n==4)) { leavechannel(); continue; } if ((menustate==3)&&(n==5)) { searchmember(); continue; } if ((menustate==3)&&(n==6)) { searchmessage(); continue; } } } void makesocket() { char* buffer[80]; struct sockaddr_in servaddr, cli; WORD wVersionRequested; WSADATA wsaData; int err; // Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { // Tell the user that we could not find a usable Winsock DLL. printf("WSAStartup failed with error: %d\n", err); return ; } // Create and verify socket client_socket = socket(AF_INET, SOCK_STREAM, 0); if (client_socket == -1) { printf("Socket creation failed...\n"); //exit(0); } //else printf("Socket successfully created..\n"); // Assign IP and port memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(PORT); // Connect the client socket to server socket if (connect(client_socket, (SA*)&servaddr, sizeof(servaddr)) != 0) { printf("Connection to the server failed...\n"); exit(0); } // else //printf("Successfully connected to the server..\n"); } void menu1() { system("cls"); printf("Account menu\n1-register:\n2-login:\n"); menustate=1; } void menu2() { system("cls"); printf("\n1-create channel\n2-join channel\n3-logout\n"); menustate=2; } void menu3() { system("cls"); printf("\n1-send message\n2-refresh\n3-channel members\n4-leave channel\n5-search member\n6-search message\n"); menustate=3; } void registeruser() { char username[MAX],password[MAX],buffer[MAX]="register "; puts("please enter username"); scanf("%s",username); puts("please enter password"); scanf("%s",password); strcat(password,"\n"); strcat(buffer, username); strcat(buffer,", "); strcat(buffer,password); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); if (javabserver[9]=='S') puts("your account has been registered"); else puts("please try again"); puts("press any key to continue"); getchar(); getchar(); menu1(); } void loginuser() { char username[MAX],password[MAX],buffer[MAX]="login "; puts("please enter username"); scanf("%s",username); puts("please enter password"); scanf("%s",password); strcat(buffer,username); strcat(buffer,", "); strcat(buffer,password); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); closesocket(client_socket); if(javabserver[9]=='E') { puts("ERROR YOU SHALL NOT PASS!\npress any key to continue."); getchar(); getchar(); menu1(); return; } printf("login successful press any key to continue.\n"); int counter=0; memset(authtoken,1,sizeof(authtoken)); for(int i=31;i<63;i++) authtoken[counter++]=javabserver[i]; authtoken[32]='\0'; getchar(); getchar(); menu2(); } void logout() { char buffer[MAX]="logout "; authtoken[32]='\0'; strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); closesocket(client_socket); authtoken[32]='\0'; if(javabserver[9]=='S') { puts("logout succesful press any key to continue"); getchar(); menu1(); return; } else { puts("logout unsuccesful press any key to continue"); getchar(); menu2(); return; } } void createchannel() { char channelname[MAX],buffer[MAX]="create channel "; authtoken[32]='\0'; puts("please enter channel name"); scanf("%s",channelname); strcat(buffer,channelname); strcat(buffer,", "); strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); //printf("FROM SERVER:%s",javabserver); closesocket(client_socket); authtoken[32]='\0'; if(javabserver[9]=='E') { puts("channel coudnt be made, press any key to continue"); getchar(); getchar(); menu2(); return; } else { puts("channel made, press any key to continue"); getchar(); getchar(); menu3(); return; } } void joinchannel() { char channelname[MAX],buffer[MAX]="join channel "; authtoken[32]='\0'; puts("please enter channel name"); scanf("%s",channelname); strcat(buffer,channelname); strcat(buffer,", "); strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); closesocket(client_socket); if(javabserver[9]=='E') { puts("there is no channel with the name you entered,press any key to continue"); getchar(); getchar(); menu2(); return; } else { puts("you joined this channel,press any key to continue"); getchar(); getchar(); menu3(); return; } } void leavechannel() { char buffer[MAX]="leave "; authtoken[32]='\0'; strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); //printf("FROM SERVER:%s",javabserver); closesocket(client_socket); authtoken[32]='\0'; if(javabserver[9]=='S') { puts("you have left this channel,press any key to continue"); getchar(); menu2(); return; } else { puts("please try again,press any key to continue"); getchar(); menu3(); return; } } void channelmembers() { char buffer[MAX]="channel members "; authtoken[32]='\0'; strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); printf("FROM SERVER:\n%s",javabserver); closesocket(client_socket); authtoken[32]='\0'; printf("\npress any key to continue"); getchar(); menu3(); } void sendmessage() { char message[MAX],buffer[MAX]="send "; authtoken[32]='\0'; puts("please enter your message"); scanf("%[^\n]%*c", message); strcat(buffer,message); strcat(buffer,", "); strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); //printf("FROM SERVER:%s",javabserver); closesocket(client_socket); authtoken[32]='\0'; if(javabserver[9]=='S') { puts("your message has been sent,press any key to continue"); getchar(); menu3(); return; } else { puts("ERROR,press any key to continue"); getchar(); getchar(); menu3(); return; } } refresh() { char buffer[MAX]="refresh "; authtoken[32]='\0'; strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); printf("FROM SERVER:\n%s\n",javabserver); closesocket(client_socket); authtoken[32]='\0'; puts("PRESS ANY KEY TO CONTINUE"); getchar(); menu3(); } searchmember() { char name[MAX],buffer[MAX]="searchmember "; authtoken[32]='\0'; puts("please enter the username you want to search"); scanf("%s",name); strcat(buffer,name); strcat(buffer,", "); strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); if(javabserver[0]=='T') printf("%s is in this channel.",name); else printf("%s is not in this channel.",name); closesocket(client_socket); getchar(); getchar(); menu3(); } void searchmessage() { char name[MAX],buffer[MAX]="searchmessage "; authtoken[32]='\0'; puts("please enter the message you want to search"); scanf("%s",name); strcat(buffer,name); strcat(buffer,", "); strcat(buffer,authtoken); strcat(buffer,"\n"); makesocket(); send(client_socket,buffer,strlen(buffer),0); memset(javabserver,0,sizeof(javabserver)); recv(client_socket,javabserver,sizeof(javabserver),0); printf("\nFROM SERVER:%s",javabserver); closesocket(client_socket); getchar(); getchar(); menu3(); }
C
#include<stdio.h> #include<stdlib.h> void merg(float *b,float *c,int x,int y,float *a); void mersort(float *a,int n); int main() { int i,j,m,l,u,v,x=0; float a[10500]; char ch[10500]; FILE *p,*q; p=fopen("NUMBERS","r"); q=fopen("OUTPUTS","w"); if(p==NULL){ printf("No contents to read\n"); } else { { i=0; j=0; while(fscanf(p,"%f%c",&a[i],&ch[j])!=EOF) { u=a[i]*10; v=u%10; if(v>0) x++; i++; j++;} } if((x>0)||(j>10000)) printf("Invalid Input\n"); else { mersort(a,j); for(i=0;i<j;i++) fprintf(q,"%5.0f\n",a[i]); fclose(p); fclose(q); }} return 0; } void mersort(float *a,int n) { float b[10000],c[10000]; int x,y,z,i,j; if(n<2) return; else { x=n/2; for(i=0;i<=x-1;i++) b[i]=a[i]; for(j=x;j<=n-1;j++) c[j-x]=a[j]; mersort(b,i); mersort(c,j-x); merg(b,c,i,j-x,a); } } void merg(float *b,float *c,int x,int y,float *a) { int i=0,j=0,k=0; while((i<x)&&(j<y)) { if(b[i]<=c[j]){ a[k]=b[i]; i++; k++; } else { a[k]=c[j]; k++; j++; } } while(i<x){ a[k]=b[i]; k++; i++; } while(j<y){ a[k]=c[j]; k++; j++; } }
C
/* * File: lab10.c * Author: Alejandro Duarte * * Created on 3 de mayo de 2021, 01:11 AM */ #include <xc.h> #include <stdint.h> #include <stdio.h>// Libreria para poder usar printf junto a la funcion putch. //------------------------------------------------------------------------------ // BITS DE CONFIGURACION //------------------------------------------------------------------------------ // CONFIG1 #pragma config FOSC = INTRC_NOCLKOUT// Oscillator Selection bits (INTOSCIO //oscillator: I/O function on RA6/OSC2/CLKOUT //pin, I/O function on RA7/OSC1/CLKIN) #pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT enabled) #pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled) #pragma config MCLRE = OFF // RE3/MCLR pin function select bit (RE3/MCLR //pin function is MCLR) #pragma config CP = OFF // Code Protection bit (Program memory code //protection is disabled) #pragma config CPD = OFF // Data Code Protection bit (Data memory code //protection is disabled) #pragma config BOREN = OFF // Brown Out Reset Selection bits (BOR enabled) #pragma config IESO = OFF // Internal External Switchover bit //(Internal/External Switchover mode is enabled) #pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enabled bit //(Fail-Safe Clock Monitor is enabled) #pragma config LVP = OFF // Low Voltage Programming Enable bit (RB3/PGM //pin has PGM function, low voltage programming //enabled) // CONFIG2 #pragma config BOR4V = BOR40V // Brown-out Reset Selection bit (Brown-out //Reset set to 4.0V) #pragma config WRT = OFF // Flash Program Memory Self Write Enable bits //(Write protection off) #define _XTAL_FREQ 4000000//Para usar la funcion de 'delay' //------------------------------------------------------------------------------ // VARIABLES //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // PROTOTIPOS FUNCIONES //------------------------------------------------------------------------------ void setup(void); void menu(void); void putch(char data); void receptar(void); // Se establece la funcion de interrupcion void __interrupt() isr(void){ } //------------------------------------------------------------------------------ // CICLO PRINCIPAL //------------------------------------------------------------------------------ void main(void) { setup();// Se llama a la funcion setup para configuracion de I/O while (1) // Se implemta el loop { menu(); // Se llama a la funcion menu para desplegar el menu de opciones receptar();// Se llama a funcion para determinar que hace cada opcion // del menu establecido } } //------------------------------------------------------------------------------ // CONFIGURACIONES //------------------------------------------------------------------------------ void setup(void){ // configuracion de puertos ANSEL = 0X00; ANSELH = 0X00;//se establecen los pines como entras y salidas digitales TRISA = 0X00; TRISB = 0X00;// Se establecen los puertos A, B y D como salidas PORTA = 0X00; PORTB = 0X00;//Se limpian los puertos utilizados // configuracion del oscilador OSCCONbits.IRCF2 = 1; OSCCONbits.IRCF1 = 1; OSCCONbits.IRCF0 = 0; //Se configura el oscilador a una frecuencia de 4 MHz. OSCCONbits.SCS = 1; //Configuracion TX y RX TXSTAbits.BRGH = 1; // Para alta velocidad. BAUDCTLbits.BRG16 = 1; // Se usan los 16 bits TXSTAbits.SYNC = 0; // transmision asincrona RCSTAbits.SPEN = 1; // Se enciende el modulo RCSTAbits.CREN = 1; // Se abilita la recepcion TXSTAbits.TXEN = 1; // Se abilita la transmision RCSTAbits.RX9 = 0; // Se determina que no se quieren 9 bits SPBRG = 103; //BAUD RATE de 9600 SPBRGH = 0; // configuracion de interrupciones INTCONbits.GIE = 1; INTCONbits.PEIE = 1; } //------------------------------------------------------------------------------ // FUNCIONES //------------------------------------------------------------------------------ void menu(void){ __delay_ms(50); printf("\rQue accion desea ejecutar? \r"); __delay_ms(50); printf("\r(1) Desplegar cadena de caracteres \r"); __delay_ms(50); printf("(2) Cambiar PORTA \r"); __delay_ms(50); printf("(3) Cambiar PORTB \r"); // Se despliegan, en filas de caracteres, las opciones del menu establecido // usando prinf que llama automaticamante a la funcion putch para que sea // transmitido con un delay de 50 ms. } void putch(char info){//Se transmite la cadena de caracteres a esta funcion // por el printf while (TXIF == 0);// Se espera algo que haya que transmitir TXREG = info;// lo que hay en data se pasa al registro de transmision para // para que se depliegue en la terminal virtual. } void receptar(void){ while(RCIF == 0); //Se espera algo que recibir (CARACTER). char entregado = RCREG;//Se crea un variable local que equivale al registro // de recepcion para usarlo en las condicionales if. if (entregado == '1'){//si la opcion que se recibe es 1 se hace lo siguiente __delay_ms(50); printf("\r YA SALIO LA PRIMERA PARTE. \r");//Se despliega la fila de } //caracteres. if (entregado == '2'){//si la opcion que se recibe es 2 se hace lo siguiente __delay_ms(50); printf("\r Por favor, ingrese un caracter. \r");//Se despliega la fila //de caracteres. while(RCIF == 0);//Se espera algo que recibir (CARACTER)elegido por // el usuario. PORTA = RCREG;// El caracter que se recibe se transmitira al puerto A. } if (entregado == '3'){//si la opcion que se recibe es 3 se hace lo siguiente __delay_ms(50); printf("\r Por favor, ingrese un caracter. \r");//Se despliega la fila //de caracteres. while(RCIF == 0);//Se espera algo que recibir (CARACTER)elegido por // el usuario. PORTB = RCREG;// El caracter que se recibe se transmitira al puerto B. } }
C
#ifndef _VEC3_H_ #define _VEC3_H_ //! simple 3D vector typedef struct Vec3 { float values[3]; } Vec3; //! dest = a*alpha_a+b*alpha_b void v3compose(Vec3* dest, const Vec3* a, const Vec3* b, float alpha_a, float alpha_b); //! returns the scalar product of a and b float v3dot(const Vec3* a, const Vec3* b); //! dest = cross_product(a,b) void v3cross(Vec3* dest, const Vec3* a, const Vec3* b); //! dest = a * dest void v3scale(Vec3* dest, float s); //! scales dest to unit norm void v3normalize(Vec3* dest); void mat4mult(float dest[], float a[], float b[]); void mat4rotationX(float dest[], float alpha); #endif
C
#include <stdio.h> #include <stdlib.h> #include <obliv.h> #include <string.h> #include <assert.h> #include "util.h" #include "dbg.h" // pretty debugging #include "pseudonymize.h" #define BUFFER_SIZE 64 // this should be enough? emails are hopefully 20 characters max . . . void check_mem(person* fullData, int party) { if (party == 1) { if (fullData == NULL) { log_err("Memory allocation failed\n"); clean_errno(); exit(1); } } } // I am trying to read a csv into an array of structs! void load_data(protocolIO *io, struct person ** fullData, int party) // { if (party == 1) { FILE *inputFile = fopen(io->src, "r"); // return error if inputFile is NULL if (inputFile == NULL) { log_err("File '%s' not found \n", io->src); clean_errno(); exit(1); } char * buf[BUFFER_SIZE]; char * tmp io->numFullData = 0; int memsize = ALLOC; while(fgets(buf, sizeof(buf), inputFile) != NULL) { tmp = strtok(buf, ","); person[i].email = tmp; tmp = strtok(NULL, ","); person[i].EUCitizenship = atoi(tmp); tmp = strtok(NULL, ","); person[i].income = atoi(tmp); io->numFullData += 1; // scaling of person array if (io->numFullData > memsize) { memsize *= 2; *fullData = realloc(*fullData, sizeof(person) * memsize); check_mem(*fullData, party); } } io->numFullData = i; log_info("Loaded %d data points . . . \n" i); fclose(inputFile); } } int main(int argc, char *argv[]) { printf("Pseudonymizing Data\n"); const char *remote_host = strtok(argv[1], ":"); const char *port = strtok(NULL, ":"); ProtocolDesc pd; ProtocolIO io; // Make connection between two shells log_info("Connecting to %s on port %s . . . \n", remote_host, port); if(argv[2][0] == '1') { if(protoclAcceptTcp2P(&pd, port) != 0) { log_err("TCP accept from %s failed \n", remote_host); exit(1); } } else { if(protoclConnectTcp2P(&pd, remote_host, port) != 0) { log_err("TCP accept from %s failed \n", remote_host); exit(1); { } // Final initializations before entering protocl cp = (argv[2][0]=='1' ? 1 : 2); setCurrentParty(&pd, cp); // only checks for a '1' (this is okay because Obliv-C only supports 2 parties atm) if (argc == 4) { // this would only apply to the DC // party 1 io.src = argv[3]; } lap = wallClock(); execYaoProtocol(&pd, pseudonymize, &io); // Should this be Yao's or DualExecution? cleanupProtocol(&pd); double runtime = wallClock() - lap; // code to create files (depends on party) if (cp == 1) { FILE *nonIdentifiableDataFile = fopen("nonidentifiable.csv", "w"); if (nonIdentifiableDataFile != NULL) { for(int i = 0; i < io->numFullData, i++) { fprintf(nonIdentifiableDataFile, "%s,%d\n", (char)itoa(io->nonIdentifiableData[i].email), io->nonIdentifiableData[i].EUCitizenship); } } fclose(nonIdentifiableDataFile); // THIS SHOULD BE UPDATED to print the encrypted hex values FILE *psudonymizedDataFile = fopen("pseudonmized.csv", "w"); if (psudonymizedDataFile != NULL) { for(int i = 0; i < io->numFullData, i++) { fprintf(psudonymizedDataFile, "%s,%d\n", (char)itoa(io->pseudonymizedData[i].encryptedEmail), io->pseudonymizedData[i].income); } } fclose(pseudonymizedDataFile); } else { // fix this one encryption key is more obvious! FILE *encryptionKey = fopen("keyPlaceholder", "w"); if (encyptionKey != NULL) { fprintf(encryptionKey, "%s", io->encryptionKey) } } log_info("Pseudonymization Successful") log_info("Total time: %1f seconds \n", runtime); printf("\n"); return 0; }
C
#include <stdint.h> #include <stdbool.h> #include "em_device.h" #include "em_chip.h" #include "em_cmu.h" #include "em_emu.h" #include "em_gpio.h" #include "em_lcd.h" #include "em_system.h" #include "segmentlcd.h" /* Max number of HFCycles for higher accuracy */ #define HFCYCLES 0xFFFFF /* HF_cycles x ref_freq / HFCLK_freq = (2^20 - 1) x 32768 / 14000000 = 2454 */ #define UP_COUNTER_TUNED 2454 /* Initial HFRCO TUNING value */ #define TUNINGMAX 0xFF /**************************************************************************//** * @brief Calibrate HFRCO for 14Mhz against LFXO * @param hfCycles down counter initial value * @param upCounterTuned value expected for the upCounter when HFRCO is tuned *****************************************************************************/ uint8_t calibrateHFRCO(uint32_t hfCycles, uint32_t upCounterTuned) { /* run the calibration routine to know the initial value * of the up counter */ uint32_t upCounter = CMU_Calibrate(hfCycles, cmuOsc_LFXO); /* Variable to store the previous upcounter value for comparison */ uint32_t upCounterPrevious; /* Read the initial tuning value */ uint8_t tuningVal = CMU_OscillatorTuningGet(cmuOsc_HFRCO); /* If the up counter result is smaller than the * tuned value, the HFRCO is running * at a higher frequency so the HFRCO tuning * register has to be decremented */ if (upCounter < upCounterTuned) { while (upCounter < upCounterTuned) { /* store the previous value for comparison */ upCounterPrevious = upCounter; /* Decrease tuning value */ tuningVal--; /* Write the new HFRCO tuning value */ CMU_OscillatorTuningSet(cmuOsc_HFRCO, tuningVal); /* Run the calibration routine again */ upCounter = CMU_Calibrate(hfCycles, cmuOsc_LFXO); } /* Check which value goes closer to the tuned one * and increase the tuningval if the previous value * is closer */ if ((upCounter - upCounterTuned) > (upCounterTuned - upCounterPrevious)) { tuningVal++; } } /* If the up counter result is higher than the * desired value, the HFRCO is running * at a higher frequency so the tuning * value has to be incremented */ if (upCounter > upCounterTuned) { while (upCounter > upCounterTuned) { /* store the previous value for comparison */ upCounterPrevious = upCounter; /* Increase tuning value */ tuningVal++; /* Write the new HFRCO tuning value */ CMU_OscillatorTuningSet(cmuOsc_HFRCO, tuningVal); /* Run the calibration routine again */ upCounter = CMU_Calibrate(hfCycles, cmuOsc_LFXO); } /* Check which value goes closer to the tuned one * and decrease the tuningval if the previous value * is closer */ if ((upCounterTuned - upCounter) > (upCounterPrevious - upCounterTuned)) { tuningVal--; } } /* Return final HFRCO tuning value */ return tuningVal; } /****************************************************************************** * @brief Main function * Main is called from _program_start, see assembly startup file *****************************************************************************/ int main(void) { /* Initialize chip */ CHIP_Init(); /* The HFRCO is the default clock source for the HF * branch, but it is explicitly selected here * for comprehension purposes */ CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFRCO); /* Enable LFXO to clock the LFA clock branch */ CMU_OscillatorEnable(cmuOsc_LFXO, true, true); /* Select LFXO as clock source for the LFA branch */ CMU_ClockSelectSet(cmuClock_LFA, cmuSelect_LFXO); /* Enable clock for LCD module */ CMU_ClockEnable(cmuClock_LCD, true); /* Enable clock for GPIO module */ CMU_ClockEnable(cmuClock_GPIO, true); /* Set PC12 as output so it can be * overriden by the peripheral, in this case the CMU */ GPIO_PinModeSet(gpioPortC, 12, gpioModePushPull, 0); /* Initialize LCD */ SegmentLCD_Init(false); /* Set the tuning to the max value so the HFRCO goes to a frequency above 14Mhz * - the frequency will depend on the chip */ CMU_OscillatorTuningSet(cmuOsc_HFRCO, TUNINGMAX); /* Select Clock Output 0 as High Frequency RC without prescalling (14 Mhz) */ CMU->CTRL = CMU->CTRL | CMU_CTRL_CLKOUTSEL1_LFRCO | CMU_CTRL_CLKOUTSEL0_HFRCO; /* Route the Clock output pin to Location 1 and enable them */ CMU->ROUTE = CMU_ROUTE_LOCATION_LOC1 | CMU_ROUTE_CLKOUT0PEN; /* Write Tuning on the LCD while the function runs */ SegmentLCD_Write("TUNING"); /* Variable for reading the tuning value after the calibration */ uint8_t tuning; /* Run HFRCO calibration for the 14Mhz band * This function takes about 10 seconds to execute because * the HFRCO was purposely untuned to the 14Mhz band upper limit * (TUNING = 0xFF) * The calibration loop inside this function will have to execute * as many times as needed for the HFRCO become calibrated * which usually happens for a TUNING value of 116-122, depending * on the chip */ tuning = calibrateHFRCO(HFCYCLES, UP_COUNTER_TUNED); /* Write the tuning result on the LCD and TUNING FINISHED */ SegmentLCD_Write("DONE"); SegmentLCD_Number(tuning); while (1) ; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ uint32_t ; /* Variables and functions */ char* parseint (char*,int /*<<< orphan*/ *,int /*<<< orphan*/ ) ; char* strchr (char*,char) ; int /*<<< orphan*/ strcpy (char*,char*) ; __attribute__((used)) static char *parsecct(char *arg, uint32_t *shift, uint32_t *multiplier) { char buf[1024] = { 0 }; char *errstr; char *ptr; strcpy(buf, arg); if (!(ptr = strchr(buf, ':'))) return "ccts are formatted shift:multiplier"; *ptr = '\0'; ptr++; if ((errstr = parseint(buf, shift, 0))) return errstr; if ((errstr = parseint(ptr, multiplier, 0))) return errstr; return NULL; }
C
#include "dog.h" /** * init_dog - Intialize the dog structure * @d: Pointer to the dog structure * @name: the name * @age: the age * @owner: the owner * * Return: Always 0. */ void init_dog(struct dog *d, char *name, float age, char *owner) { if (d != NULL) { d->name = name; d->age = age; d->owner = owner; } }
C
#include <stdio.h> #include <stdlib.h> #include<windows.h> #include<time.h> int i,j; int start(); int display(); COORD coord={0,0}; int tic[10]; int tic1[10]={'0','1','2','3','4','5','6','7','8','9'}; void gotoxy(int x,int y) { coord.X=x; coord.Y=y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord); } int result(){ if(tic1[1]== tic1[2] && tic1[2]== tic1[3] || tic1[3]==tic1[5] && tic1[3]==tic1[7] || tic1[1]== tic1[4] && tic1[1]== tic1[7] || tic1[1]== tic1[5] && tic1[1]== tic1[9] || tic1[4]== tic1[5] && tic1[4]== tic1[6] || tic1[7]== tic1[8] && tic1[7]== tic1[9] || tic1[2]== tic1[5] &&tic1[2]== tic1[8] || tic1[3]== tic1[6] && tic1[3]== tic1[9]) return (1); if(tic1[1]!='1' && tic1[2]!='2' && tic1[3]!='3' && tic1[4]!='4' && tic1[5]!='5' && tic1[6]!='6' && tic1[7]!='7' && tic1[8]!='8' && tic1[9]!='9') return 0; else return 2; } int start(){ int row,col,r,c,q; gotoxy(100,48); printf("lets play a game"); Sleep(2200); system("cls"); gotoxy(100,48); printf("loading..."); gotoxy(100,50); for(r=1;r<=20;r++){ for(q=0;q<=100000000;q++); printf("%c",177); } } int display(){ for(i=0;i<30;i++){ for(j=0;j<1;j++){ printf(" $$");} printf("\n");} for(i=0;i<73;i++){ for(j=73;j<74;j++){ printf("$"); } } } int matrix(){ printf(" | | \n");gotoxy(15,11); printf(" %c | %c | %c \n",tic[1],tic[2],tic[3]);gotoxy(15,12); printf(" | | \n");gotoxy(15,13); printf("----------------\n");gotoxy(15,14); printf(" | | \n");gotoxy(15,15); printf(" %c | %c | %c \n",tic[4],tic[5],tic[6]);gotoxy(15,16); printf(" | | \n");gotoxy(15,17); printf("----------------\n");gotoxy(15,18); printf(" | | \n");gotoxy(15,19); printf(" %c | %c | %c \n",tic[7],tic[8],tic[9]);gotoxy(15,20); printf(" | | \n"); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n"); } int main() { start(); system("cls"); int player=1,x,k,s=0,ss=0; char c,h; char a[30],b[30]; gotoxy(100,48); puts("\nenter first player name"); gets(a); system("cls"); gotoxy(100,48); puts("\nenter second player name"); gets(b); system("cls"); display(); do { matrix(); gotoxy(100,10); puts(a); gotoxy(115,10); printf("Battle with"); gotoxy(100,12); puts(b); gotoxy(70,40); player = (player % 2) ? 1 : 2; printf("Player %d, enter a number: ", player); scanf("%d", &x); c = (player == 1) ? 'X' : 'O'; if(x==1 && tic1[1]=='1'){ tic[1]=c; tic1[1]=c;} else if(x==2 && tic1[2]=='2'){ tic[2]=c; tic1[2]=c;} else if(x==3 && tic1[3]=='3'){ tic[3]=c; tic1[3]=c;} else if(x==4 && tic1[4]=='4'){ tic[4]=c; tic1[4]=c;} else if(x==5 && tic1[5]=='5'){ tic[5]=c; tic1[5]=c;} else if(x==6 && tic1[6]=='6'){ tic[6]=c; tic1[6]=c;} else if(x==7 && tic1[7]=='7'){ tic[7]=c; tic1[7]=c; } else if(x==8 && tic1[8]=='8'){ tic[8]=c; tic1[8]=c;} else if(x==9 && tic1[9]=='9'){ tic[9]=c; tic1[9]=c; } else{ printf("wrong move"); player--; } k=result(); player++; } while (k ==2);{ matrix(); } if (k == 1){ Sleep(500); system("cls"); gotoxy(74,25); printf("Game over"); Sleep(2200); system("cls"); gotoxy(74,25); printf("==> Player %d win ", --player); Sleep(2200); } else if(k==0){ Sleep(500); gotoxy(74,25); printf("Game over"); Sleep(2200); system("cls"); gotoxy(74,25); printf("==>\aGame draw");} Sleep(2200); getch(); return 0; }
C
#include "holberton.h" /** * _strncat - concatenates two words. * @dest: output * @src: input * @n: lent; * Return: x. */ char *_strncat(char *dest, char *src, int n) { char *x = dest; int largo = 0; int dest_len = largo; int i; for (; *dest != '\0' ; dest++) { largo++; } for (i = 0 ; i < n && src[i] != '\0' ; i++) dest[dest_len + i] = src[i]; dest[dest_len + i] = '\0'; return (x); }
C
// Copyright Nettention Inc. // MIT License. #pragma once #include <stdint.h> // compares two binarys and returns negative if 1 is smaller, positive if 1 is bigger, or 0 if same. inline int LexicographicBinaryCompare32(const void* pBinary1, int binary1Length, const void* pBinary2, int binary2Length) { int bigLength1 = binary1Length >> 2; int smallLength1 = binary1Length & 3; int bigLength2 = binary2Length >> 2; int smallLength2 = binary2Length & 3; uint32_t* bigPtr1 = (uint32_t*)pBinary1; uint32_t* bigPtr2 = (uint32_t*)pBinary2; // fast compare while (bigLength1 > 0 && bigLength2 > 0) { if (*bigPtr1 < *bigPtr2) return -1; if (*bigPtr1 > *bigPtr2) return 1; bigPtr1++; bigPtr2++; bigLength1--; bigLength2--; } // compare the remainder uint8_t* smallPtr1 = (uint8_t*)bigPtr1; uint8_t* smallPtr2 = (uint8_t*)bigPtr2; while (smallLength1 > 0 && smallLength2 > 0) { uint8_t v1, v2; #ifdef __ANDROID__ // some old Android compilers does not support __packed keyword. memcpy(&v1, smallPtr1, 1); memcpy(&v2, smallPtr2, 1); #else v1 = *smallPtr1; v2 = *smallPtr2; #endif if (v1 < v2) return -1; if (v1 > v2) return 1; smallLength1--; smallLength2--; } if (smallLength1 > 0) // all previous bytes are the same, and the longer binary is the bigger one. if 1 is bigger, then we return positive value. return 1; if (smallLength2 > 0) // the vice versa case return -1; // binary contents and the lengths are same. return 0; }
C
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> struct array_queue { int* data; int size; int head; int tail; }; bool init_queue(struct array_queue* queue, int size) { queue->data = malloc(sizeof(int) * size); if (queue->data == NULL) { printf("data malloc error\n"); return false; } queue->size = size; queue->head = 0; queue->tail = 0; return true; } bool enqueue(struct array_queue* queue, int data) { if (queue->tail == queue->size) { if (queue->head == 0) { printf(" ->queue is full, enqueue fail\n"); return false; } for (int i = 0; i < queue->tail; i++) { queue->data[i - queue->head] = queue->data[i]; } queue->tail = queue->tail - queue->head; queue->head = 0; } queue->data[queue->tail++] = data; return true; } int dequeue(struct array_queue* queue) { if (queue->head == queue->tail) { printf(" ->queue is empty, dequeue fail\n"); return -1; } return queue->data[queue->head++]; } int main(void) { struct array_queue queue; init_queue(&queue, 3); enqueue(&queue, 1); enqueue(&queue, 2); enqueue(&queue, 3); enqueue(&queue, 4); printf("data : %d\n", dequeue(&queue)); printf("data : %d\n", dequeue(&queue)); printf("data : %d\n", dequeue(&queue)); printf("data : %d\n", dequeue(&queue)); enqueue(&queue, 5); printf("data : %d\n", dequeue(&queue)); printf("data : %d\n", dequeue(&queue)); return 1; }
C
#include <stdio.h> #include <stdlib.h> /* ornek1:struct ogrenci { char ad[20]; char soyad[20]; char bolum[50]; int sinif; int numara; float ortalama; }ogr; //ornek 2: struct kitaplar { char ad[20]; char yazar[50]; float fiyat; }ktp1={"kayip sicil","soner yalcin",17.99},ktp2={"ilk ask","jhon green",21.00};*/ int main() {//ornek1: strcpy(ogr.ad,"dilara sevim"); strcpy(ogr.soyad,"polat"); strcpy(ogr.bolum,"bilgisayar muhendisligi"); ogr.numara=19010011064; ogr.sinif=1; ogr.ortalama=99.9; printf("ad:%s\n",ogr.ad); printf("soyad:%s\n",ogr.soyad); printf("bolum:%s\n",ogr.bolum); printf("no:%d\n",ogr.numara); printf("sinif:%d\n",ogr.sinif); printf("ortalama:%.2f\n",ogr. ortalama); //ornek 2: printf("ad:%s\n",ktp1.ad); printf("yazar:%s\n",ktp1.yazar); printf("fiyat:%.2f\n\n\n",ktp1.fiyat); printf("ad:%s\n",ktp2.ad); printf("yazar:%s\n",ktp2.yazar); printf("fiyat:%.2f\n",ktp2.fiyat); */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "string.h" int firstUniqChar(char * s){ int i, alphaList[26]; //第一次存入数组 for(i=0;i<strlen(s);i++){ alphaList[s[i] - 'a'] += 1; } //第二次提取判断第一个值为1的 for(i=0;i<strlen(s);i++){ if(alphaList[s[i] - 'a'] == 1)return i; } return -1; } int main(){ char s[] = 'leetcode'; int res = firstUniqChar(s); retrun 0; }
C
/* CSSE332 FAT12 Implementation - util.h * Header file containing function prototypes and structures for use * in implementing the FAT12 filesystem. Function definitions are contained * in util.c */ #include <stdio.h> #define T_SUBDIR 1 #define T_FILE 0 #define T_FAT12 1 #define T_NFAT12 0 #define SHM_KEY 6543 #define PATH_FOUND 1 #define VALID_FILENAME 1 #define INVALID_FILENAME 0 /* Data Structures */ struct fileinfo { char filename[9]; // Stored as null-termed string char ext[4]; // " " " " " char attrib; char ctime[2]; char cdate[2]; char atime[2]; char wtime[2]; char wdate[2]; int FLC; int fsize; }; struct shared_info { char path[260]; int FLC; int stream; }; /* Function prototypes */ void init_util(); void kill_util(); void get_abs_path(char* buffer, char* path); int parse_path (char* path, int* FLC, int* index); int cleanup_path(char* path, char* newpath); int check_filename (char* filename); struct fileinfo get_file_info (int FLC, int index); int get_file_type (struct fileinfo info); int get_dir_list (struct fileinfo* list, int max, int FLC, int index); void set_wd (char* path, int FLC); void get_wd (char* path, int *FLC); void get_free_space (long* blocks, int* block_size); int get_free_block (void); void allocate_block (int free_FLC, struct fileinfo info, int root_FLC, int* FLC, int* index); void fileinfo_to_dentry(struct fileinfo info, char* buffer); int unlink_entry (int FLC, int index); int open_file(struct fileinfo info); int read_file (char* buffer, int max); void close_file();
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "mesh.h" void clean(Domain *D) { Edge *eg,*tmpEdge; //remove edge eg=D->hull->eg; while(eg) { tmpEdge=eg->next; D->hull->eg=tmpEdge; eg->next=NULL; free(eg); eg=D->hull->eg; } free(D->hull); }
C
// Variable table // ============== // Author: Celestial Phineas @ ZJU // (Yehang YIN) // This file implements a hash table for storing variables // In bash, variables are also lists. // myshell works in the same manner. // All entries of the hash table are lists of strings. // Each records elec, element count // and elev, element value // This design approach is very alike argc and argv #ifndef CELPHI_VAR_TABLE_H #define CELPHI_VAR_TABLE_H #include "global.h" #include "hash_map.h" // It is very important to know that elev must work in a shallow way // That is because in C, we don't have such "destructor" stuff // It is impossible to destruct the hash table with the destructor // of its dependency, the general HashMap (See hash_map.h) typedef struct { int elec; char **elev; } Variable; #define MIN_QUERY_OP -2 typedef enum { ElementCount = -1, ListAll = -2 } QueryOp; extern Variable *EMPTY_VAR; // This method initialize the variable table void init_var_table(); // The update_variable method does not make a copy of var // But it will free resources that it will override // If you need to override NULL data, // Pass EMPTY_VAR to the second slot void update_variable(const char *key_, Variable *var_); // The deletion is even lazier that it takes up spaces even after rehashing. // The implementation of deleting a variable // is the same to update with EMPTY_VAR void delete_variable(const char *key_); // The get_variable method returns a new string // The return value is at least one character in size // Don't forget to free it after using it. char *get_variable(const char *key_, int index); #endif
C
void magfime() { int tema,continuar; do { do { p("Las magnitudes f%csicas y su medida:\n",161); p("===================================\n\n"); p("[1] - El sistema m%ctrico decimal.\n",130); p("[2] - El sistema internacional de unidades.\n"); p("[3] - Conversiones de unidades con factores de conversi%cn. Unidades compuestas.\n",162); p("[4] - Magnitudes escalares y vectoriales.\n\n"); p("Tema: "); fflush(stdin); s("%i",&tema); p("\n"); } while(tema < 1 || tema > 4); switch(tema) { case 1: simede(); break; case 2: sinu(); break; case 3: unco(); break; case 4: magesve(); break; default: p("No se ha seleccionado una opci%cn v%clida.\n\n",162,160); } p("%cQui%cres continuar con Las magnitudes f%csicas y su medida?\n",168,130,161); p("==================================================\n\n"); p("[1] - Continuar.\n"); p("[2] - Salir de Las magnitudes f%csicas y su medida.\n\n",161); p("%cContinuar? ",168); fflush(stdin); s("%i",&continuar); p("\n"); } while(continuar == 1); }
C
#include <stdio.h> int main(void) { int nb1, nb2, nb3, nb4, somme; printf("Entrez un premier nombre: "); scanf("%d", &nb1); printf("Entrez un deuxieme nombre: "); scanf("%d", &nb2); printf("Entrez un troisieme nombre: "); scanf("%d", &nb3); printf("Entrez un quatrieme nombre: "); scanf("%d", &nb4); somme = nb1 + nb2 + nb3 + nb4; printf("La somme de ces nombres est %d\n", somme); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* list_functions.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ggane <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/01 10:18:28 by ggane #+# #+# */ /* Updated: 2016/12/01 11:34:14 by ggane ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" void list_push_back(t_data **list, t_data *new) { t_data *tmp; tmp = NULL; if (!*list) *list = new; else { tmp = *list; while (tmp->next) tmp = tmp->next; tmp->next = new; } } t_data *create_elem(void) { t_data *new; if (!(new = (t_data *)malloc(sizeof(t_data)))) return (NULL); new->var_name = NULL; new->var_content = NULL; new->args = NULL; new->next = NULL; return (new); } void delete_list(t_data **list) { t_data *cpy; t_data *temp; if (*list) { cpy = *list; while (cpy) { temp = cpy->next; delete_data(&cpy); free(cpy); cpy = temp; } *list = NULL; } }
C
/////////////////////////////////////////////////////////////////////////////// // // Comments: // sudo insmod hello_world.ko PRINT_COUNT=5 // This will result in the hello world greeting printed 5 times // // To see the value of PRINT_COUNT after the driver is inserted // sudo cat /sys/modules/hello_world/parameters/PRINT_COUNT // // To change it after the module is inserted... // echo -n "10" > /sys.modules/hello_word/parameters/PRINT_COUNT // // To see the version of the app // cat /sys/module/hello_world/version // // to show all information on the module run the command // modinfo hello_world.ko // /////////////////////////////////////////////////////////////////////////////// #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> ////////////////////////////////////////////////////////////////////////////// #define AUTHOR "gitmogul" #define DESCRIPTION "Hello world example" #define VERSION "1.0" int PRINT_COUNT = 1; char* GREETING_STRING = NULL; char* GOODBYE_STRING = NULL; module_param( PRINT_COUNT, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); MODULE_PARM_DESC( PRINT_COUNT, "# times printed when module inserted/removed" ); module_param( GREETING_STRING, charp, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); MODULE_PARM_DESC( GREETING_STRING, "String printed when module is inserted" ); module_param( GOODBYE_STRING, charp, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); MODULE_PARM_DESC( GOODBYE_STRING, "String printed when module is removed" ); ////////////////////////////////////////////////////////////////////////////// static int __init init_hello_world( void ) { int ret = 0; int count = 0; pr_info( "%s\n", __FUNCTION__ ); for( count = 0; count < PRINT_COUNT; count++ ) { pr_info( "%s\n", (GREETING_STRING == NULL)? "KE PASA MANG !!!": GREETING_STRING ); } return ret; } ////////////////////////////////////////////////////////////////////////////// static void __exit exit_hello_world( void ) { int count; pr_info( "%s\n", __FUNCTION__ ); for( count = 0; count < PRINT_COUNT; count++ ) { pr_info( "%s\n", (GOODBYE_STRING == NULL)? "ADIOS MANG !!!": GOODBYE_STRING ); } return; } /////////////////////////////////////////////////////////////////////////////// module_init( init_hello_world ); module_exit( exit_hello_world ); MODULE_LICENSE("GPL"); MODULE_AUTHOR(AUTHOR); MODULE_DESCRIPTION(DESCRIPTION); MODULE_VERSION(VERSION); ///////////////////////////////////////////////////////////////////////////////
C
#include <stdio.h> int main(void) { int P, L,i,num=0; int a[5]; scanf_s("%d", &L); scanf_s("%d", &P); for(i=0;i<5;i++){ scanf_s("%d", &a[i]); } num = P*L; for (i = 0; i < 5; i++) { printf("%d ", a[i]-num); } return 0; }