language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
#include <pthread.h>
#include <sys/queue.h>
#include "event.h"
#include "log.h"
#include "worker.h"
struct worker
{
pthread_t tid;
STAILQ_HEAD(event_list, event) event_list;
volatile size_t event_n;
pthread_mutex_t event_lock;
pthread_cond_t event_pushed;
STAILQ_ENTRY(worker) entry;
};
static STAILQ_HEAD(worker_list, worker) g_worker_list;
static size_t g_worker_n;
static volatile size_t g_spawning;
static struct worker *create_worker()
{
struct worker *worker;
worker = (struct worker *)malloc(sizeof(*worker));
if(worker == NULL)
log_fatal_errno();
STAILQ_INIT(&worker->event_list);
worker->event_n = 0;
errno = pthread_mutex_init(&worker->event_lock, NULL);
if(errno)
log_fatal_errno();
errno = pthread_cond_init(&worker->event_pushed, NULL);
if(errno)
log_fatal_errno();
return worker;
}
struct worker *get_free_worker()
{
struct worker *free_worker = NULL;
size_t min_event_n = SIZE_MAX;
struct worker *worker;
STAILQ_FOREACH(worker, &g_worker_list, entry) {
size_t event_n = worker->event_n;
if(event_n < min_event_n) {
free_worker = worker;
min_event_n = event_n;
}
}
return free_worker;
}
void push_event(struct worker *worker, struct event *event)
{
pthread_mutex_lock(&worker->event_lock);
STAILQ_INSERT_TAIL(&worker->event_list, event, entry);
(void)__sync_add_and_fetch(&worker->event_n, 1);
pthread_cond_signal(&worker->event_pushed);
pthread_mutex_unlock(&worker->event_lock);
}
static struct event *pop_event(struct worker *worker)
{
struct event *event;
pthread_mutex_lock(&worker->event_lock);
for(;;) {
event = STAILQ_FIRST(&worker->event_list);
if(event != NULL)
break;
pthread_cond_wait(&worker->event_pushed, &worker->event_lock);
}
STAILQ_REMOVE_HEAD(&worker->event_list, entry);
pthread_mutex_unlock(&worker->event_lock);
return event;
}
static void *worker_main(void *arg)
{
struct worker *worker = (struct worker *)arg;
log_info(LOG_COLOR_NONE, "Worker %#lx is ready", (unsigned long)worker->tid);
(void)__sync_sub_and_fetch(&g_spawning, 1);
for(;;) {
struct event *event;
event = pop_event(worker);
event->ops->handle(event);
event->ops->destroy(event);
(void)__sync_sub_and_fetch(&worker->event_n, 1);
}
}
void spawn_workers(size_t worker_n)
{
pthread_attr_t attr;
int i;
log_info(LOG_COLOR_CYAN, "Spawning %zu worker(s)", worker_n);
errno = pthread_attr_init(&attr);
if(errno)
log_fatal_errno();
errno = pthread_attr_setstacksize(&attr, 0x400000);
if(errno)
log_fatal_errno();
errno = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
if(errno)
log_fatal_errno();
errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if(errno)
log_fatal_errno();
STAILQ_INIT(&g_worker_list);
g_spawning = worker_n;
for(i = 0; i < worker_n; ++i) {
struct worker *worker = create_worker();
errno = pthread_create(&worker->tid, &attr, worker_main, worker);
if(errno)
log_fatal_errno();
STAILQ_INSERT_TAIL(&g_worker_list, worker, entry);
}
log_info(LOG_COLOR_WHITE, "Waiting until all workers are ready");
do usleep(100000);
while(g_spawning > 0);
g_worker_n = worker_n;
}
|
C
|
/*!file
*
* @brief The implementation of routines for erasing and writing to the Flash.
*
* This contains the implementation for operating the LEDs.
*
* @author John Thai & Jason Garviel
* @date 2017-04-10
*/
/*!
* @addtogroup LED_module LED module documentation
* @{
*/
/* MODULE LED */
#include "LEDs.h"
#include "MK70F12.h"
bool LEDs_Init(void)
{
//Enable PORT A pin routing
SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK;
//Enables pin for LEDs (Pin MUX ALT 1 GPIO K70RefMan p.317)
PORTA_PCR11 |= PORT_PCR_MUX(1); //orange
PORTA_PCR28 |= PORT_PCR_MUX(1); //yellow
PORTA_PCR29 |= PORT_PCR_MUX(1); //green
PORTA_PCR10 |= PORT_PCR_MUX(1); //blue
//Set direction of data register
GPIOA_PDDR |= LED_ORANGE;
GPIOA_PDDR |= LED_YELLOW;
GPIOA_PDDR |= LED_GREEN;
GPIOA_PDDR |= LED_BLUE;
//SET PDOR to 1 at the appropriate pin (LED OFF)
GPIOA_PSOR |= LED_ORANGE;
GPIOA_PSOR |= LED_YELLOW;
GPIOA_PSOR |= LED_GREEN;
GPIOA_PSOR |= LED_BLUE;
return true;
}
void LEDs_On(const TLED color)
{
GPIOA_PCOR = color; // The color of the LED to turn on.
}
void LEDs_Off(const TLED color)
{
GPIOA_PSOR = color; // The color of the LED to turn off.
}
void LEDs_Toggle(const TLED color)
{
GPIOA_PTOR = color; // The color of the LED to turn toggle.
}
/*!
** @}
*/
|
C
|
#include <stdio.h>
void main() {
int n;
printf("Unesite velicinu kvadratne matrice: ");
scanf("%i", &n);
int matr[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("matr[%i][%i] = ", i, j);
scanf("%i", &matr[i][j]);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%3i", matr[i][j]);
}
printf("\n");
}
int suma = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
/*
koristi se AKKO je koriscena kvadratna matrica!!!
*/
// if (i+j < n-1)
/*
kod za iznad centralne dijagonale
if (j > i)
*/
// kod za ispod sporedne dijagonale
if (j > n-i-1)
suma+=matr[i][j];
}
}
printf("Suma brojeva ... dijagonale je: %i\n\n", suma);
}
|
C
|
#include <stdio.h>
int strlen(char* s);
void mostrar(int i);
int main(int argc, char const *argv[]){
int i;
char s[256];
scanf("%[^\n]%*c", s);
i = strlen(s);
mostrar(i);
return 0;
}
int strlen(char* s){
int i;
for(i = 0; s[i]; ++i);
return i;
}
void mostrar(int i){
printf("\nstring possui %d caracteres!!\n", i);
}
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 128
struct DataInfo
{
char data_file_name[BUFFER_SIZE];
char index_file_name[BUFFER_SIZE];
unsigned keyStart,keyEnd, record_length;
char encoding[4] , order[5];
};
struct IndexData
{
char* key;
unsigned pos;
};
char* pass_whitespaces(char* buffer)
{
while("\0" != *buffer && isspace(*buffer))buffer += 1;
return buffer;
}
void printMenu()
{
//print the user menu
printf("You can perform the following tasks: \n");
printf("open \"JSON_PATH (including extension name)\"Process JSON file and load the data and index file if exists. \n");
printf("create_index Create index file according the loaded JSON file.\n");
printf("search \"Key\" search then retrive the according record.\n");
printf("-------------------------------------\n");
printf("close Quits\n");
printf("Please Select one... \n");
printf("$ ");
}
void freeResources(struct IndexData* indecies , unsigned index_count)
{
for(size_t i = 0; i < index_count; i++)
{
free(indecies[index_count].key);
}
free(indecies);
}
int main(int argc, char *argv[])
{
char answer[BUFFER_SIZE];
bool should_close = false;
struct DataInfo data_info;
struct IndexData* indecies = NULL;
unsigned index_count = 0;
while(!should_close)
{
//print the user menu and read user answer
printMenu(answer);
fgets ( answer , BUFFER_SIZE, stdin);
fflush(stdin);
char* buffer_point = pass_whitespaces(answer);
int lenght_left = BUFFER_SIZE - (buffer_point - answer);
if(4 < lenght_left && !strncmp(buffer_point, "open", 4))
{
buffer_point = pass_whitespaces(buffer_point + 5);
int consumed_int;
sscanf(buffer_point, "%s%n" , buffer_point , &consumed_int);
if(0 == consumed_int) continue;
const char* const file_name = buffer_point;
if(NULL == (buffer_point = strrchr(buffer_point , '.'))) continue;
if(strncmp(buffer_point, ".json" , 5) && !isspace(buffer_point + 5)) continue;
*(buffer_point + 5)= '\0';
FILE* json_file = fopen(file_name , "r");
if(NULL == json_file)
{
puts("File is not found!\n");
continue;
}
fseek(json_file, 0, SEEK_END);
long fsize = ftell(json_file);
fseek(json_file, 0, SEEK_SET);
char *json_file_data = malloc(fsize + 1);
fread(json_file_data, 1, fsize, json_file);
fclose(json_file);
json_file_data[fsize] = '\0';
json_file_data = strchr(json_file_data, '{');
for(size_t i = 0; i < 7; i++)
{
char* start_pos, end_pos;
json_file_data = pass_whitespaces(json_file_data);
json_file_data = strchr(json_file_data, '\"') + 1;
if(!strncmp(json_file_data , "dataFileName" , 12 ))
{
json_file_data = strchr(json_file_data, ':') + 1;
json_file_data = start_pos = pass_whitespaces(json_file_data) + 1;
json_file_data = strchr(json_file_data, '\"');
memcpy(data_info.data_file_name , start_pos , json_file_data - start_pos);
data_info.data_file_name[json_file_data - start_pos] = '\0';
json_file_data += 1;
}
if(!strncmp(json_file_data , "indexFileName" , 13 ))
{
json_file_data = strchr(json_file_data, ':') + 1;
json_file_data = start_pos = pass_whitespaces(json_file_data) + 1;
json_file_data = strchr(json_file_data, '\"');
memcpy(data_info.index_file_name , start_pos , json_file_data - start_pos);
data_info.index_file_name[json_file_data - start_pos] = '\0';
json_file_data += 1;
}
if(!strncmp(json_file_data , "keyEncoding" , 11 ))
{
json_file_data = strchr(json_file_data, ':') + 1;
json_file_data = start_pos = pass_whitespaces(json_file_data) + 1;
json_file_data = strchr(json_file_data, '\"');
memcpy(data_info.encoding , start_pos , json_file_data - start_pos);
data_info.encoding[json_file_data - start_pos] = '\0';
json_file_data += 1;
}
if(!strncmp(json_file_data , "order" , 5 ))
{
json_file_data = strchr(json_file_data, ':') + 1;
json_file_data = start_pos = pass_whitespaces(json_file_data) + 1;
json_file_data = strchr(json_file_data, '\"');
memcpy(data_info.order , start_pos , json_file_data - start_pos);
data_info.order[json_file_data - start_pos] = '\0';
json_file_data += 1;
}
if(!strncmp(json_file_data , "recordLength" , 12 ))
{
json_file_data = strchr(json_file_data, ':') + 1;
data_info.record_length = atoi(json_file_data);
}
if(!strncmp(json_file_data , "keyStart" , 8 ))
{
json_file_data = strchr(json_file_data, ':') + 1;
data_info.keyStart = atoi(json_file_data);
}
if(!strncmp(json_file_data , "keyEnd" , 6 ))
{
json_file_data = strchr(json_file_data, ':') + 1;
data_info.keyEnd = atoi(json_file_data);
}
}
FILE* index_file = fopen(data_info.index_file_name , "r");
if(NULL != index_file)
{
freeResources(indecies , index_count);
fseek(index_file, 0, SEEK_END);
long index_file_size = ftell(index_file);
fseek(index_file, 0, SEEK_SET);
index_count = index_file_size / (data_info.keyEnd - data_info.keyStart + sizeof(int)) ;
indecies = malloc(index_count * sizeof(struct IndexData));
for(size_t i = 0; i < index_count; i++)
{
indecies[i].key = malloc(data_info.keyEnd - data_info.keyStart + 1);
fread(indecies[i].key , 1 , data_info.keyEnd - data_info.keyStart , index_file);
indecies[i].key[data_info.keyEnd - data_info.keyStart] = '\0';
fread(&indecies[i].pos , sizeof(unsigned) , 1 , index_file);
}
fclose(index_file);
}
}
else if(!strncmp(buffer_point, "create_index", 12))
{
freeResources(indecies , index_count);
FILE* data_file = fopen(data_info.data_file_name , "r");
fseek(data_file, 0, SEEK_END);
long data_file_size = ftell(data_file);
fseek(data_file, 0, SEEK_SET);
index_count = data_file_size / data_info.record_length ;
indecies = malloc(index_count * sizeof(struct IndexData));
for(size_t i = 0; i < index_count; i++)
{
indecies[i].key = malloc(data_info.keyEnd - data_info.keyStart + 1);
indecies[i].pos = i * data_info.record_length;
fseek(data_file, indecies[i].pos + data_info.keyStart , SEEK_SET);
fread(indecies[i].key , 1 , data_info.keyEnd - data_info.keyStart , data_file);
indecies[i].key[data_info.keyEnd - data_info.keyStart] = '\0';
}
fclose(data_file);
int i, j;
for (i = 0; i < index_count -1; i++)
for (j = 0; j < index_count-i-1; j++)
{
if(!strcmp(data_info.order , "ASC"))
{
if (strcmp(indecies[j].key , indecies[j+1].key) > 0)
{
struct IndexData temp;
temp.key = indecies[j].key;
temp.pos =indecies[j].pos;
indecies[j] = indecies[j+1];
indecies[j+1] = temp;
}
}
if(!strcmp(data_info.order , "DESC"))
{
if (strcmp(indecies[j].key , indecies[j+1].key) > 0)
{
struct IndexData temp;
temp.key = indecies[j + 1].key;
temp.pos =indecies[j + 1].pos;
indecies[j + 1] = indecies[j];
indecies[j] = temp;
}
}
}
FILE* index_file = fopen(data_info.index_file_name , "w+");
for(size_t i = 0; i < index_count; i++)
{
fwrite(indecies[i].key , 1 , data_info.keyEnd - data_info.keyStart , index_file);
fwrite(&indecies[i].pos , sizeof(unsigned long) , 1 , index_file);
}
fclose(index_file);
}
else if(!strncmp(buffer_point, "search", 6))
{
buffer_point = pass_whitespaces(buffer_point + 6);
int consumed_int;
sscanf(buffer_point, "%s%n" , buffer_point , &consumed_int);
if(0 == consumed_int) continue;
char* key = buffer_point;
{
char* key_end = key;
while('\0' != *key_end && !isspace(*key_end++));
*key_end = '\0';
}
if(!strcmp(data_info.encoding , "BIN"))
{
}
FILE* data_file = fopen(data_info.data_file_name , "r");
int l =0;
int r = index_count - 1;
int result_index = -1;
while (l <= r)
{
int m = l + (r - l) / 2;
int result = strcmp(indecies[m].key , key);
if(0 == result )
{
result_index = m;
break;
}
else if (0 > result)
l = m + 1;
else
r = m - 1;
}
if(-1 != result_index )
{
fseek(data_file, indecies[result_index].pos, SEEK_SET);
for(size_t i = 0; i < data_info.record_length; i++)
printf("%c" ,fgetc(data_file));
puts("");
fclose(data_file);
}
else
puts("Key not found!");
}
else if(!strncmp(buffer_point, "close", 5))
{
should_close = true;
}
}
freeResources(indecies , index_count);
return 0;
}
|
C
|
#if !defined(AFX_URLENCODE_INCLUDED_)
#define AFX_URLENCODE_INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
inline BYTE toHex(const BYTE &x)
{
return x > 9 ? x + 55: x + 48;
}
inline BYTE toByte(const BYTE &x)
{
return x > 57? x - 55: x - 48;
}
CString URLDecode(CString sIn)
{
if (sIn == "")
return CString("");
CString sOut;
const int nLen = sIn.GetLength() + 1;
register LPBYTE pOutTmp = NULL;
LPBYTE pOutBuf = NULL;
register LPBYTE pInTmp = NULL;
LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
//alloc out buffer
pOutBuf = (LPBYTE)sOut.GetBuffer(nLen);
if(pOutBuf)
{
pInTmp = pInBuf;
pOutTmp = pOutBuf;
// do encoding
while (*pInTmp)
{
if('%'==*pInTmp)
{
pInTmp++;
*pOutTmp++ = (toByte(*pInTmp)%16<<4) + toByte(*(pInTmp+1))%16;//4λ+4λ
pInTmp++;
}
else if('+'==*pInTmp)
*pOutTmp++ = ' ';
else
*pOutTmp++ = *pInTmp;
pInTmp++;
}
*pOutTmp = '\0';
sOut.ReleaseBuffer();
}
sIn.ReleaseBuffer();
return sOut;
}
CString URLEncode(CString sIn)
{
if (sIn == "")
return CString("");
CString sOut;
const int nLen = sIn.GetLength() + 1;
register LPBYTE pOutTmp = NULL;
LPBYTE pOutBuf = NULL;
register LPBYTE pInTmp = NULL;
LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
//alloc out buffer
pOutBuf = (LPBYTE)sOut.GetBuffer(nLen*3);
if(pOutBuf)
{
pInTmp = pInBuf;
pOutTmp = pOutBuf;
// do encoding
while (*pInTmp)
{
if(isalnum(*pInTmp) || '-'==*pInTmp || '_'==*pInTmp || '.'==*pInTmp)
*pOutTmp++ = *pInTmp;
else if(isspace(*pInTmp))
*pOutTmp++ = '+';
else
{
*pOutTmp++ = '%';
*pOutTmp++ = toHex(*pInTmp>>4);//4λ
*pOutTmp++ = toHex(*pInTmp%16);//4λ
}
pInTmp++;
}
*pOutTmp = '\0';
sOut.ReleaseBuffer();
}
sIn.ReleaseBuffer();
return sOut;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_THREADS 4
#define NUM_LINES 20
char *lines[NUM_LINES];
int line_diffs[NUM_LINES - 1];
void read_file();
void line_diff(size_t my_id);
int line_sum(size_t line);
void free_lines();
void print_diffs();
int main(void)
{
read_file();
for (size_t i = 0; i < NUM_THREADS; i++)
{
line_diff(i);
}
free_lines();
print_diffs();
}
void read_file()
{
FILE *fp = fopen("test.txt", "r");
if (fp == NULL)
{
perror("Failed: ");
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < NUM_LINES; i++)
{
char *line = NULL;
size_t len;
if (getline(&line, &len, fp) == -1)
{
perror("Failed: ");
free(line);
exit(EXIT_FAILURE);
}
lines[i] = line;
}
fclose(fp);
}
void line_diff(size_t id)
{
size_t start, end, i;
int previous_sum, sum, diff;
start = id * (NUM_LINES / NUM_THREADS);
end = start + (NUM_LINES / NUM_THREADS);
previous_sum = line_sum(start);
printf("id = %zu | start = %zu | end = %zu\n", id, start, end);
for (i = start + 1; i < end; i++)
{
sum = line_sum(i);
diff = previous_sum - sum;
line_diffs[i - 1] = diff;
previous_sum = sum;
}
}
int line_sum(size_t line_num)
{
char *line = lines[line_num];
int result = 0;
for (size_t i = 0; i < strlen(line); i++)
{
result += (int)line[i];
}
return result;
}
void free_lines()
{
for (size_t i = 0; i < NUM_LINES; i++)
{
free(lines[i]);
}
}
void print_diffs()
{
for (size_t i = 0; i < NUM_LINES - 1; i++)
{
printf("%zu-%zu: %d\n", i, i + 1, line_diffs[i]);
}
}
|
C
|
/**
****************************************************************************************
*
* @file menu.c
*
* @brief Implementation of application menu
*
* Copyright (C) 2015-2016 Dialog Semiconductor.
* This computer program includes Confidential, Proprietary Information
* of Dialog Semiconductor. All Rights Reserved.
*
****************************************************************************************
*/
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "menu.h"
/* 'root' menu has to be always defined */
extern const struct menu_item __MENU_root[];
#define MAX_MENU_DEPTH (3)
/** stack for nesting menu */
static const struct menu_item *menu_stack[MAX_MENU_DEPTH] = { __MENU_root };
/** current nesting level */
static size_t menu_depth = 0;
/*
* bitmask with 'checked' state of currently displayed menu items, i.e. result of 'checked_cb'
* callback for each menu item; cached 'checked' value is passed to handler when menu item is
* selected, but handler can reevaluate this by calling 'checked_cb' callback manually, if this is
* required for some reason
*/
static uint32_t menu_checked = 0;
/** try to handle menu option for given index */
static void do_numeric_opt(int opt)
{
const struct menu_item *m = menu_stack[menu_depth];
bool checked;
/* on-screen we have 1..N, but internally we use 0..(N-1) so any negative number is invalid */
if (--opt < 0) {
return;
}
/* retrieve 'checked' value from cache */
checked = menu_checked & (1 << opt);
/* find option - can't just use index directly since we don't know how many entries are theres */
while (opt && m->name) {
m++;
opt--;
}
if (!m->name || (!m->submenu && !m->func)) {
return;
}
/* if there's no submenu, execute assosiated function */
if (!m->submenu) {
m->func(m, checked);
return;
}
/* can't go deeper if already at max nesting depth */
if (menu_depth >= MAX_MENU_DEPTH - 1) {
return;
}
/* put submenu on stack */
menu_depth++;
menu_stack[menu_depth] = m->submenu;
}
void app_menu_draw(void)
{
const struct menu_item *m = menu_stack[menu_depth];
int pos = 0;
/* reset 'checked' cache */
menu_checked = 0;
printf(NEWLINE ",=== select option and press [Enter]:" NEWLINE);
while (m[pos].name) {
char *sel_mark = " ";
if (m[pos].checked_cb) {
bool sel = m[pos].checked_cb(&m[pos]);
sel_mark = sel ? "[*] " : "[ ] ";
/*
* Cache 'checked' value for menu, this will be includes in menu handler
* so there's no need to query again (but app still can choose to do this
* if necessary).
*/
if (sel) {
menu_checked |= (1 << pos);
}
}
printf("| %2d - %s%s" NEWLINE, pos + 1, sel_mark, m[pos].name);
pos++;
}
if (menu_depth) {
printf("| x - go up" NEWLINE);
}
printf("`==> ");
fflush(stdout);
}
void app_menu_parse_selection(char *s)
{
int opt;
char *s_end;
/* check if numeric option is selected */
opt = strtol(s, &s_end, 10);
if (s != s_end) {
do_numeric_opt(opt);
return;
}
/* skip leading whitespaces */
while (*s && isspace((int) *s)) {
s++;
}
/* go to end of word and null-terminate string */
s_end = s;
while (*s_end && !isspace((int) *s_end)) {
s_end++;
}
*s_end = '\0';
/* check if special option is selected (only one character allowed) */
if (strlen(s) != 1) {
return;
}
switch (tolower((int) s[0])) {
case 'x':
if (menu_depth > 0) {
menu_depth--;
}
break;
}
}
|
C
|
#include <stdio.h>
int main(void)
{
int repeat, ri;
double rate, salary, tax;
scanf("%d", &repeat);
for(ri = 1; ri <= repeat; ri++){
scanf("%lf", &salary);
if(salary<=850){
tax=0;
}
else if(salary<=1350){
rate=0.05;
tax= rate * (salary - 850);
}
else if(salary<=2850){
rate=0.1;
tax=rate * (salary - 850);
}
else if(salary<=5850){
rate=0.15;
tax=rate * (salary - 850);
}
else {
rate=0.2;
tax=rate * (salary - 850);
}
printf("tax = %0.2f\n", tax);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 16
void mojisort(char *h){
int i, j;
char a;
for(i=0; h[i] != 0; i++){
for(j=i+1; h[j] != 0; j++){
if(h[i]>h[j]){
a = h[i];
h[i] = h[j];
h[j] = a;
}
}
}
}
int main(void){
char t[17];
FILE *fp;
char *fname = "dictionary.txt";
char s[16], p[16];
int sum = 0;
scanf("%s", t);
mojisort(t);
fp = fopen(fname, "r");
if(fp == NULL){
printf("%s error\n", fname);
return -1;
}
while(fgets(s, 16, fp) != NULL){
strcpy(p, s);
if(strlen(s)<16 || s[15] == '\n'){
s[strlen(s)-1] = '\0';
}
mojisort(s);
if(strncmp(t, s, strlen(t))==0){
printf("%s", p);
}
}
fclose(fp);
return 0;
}
|
C
|
/*******************************************************************************
@brief: ģڶjsonзװ,ʹkeyԽṹԱֵԼ
ṹԱ.ģзkeyбֳĽṹ,
ݵõIJηλ.ģṩֻ
,洢ṹСԱ,ֱΪ:long long ;doubleĸ
Լַ;(ָ,boolδ洢).
ģ洢ݳԱʱ,һ˳洢,ģԹϣķʽ
洢Ա,Լӿٶ.
ģṩʽkey,ѭԱ.
*******************************************************************************/
#ifndef __GX_JANSSON_H__
#ifdef __cplusplus
extern "C" {
#endif
#define __GX_JANSSON_H__
#define MAX_JSON_KEY_LEN (128)
typedef void* GxJson_t;
/**
* @brief New a container to contain all member
* @return pointer to container. NULL: failure
*/
GxJson_t GxJson_New(void);
/**
* @brief append a string member to container
* @param GxJson_t container: pointer to container.
* @param const char* key: key to bind the member
* @param const char* string: the value
* @return int <0,failure;>=o,success;
*/
int GxJson_SetString(GxJson_t container,const char* key,const char*string);
/**
* @brief get a string member from container
* @param GxJson_t container: pointer to container.
* @param const char* key: key to find the member
* @return char* if(NULL),failure;else,the string;
*/
const char* GxJson_GetString(GxJson_t container,const char* key);
/**
* @brief append a float member to container
* @param GxJson_t container: pointer to container.
* @param const char* key: key to bind the member
* @param double val: the value
* @return int <0,failure;>=o,success;
*/
int GxJson_SetFloat(GxJson_t container,const char* key,double val);
/**
* @brief get a flot member from container
* @param GxJson_t container: pointer to container.
* @param const char* key: key to find the member
* @return double if(0.0) the value of float is 0.0 or failure;else,the float value;
*/
double GxJson_GetFloat(GxJson_t container,const char* key);
/**
* @brief append a integer member to container
* @param GxJson_t container: pointer to container.
* @param const char* key: key to bind the member
* @param long long val: the value
* @return int <0,failure;>=o,success;
*/
int GxJson_SetInteger(GxJson_t container,const char* key,long long val);
/**
* @brief get a integer member from container
* @param GxJson_t container: pointer to container.
* @param const char* key: key to find the member
* @return long long if(0) the value of integer is 0 or failure;else,the integer value;
*/
long long GxJson_GetInteger(GxJson_t container,const char* key);
/**
* @brief append a string member to container with format key
* @param GxJson_t container: pointer to container.
* @param const char*string: the value
* @param const char* fmt ...: key to bind the member. i.e ("frends[%d].englishname",1)
* @return int <0,failure;>=o,success;
*/
int GxJson_SetStringWithFmtKey(GxJson_t container,const char*string,const char* fmt,...);
/**
* @brief get a string member from container
* @param GxJson_t container: pointer to container.
* @param const char* fmt,...: format key to find the member i.e ("frends[%d].englishname",1)
* @return char* if(NULL),failure;else,the string;
*/
const char* GxJson_GetStringWithFmtKey(GxJson_t container,const char* fmt,...);
/**
* @brief append a float member to container with format key
* @param GxJson_t container: pointer to container.
* @param double val: the value
* @param const char* fmt ...: key to bind the member. i.e ("frends[%d].englishname",1)
* @return int <0,failure;>=o,success;
*/
int GxJson_SetFloatWithFmtKey(GxJson_t container,double val,const char* fmt,...);
/**
* @brief get a float member from container
* @param GxJson_t container: pointer to container.
* @param const char* fmt,...: format key to find the member i.e ("frends[%d].englishname",1)
* @return double if(0.0) the value of float is 0.0 or failure;else,the float value;
*/
double GxJson_GetFloatWithFmtKey(GxJson_t container,const char* fmt,...);
/**
* @brief append a integer member to container with format key
* @param GxJson_t container: pointer to container.
* @param long long val: the value
* @param const char* fmt ...: key to bind the member. i.e ("frends[%d].englishname",1)
* @return int <0,failure;>=o,success;
*/
int GxJson_SetIntegerWithFmtKey(GxJson_t container,long long val,const char* fmt,...);
/**
* @brief get a integer member from container
* @param GxJson_t container: pointer to container.
* @param const char* fmt,...: format key to find the member i.e ("frends[%d].englishname",1)
* @return long long if(0) the value of integer is 0 or failure;else,the integer value;
*/
long long GxJson_GetIntegerWithFmtKey(GxJson_t container,const char* fmt,...);
/**
* @brief get array size
* @param GxJson_t container: pointer to container.
* @param const char* key
* @return long long if(0) the value of integer is 0 or failure;else,the integer value;
*/
int GxJson_GetArraySizeWithFmtKey(GxJson_t container,const char* fmt,...);
/**
* @brief free the container and all item that appended to it will be free
* @param GxJson_t container: pointer to container.
* @return int <0,failure;>=o,success;
*/
int GxJson_Free(GxJson_t container);
/**
* @brief dump string,make the content of the container as a format string.
* @param GxJson_t container: pointer to container.
* @return char* if(NULL),failure;else,the string;
*/
char* GxJson_DumpString(GxJson_t container);
/**
* @brief load string,change string to a json container.
* @param const char* string: pointer to string;
* @return GxJson_t if(NULL),failure;else,the string;
*/
void *GxJson_LoadString(const char* string);
/**
* @brief free string buffer
* @param const char* string: pointer to string;
* @return void;
*/
void GxJson_FreeString(char* string);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
/*
* File : mod_communication.c
* Project : e_puck_project
* Description : Module in charge of bluetooth communcations with distant device
*
* Written by Maxime Marchionno and Nicolas Peslerbe, April 2018
* MICRO-315 | École Polytechnique Fédérale de Lausanne
*/
#include "headers/mod_communication.h"
// Standard headers
#include <stdio.h>
#include <string.h>
// Epuck/ChibiOS headers
#include <ch.h>
#include <hal.h>
#include <chprintf.h>
// Our headers
#include "mod_check.h"
#include "mod_secure_conv.h"
#define SEPARATOR_SIZE 2
#define UNSIGNED_INT_IN_CHAR_SIZE 6
#define NULL_CHAR_SIZE 1
#define SERIAL_BIT_RATE 115200
#define DISPLAY_LEVEL 1
/********************
* Private functions
*/
/**
* @brief Load parameters and start serial drivers
*/
static void serial_start(void)
{
static SerialConfig ser_cfg = {
SERIAL_BIT_RATE,
0,
0,
0,
};
sdStart(&SD3, &ser_cfg); // UART3. Connected to the second com port of the programmer
}
/********************
* Public functions (Informations in header)
*/
void mod_com_initModule(){
serial_start();
}
void mod_com_writeDatas(char* type, char* toWrite, size_t toWriteSize){
void* toSend = NULL;
// Prepare the size of datas to introduce it in the header
if(toWriteSize == 0) toWriteSize = strlen(toWrite);
char sizeText[sizeof(char)*(UNSIGNED_INT_IN_CHAR_SIZE + NULL_CHAR_SIZE)];
sprintf(sizeText, "%5d", size_t2int(toWriteSize));
size_t sizeOfType = strlen(type);
const char separator[SEPARATOR_SIZE] = "||";
size_t headerSize = strlen(sizeText) + SEPARATOR_SIZE +
sizeOfType +
SEPARATOR_SIZE;
toSend = malloc(headerSize*sizeof(char));
assert (toSend != NULL);
// Prepare the header
void * toSendPointer = toSend;
memcpy(toSendPointer, sizeText, strlen(sizeText));
toSendPointer += strlen(sizeText);
memcpy(toSendPointer, separator, (size_t) SEPARATOR_SIZE);
toSendPointer += SEPARATOR_SIZE;
memcpy(toSendPointer, type, sizeOfType);
toSendPointer += sizeOfType;
memcpy(toSendPointer, separator, (size_t) SEPARATOR_SIZE);
size_t i;
chSequentialStreamWrite((BaseSequentialStream *)&SD3, (uint8_t*)"START", 5);
// Write the header first
for(i=0; i<headerSize;i++)
chprintf((BaseSequentialStream *)&SD3, "%c",((uint8_t*) toSend)[i]);
// Write content of the message
int written = 0;
while(toWriteSize > 0){
if(toWriteSize > 4000){
chSequentialStreamWrite((BaseSequentialStream *)&SD3, (uint8_t*)toWrite+written, 4000);
chThdSleepMilliseconds(400);
written+=4000;
toWriteSize -= 4000;
}
else{
chSequentialStreamWrite((BaseSequentialStream *)&SD3, (uint8_t*)toWrite+written, toWriteSize);
toWriteSize = 0;
}
}
free(toSend);
toSend = NULL;
}
void mod_com_writeMessage(char* message, int level){
if(level < DISPLAY_LEVEL){
return;
}
strcat(message,"\n");
void* toSend = NULL;
// Prepare the size of datas to introduce it in the header
size_t toWriteSize = strlen(message);
char sizeText[sizeof(char)*(UNSIGNED_INT_IN_CHAR_SIZE + NULL_CHAR_SIZE)];
sprintf(sizeText, "%5d", size_t2int(toWriteSize));
size_t sizeOfType = strlen("Message");
const char separator[SEPARATOR_SIZE] = "||";
size_t totalSize = strlen(sizeText) + SEPARATOR_SIZE +
sizeOfType + SEPARATOR_SIZE + strlen(message) ;
toSend = malloc(totalSize*sizeof(char));
assert (toSend != NULL);
// Prepare the header
void * toSendPointer = toSend;
memcpy(toSendPointer, sizeText, strlen(sizeText));
toSendPointer += strlen(sizeText);
memcpy(toSendPointer, separator, (size_t) SEPARATOR_SIZE);
toSendPointer += SEPARATOR_SIZE;
memcpy(toSendPointer, "Message", sizeOfType);
toSendPointer += sizeOfType;
memcpy(toSendPointer, separator, (size_t) SEPARATOR_SIZE);
toSendPointer += SEPARATOR_SIZE;
memcpy(toSendPointer, message, (size_t) strlen(message));
size_t i;
chSequentialStreamWrite((BaseSequentialStream *)&SD3, (uint8_t*)"START", 5);
// Write the header first
for(i=0; i<totalSize;i++)
chprintf((BaseSequentialStream *)&SD3, "%c",((uint8_t*) toSend)[i]);
free(toSend);
toSend = NULL;
}
void mod_com_writeCommand(cmd_t order){
void* toSend = NULL;
char orderString[30];
switch (order) {
case SEND_MAP:
strcpy(orderString, "Send map\n");
break;
}
// Prepare the size of datas to introduce it in the header
size_t toWriteSize = strlen(orderString);
char sizeText[sizeof(char)*(UNSIGNED_INT_IN_CHAR_SIZE + NULL_CHAR_SIZE)];
sprintf(sizeText, "%5d", size_t2int(toWriteSize));
size_t sizeOfType = strlen("Command");
const char separator[SEPARATOR_SIZE] = "||";
size_t totalSize = strlen(sizeText) + SEPARATOR_SIZE +
sizeOfType + SEPARATOR_SIZE + strlen(orderString) ;
toSend = malloc(totalSize*sizeof(char));
assert (toSend != NULL);
// Prepare the header
void * toSendPointer = toSend;
memcpy(toSendPointer, sizeText, strlen(sizeText));
toSendPointer += strlen(sizeText);
memcpy(toSendPointer, separator, (size_t) SEPARATOR_SIZE);
toSendPointer += SEPARATOR_SIZE;
memcpy(toSendPointer, "Command", sizeOfType);
toSendPointer += sizeOfType;
memcpy(toSendPointer, separator, (size_t) SEPARATOR_SIZE);
toSendPointer += SEPARATOR_SIZE;
memcpy(toSendPointer, orderString, (size_t) strlen(orderString));
size_t i;
chSequentialStreamWrite((BaseSequentialStream *)&SD3, (uint8_t*)"START", 5);
// Write the header first
for(i=0; i<totalSize;i++)
chprintf((BaseSequentialStream *)&SD3, "%c",((uint8_t*) toSend)[i]);
free(toSend);
toSend = NULL;
}
|
C
|
//
// Climbing Stairs
// https://leetcode.com/problems/climbing-stairs/#/description
//
#include <stdio.h>
#include <stdlib.h>
int climbStairs(int n)
{
int i;
int *a;
int s;
if (1 == n)
return 1;
if (2 == n)
return 2;
a = (int *)malloc(n * sizeof(int));
a[n - 1] = 1;
a[n - 2] = 2;
for (i = n - 3; i >= 0; --i) {
a[i] = a[i + 1] + a[i + 2];
}
s = a[0];
free(a);
return s;
}
int main(int argc, char const *argv[])
{
printf("%d\n", climbStairs(5));
return 0;
}
|
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 */
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
struct TYPE_4__ {int /*<<< orphan*/ parent_path; } ;
typedef TYPE_1__ git_worktree ;
typedef int /*<<< orphan*/ git_repository ;
typedef int /*<<< orphan*/ git_remote ;
typedef int /*<<< orphan*/ git_buf ;
/* Variables and functions */
int GIT_ENOTFOUND ;
int git_buf_sets (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ git_error_clear () ;
int /*<<< orphan*/ git_remote_free (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ git_remote_url (int /*<<< orphan*/ *) ;
scalar_t__ git_repository_is_worktree (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ git_repository_workdir (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ git_worktree_free (TYPE_1__*) ;
int git_worktree_open_from_repository (TYPE_1__**,int /*<<< orphan*/ *) ;
int lookup_default_remote (int /*<<< orphan*/ **,int /*<<< orphan*/ *) ;
__attribute__((used)) static int get_url_base(git_buf *url, git_repository *repo)
{
int error;
git_worktree *wt = NULL;
git_remote *remote = NULL;
if ((error = lookup_default_remote(&remote, repo)) == 0) {
error = git_buf_sets(url, git_remote_url(remote));
goto out;
} else if (error != GIT_ENOTFOUND)
goto out;
else
git_error_clear();
/* if repository does not have a default remote, use workdir instead */
if (git_repository_is_worktree(repo)) {
if ((error = git_worktree_open_from_repository(&wt, repo)) < 0)
goto out;
error = git_buf_sets(url, wt->parent_path);
} else
error = git_buf_sets(url, git_repository_workdir(repo));
out:
git_remote_free(remote);
git_worktree_free(wt);
return error;
}
|
C
|
//Made for Arduino nano by John Arild Lolland
//psudo code:
//Master skal fungere som ledd mellom RS485 og RS232
//RS485 brukes for å kommunisere med slavene.
//RS232 brukes for å kommunisere med VS481B
//Det forventes ikke kommunikasjon fra VS481B hvis ikke kommando er sendt først
//To seriell porter er nødvendig for master. Software serial må brukes.
//hardware seriell brukes for RS232 og sofrware seriell for RS485.
//Slave kommandoer:
//s = status request
//t = power on
//u = power off
//v = sw01
//w = sw02
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
int statusByte = 33;
int incommingByte = 0;
String inputString = ""; // a string to hold incoming data from VS481B
String debugString = "";
boolean stringComplete = false; // whether the string is complete
bool powerOn = false;
bool sw01 = true;
bool sw02 = false;
int RS485_Send_pin = 9;
bool AskForStatus = false; //Set true to make loop send "read" through RS232
int counter = 0;
void setup() {
// reserve 200 bytes for the inputString:
inputString.reserve(200);
// Open hardware serial communications:
Serial.begin(19200);
// set the data rate for the SoftwareSerial port
mySerial.begin(4800);
pinMode(RS485_Send_pin, OUTPUT);
//Set pin13 (LED on Arduino board) as output for debug
pinMode(13, OUTPUT);
}
void loop() { // run over and over
if (mySerial.available()) {
incommingByte = mySerial.read();
}
if (incommingByte == 115) //ASCII s
{
//ask VS481B for status
AskForStatus = true;
}
else if (incommingByte == 116) //ASCII t
{
//ask VS481B to turn on ouputs
Serial.println("sw on");
//ask VS481B for status
AskForStatus = true;
}
else if (incommingByte == 117) //ASCII u
{
//ask VS481B to turn off outputs
Serial.println("sw off");
//ask VS481B for status
AskForStatus = true;
}
else if (incommingByte == 118) //ASCII v
{
//ask VS481B to change input to 01
Serial.println("sw i01");
//ask VS481B for status
AskForStatus = true;
}
else if (incommingByte == 119) //ASCII w
{
//ask VS481B to change input to 02
Serial.println("sw i02");
//ask VS481B for status
AskForStatus = true;
}
incommingByte = 0;
//-------------------------------------------------
if (stringComplete) //data recieved from VS481B
{
//Used under development:
//digitalWrite(13, HIGH); //onboard LED
//digitalWrite(RS485_Send_pin, HIGH); //turn on RS485 send pin
//mySerial.println(inputString);
//mySerial.println("sw01: " + String(sw01));
//mySerial.println("sw02: " + String(sw02));
//mySerial.println("powerOn: " + String(powerOn));
//mySerial.println("debugString:" + debugString + ":");
//mySerial.println("statusByte:" + String(statusByte) + ":");
//digitalWrite(RS485_Send_pin, LOW); //turn off RS485 send pin
statusByte = 33 + powerOn + (sw01 * 2) + (sw02 * 4); //makes statusByte to be sendt to slave
digitalWrite(RS485_Send_pin, HIGH); //turn on RS485 send pin
mySerial.write(statusByte);
digitalWrite(RS485_Send_pin, LOW); //turn off RS485 send pin
inputString = "";
stringComplete = false;
}
if (AskForStatus == true)
{
counter ++;
if(counter > 10000)
{
AskForStatus = false;
counter = 0;
Serial.println("read"); //the command 'read' asks VS481B to return config
}
}
}
void serialEvent()
{
while (Serial.available())
{
// get the new byte:
char inChar = (char)Serial.read();
inputString += inChar;
//Search for Input port number. This is part of the "read" response
if (inputString.substring(inputString.length() - 12,inputString.length() - 1) == "Input:port ")
{
debugString = inputString.substring(inputString.length() - 1);
if(inputString.substring(inputString.length() - 1) == "2")
{
sw02 = true;
sw01 = false;
}
if(inputString.substring(inputString.length() - 1) == "1")
{
sw01 = true;
sw02 = false;
}
}
//Search for HDMI output on/off. This is part of the "read" response
if (inputString.substring(inputString.length() - 9,inputString.length() - 2) == "Output:")
{
debugString = inputString.substring(inputString.length() - 2);
if(inputString.substring(inputString.length() - 2) == "ON")
{
powerOn = true;
}
if(inputString.substring(inputString.length() - 2) == "OF") //This is "OFF", but I only check 2 characters
{
powerOn = false;
}
}
//When F/W is recieved, then no more usefull information will come.
//Set stringComplete to true indicating that data can be sendt to slaves
//This also clears inputString to clear up memory.
if (inputString.substring(inputString.length() - 3) == "F/W")
{
stringComplete = true;
//inputString = "";
}
//if for any reason the inputString gets too long, then delete it
//This 'if' should never be 'true'
if (inputString.length() > 1000) {inputString = "";}
}
}
|
C
|
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (C) 2018 Oracle. All Rights Reserved.
* Author: Darrick J. Wong <[email protected]>
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#include "platform_defs.h"
#include "ptvar.h"
/*
* Per-thread Variables
*
* This data structure manages a lockless per-thread variable. We
* implement this by allocating an array of memory regions, and as each
* thread tries to acquire its own region, we hand out the array
* elements to each thread. This way, each thread gets its own
* cacheline and (after the first access) doesn't have to contend for a
* lock for each access.
*/
struct ptvar {
pthread_key_t key;
pthread_mutex_t lock;
size_t nr_used;
size_t nr_counters;
size_t data_size;
unsigned char data[0];
};
#define PTVAR_SIZE(nr, sz) (sizeof(struct ptvar) + ((nr) * (size)))
/* Allocate a new per-thread counter. */
int
ptvar_alloc(
size_t nr,
size_t size,
struct ptvar **pptv)
{
struct ptvar *ptv;
int ret;
#ifdef _SC_LEVEL1_DCACHE_LINESIZE
long l1_dcache;
/* Try to prevent cache pingpong by aligning to cacheline size. */
l1_dcache = sysconf(_SC_LEVEL1_DCACHE_LINESIZE);
if (l1_dcache > 0)
size = roundup(size, l1_dcache);
#endif
ptv = malloc(PTVAR_SIZE(nr, size));
if (!ptv)
return -errno;
ptv->data_size = size;
ptv->nr_counters = nr;
ptv->nr_used = 0;
memset(ptv->data, 0, nr * size);
ret = -pthread_mutex_init(&ptv->lock, NULL);
if (ret)
goto out;
ret = -pthread_key_create(&ptv->key, NULL);
if (ret)
goto out_mutex;
*pptv = ptv;
return 0;
out_mutex:
pthread_mutex_destroy(&ptv->lock);
out:
free(ptv);
return ret;
}
/* Free per-thread counter. */
void
ptvar_free(
struct ptvar *ptv)
{
pthread_key_delete(ptv->key);
pthread_mutex_destroy(&ptv->lock);
free(ptv);
}
/* Get a reference to this thread's variable. */
void *
ptvar_get(
struct ptvar *ptv,
int *retp)
{
void *p;
int ret;
p = pthread_getspecific(ptv->key);
if (!p) {
pthread_mutex_lock(&ptv->lock);
assert(ptv->nr_used < ptv->nr_counters);
p = &ptv->data[(ptv->nr_used++) * ptv->data_size];
ret = -pthread_setspecific(ptv->key, p);
if (ret)
goto out_unlock;
pthread_mutex_unlock(&ptv->lock);
}
*retp = 0;
return p;
out_unlock:
ptv->nr_used--;
pthread_mutex_unlock(&ptv->lock);
*retp = ret;
return NULL;
}
/* Iterate all of the per-thread variables. */
int
ptvar_foreach(
struct ptvar *ptv,
ptvar_iter_fn fn,
void *foreach_arg)
{
size_t i;
int ret = 0;
pthread_mutex_lock(&ptv->lock);
for (i = 0; i < ptv->nr_used; i++) {
ret = fn(ptv, &ptv->data[i * ptv->data_size], foreach_arg);
if (ret)
break;
}
pthread_mutex_unlock(&ptv->lock);
return ret;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*=============================================================================================
Universidade Federal Fluminense
Curso de Ciencia da Computacao
Estrutura de dados - Arvore Binaria de Busca
Professor: Dalessandro
Alunos: Claudio Rodrigues Nunes
Ramon dos Santos Ferreira
13/04/2018
=============================================================================================*/
typedef struct arvore
{
int info;
struct arvore *esq;
struct arvore *dir;
}Arvore;
Arvore* LerArvore(Arvore *a,FILE *arq) // Opo 1
{
int num;
char ch;
fscanf(arq,"%c",&ch);
fscanf(arq,"%d",&num);
if(num==-1)
a=NULL;
else
{
a=(Arvore*)malloc(sizeof(Arvore));
a->info=num;
a->esq=LerArvore(a->esq,arq);
a->dir=LerArvore(a->dir,arq);
}
fscanf(arq,"%c",&ch);
return a;
}
int VerificarOrdenada(Arvore *a,int min,int max) // Complemento da opo 1
{
if(a==NULL)
return 1;
else if((a->info < min) || (a->info > max))
{
printf("Entrou segundo if");
return 0;
}
return VerificarOrdenada(a->esq,min,a->info) && VerificarOrdenada(a->dir,a->info,max);
}
Arvore* InserirElemento(Arvore *a,int x) // Opo 2
{
if(a==NULL)
{
a=(Arvore*)malloc(sizeof(Arvore));
a->info=x;
a->esq=NULL;
a->dir=NULL;
}
else if(a->info > x)
a->esq=InserirElemento(a->esq,x);
else
a->dir=InserirElemento(a->dir,x);
return a;
}
Arvore* RemoverElemento(Arvore *a,int x) // Opo 3
{
if(a!=NULL){
if(a->info==x){
if(a->esq==NULL && a->dir==NULL){
free(a);
return NULL;
}
else if(a->esq==NULL || a->dir==NULL){
Arvore *aux;
if(a->esq==NULL)
aux=a->dir;
else
aux=a->esq;
free(a);
return aux;
}
else{
Arvore *m=a->esq;
while(m->dir!=NULL)
{
m=m->dir;
}
a->info=m->info;
a->esq=RemoverElemento(a->esq,m->info);
return a;
}
}
else if(x<a->info)
a->esq=RemoverElemento(a->esq,x);
else a->dir=RemoverElemento(a->dir,x);
}
return a;
}
void ImprimirArvore(Arvore* a,int op) // Opo 4
{
if(op==1)
{
if(a!=NULL)
{
ImprimirArvore(a->esq,op);
printf("%d ",a->info);
ImprimirArvore(a->dir,op);
}
}
else if(op==2)
{
if(a==NULL)
printf("(-1)");
else
{
printf("(");
printf("%d",a->info);
ImprimirArvore(a->esq,op);
ImprimirArvore(a->dir,op);
printf(")");
}
}
else
printf("Opcao invalida!");
}
int CalcularAltura(Arvore *a) // Opo 5
{
if(a==NULL)
return 0;
else
{
int he=CalcularAltura(a->esq);
int hd=CalcularAltura(a->dir);
if(he<hd)
return hd+1;
else
return he+1;
}
}
void ImprimirEntreXY(Arvore *a,int x,int y) // Opo 6
{
if(a!=NULL)
{
if(a->info > x)
ImprimirEntreXY(a->esq,x,y);
if(a->info >= x && a->info <= y)
printf("%d ",a->info);
if(a->info < y)
ImprimirEntreXY(a->dir,x,y);
}
}
void ImprimirMaouMe(Arvore *a,int x,int y)
{
if(a!=NULL)
{
ImprimirMaouMe(a->esq,x,y);
if(a->info < x || a->info > y)
printf("%d ",a->info);
ImprimirMaouMe(a->dir,x,y);
}
}
Arvore* DestruirArvore(Arvore* a) // Opo 8
{
if(a!=NULL)
{
a->esq=DestruirArvore(a->esq);
a->dir=DestruirArvore(a->dir);
free(a);
}
return NULL;
}
int main()
{
Arvore *a;
int num,x,y,op,op2;
char arquivo[20];
FILE *arq;
do{
printf("Selecione uma opcao");
printf("\n\n1 - Ler uma arvore a partir de um arquivo e verificar se ela e ordenada");
printf("\n2 - Inserir um elemento na arvore.");
printf("\n3 - Remover um elemento na arvore.");
printf("\n4 - Imprimir arvore.");
printf("\n5 - Altura da arvore.");
printf("\n6 - Imprimir elementos entre x e y.");
printf("\n7 - Imprimir elementos menores que x ou maiores que y.");
printf("\n8 - Sair destruindo a arvore.");
printf("\n\n Informe a opcao escolhida: ");
scanf("%d",&op);
fflush(stdin);
switch(op)
{
case 1:
printf("\nDigite o nome do arquivo que devera ser lido: ");
gets(arquivo);
fflush(stdin);
arq=fopen(arquivo,"r");
a=LerArvore(a,arq);
if(VerificarOrdenada(a,-894351,894561))
printf("\nA arvore esta ordenada.");
else
printf("\nA arvore nao e ordenada.");
break;
case 2:
printf("Digite o numero a ser inserido na arvore: ");
scanf("%d",&num);
a=InserirElemento(a,num);
break;
case 3:
printf("\nDigite um valor para remover da arvore: ");
scanf("%d",&num);
a=RemoverElemento(a,num);
break;
case 4:
printf("\nDigite a forma de impressao: ");
printf("\n1 - Em Ordem.");
printf("\n2 - Notacao textual.");
scanf("%d",&op2);
fflush(stdin);
ImprimirArvore(a,op2);
break;
case 5:
printf("\nA arvore tem altura %d.\n",CalcularAltura(a));
break;
case 6:
printf("Insira os dois numeros do intervalo: ");
scanf("%d %d",&x,&y);
fflush(stdin);
ImprimirEntreXY(a,x,y);
break;
case 7:
printf("Digite os dois numeros: ");
scanf("%d %d",&x,&y);
fflush(stdin);
ImprimirMaouMe(a,x,y);
break;
case 8:
a=DestruirArvore(a);
exit(1);
break;
default:
printf("\nOpcao invalida.");
system("PAUSE");
break;
}
getchar();
system("cls");
} while (1);
return 0;
}
|
C
|
/******************************************************************/
/* Copyright (c) 1989, Intel Corporation
Intel hereby grants you permission to copy, modify, and
distribute this software and its documentation. Intel grants
this permission provided that the above copyright notice
appears in all copies and that both the copyright notice and
this permission notice appear in supporting documentation. In
addition, Intel grants this permission provided that you
prominently mark as not part of the original any modifications
made to this software or documentation, and that the name of
Intel Corporation not be used in advertising or publicity
pertaining to distribution of the software or the documentation
without specific, written prior permission.
Intel Corporation does not warrant, guarantee or make any
representations regarding the use of, or the results of the use
of, the software and documentation in terms of correctness,
accuracy, reliability, currentness, or otherwise; and you rely
on the software, documentation and results solely at your own
risk. */
/******************************************************************/
#include "defines.h"
#include "globals.h"
#include "regs.h"
extern double log10();
extern double pow();
/************************************************/
/* Display Floating Point Registers */
/* */
/* this routine will display the last stored */
/* fp register values from the global register */
/* storage area */
/************************************************/
display_fp_regs()
{
prtf("\n fp0:"); disp_fp_register(REG_FP0);
prtf("\n fp1:"); disp_fp_register(REG_FP1);
prtf("\n fp2:"); disp_fp_register(REG_FP2);
prtf("\n fp3:"); disp_fp_register(REG_FP3);
prtf("\n");
}
/************************************************/
/* Output a Floating Point number */
/* */
/************************************************/
out_fp(fp, precision)
double fp;
int precision;
{
int exponent, whole, fract;
double num;
unsigned char exp_str[LONG];
unsigned char whole_str[LONG];
unsigned char fract_str[LONG];
if (fp < 0.0) {
fp = -fp;
prtf("-");
}
errno = FALSE;
exponent = (int) log10(fp);
if (errno != FALSE)
exponent = 0;
htoad(exponent, MAXDIGITS, exp_str, TRUE);
num = fp * (pow(10.0,(double)-exponent));
whole = (int)num;
htoad(whole, MAXDIGITS, whole_str, TRUE);
fract = (int)((num-(double)whole)*pow(10.0,(double)precision));
htoad(fract, precision, fract_str, FALSE);
prtf ("%s.%se%s", whole_str, fract_str, exp_str);
}
/************************************************/
/* Display Floating Point */
/* */
/************************************************/
disp_float( size, nargs, addr, cnt )
int size; /* INT, LONG, or EXTENDED */
int nargs; /* Number of the following arguments that are valid (1 or 2) */
unsigned *addr; /* Address of floating point number in memory (required) */
int cnt; /* Number of numbers to display (optional, default 1) */
{
float real;
double long_real;
long double ext_real;
int valid;
if ( nargs == 1 ){
cnt = 1; /* Set default */
}
while ( cnt-- ){
prtf("\n%X : ", addr);
switch (size) {
case INT:
real = *(float *)addr;
valid = class_f(real);
addr++;
if (validate(valid) != ERROR) {
out_fp((double)real, 4);
}
break;
case LONG:
long_real = *(double *)addr;
valid = class_d(long_real);
addr += 2;
if (validate(valid) != ERROR) {
out_fp(long_real, 8);
}
break;
case EXTENDED:
ext_real = *(long double *)addr;
valid = class_e(ext_real);
addr += 3;
if (validate(valid) != ERROR) {
out_fp((double)ext_real, 8);
}
break;
}
}
prtf( "\n" );
}
/************************************************/
/* Display FP Register */
/* */
/************************************************/
disp_fp_register(num)
int num; /* index into 'fp_register_set[]' */
{
if (validate(class_d(fp_register_set[num])) != ERROR){
out_fp(fp_register_set[num], 6);
}
}
/************************************************/
/* Get Floating Point Register Number */
/* */
/* Returns: */
/* */
/* - NUM_REGS+(offset into fp_register_set)*/
/* if register is a floating pt reg. */
/* */
/* - ERROR otherwise */
/************************************************/
get_fp_regnum(reg)
char *reg; /* Name of register */
{
struct tabentry { char *name; int num; };
static struct tabentry reg_tab[] = {
"fp0", NUM_REGS+REG_FP0,
"fp1", NUM_REGS+REG_FP1,
"fp2", NUM_REGS+REG_FP2,
"fp3", NUM_REGS+REG_FP3,
0, 0
};
struct tabentry *tp;
for (tp=reg_tab; tp->name != 0; tp++) {
if (!strcmp(reg,tp->name)) {
return (tp->num);
}
}
return(ERROR);
}
/************************************************/
/* Validate a floating point number */
/* */
/* If anything but a Normal Finite Number, */
/* print out the type and return ERROR */
/************************************************/
static
validate (type)
int type;
{
char *p;
switch (type) {
case 0: p ="0.000000e 0"; break;
case 1: p ="Denormalized Number"; break;
case 2: return (0);
case 3: p ="Infinity"; break;
case 4: p ="QNaN"; break;
case 5: p ="SNaN"; break;
case 6: p ="Reserved Operand"; break;
default:p =" * * * "; break;
}
prtf(p);
return (ERROR);
}
|
C
|
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <time.h>
#include "../util.h"
const char *
datetime(void)
{
time_t timer;
struct tm* tm_info;
time(&timer);
tm_info = localtime(&timer);
strftime(buf, 25, " %d.%m.%Y %H:%M", tm_info);
return buf;
}
/*
const char *
datetime(const char *fmt)
{
time_t t;
t = time(NULL);
if (!strftime(buf, sizeof(buf), fmt, localtime(&t))) {
warn("strftime: Result string exceeds buffer size");
return NULL;
}
return buf;
}
*/
|
C
|
#ifndef DOUBLELIST_H
#define DOUBLELIST_H
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
struct node *next, *back;
void* info;
} DNODE;
void add(DNODE** head, int n, void* x);
void add_to_beginning(DNODE** head, void* x);
void add_to_end(DNODE** head, void* x);
void rem(DNODE** head, int n);
void remove_all(DNODE** head);
void sort(DNODE* head, int (*p)(void*, void*));
void sort_add(DNODE**, void*, int (*)(void*, void*));
DNODE* access(DNODE* head, int n);
DNODE* aloc(void*);
void swap_info(DNODE* a, DNODE* b);
void print_list(DNODE* head, void (*pr1)(void*));
void connect(DNODE* first, DNODE* second);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* strmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amontaut <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/09 15:25:54 by amontaut #+# #+# */
/* Updated: 2021/09/13 21:45:56 by amontaut ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/cub3d.h"
/*
** To isolate the map from our all_cub, we need to know
** where it starts. This fct gives us the i where the map
** starts in the all cub.
*/
void count_i(t_mlx *data, int *is_path, char *name)
{
if (ft_strlen(name) == 2)
{
if (data->all_cub[data->i] == name[0] && \
data->all_cub[data->i + 1] == name[1])
{
(*is_path) = 1;
while (data->all_cub[data->i] != '\n')
data->i++;
}
}
else if (ft_strlen(name) == 1)
{
if (data->all_cub[data->i] == name[0])
{
(*is_path) = 1;
while (data->all_cub[data->i] != '\n')
data->i++;
}
}
}
/*
** Calc the malloc to isolate the map and checks if a map
** is def and def in last.
*/
void calc_malloc_fill1(t_mlx *data, int *malloc_map)
{
data->start_map = data->tmp_start_map;
while (data->all_cub[data->start_map] == ' ' \
|| data->all_cub[data->start_map] == '\n')
data->start_map++;
data->tmp_start_map = data->start_map;
while (data->all_cub[data->start_map])
{
(*malloc_map)++;
data->start_map++;
}
if ((*malloc_map) == 0)
ft_error(data, "Error, no map def in the .cub file \
OR map not def in last");
while (data->all_cub[data->start_map] == ' ' \
|| data->all_cub[data->start_map] == '\n' \
|| data->all_cub[data->start_map] == '\0')
{
data->start_map--;
(*malloc_map)--;
}
}
/*
** Assigns the map (spaces have alredy been remplaced by 1)
** in a unique str str_map.
*/
void assign_map_fill1(t_mlx *data, int malloc_map)
{
data->i = 0;
data->str_map = (char *)(malloc((sizeof(char *) * malloc_map) + 1));
if (data->str_map == NULL)
ft_error(data, "malloc str_map failed");
while (data->tmp_start_map <= data->start_map)
{
data->str_map[data->i] = data->all_cub[data->tmp_start_map];
data->tmp_start_map++;
data->i++;
}
data->str_map[data->i] = '\0';
ft_memdel((void *)&data->all_cub);
}
/*
** Remplaces spaces by 1 in the map since it's up to
** us to handle the spaces as we like.
*/
void remp_space_by_1(t_mlx *data)
{
int error;
int totlen;
error = 0;
totlen = ft_strlen(data->all_cub);
data->tmp_start_map = data->start_map;
while (data->all_cub[totlen] != ' ' && data->all_cub[totlen] != '1')
totlen--;
while (data->all_cub[totlen] == '1')
totlen--;
while (data->all_cub[totlen] == ' ')
totlen--;
if (data->all_cub[totlen] == '\n' && (data->all_cub[totlen - 1] != '1'))
error = 1;
if (error == 1)
ft_error(data, "Error, incorrect bottom line");
while (data->all_cub[data->start_map])
{
if (data->all_cub[data->start_map] == ' ')
data->all_cub[data->start_map] = '1';
data->start_map++;
}
}
/*
** Launch fct to put the map in a seperated str, remplace spaces
** by 1, check if a map is def and def in last.
*/
void malloc_strmap_remp_1(t_mlx *data)
{
int is_c;
int is_f;
int malloc_map;
init_malloc_strmap_remp_1(data, &malloc_map, &is_c, &is_f);
while (data->all_cub[data->i] == ' ' || data->all_cub[data->i] == '\n')
data->i++;
while (data->all_cub[data->i])
{
count_i(data, &data->ino, "NO");
count_i(data, &data->iwe, "WE");
count_i(data, &data->iea, "EA");
count_i(data, &data->iso, "SO");
count_i(data, &is_c, "C");
count_i(data, &is_f, "F");
if (data->ino == 1 && data->iso == 1 && data->iea == 1 \
&& data->iwe == 1 && is_c == 1 && is_f == 1 \
&& data->start_map == 0)
data->start_map = data->i;
data->i++;
}
remp_space_by_1(data);
calc_malloc_fill1(data, &malloc_map);
assign_map_fill1(data, malloc_map);
}
|
C
|
#include <stdio.h>
void swap(char *a, char *b, int width){
char tmp;
while(width){
tmp = *a;
*a = *b;
*b = tmp;
a++;
b++;
width--;
}
}
int main(){
int a = 5;
int b = 10;
char str1[10] = "abcde";
char str2[10] = "xxx";
printf("a = %d b = %d\n", a, b);
printf("str1 = %s str2 = %s\n", str1, str2);
swap((char *)&a, (char *)&b, sizeof(int));
swap(str1, str2, sizeof(str1));
printf("a = %d b = %d\n", a, b);
printf("str1 = %s str2 = %s\n", str1, str2);
return 0;
}
|
C
|
#include <stdio.h>
int binary_search(int *arr, int low, int high, int search_num){
int mid;
if (low > high)
return -1;
mid = (high + low) / 2;
if (search_num == arr[mid])
return mid + 1;
if (search_num > arr[mid])
return binary_search(arr, mid + 1, high, search_num);
else
return binary_search(arr, low, mid - 1, search_num);
}
int main(int argc, char const *argv[])
{
int num[] = {1,2,3,4,5,6,7,8,9,10};
int search_num;
int pos;
int low = 0;
int high = (sizeof(num)/sizeof(num[0]));
printf("Enter the element to search for\n");
scanf("%d", &search_num);
pos = binary_search(num, low, high, search_num);
if (pos != -1)
printf("The number was found at position %d\n",pos);
printf("The number couldn't be found\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int *ptr = NULL;
int num = 0;
int i = 0;
while(num != -1)
{
printf("请输入一个数字: ");
scanf("%d",&num);
i++;
ptr = realloc(ptr,sizeof(int)*i);
if(ptr == NULL)exit(1);
ptr[i-1] = num;
}
if(num == -1)
{
for(int n = 0; n < i; n++)
{
printf("%d ",ptr[n]);
}
puts("");
}
free(ptr);
return 0;
}
|
C
|
#include <stdio.h>
int factorial(int n)
{
int i;
int fact = 1;
for (i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int enshu_2_1(int begin, int end){
if(begin>end){
return 0;
}
int i=begin;
while(i<end+1){
printf("%d! = %d\n",i,factorial(i));
i=i+1;
}
return end-begin +1;
}
int main(){
printf("%d",enshu_2_1(2,4));
return 0;
}
|
C
|
#include<stdio.h>
void inverted_triangle()
{
int n;
printf("enter value");
scanf("%d",&n);
//inverted 01
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
printf("01");
}
printf("\n");
}
}
void hollow_square()
{
int n;
printf("enter value");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i==1 || i==n || j==1 || j==n)
printf("*\t");
else
printf("\t");
}
printf("\n\n");
}
}
void hollow_rect()
{
int a,b;
printf("enter length and breadth with space");
scanf("%d %d",&a,&b);
for(int i=1;i<=a;i++)
{
for(int j=1;j<=b;j++)
{
if(i==1 || i==a || j==1 || j==b)
printf("*");
else
printf(" ");
}
printf("\n");
}
}
void pyramid()
{
int n,k=0;
scanf("%d",&n);
for(int i=1;i<=n;++i,k=0)
{
for(int j=0;j<=n-i;++j)
{
printf(" ");
}
while(k!=2*i-1)
{
printf("*");
++k;
}
printf("\n");
}
}
void main()
{
while(1)
{
printf("1) inverted 01 \n 2) hollow square \n 3) hollow rectangle \n 4) pyramid \n");
int ch;
printf("enter choice");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("inverted 01\n");
inverted_triangle();break;
case 2:printf("hollow square\n");
hollow_square();break;
case 3:printf("hollow rectangle\n");
hollow_rect();break;
case 4:printf("pyramid\n");
pyramid();break;
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main (){
int arr[]={100,200,300,400,500};
int *pointer=&arr;
int i;
for(i=0;i<5;i++){
printf("arr[%d]=%d\n",i,arr[i]);
}
//t@تܤ覡//
printf("\nt@تܤ覡\n");
for(i=0;i<5;i++){
printf("arr[%d]=%d\n",i,*(arr+i));
}
//ĤTتܤ覡//
printf("\nĤTتܤ覡\n");
for(i=0;i<5;i++){
printf("arr[%d]=%d\n",i,*((pointer)+i));
}
system("pause");
return 0;
}
|
C
|
#define _GNU_SOURCE
#define debug
#include <getopt.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "cachelab.h"
#define FILENAMELEN 40
#define TRACESIZE 30
#define check(s,c) (s[0]==c)
typedef struct{
int is_valid;
int tag;
int access_timestamp;
}line;
static int hits = 0;
static int misses = 0;
static int evictions = 0;
int power(int x, int y)
{
int temp = 0;
if(y == 0)
return 1;
temp = power(x, y/2);
if(y%2 == 0)
return temp*temp;
else
return x*temp*temp;
}
int main(int argc, char** argv)
{
extern char *optarg;
extern int optind;
int retval;
int num_sets = 0, num_lines = 0, num_blocks = 0;
char trace_file[FILENAMELEN];
line* cache = NULL;
FILE* fd = NULL;
char* trace_line = NULL;
size_t line_size, len = 0;
char* token = NULL;
unsigned long int address;
int bytes;
while((retval = getopt(argc, argv, "s:E:b:t:"))!= -1){
switch(retval){
case 's':
num_sets = atoi(optarg);
break;
case 'E':
num_lines = atoi(optarg);
break;
case 'b':
num_blocks = atoi(optarg);
break;
case 't':
strcpy(trace_file, optarg);
break;
}
}
#ifdef debug
printf("s=%d\tE=%d\tb=%d\ttrace_file=%s\n",num_sets,num_lines,num_blocks,\
trace_file);
#endif
cache = calloc( power(2, num_sets)*num_lines, sizeof(line));
#ifdef debug
printf("Cache allocated of size %d sets and %d lines. \
Block Size = %d Cache Pointer = %p \n",\
power(2, num_sets), num_lines, num_blocks, cache);
#endif
fd = fopen(trace_file, "r");
if(fd == NULL)
exit(EXIT_FAILURE);
while((line_size = getline(&trace_line, &len, fd)) != -1)
{
#ifdef debug
printf("Line: %s\n",trace_line);
#endif
if(check(trace_line,'I'))
continue;
token = strtok(trace_line," ");
switch(*token){
case 'L':
address = atol(strtok(NULL,","));
bytes = atoi(strtok(NULL,","));
#ifdef debug
printf("L:Address:%lu\tbytes:%d\n",address,bytes);
#endif
break;
case 'S':
address = atol(strtok(NULL,","));
bytes = atoi(strtok(NULL,","));
#ifdef debug
printf("S:Address:%lu\tbytes:%d\n",address,bytes);
#endif
break;
case 'M':
address = atol(strtok(NULL,","));
bytes = atoi(strtok(NULL,","));
#ifdef debug
printf("M:Address:%lu\tbytes:%d\n",address,bytes);
#endif
break;
}
}
printSummary(hits, misses, evictions);
free(cache);
return 0;
}
|
C
|
/*abdullah c
assign 3 prob 1
feb 10
*/
#include <stdio.h>
int main(void){
//variables
int howmany,i ;
float value,total=0;
//initial input
printf("Enter integers (first number is how many): ");
scanf("%d",&howmany);
//gets numbers in loop
for(i=1;i<=howmany;i++){
scanf("%f",&value);
total+=value;
}
//output
printf("\nSum is %.2f",total);
}
|
C
|
#ifndef MQTTCONF_H
#define MQTTCONF_H
#include <Arduino.h>
#include <ArduinoJson.h>
#include <tools.h>
#ifndef ESP32
#if filesystem==littlefs
#include <LittleFS.h>
#else
#include <FS.h>
#define SPIFFS_USE_MAGIC
#endif
#else
#include <FS.h>
#include <SPIFFS.h>
#define SPIFFS_USE_MAGIC
#endif
#define MQTT_SIZE 256
#define MQTT_FILE_NAME "/mqtt.json"
// global variables for MQTTClient
File mqttFile;
String mqttServer=".";
uint16_t mqttPort=1833;
String mqttPrefix=getESPDevName();
String mqttUser="";
String mqttPass="";
/**********************************************************************************************************
* Config File Helper Functions
***********************************************************************************************************/
void writeMqttConfig(String server=".",uint16_t port=1883,String prefix=getESPDevName(),String user="",String pass="")
{
DynamicJsonDocument mdoc(256);
#if defined ESP8266 && filesystem == littlefs
mqttFile=LittleFS.open(MQTT_FILE_NAME,"w");
#else
mqttFile=SPIFFS.open(MQTT_FILE_NAME,"w");
#endif
if(server.length()>1 )
{
mdoc["mqttServer"]=server;
mdoc["mqttPort"]=port;
mdoc["mqttPrefix"]=prefix;
mdoc["mqttUser"]=user;
mdoc["mqttPass"]=pass;
}
else
{
mdoc["mqttServer"]=".";
mdoc["mqttPort"]=1883;
mdoc["mqttPrefix"]=getESPDevName();
mdoc["mqttUser"]="";
mdoc["mqttPass"]="";
}
serializeJson(mdoc,mqttFile);
mqttFile.flush();
mqttFile.close();
}
/*************************************************************************************************************************
* Read MQTT Config from File
* ***********************************************************************************************************************/
void readMqttConfig()
{
DynamicJsonDocument mdoc(256);
Serial.println("Try to load MQTT-Config from file");
#if defined ESP8266 && filesystem == littlefs
mqttFile=LittleFS.open(MQTT_FILE_NAME,"r");
#else
mqttFile=SPIFFS.open(MQTT_FILE_NAME,"r");
#endif
DeserializationError err = deserializeJson(mdoc, mqttFile);
mqttFile.close();
if(err)
{
Serial.println("Unable to read Config Data (Json Error)");
Serial.println(err.c_str());
}
else
{
mqttServer= mdoc["mqttServer"].as<String>();
mqttPort=mdoc["mqttPort"].as<uint16_t>();
mqttPrefix=mdoc["mqttPrefix"].as<String>();
mqttUser=mdoc["mqttUser"].as<String>();
mqttPass=mdoc["mqttPass"].as<String>();
}
}
/*********************************************************************************************************************
* Check Mqtt Config File exists
* *******************************************************************************************************************/
void checkMqttConfig()
{
//check Config File is exists, or create one
#if defined ESP8266 && filesystem == littlefs
if(!LittleFS.exists(MQTT_FILE_NAME))
{
Serial.println("Try to create Config File");
writeMqttConfig("");
}
#else
if(!SPIFFS.exists(MQTT_FILE_NAME))
{
Serial.println("Try to create Config File");
writeMqttConfig("");
}
#endif
}
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "hpctimer.h"
#define TN 64 * 1024
#define PAGE_SIZE 4 * 1024
#define T_SIZE PAGE_SIZE/3
struct Foo
{
char arr[T_SIZE];
char arr1[T_SIZE];
char arr2[T_SIZE];
char arr3[T_SIZE];
char arr4[T_SIZE];
char arr5[T_SIZE];
};
int main(void)
{
int i, size;
struct Foo *Bar;
struct Foo *Bar1;
double t;
size = sizeof (struct Foo) * TN;
if ( (Bar = malloc(size)) == NULL) {
fprintf(stderr, "No enough memory\n");
exit(EXIT_FAILURE);
}
if ( (Bar1 = malloc(size)) == NULL) {
fprintf(stderr, "No enough memory\n");
exit(EXIT_FAILURE);
}
memset (Bar, 0 ,sizeof (struct Foo));
memset (Bar1, 0 ,sizeof (struct Foo));
t = hpctimer_getwtime();
int j;
for (i = 0; i < TN; i++)
{
for (j = 0; j < T_SIZE; j++)
{
Bar1[i].arr[j] = Bar[i].arr[j];
Bar1[i].arr1[j] = Bar[i].arr1[j];
Bar1[i].arr2[j] = Bar[i].arr2[j];
Bar1[i].arr3[j] = Bar[i].arr3[j];
Bar1[i].arr4[j] = Bar[i].arr4[j];
Bar1[i].arr5[j] = Bar[i].arr5[j];
}
}
t = hpctimer_getwtime() - t;
printf("T_SIZE: %d\nElapsed time (sec.): %.6f\n", T_SIZE, t);
free(Bar);
free(Bar1);
return 0;
}
|
C
|
#include "command.h"
#include "client.h"
#include "upload.h"
#include "download.h"
#include "select_cycle.h"
#include <unistd.h>
struct toy_select_cycle_s
{
fd_set rd_set;
fd_set wr_set;
fd_set excep_set;
int max_fd;
} toy_select_cycle_global;
void toy_selcycle_fdset_add_fd(int fd, enum FDSET_TYPE set_type)
{
if(set_type == FT_READ)
FD_SET(fd, &toy_select_cycle_global.rd_set);
else if(set_type == FT_WRITE)
FD_SET(fd, &toy_select_cycle_global.wr_set);
else
FD_SET(fd, &toy_select_cycle_global.excep_set);
if(fd > toy_select_cycle_global.max_fd)
toy_select_cycle_global.max_fd = fd;
// must judge if the number greater than FD_SETSIZE
}
void toy_selcycle_fdset_rm_fd(int fd, enum FDSET_TYPE set_type)
{
if(set_type == FT_READ)
FD_CLR(fd, &toy_select_cycle_global.rd_set);
else if(set_type == FT_WRITE)
FD_CLR(fd, &toy_select_cycle_global.wr_set);
else
FD_CLR(fd, &toy_select_cycle_global.excep_set);
}
int toy_selcycle_isset(int fd, enum FDSET_TYPE set_type)
{
if(set_type == FT_READ)
return FD_ISSET(fd, &toy_select_cycle_global.rd_set);
else if(set_type == FT_WRITE)
return FD_ISSET(fd, &toy_select_cycle_global.wr_set);
return FD_ISSET(fd, &toy_select_cycle_global.excep_set);
}
void toy_select_cycle()
{
FD_ZERO(&toy_select_cycle_global.rd_set);
FD_ZERO(&toy_select_cycle_global.wr_set);
toy_selcycle_fdset_add_fd(STDIN_FILENO, FT_READ);
fd_set rdset_tmp;
fd_set wrset_tmp;
int fd_ready;
struct toy_upload_s *uploads_array;
struct toy_download_s *downloads_array;
for(;;)
{
rdset_tmp = toy_select_cycle_global.rd_set;
wrset_tmp = toy_select_cycle_global.wr_set;
fd_ready = select(toy_select_cycle_global.max_fd + 1, &rdset_tmp, &wrset_tmp, 0, 0);
// never happened
if(fd_ready == 0)
{
}
else if( fd_ready == -1 )
{
// do something on select error
toy_warning("select error");
}
else
{
if(FD_ISSET(STDIN_FILENO, &rdset_tmp))
toy_cmd_handler();
if(FD_ISSET(toy_client_global.fd, &rdset_tmp))
toy_client_handler();
u_int i;
uploads_array = toy_upload_global_pool.uploads_array;
for(i = 0; i < toy_upload_global_pool.capacity; ++i)
{
if(uploads_array[i].used == 1)
{
if(FD_ISSET(uploads_array[i].fd, &rdset_tmp) || FD_ISSET(uploads_array[i].fd, &wrset_tmp))
toy_upload_handler(uploads_array + i);
}
}
downloads_array = toy_download_global_pool.downloads_array;
for(i = 0; i < toy_download_global_pool.capacity; ++i)
{
if(downloads_array[i].used == 1)
{
if(FD_ISSET(downloads_array[i].fd, &rdset_tmp) || FD_ISSET(downloads_array[i].fd, &wrset_tmp))
toy_download_handler(downloads_array + i);
}
}
}
}
}
|
C
|
#include"wordSystem.h"
#include<stdio.h>
#include<string.h>
int
wordSysPat()
{
printf("请选择登录的模式‘1’离线模式,‘2’在线模式:");
char answer[10];
while(1)
{
fscanf(stdin,"%s",answer);
if(!strcmp(answer,"1"))
{
system("clear");
wordSysLogin();
return 1;
}
else if(!strcmp(answer,"2"))
{
system("clear");
wordSqlLogin();
return 0;
}
else
printf("输入有误,请重新输入:");
}
}
|
C
|
//Multi-dimensional arrays in C
#include <stdio.h>
void main()
{
int a1[4];
int a2[2][3];
float a3[4][5][2];
char a4[1][2][3][4];
int ar[3][3][3];
int count = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
for (int k = 0; k < 3; ++k)
{
ar[i][j][k] = count++;
printf("a[%d][%d][%d] = %d\n", i, j, k, ar[i][j][k]);
}
}
|
C
|
/*
* sun_au.datatype by Fredrik Wikstrom
*
*/
#include "au_class.h"
#include "au_format.h"
#include "au_alaw.h"
static int16 decode_alaw (uint8 a_val);
static int16 decode_mulaw(uint8 u_val);
DEC_SETUPPROTO(SetupALAW) {
data->sample.size = 1;
data->block.size = data->sample.size * data->au.channels;
data->block.frames = 1;
return OK;
}
DECODERPROTO(DecodeALAW) {
int32 fr, ch;
for (fr = 0; fr < numFrames; fr++) {
for (ch = 0; ch < data->au.channels; ch++) {
*Dst[ch]++ = decode_alaw(*Src++) >> 8;
}
}
return frameIndex + numFrames;
}
DECODERPROTO(DecodeULAW) {
int32 fr, ch;
for (fr = 0; fr < numFrames; fr++) {
for (ch = 0; ch < data->au.channels; ch++) {
*Dst[ch]++ = decode_mulaw(*Src++) >> 8;
}
}
return frameIndex + numFrames;
}
#define SIGN_BIT (0x80) /* Sign bit for a A-law byte. */
#define QUANT_MASK (0xf) /* Quantization field mask. */
#define SEG_SHIFT (4) /* Left shift for segment number. */
#define SEG_MASK (0x70) /* Segment field mask. */
#define BIAS (0x84) /* Bias for linear code. */
static int16 decode_alaw (uint8 a_val) {
int16 t;
int16 seg;
a_val ^= 0x55;
t = (a_val & QUANT_MASK) << 4;
seg = ((unsigned)a_val & SEG_MASK) >> SEG_SHIFT;
switch (seg) {
case 0:
t += 8;
break;
case 1:
t += 0x108;
break;
default:
t += 0x108;
t <<= seg - 1;
}
return ((a_val & SIGN_BIT) ? t : -t);
}
static int16 decode_mulaw(uint8 u_val) {
int16 t;
/* Complement to obtain normal u-law value. */
u_val = ~u_val;
/*
* Extract and bias the quantization bits. Then
* shift up by the segment number and subtract out the bias.
*/
t = ((u_val & QUANT_MASK) << 3) + BIAS;
t <<= ((unsigned)u_val & SEG_MASK) >> SEG_SHIFT;
return ((u_val & SIGN_BIT) ? (BIAS - t) : (t - BIAS));
}
|
C
|
/***
void add_to_list( list* lista, int value);
list* ColumnSearch(column *Column,void* data);
***/
#include <stdlib.h>
#include <stdio.h>
#include "table.h"
#include "list.h"
#ifndef SEARCH
#define SEARCH
///
// DEFAULT -> used for search of not interesting stuff, looks for
// numbers in case of INT or REAL and PARTIAL on strings
// ABSOLUTE ->search for the exact string or value
// PARTIAL -> search of a piece of string
// CASE_SENSITIVE -> the search is case sensitive
// HISTORIC -> Search the historic records, always case sensitive
typedef enum{DEFAULT, ABSOLUTE,PARTIAL,CASE_SENSITIVE,HISTORIC}SearchTypes;
list* ColumnSearch(column *Column,void* data, SearchTypes WHAT);
#endif // SEARCH
|
C
|
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include "sish.h"
int last_cmd = 0;
int main(int argc, char*argv[]){
char buf[BUFSIZ];
last_cmd = 0;
int x_flag = 0, c_flag = 0;
char *query_string = NULL;
char *line = NULL;
line = (char *)malloc((size_t)BUFSIZ);
size_t size;
int len = 0;
char opt;
char *tokens[MAXTOKEN];
int tokens_num = 0;
signal(SIGINT, SIG_IGN);
memset(buf,'\0',BUFSIZ);
if(getcwd(buf, BUFSIZ) == NULL)
fprintf(stderr, "getcwd err,errno: %d\n",errno);
if(setenv("SHELL", buf, 1) == -1)
fprintf(stderr, "setenv err,errno: %d\n",errno);
while((opt = getopt(argc, argv, "xc:")) != -1){
switch(opt){
case 'x' :
x_flag = 1;
break;
case 'c' :
c_flag = 1;
query_string = optarg;
break;
case '?':
fprintf(stderr,"sish [ −x] [ −c command]\n");
exit(EXIT_STATUS);
}
}
if(c_flag){
query_string = replace(query_string, "<", " < ");
query_string = replace(query_string, "&", " & ");
query_string = replace(query_string, "|", " | ");
query_string = replace(query_string, ">>", " >> ");
query_string = add_space(query_string);
query_string = trim_string(query_string);
if(query_string == NULL){
fprintf(stderr, "parse err\n");
exit(EXIT_STATUS);
}
if ((tokens[0] = strtok(query_string, " \t\n")) == NULL) {
fprintf(stderr,"sish [ −x] [ −c command]\n");
exit(EXIT_STATUS);
}
tokens_num++;
while ((tokens[tokens_num] = strtok(NULL, " \t\n")) != NULL)
tokens_num++;
parse_tokens(tokens_num,tokens,x_flag);
}else{
while (1) {
printf("sish$ ");
tokens_num = 0;
line = NULL;
if ((len = getline(&line, &size, stdin)) == -1){
fprintf(stderr, "getline err\n");
continue;
}
line[len - 1] = '\0';
line = trim_string(line);
if(strlen(line) == 0)
continue;
if (strcmp(line, "exit") == 0){
if (x_flag)
fprintf(stderr,"+ exit\n");
if (last_cmd)
exit(127);
exit(EXIT_SUCCESS);
}
line = replace(line, "<", " < ");
line = replace(line, "&", " & ");
line = replace(line, "|", " | ");
line = replace(line, ">>", " >> ");
line = add_space(line);
line = trim_string(line);
if (line == NULL) {
last_cmd = 1;
fprintf(stderr, "read error");
continue;
}
if ((tokens[0] = strtok(line, " \t")) == NULL) {
fprintf(stderr,"sish: No tokens\n");
continue;
}
tokens_num++;
while ((tokens[tokens_num] = strtok(NULL, " \t")) != NULL)
tokens_num++;
parse_tokens(tokens_num,tokens,x_flag);
}
}
}
void exit_cmd(char *tokens[], int x_flag){
if (x_flag) {
int i = 0;
fprintf(stderr, "+ ");
while (tokens[i] != NULL) {
fprintf(stderr, "%s ",tokens[i]);
i++;
}
fprintf(stderr, "\n");
}
exit(EXIT_SUCCESS);
}
int cd_cmd(char *tokens[],int x_flag){
if (tokens[1] == NULL){
if(chdir(getenv("HOME")) == -1){
last_cmd = 1;
fprintf(stderr, "getenv error,errno: %d\n",errno);
return -1;
}
if (x_flag)
fprintf(stderr,"+ cd\n");
return 0;
}
if (x_flag) {
int i = 0;
fprintf(stderr,"+ ");
while (tokens[i] != NULL){
fprintf(stderr,"%s ",tokens[i]);
i++;
}
fprintf(stderr,"\n");
}
if (chdir(tokens[1]) < 0) {
fprintf(stderr,"cd: %s: No such file or directory\n",tokens[1]);
last_cmd = 1;
return -1;
}
return 0;
}
int echo_cmd(int tokens_num, char *tokens[], int x_flag){
int i = 0;
int fd;
int std_out;
if((std_out = dup(STDOUT_FILENO)) == -1){
last_cmd = 1;
close(std_out);
fprintf(stderr, "dup err,errno: %d\n",errno);
return -1;
}
if (x_flag) {
fprintf(stderr,"+ ");
for (int j = 0; j < tokens_num; j++)
fprintf(stderr,"%s ",tokens[j]);
fprintf(stderr,"\n");
}
while (tokens[i] != NULL) {
if (strcmp(">", tokens[i]) == 0){
if (tokens[i + 1] == NULL) {
fprintf(stderr,"syntax error near unexpected token `newline'\n");
last_cmd = 1;
return -1;
}
if((fd = open(tokens[i + 1], O_CREAT | O_TRUNC | O_WRONLY)) == -1){
fprintf(stderr,"sish: %s: Create file error\n",tokens[i + 1]);
last_cmd = 1;
return -1;
}
if (dup2(fd, STDOUT_FILENO) == -1){
last_cmd = 1;
close(fd);
fprintf(stderr, "dup2 err,errno: %d\n",errno);
return -1;
}
close(fd);
break;
}
if (strcmp(">>", tokens[i]) == 0){
if (tokens[i + 1] == NULL) {
fprintf(stderr,"syntax error near unexpected token `newline'\n");
last_cmd = 1;
return -1;
}
if((fd = open(tokens[i + 1], O_CREAT | O_APPEND | O_WRONLY, DFTPERMISSION)) == -1){
fprintf(stderr,"sish: %s: Create file error\n",tokens[i + 1]);
last_cmd = 1;
return -1;
}
if(dup2(fd, STDOUT_FILENO) == -1){
last_cmd = 1;
close(fd);
fprintf(stderr, "dup2 err,errno: %d\n",errno);
return -1;
}
close(fd);
break;
}
i++;
}
for (int j = 1; j < i; j++) {
if(strcmp("$$", tokens[j]) == 0)
printf("%d ",(int)getpid());
else if (strcmp("$?", tokens[j]) == 0)
printf("%d ",last_cmd);
else
printf("%s ",tokens[j]);
}
printf("\n");
last_cmd = 0;
if(dup2(std_out, STDOUT_FILENO) == -1){
last_cmd = 1;
close(std_out);
fprintf(stderr, "dup2 err,errno: %d\n",errno);
return -1;
}
return 0;
}
char *replace (const char *src, const char *old, const char *new) {
char *result = NULL;
int i, cnt = 0;
int new_len = strlen(new);
int old_len = strlen(old);
for (i = 0; src[i] != '\0'; i++) {
if (strstr(&src[i], old) == &src[i]) {
cnt++;
i += old_len - 1;
}
}
result = (char *)malloc(i + cnt * (new_len - old_len) + 1);
i = 0;
while (*src) {
if (strstr(src, old) == src) {
strcpy(&result[i], new);
i += new_len;
src += old_len;
}
else
result[i++] = *src++;
}
result[i] = '\0';
return result;
}
/* use strtok to solve > and >> */
char* add_space(const char *line){
char *result;
result = (char*)malloc((size_t)BUFSIZ);
int i = 0, j = 0;
while(i < BUFSIZ - 1 && line[i] != '\0' && j < BUFSIZ - 1){
if ((isspace(line[i]) !=0) || (isspace(line[i + 1]) != 0)) {
result[j++] = line[i++];
continue;
}
if(line[i] == '>'){
if (line[i + 1] == '>') {
result[j++] = line[i++];
result[j++] = line[i++];
}else {
result[j++] = line[i++];
result[j] = ' ';
j++;
}
continue;
}
if (line[i + 1] == '>') {
result[j++] = line[i++];
result[j] = ' ';
j++;
}else
result[j++] = line[i++];
}
result[BUFSIZ - 1] = '\0';
return result;
}
char* trim_string(const char *line){
char *result = NULL;
result = (char *)malloc((size_t)BUFSIZ);
strcpy(result,line);
char *end = NULL;
while (isspace(*result))
result++;
if (*result == 0)
return result;
end = result + strlen(result) - 1;
while (end > result && isspace(*end))
end--;
end[1] = '\0';
return result;
}
/*
out in out in out in out in out
cmd0 cmd1 cmd2 cmd3 ... ... cmdn
p_out p_in p_out p_in ...
n % 2 == 0 -> p_in to in p_out to out
*/
void pipe_exe(int tokens_num, char *tokens[], int x_flag){
int pipe_num = 0;
int temp, status;
int fd_out[2];
int fd_in[2];
pid_t pid;
for (int i = 0; i < tokens_num; i++) {
if (strcmp("|", tokens[i]) == 0){
if ((i - 1 == -1) || (tokens[i - 1] == NULL)) {
fprintf(stderr, "syntax error near unexpected token `|'\n");
last_cmd = 1;
return;
}
if (tokens[i + 1] == NULL) {
fprintf(stderr, "syntax error near unexpected token `|'\n");
last_cmd = 1;
return;
}
pipe_num++;
}
}
mycmd cmd[pipe_num + 1];
memset(cmd, 0, sizeof(cmd));
for (int i = 0, j = 0; i < pipe_num + 1; i++) {
temp = 0;
if (x_flag)
fprintf(stderr, "+ ");
for (; tokens[j] != NULL; j++) {
if(strcmp("|", tokens[j]) == 0){
j++;
break;
}
cmd[i].cmd_token[temp] = tokens[j];
if (x_flag)
fprintf(stderr, "%s ",tokens[j]);
temp++;
cmd[i].tk_len++;
}
if (x_flag)
fprintf(stderr, "\n");
}
for (int i = 0; i < pipe_num + 1; i++) {
if(i % 2 == 0)
pipe(fd_out);
else
pipe(fd_in);
if((pid = fork()) == -1){
last_cmd = 1;
if(i != pipe_num)
(i % 2 == 0) ? close(fd_out[1]) : close(fd_in[1]);
fprintf(stderr, "pipe fork error\n");
return;
}else if (pid > 0) {
if (i == 0)
close(fd_out[1]);
else if(i == pipe_num)
(i % 2 == 0) ? close(fd_out[0]) : close(fd_in[0]);
else {
if (i % 2 == 0) {
close(fd_out[0]);
close(fd_in[1]);
}else {
close(fd_out[1]);
close(fd_in[0]);
}
}
waitpid(pid, &status, 0);
if(WIFEXITED(status))
last_cmd = WEXITSTATUS(status);
else if (WIFSIGNALED(status))
last_cmd = 127;
}else if (pid == 0){
signal(SIGINT, SIG_DFL);
if(i == 0){
if (dup2(fd_out[1], STDOUT_FILENO) == -1) {
close(fd_out[1]);
fprintf(stderr, "pipe dup2 err\n");
kill(getpid(),SIGTERM);
}
}else if (i == pipe_num) {
if ((pipe_num + 1) % 2 == 0) {
if (dup2(fd_out[0], STDIN_FILENO) == -1){
close(fd_out[0]);
fprintf(stderr, "pipe dup2 err\n");
kill(getpid(),SIGTERM);
}
}else {
if(dup2(fd_in[0], STDIN_FILENO) == -1){
close(fd_in[0]);
fprintf(stderr, "pipe dup2 err\n");
kill(getpid(),SIGTERM);
}
}
}else if (i % 2 == 0) {
if(dup2(fd_out[1], STDOUT_FILENO) == -1){
close(fd_out[1]);
fprintf(stderr, "pipe dup2 err\n");
kill(getpid(),SIGTERM);
}
if(dup2(fd_in[0], STDIN_FILENO) == -1){
close(fd_in[0]);
fprintf(stderr, "pipe dup2 err\n");
kill(getpid(),SIGTERM);
}
}else {
if(dup2(fd_out[0], STDIN_FILENO) == -1){
close(fd_out[0]);
fprintf(stderr, "pipe dup2 err\n");
kill(getpid(),SIGTERM);
}
if(dup2(fd_in[1], STDOUT_FILENO) == -1){
close(fd_in[1]);
fprintf(stderr, "pipe dup2 err\n");
kill(getpid(),SIGTERM);
}
}
if (execvp(cmd[i].cmd_token[0], cmd[i].cmd_token) == -1) {
fprintf(stderr,"%s: command not found\n",cmd[i].cmd_token[0]);
kill(getpid(), SIGTERM);
}
}
}
}
int parse_tokens(int tokens_num,char *tokens[], int x_flag){
int i = 0,j = 0;
int temp;
int background = 0;
char *buf[MAXTOKEN];
memset(buf,0,sizeof(buf));
if (strcmp("exit", tokens[0]) == 0)
exit_cmd(tokens, x_flag);
if(strcmp("cd", tokens[0]) == 0)
return cd_cmd(tokens,x_flag);
if (strcmp("echo", tokens[0]) == 0)
return echo_cmd(tokens_num, tokens, x_flag);
while (tokens[j] != NULL) {
if (strcmp("|", tokens[j]) == 0){
pipe_exe(tokens_num, tokens, x_flag);
return 0;
}
j++;
}
if (strcmp("&", tokens[tokens_num - 1]) == 0)
background = 1;
while (tokens[i] != NULL) {
if((strcmp(">", tokens[i]) == 0) || (strcmp(">>", tokens[i]) == 0) ||
(strcmp("&", tokens[i]) == 0) || (strcmp("<", tokens[i]) == 0))
break;
buf[i] = tokens[i];
i++;
}
if (x_flag) {
int i = 0;
fprintf(stderr, "+ ");
while (tokens[i] != NULL){
fprintf(stderr,"%s ",tokens[i]);
i++;
}
fprintf(stderr,"\n");
}
while (tokens[i] != NULL) {
if(strcmp("&", tokens[i]) == 0)
background = 1;
if(strcmp("<", tokens[i]) == 0) {
temp = i + 1;
if (tokens[temp] == NULL) {
fprintf(stderr,"Expect input argv after <\n");
last_cmd = 1;
return -1;
}
if ((tokens[temp + 1] != NULL ) && (strcmp(">", tokens[temp + 1]) == 0)) {
if (tokens[temp + 2] == NULL) {
fprintf(stderr,"Expect output argv after >\n");
last_cmd = 1;
return -1;
}
red_exe(buf, tokens[temp], tokens[temp + 2], 0, background);
return 0;
}else if ((tokens[temp + 1] != NULL) && (strcmp(">>", tokens[temp + 1])) == 0){
if (tokens[temp + 2] == NULL) {
fprintf(stderr,"syntax error near unexpected token `newline'\n");
last_cmd = 1;
return -1;
}
red_exe(buf, tokens[temp], tokens[temp + 2], REDIRECTION_APPEND, background);
return 0;
}else{
red_exe(buf, tokens[temp], NULL, 0, background);
return 0;
}
}
if (strcmp(">", tokens[i]) == 0) {
temp = i + 1;
if (tokens[temp] == NULL) {
fprintf(stderr,"syntax error near unexpected token `newline'\n");
last_cmd = 1;
return -1;
}
red_exe(buf, NULL, tokens[temp], 0, background);
return 0;
}
if (strcmp(">>", tokens[i]) == 0) {
temp = i + 1;
if (tokens[temp] == NULL) {
fprintf(stderr,"syntax error near unexpected token `newline'\n");
last_cmd = 1;
return -1;
}
red_exe(buf, NULL, tokens[temp], REDIRECTION_APPEND, background);
return 0;
}
i++;
}
sim_exe(buf,background);
return 0;
}
void red_exe(char *cmd[], char *input, char *output, int append, int background){
int fd,status;
pid_t pid;
if ((pid = fork()) == -1) {
last_cmd = 1;
fprintf(stderr,"Redirection fork error\n");
return;
}
if (pid == 0) {
// if (background == 0)
signal(SIGINT, SIG_DFL);
if (input) {
if((fd = open(input, O_RDONLY)) == -1){
fprintf(stderr,"sish: %s: No such file or directory\n",input);
close(fd);
kill(getpid(), SIGTERM);
}
if(dup2(fd, STDIN_FILENO) == -1){
fprintf(stderr, "dup2 err,errno: %d\n",errno);
close(fd);
kill(getpid(), SIGTERM);
}
close(fd);
}
if (output) {
if (append) {
if((fd = open(output, O_CREAT | O_TRUNC | O_WRONLY, DFTPERMISSION)) == -1){
fprintf(stderr,"sish: %s: Create file error\n",output);
close(fd);
kill(getpid(), SIGTERM);
}
if(dup2(fd, STDOUT_FILENO) == -1){
fprintf(stderr, "dup2 err,errno: %d\n",errno);
close(fd);
kill(getpid(), SIGTERM);
}
close(fd);
}
if((fd = open(output, O_CREAT | O_APPEND | O_WRONLY, DFTPERMISSION)) == -1){
fprintf(stderr,"sish: %s: Create file error\n",output);
close(fd);
kill(getpid(), SIGTERM);
}
if(dup2(fd, STDOUT_FILENO) == -1){
fprintf(stderr, "dup2 err,errno: %d\n",errno);
close(fd);
kill(getpid(), SIGTERM);
}
close(fd);
}
if (execvp(cmd[0], cmd) == -1) {
fprintf(stderr,"%s: Command not found\n",cmd[0]);
kill(getpid(), SIGTERM);
}
}else {
if (background == 0) {
waitpid(pid, &status, 0);
if(WIFEXITED(status))
last_cmd = WEXITSTATUS(status);
else if (WIFSIGNALED(status))
last_cmd = EXIT_STATUS;
}else {
printf("Pid: %d\n",pid);
waitpid(pid, NULL, WNOHANG);
}
}
}
void sim_exe(char *cmd[], int background){
pid_t pid;
int status;
if ((pid = fork()) < 0) {
last_cmd = 1;
fprintf(stderr,"simple cmd fork error\n");
return;
}
if (pid == 0) {
// if (background == 0)
signal(SIGINT, SIG_DFL);
if (execvp(cmd[0], cmd) == -1) {
fprintf(stderr,"%s: command not found\n",cmd[0]);
kill(getpid(), SIGTERM);
}
}else {
if (background == 0) {
waitpid(pid, &status, 0);
if(WIFEXITED(status))
last_cmd = WEXITSTATUS(status);
else if (WIFSIGNALED(status))
last_cmd = EXIT_STATUS;
}else {
printf("Pid: %d\n",pid);
waitpid(pid, NULL, WNOHANG);
}
}
}
|
C
|
/*
** EPITECH PROJECT, 2019
** my_strlan.c
** File description:
** my_strlen.c
*/
#include "my.h"
int my_strlen(char const *str)
{
int i = 0;
if (!str)
return 84;
while (str[i] != '\0' && str[i] != '\n') {
i++;
}
return i;
}
int my_strlen_pipe(char const *str)
{
int i = 0;
if (!str)
return 84;
while (str[i] != '\0' && str[i] != '\n' && str[i] != '|') {
i++;
}
return i;
}
int my_strlen_comma(char const *str)
{
int i = 0;
if (!str)
return 84;
while (str[i] != '\0' && str[i] != '\n' && str[i] != ';') {
i++;
}
return i;
}
int my_strlen_egale(char const *str)
{
int i = 0;
if (!str)
return 84;
while (str[i] != '=') {
i++;
}
return i;
}
int my_strlen_env(char *str)
{
int i = 0;
if (!str)
return 84;
while (str[i] != '\n' && str[i] != '\0') {
i++;
}
return i;
}
|
C
|
/*
** EPITECH PROJECT, 2017
** my_printf
** File description:
** [email protected]
*/
#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
#include "my.h"
int flags1(int i, char *str, va_list ap);
int flags2(int i, char *str, va_list ap);
int flags3(int i, char *str, va_list ap);
void compile(va_list ap, int i, char *str)
{
while (str[i] != 0) {
flags1(i, str, ap);
if (str[i] == '%')
i++;
else
write(1, &str[i], sizeof(char));
i++;
}
}
int flags1(int i, char *str, va_list ap)
{
if (str[i] == '%') {
i++;
switch (str[i]) {
case 's':
my_putstr(va_arg(ap, char*));
break;
case 'S':
my_putstr_octal(va_arg(ap, char*));
break;
case 'd':
my_put_nbr(va_arg(ap, int));
break;
case 'b':
my_put_nbr_bin(va_arg(ap, unsigned int), "01");
break;
default:
flags2(i, str, ap);
}
}
}
int flags2(int i, char *str, va_list ap)
{
switch (str[i]) {
case 'i':
my_put_nbr(va_arg(ap, int));
break;
case 'c':
my_putchar((char) va_arg(ap, int));
break;
case '%':
my_putchar('%');
break;
case 'p':
my_put_nbr_hexa(va_arg(ap,
unsigned int),
"0123456789abcdef");
break;
default:
flags3(i, str, ap);
}
}
int flags3(int i, char *str, va_list ap)
{
switch (str[i]) {
case 'x':
my_put_nbr_base(va_arg(ap, int), "0123456789abcdef");
break;
case 'X':
my_put_nbr_base(va_arg(ap, long), "0123456789ABCDEF");
break;
case 'u':
my_put_nbrunsigned(va_arg(ap, unsigned int));
break;
case 'o':
my_put_nbr_base(va_arg(ap, long), "01234567");
break;
default:
write(1, "%", sizeof(char));
write(1, &str[i], sizeof(char));
}
}
int my_printf(char *str, ...)
{
int i = 0;
va_list ap;
va_start(ap, str);
compile(ap, i, str);
va_end(ap);
return 0;
}
int main(int ac, char **av)
{
char *name = NULL;
int age = 23;
int pct = 100;
int nom = 1;
char str[5]
;
strcpy(str, "toto");
str[1] = 6;
my_printf("%S\n", str);
// my_printf("%S", age);
my_putchar('\n');
printf("%o", age);
return 0;
}
|
C
|
/*
** my_subtract.c for bistromathique in /home/semana_r/rendu/Piscine_C_infinadd
**
** Made by romain semanaz
** Login <[email protected]>
**
** Started on Wed Oct 28 18:04:32 2015 romain semanaz
** Last update Sun Nov 1 22:50:56 2015 Yann Pichereau
*/
#include <stdlib.h>
#include "my.h"
#include "bistromathique.h"
void reorder_nb_sub(t_operation *sub)
{
t_number tmp;
if ((sub->nb1.end - sub->nb1.str) < (sub->nb2.end - sub->nb2.str))
{
tmp = sub->nb1;
sub->nb1 = sub->nb2;
sub->nb2 = tmp;
}
else if (((sub->nb1.end - sub->nb1.str) == (sub->nb2.end - sub->nb2.str)) &&
my_strcmp(sub->nb1.str, sub->nb2.str) < 0)
{
tmp = sub->nb1;
sub->nb1 = sub->nb2;
sub->nb2 = tmp;
}
}
int init_result_sub(t_operation *sub)
{
unsigned int len_alloc;
char *ptr;
len_alloc = ((sub->nb1.end) - (sub->nb1.str) + 1 + 1);
sub->result.str = malloc(sizeof(char) * len_alloc);
if (sub->result.str == NULL)
my_error_mal();
sub->result.end = sub->result.str + len_alloc - 2;
ptr = sub->result.str;
while (ptr <= (sub->result.end + 1))
{
*ptr = 0;
ptr += 1;
}
return (0);
}
void process_sub_nb1(t_operation *sub, int ret, char *ptr)
{
int sum;
while (sub->nb1.end >= sub->nb1.str)
{
if (*(sub->nb1.end) < ret)
{
sum = (*(sub->nb1.end) + 10 - ret);
*ptr = sum + '0';
ret = 1;
}
else
{
sum = (*(sub->nb1.end) - ret);
*ptr = sum + '0';
ret = 0;
}
ptr++;
sub->nb1.end--;
}
}
void process_sub_nb2(t_operation *sub)
{
int ret;
int sum;
char *ptr;
ptr = sub->result.str;
ret = 0;
while (sub->nb2.end >= sub->nb2.str)
{
if (*(sub->nb1.end) < (*(sub->nb2.end) + ret))
{
sum = ((*(sub->nb1.end) + 10) - (*(sub->nb2.end) + ret));
*ptr = sum + '0';
ret = 1;
}
else
{
sum = (*(sub->nb1.end) - (*(sub->nb2.end) + ret));
*ptr = sum + '0';
ret = 0;
}
ptr++;
sub->nb1.end--;
sub->nb2.end--;
}
process_sub_nb1(sub, ret, ptr);
}
char *my_sub(char *nb1, char *nb2)
{
t_operation sub;
char *end;
init_nb(&sub.nb1, nb1);
init_nb(&sub.nb2, nb2);
reorder_nb_sub(&sub);
init_result_sub(&sub);
process_sub_nb2(&sub);
end = sub.result.end;
while ((end > sub.result.str) && (*end == '0'))
{
*end = '\0';
end -= 1;
}
return (my_revstr(sub.result.str));
}
|
C
|
/* Shift Cipher by Barrientos, Monica */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
char* encryption();
char* decryption();
int main()
{
int choice;
char* encrypted;
char* decrypted;
do
{
printf("\nWelcome to Monoalphabetic Encryption and Decryption\n");
printf("\nMenu\n");
printf("1. Encrypt\n");
printf("2. Decrypt\n");
printf("3. Exit\n");
scanf("%d",&choice);
switch (choice)
{
case 1:
encrypted = encryption();
printf("\nEncrypted Text : %s", encrypted);
getch();
system("cls");
break;
case 2:
decrypted = decryption();
printf("\nDecrypted Text : %s", decrypted);
getch();
system("cls");
break;
case 3:
printf("Goodbye!\n");
break;
default:
printf("Wrong Choice. Enter again\n");
getch();
system("cls");
break;
}
} while (choice != 3);
return 0;
}
char* encryption(){ //(x+k)mod26
int x, key;
char message[256];
char *enc = malloc (sizeof (char) * 256);
printf("Enter Message to Encrypt: ");
fflush(stdin);
scanf ("%[^\n]%*c", message);
printf("Enter Key : ");
scanf("%d", &key);
for (x = 0; x < strlen(message); x++) {
if (message[x] >= 'a' && message[x] <= 'z') enc[x] = 'a' + (message[x] - 'a' + key) % 26;
else if (message[x] >= 'A' && message[x] <= 'Z') enc[x] = 'A' + (message[x] - 'A' + key) % 26;
else enc[x]= ' ';
}
enc[x]='\0';
return enc;
}
char* decryption(){ //(x-k)mod26
int x, key;
char message[256];
char *dec = malloc (sizeof (char) * 256);
printf("Enter Message to Decrypt: ");
fflush(stdin);
scanf ("%[^\n]%*c", message);
printf("Enter Key : ");
scanf("%d", &key);
for (x = 0; x < strlen(message); x++) {
if (message[x] >= 'a' && message[x] <= 'z') dec[x] = 'a' + (message[x] - 'a' - key +26) % 26;
else if (message[x] >= 'A' && message[x] <= 'Z') dec[x] = 'A' + (message[x] - 'A' - key+26) % 26;
else dec[x]= ' ';
}
dec[x]='\0';
return dec;
}
|
C
|
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <unistd.h>
int main() {
int s;
struct sockaddr_in server, client;
int c, l, i;
uint16_t k, old = 0;
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
printf("Eroare la crearea socketului server\n");
return 1;
}
memset(&server, 0, sizeof(server));
server.sin_port = htons(1345);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr *) &server, sizeof(server)) < 0) {
printf("Eroare la bind\n");
return 1;
}
l = sizeof(client);
memset(&client, 0, sizeof(client));
while(1){
sleep(0.5);
unsigned int number = 0;
old = 0;
for (i = 0; i < 2; i++) {
recvfrom(s, &k, sizeof(k), MSG_WAITALL, (struct sockaddr *) &client, &l);
k = ntohs(k);
// printf("Am primit: %hu la pasul %d\n", k, i+1);
if (k != old + 1){
number ++;
}
old = k;
}
printf("Gresite din 2: %f\n", (double)((2-number*1.0)/(2)));
}
close(s);
}
|
C
|
#ifndef DINO_STEAM_CONTROLLER_H
#define DINO_STEAM_CONTROLLER_H
#include <stdint.h>
#include <usbdrvce.h>
#include <stdbool.h>
enum {
SC_HAPTIC_RIGHT,
SC_HAPTIC_LEFT
};
typedef bool sc_haptic_t;
/**
* Gets the interface number to use for controlling haptic feedback
* @param dev USB device to check
* @return Interface number, or -1 if not a steam controller
*/
int8_t sc_GetInterface(usb_device_t dev);
/**
* Plays a tone on the Steam controller
* @param dev USB device
* @param interface Interface from \c sc_GetInterface
* @param haptic Which haptic feedback motor to use
* @param pulse_duration Duration of each pulse. Use \c sc_FrequencyToDuration
* @param repeat_count Number of times to repeat. Use \c sc_TimeToRepeatCount
*/
void sc_PlayTone(usb_device_t dev, uint8_t interface,
sc_haptic_t haptic, uint16_t pulse_duration,
uint16_t repeat_count);
/**
* Stops playing a tone on the Steam controller
* @param dev USB device
* @param interface Interface from \c sc_GetInterface
* @param haptic Which haptic feedback motor to stop
*/
void sc_StopTone(usb_device_t dev, uint8_t interface,
sc_haptic_t haptic);
#define STEAM_CONTROLLER_MAGIC_PERIOD_RATIO 495483
/**
* Converts a frequency to a pulse duration
* @param freq Frequency in hertz
* @return Pulse duration for use with sc_PlayTone
*/
#define sc_FrequencyToDuration(freq) ((uint16_t)(STEAM_CONTROLLER_MAGIC_PERIOD_RATIO / freq))
/**
* Converts a time and frequency to a repeat count
* @param ms Time in milliseconds
* @param freq Frequency in hertz
* @return Repeat count for use with sc_PlayTone
*/
#define sc_TimeToRepeatCount(ms, freq) ((uint16_t)((ms * freq) / 1000))
#endif //DINO_STEAM_CONTROLLER_H
|
C
|
#include "lists.h"
/**
* add_node_end - adds a new node at the end of a list_t list.
* @head: double pointer to a data structure.
* @str: pointer to a string.
*
* Return: the address of the new element, or NULL if it failed.
*/
list_t *add_node_end(list_t **head, const char *str)
{
list_t *newend;
int i;
list_t *temp = NULL;
newend = malloc(sizeof(list_t));
if (newend == NULL)
return (NULL);
newend->str = strdup(str);
for (i = 0; str[i] != '\0'; i++)
{}
newend->len = i;
if (*head == NULL)
{
*head = newend;
return (newend);
}
temp = *head;
for (i = 0; temp->next != NULL; i++)
{
temp = temp->next;
}
temp->next = newend;
return (newend);
}
|
C
|
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// TODO: Prompt for start size
int start;
do {
start = get_int("Start size: ");
}
while(start < 9);
// TODO: Prompt for end size
int ends;
do{
ends =get_int("End size:");
}
while(ends < start );
// TODO: Calculate number of years until we reach threshold
int year = 0;
while(start < ends)
{
start = start + (start/3) - (start/4);
year++;
}
// TODO: Print number of years
printf("Year:, %i\n", year);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct Person {
char name[30];
int* age;
} Person;
void print_person(Person* p) {
printf("%s: %d\n", p->name, *p->age);
}
int main() {
Person p;
strcpy(p.name, "safdas");
p.age = (int*)malloc(sizeof(int));
*p.age = 23;
Person p2 = p;
print_person(&p);
print_person(&p2);
*p.age = 24;
print_person(&p);
print_person(&p2);
Person p3;
strcpy(p3.name, p.name);
p3.age = (int*)malloc(sizeof(int));
*p3.age = *p.age;
*p3.age = 32;
print_person(&p);
print_person(&p3);
free(p.age);
free(p3.age);
return 0;
}
|
C
|
#include"my402list.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
/*
typedef struct data
{
char type[2];
unsigned long int timestamp;
unsigned long int amt;
char *desc;
//int num;
}data;
*/
//int My402ListTraverse(My402List*);
//void processfile(FILE *,My402List*);
//void ListDispTransac(My402List*);
//static void BubbleForward(My402List *, My402ListElem **, My402ListElem **);
//static void BubbleSortForwardList(My402List *pList, int num_items);
/*
int i=0;
int cnt;
printf("\nEnter the number of elements you want ");
scanf("%d",&cnt);
if(cnt!=0)
for(i=0;i<cnt;i++)
{
data *dataptr=(struct data *)malloc(sizeof(struct data));
printf("\nPlease Enter the element to be added to the list\n");
scanf("%d",&dataptr->num);
My402ListPrepend(list,&dataptr->num);
//My402ListAppend(list,&dataptr->num);
}
//My402ListTraverse(list);
My402ListElem *elem;
//First Element
elem=My402ListFirst(list);
if(elem!=NULL)
{
int *numptr;
numptr=(int *)elem->obj;
printf("\nThe first element is %d\n",*numptr);
}
//Last Element
elem=My402ListLast(list);
if(elem!=NULL)
{
int *numptr1;
numptr1=(int *)elem->obj;
if(*numptr1!=0)
printf("\nThe last element is %d\n",*numptr1);
}
//Length
int len=0;
len=My402ListLength(list);
printf("\nThe length of the list is %d\n",len);
//EMPTY LIST
int flag=0;
flag=My402ListEmpty(list);
if(flag==1)
printf("The List is empty..!!\n");
else
printf("The list is not empty..!!\n");
*/
//Find Element
/*
int srch=0;
printf("\nEnter the element to be searched");
scanf("%d",&srch);
int *srchptr;
srchptr=&srch;
elem=My402ListFind(list,&list->anchor.next);
if(elem!=NULL)
{
int *numptr2;
numptr2=(int *)elem->obj;
printf("\nThe element found is %d\n",*numptr2);
}
*/
/*
//UNLINK ALL
My402ListUnlinkAll(list);
printf("All elements deleted successfully...\n");
My402ListTraverse(list);
*/
/*
//Delete Specific
My402ListUnlink(list,list->anchor.next->next);
printf("\nThe second element has been deleted succesffully...\n");
My402ListTraverse(list);
*/
/*
//Insert After
int n=100;
My402ListInsertAfter(list,&n,list->anchor.next);
printf("\n 100 inserted after the 1st element....\n");
My402ListTraverse(list);
//Insert Before
n=100;
My402ListInsertBefore(list,&n,list->anchor.next);
printf("\n 100 inserted before the 1st element....\n");
My402ListTraverse(list);
*/
/*
return 0;
}
*/
int My402ListInit(My402List* list)
{
//list = malloc(sizeof(struct tagMy402List));
if(list)
{
list->num_members=0;
//My402ListElem* anchor=(struct tagMy402ListElem *)malloc(sizeof(struct tagMy402ListElem));
//if(anchor)
//{
//list->anchor=*anchor;
list->anchor.next=&(list->anchor);
list->anchor.prev=&(list->anchor);
list->anchor.obj=NULL;
//printf("Init successful\n");
//}
//else
// return FALSE;
}
else
return FALSE;
return TRUE;
}
//Original works for prepend
/*
int My402ListTraverse(My402List* list)
{
My402ListElem *elem=NULL;
int i=0;
for(elem=list->anchor.next;i<5; elem=elem->next)
{
i++;
int *data=NULL;
data=(int *)elem->obj;
printf("%d -> \t",*data);
}
return TRUE;
}
*/
/*
int My402ListTraverse(My402List* list)
{
My402ListElem *elem=NULL;
//int i=0;
for(elem=My402ListFirst(list);elem!=NULL; elem=My402ListNext(list,elem))
{
//i++;
int *data=NULL;
data=(int *)elem->obj;
printf("%d -> \t",*data);
}
return TRUE;
}
*/
/*
int My402ListLength(My402List* list)
{
int len=0;
My402ListElem *elem=NULL;
for (elem=My402ListFirst(list);elem != NULL;elem=My402ListNext(list, elem))
{
len++;
Foo *foo=(Foo*)(elem->obj);
}
return len;
}
*/
My402ListElem *My402ListFirst(My402List* list)
{
My402ListElem *elem=NULL;
if(list->anchor.next==&list->anchor)
return NULL;
else
{
elem=list->anchor.next;
return elem;
}
}
My402ListElem *My402ListLast(My402List* list)
{
My402ListElem *elem=NULL;
if(list->anchor.prev==&list->anchor)
return NULL;
else
{
elem=list->anchor.prev;
return elem;
}
}
int My402ListLength(My402List* list)
{
return list->num_members;
}
int My402ListEmpty(My402List* list)
{
if(list->anchor.next==&list->anchor && list->anchor.prev==&list->anchor)
return TRUE;
else
return FALSE;
}
int My402ListPrepend(My402List* list, void* obj)
{
My402ListElem *elem=(struct tagMy402ListElem *)malloc(sizeof(struct tagMy402ListElem));
if(list->anchor.next==NULL)
{
list->anchor.next=elem;
list->anchor.prev=elem;
elem->next=&list->anchor;
elem->prev=&list->anchor;
elem->obj=obj;
}
else
{
//list->anchor.next=elem;
My402ListElem *elem1;
elem1=list->anchor.next;
elem->next=elem1;
elem->prev=&list->anchor;
elem->obj=obj;
list->anchor.next=elem;
elem1->prev=elem;
}
list->num_members++;
return TRUE;
}
int My402ListAppend(My402List* list, void* obj)
{
My402ListElem *elem=(struct tagMy402ListElem *)malloc(sizeof(struct tagMy402ListElem));
if(list->anchor.prev==NULL)
{
list->anchor.prev=elem;
list->anchor.next=elem;
elem->next=&list->anchor;
elem->prev=&list->anchor;
elem->obj=obj;
}
else
{
My402ListElem *elem1=list->anchor.prev;
elem->prev=elem1;
elem->next=&list->anchor;
elem->obj=obj;
list->anchor.prev=elem;
elem1->next=elem;
}
list->num_members++;
return TRUE;
}
My402ListElem *My402ListNext(My402List* list, My402ListElem* elem)
{
if(elem->next != &list->anchor)
return elem->next;
else
return NULL;
}
My402ListElem *My402ListPrev(My402List* list, My402ListElem* elem)
{
if(elem->prev != &list->anchor)
return elem->prev;
else
return NULL;
}
My402ListElem *My402ListFind(My402List* list, void* obj)
{
int flag=0;
My402ListElem *elem=NULL;
for(elem=My402ListFirst(list);elem!=NULL; elem=My402ListNext(list,elem))
{
if(elem->obj==obj)
{
flag=1;
break;
}
}
if(flag==1)
return elem;
else
return NULL;
}
void My402ListUnlinkAll(My402List* list)
{
My402ListElem *elem=NULL;
My402ListElem *elem1=NULL;
elem=My402ListFirst(list);
while(elem!=NULL)
{
elem1=My402ListNext(list,elem);
free(elem);
elem=elem1;
}
list->anchor.next=NULL;
list->anchor.prev=NULL;
list->num_members=0;
}
void My402ListUnlink(My402List* list, My402ListElem* elem)
{
//My402ListElem *cur=NULL;
My402ListElem *prev=NULL;
//cur=My402ListFirst(list);
//while(cur!=elem)
// cur=My402ListNext(list,cur);
prev=elem->prev;
prev->next=elem->next;
elem->next->prev=prev;
list->num_members--;
free(elem);
}
int My402ListInsertAfter(My402List* list, void* obj, My402ListElem* elem)
{
My402ListElem *cur=(struct tagMy402ListElem *)malloc(sizeof(struct tagMy402ListElem));
if(elem==NULL)
{
My402ListAppend(list,obj);
return TRUE;
}
else
{
cur->next=elem->next;
cur->prev=elem;
cur->obj=obj;
elem->next->prev=cur;
elem->next=cur;
list->num_members++;
return TRUE;
}
return FALSE;
}
int My402ListInsertBefore(My402List* list, void* obj, My402ListElem* elem)
{
My402ListElem *cur=(struct tagMy402ListElem *)malloc(sizeof(struct tagMy402ListElem));
if(elem==NULL)
{
My402ListPrepend(list,obj);
return TRUE;
}
else
{
cur->next=elem;
cur->prev=elem->prev;
cur->obj=obj;
elem->prev->next=cur;
elem->prev=cur;
list->num_members++;
return TRUE;
}
return FALSE;
}
|
C
|
#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
int pipefd[2];
char* str = "hello\n";
char buf[200];
int ret;
pipe(pipefd);
ret = fork();
assert(ret >= 0);
if (ret == 0) {
close(pipefd[0]); /*for read*/
write(pipefd[1], str, strlen(str) + 1);
} else {
close(pipefd[1]);
read(pipefd[0], buf, 200);
printf("child: %s", buf);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <limits.h>
int dp[101][101];
int chain_mul(int arr[],int i,int j)
{
if(i==j)
return 0;
if(dp[i][j]!=-1)
return dp[i][j];
dp[i][j]=INT_MAX;
int k;
for(k=i;k<j;k++)
{
int curr=chain_mul(arr,i,k)+chain_mul(arr,k+1,j)+(arr[i-1]*arr[k]*arr[j]);
dp[i][j]=dp[i][j]<curr?dp[i][j]:curr;
}
return dp[i][j];
}
int main()
{
int n,i;
memset(dp,-1,sizeof(dp));
printf("Enter size of dimension array:");
scanf("%d",&n);
int arr[n];
printf("Array:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Minimum number of multiplications is :%d",chain_mul(arr,1,n-1));
return 0;
}
|
C
|
#include <stdio.h>
// define some constants
#define LOWER 0
#define UPPER 300
#define STEP 20
#define NAME "Alexander"
main()
{
int c;
long fahr;
double nc;
/** Print Fahrenheit-Celsious table
Conversion: C = (F-32)*5/9
*/
printf("Fahrenheit-Celsius table\n");
for (fahr = LOWER; fahr <= UPPER; fahr += STEP)
// ld is long d (use "d" for integer)
printf("%3ld %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
/** A parrot program:
Repeat what you says
*/
printf("\n** Parrot talks **\n");
printf("(Say something, Ctrl-D or EOF to stop)\n");
while ((c = getchar()) != EOF) // Assignment expr returns the lhs' value
{
putchar(c);
printf("%c", c);
}
/** Count number of input characters
*/
printf("\nMy name is %s\nYour name is: ", NAME);
for (nc = 0; getchar() != EOF; ++nc)
;
printf("Your name has %.0f characters\n", nc);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "numeric.h"
/*newtonRhapson function starts*/
void newtonRhapson(void){
/*Variable declarations
*@degree: Maximum exponent of variable
*@iteration: Iteration number
*@xZero: Starting value
*@xNew: x0 + deltax value
*@epsilon: Tolerance. Equals difference between last x values
*@fxZero: f(x0)
*@fdxZero: f'(x0)
*@ *array: Coefficient array's pointer
*/
int degree, i, iteration=1;
double xZero, xNew, epsilon, fxZero, fdxZero, *array;
double DX = 0.001;
system("clear");
printf("Sayisal Analiz Kok Bulma Yontemleri Newton Rhapson Metodu");
printf("\nOndalikli sayi girerken nokta isareti kullaniniz\n");
/*Read equation degree*/
do{
printf("\nLutfen polinomunuzun derecesini giriniz: ");
scanf("%d", °ree);
}while(degree <= 0);
/*Memory allocation for coefficient array*/
array = (double*) malloc( (degree+1) * sizeof(double) );
/*Error handling*/
if(array == NULL){
printf("\nHata! Bellek ayrilamadi\n");
exit(0);
}
/*Read coefficient array*/
for(i=degree; i>=0; i--){
printf("\nx^%d teriminin katsayisini isaretli olarak giriniz: ", i);
scanf("%lf", (array+i));
}
/*Read X0*/
printf("\nLutfen ilk x degerini giriniz(x0):\t");
scanf("%lf", &xZero);
/*Read epsilon value*/
do{
printf("\nLutfen epsilon degerini giriniz:\t");
scanf("%lf", &epsilon);
}while(epsilon == 0);
/*Read DX value*/
do{
printf("\nLutfen turev alma esnasinda kullanilan artirim miktari dx i giriniz: ");
scanf("%lf", &DX);
}while(DX <= 0);
/*Compute x values
*Difference between consecutive x values equals
*absolute value of fx0/fdx0
*Loop goes until it is smaller than tolerance value
*/
do{
/*Compute f(x0) and f'(x0)
*fx0: f(x0)
*fdx0: f derivative x: f'(x0)
*fx: Calling function y=f(x)
*/
fxZero = fx(array, degree, xZero);
/*Numerical derivative*/
fdxZero = fx(array, degree, xZero+DX) - fx(array, degree, xZero-DX);
fdxZero /= (2*DX);
/*X(i+1) = X(i) - ( f(Xi) / f'(Xi) )*/
xNew = xZero - (fxZero / fdxZero);
/*Print values*/
printf("\nXi: %lf\n", xZero);
printf("f(Xi): %lf\n", fxZero);
printf("f'(Xi): %lf\n", fdxZero);
printf("Xi+1: %lf\n", xNew);
printf("\n--- %d -inci iterasyon sonlandi ---\n", iteration);
iteration++;
xZero = xNew;
}while( fabs(fxZero/fdxZero) > epsilon );
/*Print root value 5 decimal point*/
printf("\nKok: %.5lf", xZero);
free(array);
}/*newtonRhapson function ends*/
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <math.h>
int count_letters();
int count_sentences();
int count_words();
double calc_readability();
int main(void)
{
//string phrase = get_string("Text: ");
string phrase = "";
double letters = count_letters(phrase);
//printf("Number of letters: %f\n\n", letters);
double sentances = count_sentences(phrase);
//printf("Number of Sentances: %f\n", sentances);
double words = count_words(phrase);
//printf("Number of words: %f\n", words);
double col_index = (calc_readability(letters, words, sentances));
if (col_index >= 16)
{
printf("Grade 16+\n");
}
else if (col_index < 1)
{
printf("Before Grade 1\n");
}
else
{
printf("Grade %.0f\n", col_index);
}
}
int count_letters(string in_phrase)
{
int counter = 0;
for (size_t i = 0; in_phrase[i] != '\0'; i++)
{
if (isalpha(in_phrase[i]))
{
counter++;
//printf("%c", in_phrase[i]);
}
}
//printf("\n");
return counter;
}
int count_sentences(string in_phrase)
{
int counter = 0;
for (size_t i = 0; in_phrase[i] != '\0'; i++)
{
if (in_phrase[i] == '.' || in_phrase[i] == '?' || in_phrase[i] == '!')
{
counter++;
//printf("%c", in_phrase[i]);
}
}
//printf("\n");
return counter;
}
int count_words(string in_phrase)
{
int counter = 0;
for (size_t i = 0; in_phrase[i] != '\0'; i++)
{
if (in_phrase[i] == ' ')
{
counter++;
//printf("%c", in_phrase[i]);
}
}
//printf("\n");
return counter + 1;
}
double calc_readability(double letters, double words, double sentences)
{
//printf("L: %f\n", letters);
//printf("W: %f\n", words);
//printf("S: %f\n", sentences);
double l = letters / words * 100.0;
//printf("l: %f\n", l);
double s = sentences / words * 100.0;
//printf("s: %f\n", s);
double index = (0.0588 * l) - (0.296 * s) - 15.8;
//printf("index: %f\n", index);
return index;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
char* solution(int a, int b) {
int SumODays, i;
SumODays = 0;
int dateArr[12] = {31,29,31,30,31,30,31,31,30,31,30,31};
char* dayArr[7] = {"FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"};
char* answer;
// 리턴할 값은 메모리를 동적 할당해주세요.
for(i = 0; i < a;i++){
SumODays += dateArr[i];
}
SumODays += b;
SumODays -= 1;
answer = (char*)malloc(10);
strcpy(answer, dayArr[SumODays%7]);
return answer;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tools_env.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: basle-qu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/10/14 17:05:36 by basle-qu #+# #+# */
/* Updated: 2016/02/26 17:25:09 by basle-qu ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "env.h"
#include "ft_minishell1.h"
t_env *ft_add_link(t_env *e, char *s1, char *s2)
{
t_env *new;
t_env *tmp;
new = malloc(sizeof(t_env));
new->name = ft_strdup(s1);
if (s2)
new->value = ft_strdup(s2);
else
new->value = NULL;
new->next = NULL;
tmp = e;
if (e == NULL)
return (new);
else
{
while (tmp->next)
tmp = tmp->next;
tmp->next = new;
return (e);
}
}
void ft_print_env(t_env *env)
{
t_env *tmp;
tmp = env;
while (tmp)
{
ft_putstr(tmp->name);
ft_putchar('=');
if (tmp->value)
ft_putstr(tmp->value);
ft_putchar('\n');
tmp = tmp->next;
}
}
int char_in_tab(char **tab, char c)
{
int i;
i = 0;
while (tab[i])
{
if (ft_strchr(tab[i], c))
return (1);
i++;
}
return (0);
}
int find_list(char *str, t_env *e)
{
int i;
t_env *tmp;
i = 0;
tmp = e;
while (tmp)
{
if (!ft_strcmp(tmp->name, str))
return (i);
i++;
tmp = tmp->next;
}
return (0);
}
t_env *var_del(t_env *e, char *name, int n)
{
int i;
t_env *tmp;
i = 1;
tmp = e;
while (name && i < n)
{
tmp = tmp->next;
i++;
}
if (tmp->next)
{
free(tmp->next->name);
free(tmp->next->value);
free(tmp->next);
if (tmp->next->next)
tmp->next = tmp->next->next;
else
tmp->next = NULL;
}
return (e);
}
|
C
|
#include "ft_door.h"
#include <unistd.h>
#include <stdlib.h>
void ft_putstr(char *str)
{
int i;
i = 0;
while (str[i])
{
write(1, &str[i], 1);
i++;
}
}
void ft_close_door(t_door *door)
{
ft_putstr("Door closing...");
door->state = CLOSE;
return;
}
t_bool is_door_open(t_door *door)
{
ft_putstr("Is door open ?");
return (door->state == OPEN);
}
t_bool is_door_close(t_door *door)
{
ft_putstr("Is door close ?");
return (door->state == CLOSE);
}
int main(void)
{
t_door *door;
door = malloc(sizeof(t_door));
door->state = OPEN;
is_door_open(door);
is_door_close(door);
ft_close_door(door);
is_door_open(door);
is_door_close(door);
}
|
C
|
// list.c
#include "list.h"
#include <stdlib.h>
ListNode * ListNode_create(TreeNode * tn)
{
ListNode * ln = malloc(sizeof(ListNode));
ln -> next = NULL;
ln -> tnptr = tn;
return ln;
}
// head may be NULL
// ln must not be NULL
// ln -> next must be NULL
ListNode * List_insert(ListNode * head, ListNode * ln,
int mode)
{
if (ln == NULL)
{
printf("ERROR! ln is NULL\n");
return NULL;
}
if ((ln -> next) != NULL)
{
printf("ERROR! ln -> next is not NULL\n");
}
if (head == NULL)
{
return ln;
}
if (mode == STACK)
{
ln -> next = head;
return ln;
}
if (mode == QUEUE)
{
head -> next = List_insert(head -> next, ln, mode);
return head;
}
// insert in increasing order
int freq1 = (head -> tnptr) -> freq;
int freq2 = (ln -> tnptr) -> freq;
if (freq1 > freq2)
{
// ln should be the first node
ln -> next = head;
return ln;
}
// ln should be after head
head -> next = List_insert(head -> next, ln, mode);
return head;
}
// frequencies must be sorted
ListNode * List_build(CharFreq * frequencies)
{
// find the first index whose frequency is nonzero
int ind = 0;
while (frequencies[ind].freq == 0)
{
ind ++;
}
if (ind == NUMLETTER)
{
// no letter appears
return NULL;
}
// create a linked list, each node points to a tree node
ListNode * head = NULL;
while (ind < NUMLETTER)
{
TreeNode * tn =
TreeNode_create(frequencies[ind].value,
frequencies[ind].freq);
ListNode * ln = ListNode_create(tn);
head = List_insert(head, ln, SORTED);
ind ++;
}
return head;
}
void List_print(ListNode * head)
{
if (head == NULL)
{
return;
}
Tree_print(head -> tnptr, 0);
List_print(head -> next);
}
|
C
|
#ifndef factorial_function
#define factorial_function
int factorial(int a)
{
int result =1;
// printf("funtion %d\n",a);
if (a>1)
{
result=a*factorial(a-1);
}
return result;
}
#endif
|
C
|
/*******************************************************************************
* mb_motors.c
*
* Control up to 2 DC motordrivers
*
*******************************************************************************/
#include "mb_motors.h"
// global initialized flag
int mb_motors_initialized = 0;
/*******************************************************************************
* int mb_initialize_motors()
*
* set up gpio assignments, pwm channels, and make sure motors are left off.
* GPIO exporting must be done previously with simple_init_gpio()
* initialized motors should start disabled
*******************************************************************************/
int mb_initialize_motors(){
//#ifdef DEBUG
printf("Initializing: PWM\n");
//#endif
if(rc_pwm_init(1,DEFAULT_PWM_FREQ)){
printf("ERROR: failed to initialize hrpwm1\n");
return -1;
}
if(rc_pwm_init(2,DEFAULT_PWM_FREQ)){
printf("ERROR: failed to initialize hrpwm2\n");
return -1;
}
mb_motors_initialized = 1;
//#ifdef DEBUG
printf("motors initialized...\n");
//#endif
mb_disable_motors();
return 0;
}
/*******************************************************************************
* mb_enable_motors()
*
* turns on the standby pin to enable the h-bridge ICs
* returns 0 on success, -1 on failure
*******************************************************************************/
int mb_enable_motors(){
if(mb_motors_initialized==0){
printf("ERROR: trying to enable motors before they have been initialized\n");
return -1;
}
//_set_motor_free_spin_all();
rc_gpio_set_value_mmap(MOT_EN , 0);
return 0;
}
/*******************************************************************************
* int mb_disable_motors()
*
* disables PWM output signals and
* turns off the enable pin to disable the h-bridge ICs
* returns 0 on success
*******************************************************************************/
int mb_disable_motors(){
if(mb_motors_initialized==0){
printf("ERROR: trying to disable motors before they have been initialized\n");
return -1;
}
rc_gpio_set_value_mmap((MOT_EN) , 1);
//rc_gpio_set_value_mmap((MDIR1) , 1);
//rc_gpio_set_value_mmap((MDIR2) , 1);
return 0;
}
/*******************************************************************************
* int mb_set_motor(int motor, float duty)
*
* set a motor direction and power
* motor is from 1 to 2, duty is from -1.0 to +1.0
* returns 0 on success
*******************************************************************************/
int mb_set_motor(int motor, float duty){
if(mb_motors_initialized==0){
printf("ERROR: trying to rc_set_motor_all before they have been initialized\n");
return -1;
}
int direction = 1;
//rc_pwm_init(1,DEFAULT_PWM_FREQ);
//rc_pwm_init(2,DEFAULT_PWM_FREQ);
//printf("set motors\n");
if(duty < 0)
{
duty = fabs(duty);
direction = -1;
}
if(motor == 1)
{
//printf("motor1 duty: %f\n",duty);
direction = direction * MOT_1_POL;
if(direction == -1){
direction = 0;
}
rc_gpio_set_value_mmap(MDIR1, direction);
rc_pwm_set_duty_mmap(1, 'A', duty);
}
if(motor == 2)
{
//printf("motor2 duty %f\n",duty);
direction = direction * MOT_2_POL;
if(direction == -1){
direction = 0;
}
rc_gpio_set_value_mmap(MDIR2, direction);
rc_pwm_set_duty_mmap(1, 'B', duty);
}
return 0;
}
/*******************************************************************************
* int mb_set_motor_all(float duty)
*
* applies the same duty cycle argument to both motors
*******************************************************************************/
int mb_set_motor_all(float duty){
if(mb_motors_initialized==0){
printf("ERROR: trying to rc_set_motor_all before they have been initialized\n");
return -1;
}
mb_set_motor(LEFT_MOTOR, duty);
mb_set_motor(RIGHT_MOTOR, duty);
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/mman.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define PAGE_SIZE 4096
int main()
{
printf("%d\n", PAGE_SIZE);
int fd;
fd = open("test2.txt",O_RDWR | O_APPEND);
printf("%d\n", fd);
char* ptr1 = NULL;
ptr1 = (char*) mmap(0, 4096, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_SHARED, fd, 0);
if(ptr1 == MAP_FAILED || ptr1 == NULL)
{
perror("Erorr while mapping memory\n");
return -2;
}
int i = 0;
while(i != 20)
{
ptr1[i] = 'Y';
++i;
}
i = 0;
while(i != PAGE_SIZE)
{
putchar(ptr1[i]);
++i;
}
munmap(ptr1, PAGE_SIZE);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
static double getDistance(double x1, double y1, double x2, double y2)
{
return(sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)));
}
int main()
{
double x1 = 0.0;
double y1 = 0.0;
double x2 = 4.0;
double y2 = 3.0;
double distance = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
printf("Distance from: (%f, %f) to: (%f, %f) is: %f\n", x1, y1, x2, y2, distance);
double xDelta = (x2 - x1);
double yDelta = (y2 - y1);
distance = sqrt(xDelta * xDelta + yDelta * yDelta);
printf("Distance from: (%f, %f) to: (%f, %f) is: %f\n", x1, y1, x2, y2, distance);
printf("Distance from: (%f, %f) to: (%f, %f) is: %f\n", x1, y1, x2, y2, getDistance(x1, y1, x2, y2));
return(0);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct CARD {
char *face;
char *suit;
}card;
int main()
{
card acard;
card *cardPtr;
cardPtr = &acard;
acard.face = "Ace";
acard.suit = "Spades";
cardPtr = &acard;
printf("%s %s %s\n%s %s %s\n%s %s %s\n",acard.face,"of",acard.suit,cardPtr->face,"of",cardPtr->suit,(*cardPtr).face,"of",(*cardPtr).suit);
system("pause");
}
|
C
|
//David Krampert
//
//
//
//
///////////////////////////////////////////////////////////////////////////////
// Includes -------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//Main Function
int main(int args, const char* argv[])
{
//Welcome message
printf("\n");
printf("===========================================\n");
printf("Welcome to myShell. A program wrtten by me\n");
printf("===========================================\n");
printf("\n");
printf("\n");
//delcare variables------------------------------------------------------------
//alocating space for cwd_buf
char cwd_buf[500];
//size should be the size of whatever element that is being used in the call
size_t size = sizeof(char);
//to hold user input
char* userInput = (char*)malloc(sizeof(char) * 100);
//boolean to exit the program when "exit" is entered
int exit_bool = 1; //1 = false, 0 = true
//parent process: child's exit status
int status;
//variable to store the child's pid
pid_t child_pid;
char *input_arr[100];
const char delim[2] = " ";
//------------------------------------------------------------------------------
while( exit_bool == 1 )
{
getcwd(cwd_buf, 500);//gets pathname of current working directory
printf("%s ? ", cwd_buf);//prints the current workinng directory
scanf("%[^\n]%*c", userInput);//gets input from user
//tokenize the user input command into directive
char* directive;
directive = strtok(userInput, delim);
int i = 0;
while(directive != NULL)
{
//loads the tokenized input stored in "directive" into the input_arr array
input_arr[i] = directive;
directive = strtok(NULL, delim);
i++;
}
//Do commands--------------------------------------------------------------
//if the user enters "exit" the program will stop
if( strcmp((input_arr[0]), "exit") == 0 )
{
exit_bool = 0;//exit is true
printf("\nThe program was killed\n");
exit(1);
}
//else if the user enters "cd" the current directory will be changed
else if( strcmp(input_arr[0], "cd") == 0 )
{
//char* path = strtok(NULL, delim);//tok the next word in the string
chdir( input_arr[1] );//change the directory
printf("\nDirectory changed to %s\n", input_arr[1]);//print the new directory
}
//else the user enters anything else exec is used to handle the UNIX command
//fork a child process
else
{
child_pid = fork();//create child
if(child_pid == 0)//child
{
execlp(input_arr[0], input_arr[0], input_arr[1], (char*)0);
}
else
{
wait(NULL);
}
fflush(stdout);
}//end of else
}//end of while loop
return 0;
}//end of main
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
// Ringrazio Kledi (Negahertz) per avermi aiutato nel debugging
// Qesto programma contiene una struttura lista in grado di
// contenere più tipi di variabile
// Per ora solo interi caratteri e stringhe
// definisco le strutture lista e nodo
typedef struct node {
void *val;
char *type;
} node_t;
typedef struct list {
struct list *prev;
struct list *next;
struct list *last;
int index;
node_t *val;
} list_t;
// funzione per evitare ripetizioni in un codice che ha bisogno di più liste
list_t *init() {
list_t *list = (list_t*)malloc(sizeof(list_t));
list->prev = NULL;
list->next = NULL;
list->val = NULL;
// se avessi messo zero gli indici sarebbero partiti da 1
// a causa della funzione baseAdd (vedi sotto)
list->index = -1;
return list;
}
// codice che viene eseguito a prescindere dal tipo di elemento che viene inserito
void baseAdd(list_t *list) {
list_t *ptr = list;
list_t *prev = NULL;
int index = ptr->index;
while (ptr->next != NULL) {
ptr = ptr->next;
index = ptr->index;
}
ptr->next = (list_t*)malloc(sizeof(list_t));
list->last = ptr->next;
list_t *next = ptr->next;
next->next = NULL;
next->prev = ptr;
next->val = NULL;
next->index = ptr->index + 1;
if (ptr->index == -1 || ptr->index == 0)
ptr->prev = NULL;
}
void setVal(list_t *ptr, char *type) {
ptr->val = (node_t *)malloc(sizeof(node_t));
node_t *n = ptr->val;
n->type = (char *)calloc(strlen(type) + 1, sizeof(char));
int i;
for (i = 0; i < strlen(type); i++) {
*(n->type + i) = type[i];
}
*(n->type + i) = '\0';
}
// funzione per aggiungere un intero alla lista
void addInt(list_t *list, int item) {
char c[] = "int";
list_t *ptr = list;
baseAdd(list);
while (ptr->next != NULL)
ptr = ptr->next;
setVal(ptr, c);
node_t *n = ptr->val;
n->val = (void*)malloc(sizeof(int));
*((int *)n->val) = item;
}
// funzione per aggiungere un carattere alla lista
void addChar(list_t *list, char item) {
char c[] = "char";
list_t *ptr = list;
baseAdd(list);
while (ptr->next != NULL)
ptr = ptr->next;
setVal(ptr, c);
node_t *n = ptr->val;
n->val = (void*)malloc(sizeof(char));
*((char *)n->val) = item;
}
void addString(list_t *list, char* string) {
char c[] = "string";
list_t *ptr = list;
baseAdd(list);
while (ptr->next != NULL)
ptr = ptr->next;
setVal(ptr, c);
node_t *n = ptr->val;
n->val = (char*)calloc(strlen(string), sizeof(char) + 1);
int i;
for (i = 0; i < strlen(string); i++)
*((char*)(n->val + i)) = *(string + i);
*((char*)(n->val + i)) = '\0';
}
void printElement(node_t *node) {
if (strcmp(node->type, "char") == 0)
printf("%c\n", *((char*)node->val));
if (strcmp(node->type, "int") == 0)
printf("%d\n", *((int*)node->val));
if (strcmp(node->type, "string") == 0)
printf("%s\n", (char*)node->val);
}
void printList(list_t* list) {
list_t* ptr = list;
while (ptr != NULL) {
if(ptr->val != NULL){
node_t *node = ptr->val;
printElement(node);
}
ptr = ptr->next;
}
}
void printReversedList(list_t *list) {
list_t *ptr = list->last;
while (ptr != NULL) {
node_t *node = ptr->val;
printElement(node);
ptr = ptr->prev;
}
}
int main() {
list_t *list = init();
addChar(list, 'e');
addChar(list, '2');
addInt(list, 6);
addChar(list, 'p');
addString(list, "Ciao");
printList(list);
printf("\n\n");
printReversedList(list);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main(){
int len;
char label[20], mne[20], opnd[20], name[20], mne1[20], opnd1[20], arg[20];
FILE *inp, *argtab, *deftab, *namtab, *output;
inp = fopen("inp_self.txt", "r");
argtab = fopen("argtab.txt", "w+");
deftab = fopen("deftab_self.txt", "r");
namtab = fopen("namtab_self.txt", "r");
output = fopen("output_self.txt", "w");
fscanf(inp , "%s%s%s", label, mne, opnd);
while(strcmp("END", mne) != 0){
if(strcmp(mne, "MACRO") == 0){
fscanf(inp , "%s%s%s", label, mne, opnd);
while(strcmp(mne, "MEND") != 0){
fscanf(inp , "%s%s%s", label, mne, opnd);
}
}else{
fscanf(namtab, "%s", name);
if(strcmp(mne, name) == 0){
// taking length of args
// Storing args in argtab
len = strlen(opnd);
for(int i=0; i<len; i++){
if(opnd[i] != ','){
fprintf(argtab, "%c", opnd[i]);
}else{
fprintf(argtab, "\n");
}
}
fseek(namtab, SEEK_SET, 0);
fseek(argtab, SEEK_SET, 0);
// writing from deftab to output
fscanf(deftab, "%s%s", mne1, opnd1);
fprintf(output, ".\t%s\t%s\n", mne1, opnd);
fscanf(deftab, "%s%s", mne1, opnd1);
while(strcmp(mne1, "MEND") != 0){
if(opnd1[0] == '&'){
fscanf(argtab, "%s", arg);
fprintf(output, "-\t%s\t%s\n", mne1, arg);
}else{
fprintf(output, "-\t%s\t%s\n", mne1, opnd1);
}
fscanf(deftab, "%s%s", mne1, opnd1);
}
}else{
fprintf(output, "%s\t%s\t%s\n", label, mne, opnd);
}
}
fscanf(inp , "%s%s%s", label, mne, opnd);
}
fprintf(output, "%s\t%s\t%s\n", label, mne, opnd);
fclose(inp);
fclose(argtab);
fclose(namtab);
fclose(deftab);
fclose(output);
printf("Pass 2 complete\n");
}
|
C
|
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "dictionary.h"
#define ALPHABET_LENGTH 27
typedef struct node
{
bool is_word;
struct node* children[ALPHABET_LENGTH];
}
node;
node *root = NULL;
int numberOfWords = 0;
void freenode(node* firstnode)
{
for(int i = 0; i < ALPHABET_LENGTH; i++)
{
if (firstnode -> children[i] != NULL)
{
freenode(firstnode -> children[i]);
}
}
free(firstnode);
return;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
node* crawl = NULL;
crawl=root;
// traverse trie per char
for (int x = 0; x < strlen(word); x++)
{
int index = 0;
if (isalpha(word[x]))
{
index = tolower(word[x]) - 'a';
}
else if (word[x] == '\'')
{
index = ALPHABET_LENGTH - 1;
}
else
{
printf("ERROR: Could not parse word\n");
return false;
}
if (crawl->children[index] == NULL)
{
//not a word - false
return false;
}
crawl = crawl->children[index];
}
return crawl -> is_word;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
root = (struct node *)malloc(sizeof(struct node));
root->is_word = false;
for (int i = 0; i < ALPHABET_LENGTH; i++)
{
root->children[i] = NULL;
}
// Open dictionary
FILE *dict = fopen(dictionary, "r");
if (dict == NULL)
{
printf("Could not open %s.\n", dictionary);
unload();
return false;
}
node* trav = NULL;
int character = 0;
// for every dictionary word, iterate through the trie
while (EOF != (character = fgetc(dict)))
{
trav = root;
// for each character in word
for(; isalpha(character) || character == '\'' ; character = fgetc(dict))
{
int index = 0;
if (isalpha(character))
{
index = tolower(character) - 'a';
}
else if (character == '\'')
{
index = ALPHABET_LENGTH - 1;
}
else
{
printf("ERROR: Could not parse dictionary word\n");
fclose(dict);
return false;
}
if (trav->children[index] == NULL)
{
// trav->children[index] = (struct node *)malloc(sizeof(struct node));
node *pNode = (node *)malloc(sizeof(node));
if (pNode)
{
pNode->is_word = false;
// init node
for (int i = 0; i < ALPHABET_LENGTH; i++)
{
pNode->children[i] = NULL;
}
trav->children[index] = pNode;
}
else
{
printf("ERROR: Could not allocate space for node, memory issue.");
fclose(dict);
return false;
}
}
trav = trav->children[index];
}
// reached end of word, set end of word to true for current pointer.
trav->is_word = true;
numberOfWords++;
}
fclose(dict);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return numberOfWords;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
node* firstnode = root;
freenode(firstnode);
return true;
}
|
C
|
/*
llcv.h: definitions enabling the use of in-memory doubly-
linked lists (Lysts) as inter-thread communication
flows.
Like sdrpipes and sdrcvs, llcvs transmit variable-
length messages without flow control: the writing
rate is completely decoupled from the reading rate.
An llcv comprises a Lyst, a mutex, and a condition
variable. The Lyst may be in either private
or shared memory, but the Lyst itself is not shared
with other processes. The reader thread waits on
the condition variable until signaled by a writer
that some condition is now true. The standard
lyst_* API functions are used to populate and
drain the linked list; in order to protect linked
list integrity, each thread must call llcv_lock
before operating on the Lyst and llcv_unlock
afterwards. The other llcv functions merely effect
flow signaling in a way that makes it unnecessary for
the reader to poll or busy-wait on the Lyst.
Copyright (c) 2003, California Institute of Technology.
ALL RIGHTS RESERVED. U.S. Government Sponsorship
acknowledged.
*/
/* Author: Scott Burleigh, Jet Propulsion Laboratory */
/* */
#ifndef _LLCV_H_
#define _LLCV_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "platform.h"
#include "lyst.h"
typedef struct llcv_str
{
Lyst list;
pthread_mutex_t mutex;
pthread_cond_t cv;
} *Llcv;
typedef int (*LlcvPredicate)(Llcv);
/* llcv_wait timeout values */
#define LLCV_POLL (0)
#define LLCV_BLOCKING (-1)
extern int llcv_lyst_is_empty(Llcv Llcv);
/* A built-in "convenience" predicate.
* Returns true if the length of the
* Llcv's encapsulated Lyst is zero,
* false otherwise. */
extern int llcv_lyst_not_empty(Llcv Llcv);
/* A built-in "convenience" predicate.
* Returns true if the length of the
* Llcv's encapsulated Lyst is non-
* zero, false otherwise. */
extern Llcv llcv_open(Lyst list, Llcv llcv);
/* Opens an Llcv, initializing as
* necessary. The list argument must
* point to an existing Lyst, which
* may reside in either private or
* shared dynamic memory. The llcv
* argument must point to an existing
* Llcv management object, which may
* reside in either static or dynamic
* (private or shared) memory -- but
* *NOT* in stack space. Returns NULL
* on any error. */
extern void llcv_lock(Llcv llcv);
/* Locks the Lyst so that it may be
* updated or examined safely by the
* calling thread. Fails silently
* on any error. */
extern void llcv_unlock(Llcv llcv);
/* Unlocks the Lyst so that another
* thread may lock and update or
* examine it. Fails silently on
* any error. */
extern int llcv_wait(Llcv llcv, LlcvPredicate cond, int microseconds);
/* Returns when the Lyst encapsulated
* within the Llcv meets the indicated
* condition. If microseconds is non-
* negative, will alternatively return
* -1 and set errno to ETIMEDOUT when
* the indicated number of microseconds
* has passed. Negative values of the
* microseconds argument other than
* LLCV_BLOCKING are illegal. Returns
* -1 on any error. */
extern void llcv_signal(Llcv llcv, LlcvPredicate cond);
/* Signals to the waiting reader (if
* any) that the Lyst encapsulated in
* the Llcv now meets the indicated
* condition -- but only if it in fact
* does meet that condition. */
extern void llcv_signal_while_locked(Llcv llcv, LlcvPredicate cond);
/* Same as llcv_signal() except does not
* lock the Llcv's mutex before signalling
* or unlock afterwards. For use when
* the Llcv is already locked, to prevent
* deadlock. */
extern void llcv_close(Llcv llcv);
/* Destroys the Llcv management object's
* mutex and condition variable. Fails
* silently (and has no effect) if a
* reader is currently waiting on the Llcv.*/
#ifdef __cplusplus
}
#endif
#endif /* _LLCV_H_ */
|
C
|
/* $begin shellmain */
#include "csapp.h"
#define MAXARGS 128
typedef struct redirects{
char* in;
char* out;
char* err;
} RedirectionPaths;
RedirectionPaths init_r_paths(){
RedirectionPaths rpath;
rpath.in = NULL;
rpath.out = NULL;
rpath.err = NULL;
return rpath;
}
/* function prototypes */
void eval(char *cmdline);
int parseline(char *buf, char **argv, RedirectionPaths*);
int builtin_command(char **argv);
int redirect_stream(int, char*);
void bgreap_handle(int sig){
int status;
int id = wait(&status);
printf("child reaped\nID: %d\nstatus: %d\n",id,status);
}
int main()
{
char cmdline[MAXLINE]; /* Command line */
Signal(SIGCHLD, bgreap_handle);
while (1) {
/* Read */
printf("> ");
Fgets(cmdline, MAXLINE, stdin);
if (feof(stdin))
exit(0);
/* Evaluate */
eval(cmdline);
}
}
/* $end shellmain */
/* $begin eval */
/* eval - Evaluate a command line */
void eval(char *cmdline)
{
char *argv[MAXARGS]; /* Argument list execve() */
char buf[MAXLINE]; /* Holds modified command line */
int bg; /* Should the job run in bg or fg? */
pid_t pid; /* Process id */
RedirectionPaths rpath = init_r_paths();
strcpy(buf, cmdline);
bg = parseline(buf, argv, &rpath);
if(rpath.out != NULL)
printf("stdout redirection: %s\n",rpath.out);
if (argv[0] == NULL)
return; /* Ignore empty lines */
if (!builtin_command(argv)) {
if ((pid = Fork()) == 0) { /* Child runs user job */
if(rpath.in != NULL)
redirect_stream(0,rpath.in);
if(rpath.out != NULL)
redirect_stream(1,rpath.out);
if(rpath.err != NULL)
redirect_stream(2,rpath.err);
if (execve(argv[0], argv, environ) < 0) {
printf("%s: Command not found.\n", argv[0]);
exit(0);
}
}
}
/* Parent waits for foreground job to terminate */
if (!bg) {
int status;
if (waitpid(pid, &status, 0) < 0)
unix_error("waitfg: waitpid error");
}
else
printf("%d %s", pid, cmdline);
return;
}
/* If first arg is a builtin command, run it and return true */
int builtin_command(char **argv)
{
if (!strcmp(argv[0], "quit")) /* quit command */
exit(0);
if (!strcmp(argv[0], "&")) /* Ignore singleton & */
return 1;
return 0; /* Not a builtin command */
}
/* $end eval */
/* $begin parseline */
/* parseline - Parse the command line and build the argv array */
typedef enum {PT_ARG,PT_STDIN,PT_STDOUT,PT_STDERR} ParseMode;
int parseline(char *buf, char **argv, RedirectionPaths *rpath)
{
char *delim; /* Points to first space delimiter */
int argc; /* Number of args */
int bg; /* Background job? */
ParseMode mode = PT_ARG;
buf[strlen(buf)-1] = ' '; /* Replace trailing '\n' with space */
while (*buf && (*buf == ' ')) /* Ignore leading spaces */
buf++;
/* Build the argv list */
argc = 0;
while ((delim = strchr(buf, ' '))) {
*delim = '\0';
if(strcmp(buf,"<")==0){
mode = PT_STDIN;
}else if(strcmp(buf,">")==0){
mode = PT_STDOUT;
}else if(strcmp(buf,"2>")==0){
mode = PT_STDERR;
}else{
switch(mode){
case PT_ARG:
argv[argc++] = buf;
break;
case PT_STDIN:
rpath->in = buf;
break;
case PT_STDOUT:
rpath->out = buf;
break;
case PT_STDERR:
rpath->err = buf;
break;
}
mode = PT_ARG;
}
buf = delim + 1;
while (*buf && (*buf == ' ')) /* Ignore spaces */
buf++;
}
argv[argc] = NULL;
if (argc == 0) /* Ignore blank line */
return 1;
/* Should the job run in the background? */
if ((bg = (*argv[argc-1] == '&')) != 0)
argv[--argc] = NULL;
return bg;
}
/* $end parseline */
int redirect_stream(int stream, char* filename){
int file;
switch(stream){
case 0:
file = open(filename,O_RDONLY);
if (file <= 0) {
printf("You done goofed. %s does not exist\n", filename);
return -1;
}
break;
case 1:
file = open(filename,O_WRONLY|O_CREAT,0666);
break;
case 2:
file = open(filename,O_WRONLY|O_CREAT,0666);
break;
default:
return -1;
}
dup2(file,stream);
close(file);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node* link;
int data;
};
void enumerate(struct node *head)
{
printf("your list is ==> \n \n");
struct node* current=head;
while(current!=NULL)
{
printf("%d \n",current->data);
current = current->link;
}
}
int is_element(struct node* head,int num)
{
struct node* current = head;
while(current!=NULL)
{
if(num==current->data)
{
printf(" element exists==>%d\n \n",num);
return 1;
}
current=current->link;
}
return 0;
}
void is_empty(struct node* head)
{
struct node* temp=head;
if(temp!=NULL)
{
printf("list is not empty \n \n");
}
else
{
printf("set is empty \n");
}
}
void size_of_list(struct node* head)
{
int n=0;
struct node* current=head;
while(current!=NULL)
{
n++;
current = current->link;
}
printf("size of the list is==> %d \n",n);
}
struct node* add_element(struct node* head,int n)
{
if(!is_element(head,n))
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=n;
temp->link=NULL;
// for 1st element
if(head==NULL)
{
head=temp;
}
// for rest of the elements
else
{
struct node* current = head;
// traversing till last node
while(current->link != NULL)
{
current=current->link;
}
current->link = temp;
}
}
return head;
}
struct node * remove_element(struct node *head, int n)
{
struct node *current= head;
struct node *prev;
// checking and removing first element
if(current!=NULL && current -> data == n)
{
head = head->link;
free(current);
return head;
}
//removing other elements
if(is_element(current,n)==1)
{
while(current !=NULL && current->data!=n)
{
prev = current;
current=current->link;
}
if(current==NULL)
return head;
prev -> link = current -> link;
free(current);
}
return head;
}
struct node* build(int a[],int n)
{
int i;
struct node* head = NULL;
// passing array into list
for(i=0;i<n;i++)
{
head=add_element(head,a[i]);
}
return head;
}
struct node* union_of_set(struct node* s1,struct node* s2)
{
struct node * s2_copy = s2;
struct node * temp = NULL;
// s1_copy created
while (s2_copy != NULL)
{
temp = add_element(temp, s2_copy->data);
s2_copy = s2_copy->link;
}
int data;
//temp variable will used if loop
for (s2_copy = s1; s2_copy!= NULL; )
{
data = s2_copy->data;
s2_copy = s2_copy->link;
if (is_element(s2,data) != 1)
temp = add_element(temp,data); // adding elements which are not present at set1
}
return temp;
}
struct node * difference(struct node* s1, struct node* s2)
{
struct node * s1_copy = NULL;
struct node * temp = s1;
// s1_copy created
while (temp != NULL)
{
s1_copy = add_element(s1_copy, temp->data);
temp = temp->link;
}
int data;
//temp variable will used if loop
for (temp = s1_copy; temp!= NULL; )
{
data = temp->data;
temp = temp->link;
if (is_element(s2,data) == 1)
s1_copy = remove_element(s1_copy, data); // removing elements which are not present at set2
}
return s1_copy;
}
struct node* intersection_of_sets(struct node* s1,struct node* s2)
{
struct node* temp = difference(s1,s2);
temp = difference(s1,temp);
return temp;
}
int is_subset(struct node* s1,struct node* s2)
{
struct node* temp;
temp=s1;
while(temp!=NULL)
{
if(is_element(temp->data,s2)!= 1)
return 0;
temp = temp->link;
}
return 1;
}
int main()
{
int choice,x,y,i;
struct node* set_1 = NULL;
struct node* set_2 = NULL;
printf("enter the number of elements you want to enter in array a \n");
scanf("%d",&x);
int a[x];
for(i=0;i<x;i++)
{
printf("enter the elements==> \n");
scanf("%d",&a[i]);
}
set_1=build(a,x);
printf("enter the number of elements you want to enter in array b \n");
scanf("%d",&y);
int b[y];
for(i=0;i<y;i++)
{
printf("enter the elements==> \n");
scanf("%d",&b[i]);
}
set_2=build(b,y);
enumerate(set_1);
enumerate(set_2);
struct node* union_of_sets = union_of_set(set_1,set_2);
printf("your union of set is \n");
enumerate(union_of_sets);
struct node * diff_set = difference (set_1, set_2);
printf("your difference of set is \n");
enumerate(diff_set);
printf("your intersection of set is \n");
struct node* intersection = intersection_of_sets(set_1,set_2);
enumerate(intersection);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
const int N = 4;
int g_next = 938;
int prng()
{
g_next += 3827;
g_next %= 97;
return g_next;
}
int main()
{
int *buf = (int*)malloc(sizeof(int) * N);
for (int i=0; i<N; i++)
buf[i] = prng();
printf("negative: ");
for (int i=0; i<N; i++)
printf("%d ", -buf[i]);
puts("");
printf("logical negate: ");
for (int i=0; i<N; i++)
printf("%d ", !buf[i]);
puts("");
printf("bitwise negate: ");
for (int i=0; i<N; i++)
printf("%d ", ~buf[i]);
puts("");
printf("addrof-diff: ");
for (int i=0; i<N; i++)
printf("%d ", (int)(&buf[i]) - (int)buf);
puts("");
short sh = 59;
short *shPtr = &sh;
printf("sizeof: %d\n", sizeof(shPtr[0]));
free(buf);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "geladeira.h"
void criageladeira(geladeira *q,char Cor[10],char Material[15], float Peso, float Preco, float Altura){
strcpy(q->cor,Cor);
strcpy(q->material,Material);
q->peso=Peso;
q->preco=Preco;
q->altura=Altura;
}
void trocacor(geladeira *q,char Cor[10]){
strcpy(q->cor,Cor);
}
void alterapreco(geladeira *q,float Preco){
q->preco=Preco;
}
void vergeladeira(geladeira *q){
printf("\n\nGeladeira\n\n");
printf("Cor: %s\n",q->cor);
printf("Material: %s\n",q->material);
printf("Preco: R$%.2f\n",q->preco);
printf("Peso: %.2fKm\n",q->peso);
printf("Altura: %.2fm\n",q->altura);
}
|
C
|
//
// Created by Sakura on 2020/10/30.
//
#include <stdio.h>
#include <stdbool.h>
int FactorialRecursive(int num)
{
int res;
if (num < 0)
{
printf("С0!");
return false;
} else if (num == 0 || num == 1)
{
res = 1;
}
else
{
res = FactorialRecursive(num - 1) * num; //num>1ʱ,n! = n * (n -1)
}
return res;
}
int main(void)
{
int num;
printf("׳:");
scanf("%d",&num);
printf("%dĽ׳Ϊ:%d",num,FactorialRecursive(num));
}
|
C
|
#include <stdio.h>
int main(void) {
int zippo[4][2] = {
{2, 4},
{6, 8},
{1, 3},
{5, 7}
};
printf("zippo = %p, zippo + 1 = %p\n", zippo, zippo + 1); //zippo = 00D6F760, zippo + 1 = 00D6F768 zippointСԪ
printf("zippo[0] = %p, zippo[0] + 1 = %p\n", zippo[0], zippo[0] + 1); //zippo[0] = 00D6F760, zippo[0] + 1 = 00D6F764 ŵĻǵַ
printf("*zippo = %p, *zippo+1=%p\n", *zippo, *zippo + 1); //*zippo = 00D6F760, *zippo+1=00D6F764
printf("zippo[0][0] = %d\n", zippo[0][0]); //zippo[0][0] = 2 ʹ±귨ȡһԪ
printf("*zippo[0]=%d\n", *zippo[0]); // *zippo[0]=2 ʹָ뷨ȡһԪ
printf(" **zippo=%d\n", **zippo); // **zippo=2 ʹָ뷨λȡһԪ
printf("zippo[2][1]=%d\n", zippo[2][1]); // zippo[2][1]=3 ʹ±귨ȡеڶеԪصֵ
printf("*(*(zippo+2)+1)=%d\n", *(*(zippo + 2) + 1)); //*(*(zippo+2)+1)=3 ʹָ뷨λȡеڶеԪصֵ
return 0;
}
|
C
|
#include <sys/time.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_WIDTH (8192)
#define DEFAULT_HEIGHT (4096)
/* from: https://qiita.com/NaOHaq/items/55573f088d0b1d3b0dc6
*
* perf stat -d ./horizontal
* perf stat -d ./vertical
*/
static double
get_current_time( void )
{
double t;
struct timeval tv;
gettimeofday(&tv, NULL);
t = ((double)tv.tv_usec) * 1.0e-6;
t += (double)tv.tv_sec;
return t;
}
#ifdef SCAN_VERTICAL
static void
process_pixels(uint8_t * pixbuf, int32_t w, int32_t h)
{
for (int32_t x=0; x<w; x+=1) {
for (int32_t y=0; y<h; y+=1) {
pixbuf[y*w + x] += 1;
}
}
}
#else
static void
process_pixels(uint8_t * pixbuf, int32_t w, int32_t h)
{
for (int32_t y=0; y<h; y+=1) {
for (int32_t x=0; x<w; x+=1) {
pixbuf[y*w + x] += 1;
}
}
}
#endif
int
main(int argc, char * argv[])
{
uint8_t * pixbuf;
int32_t w = DEFAULT_WIDTH;
int32_t h = DEFAULT_HEIGHT;
double t0;
double t1;
if (argc > 1) {
w = strtol(argv[1], NULL, 10);
}
if (argc > 2) {
h = strtol(argv[2], NULL, 10);
}
pixbuf = malloc(w * h);
if (pixbuf == NULL) {
fprintf(stderr, "Not enough memory...\n");
exit(1);
}
memset(pixbuf, 0, w * h);
t0 = get_current_time( );
for (int32_t k=0; k<128; k+=1) {
process_pixels(pixbuf, w, h);
fputc('.', stdout);
fflush(stdout);
}
fputc('\n', stdout);
t1 = get_current_time( );
printf("Elapsed time: %.3f\n", t1 - t0);
return 0;
}
|
C
|
#include "log.h"
#include "uart.h"
#include "flash.h"
#include "xc.h"
// Number of bits to shift the upper nibble of a byte into the lower nibble.
#define UPPER_NIBBLE_SHIFT 4U
// Bitmask for isolating the lower nibble of a byte.
#define LOWER_NIBBLE_MASK 0x0F
// Number of bits to shift the middle byte of a flash word into the lower byte.
#define MIDDLE_BYTE_SHIFT 8U
// Number of bits to shift the upper byte of a flash word into the lower byte.
#define UPPER_BYTE_SHIFT 16U
// Bitmask for isolating the lower byte of a word.
#define LOWER_BYTE_MASK 0x00FF
// Number of 16-bit words per instruction space in flash.
#define WORDS_PER_INSTRUCTION 2U
// Number of instructions used to store the UDID.
#define UDID_LENGTH 5U
// The address offset of the least-significant double-word of the UDID.
#define UDID_FIRST_ADDRESS 0x801200
// The address of the most-significant double-word of the UDID.
#define UDID_LAST_ADDRESS \
(UDID_FIRST_ADDRESS + (WORDS_PER_INSTRUCTION * (UDID_LENGTH - 1U)))
// Convert a 4-bit nibble to its corresponding hex character.
#define NIBBLE_TO_HEX_CHAR(x) ((x) < 0xA ? (x) + '0' : (x - 0xA) + 'a')
void log_str(char *str)
{
uart_write_string(str);
}
void log_line(char *str)
{
uart_write_string(str);
uart_write('\n');
}
void log_serial_number(void)
{
log_str("Serial Number: ");
for (uint32_t address = UDID_LAST_ADDRESS;
address >= UDID_FIRST_ADDRESS;
address -= WORDS_PER_INSTRUCTION)
{
uint32_t data_word;
flash_status_t ret;
ret = flash_read_word(address, &data_word);
if (FLASH_OK == ret)
{
// Log bytes via UART.
log_hex((data_word >> UPPER_BYTE_SHIFT) & LOWER_BYTE_MASK);
log_hex((data_word >> MIDDLE_BYTE_SHIFT) & LOWER_BYTE_MASK);
log_hex(data_word & LOWER_BYTE_MASK);
}
else
{
log_str("Error: Failed to read serial number: ");
log_hex(ret);
log_line("");
}
// Log dashes between three-byte sections.
if (address != UDID_FIRST_ADDRESS)
{
uart_write('-');
}
}
uart_write('\n');
}
void log_hex(uint8_t data)
{
uint8_t lower_nibble = data & LOWER_NIBBLE_MASK;
uint8_t upper_nibble = data >> UPPER_NIBBLE_SHIFT;
uart_write(NIBBLE_TO_HEX_CHAR(upper_nibble));
uart_write(NIBBLE_TO_HEX_CHAR(lower_nibble));
}
|
C
|
#include<stdio.h>
int main()
{
printf(" Today's class we learnt basics of C programming \n \n");
printf(" It was interactive class\b\b");
printf(" \'Mam teaching method was good \a\a'" );
printf(" I have made some friends " );
printf(" Today we have covered Datatypes,Variables,Format specifiers, Escape sequence characters \t \t ");
}
|
C
|
#include<stdio.h>
int main(){
int i, num, row;
printf("Enter no : ");
scanf("%d",&num);
printf("row : ");
scanf("%d",&row);
for(i=1; i<=row; i++ ){
printf("%d * %2d = %d",num,i,num*i);
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <string.h>
void dtoh(int n)
{
char arr[10];
int i;
int temp = n;
for (i = 0; temp > 0; i++)
{
int r = temp % 16;
if (r<10)
arr[i] = r + 48;
else
arr[i] = r + 55;
temp = temp / 16;
}
int j;
printf("\nhex of %d is ", n);
for (j = i - 1; j >= 0; j--)
printf("%c", arr[j]);
}
void htod(char hex[])
{
long dec = 0;
int val;
int len = strlen(hex);
len--;
for (int i = 0; hex[i] != '\0'; i++)
{
if (hex[i] >= '0' && hex[i] <= '9')
{
val = hex[i] - 48;
}
else if (hex[i] >= 'a' && hex[i] <= 'f')
{
val = hex[i] - 97 + 10;
}
else if (hex[i] >= 'A' && hex[i] <= 'F')
{
val = hex[i] - 65 + 10;
}
dec += val * pow(16, len);
len--;
}
printf("\nDecimal of %s is ", hex);
printf("%ld", dec);
}
int main()
{
int n;
char hex[10];
printf("\nEnter a hex number\n");
//scanf_s("%s", hex);
gets(hex);
htod(hex);
printf("\nEnter a decimal number\n");
scanf_s("%d", &n);
dtoh(n);
getchar();
getchar();
return 0;
}
|
C
|
/*
* Calling C code from go
*
* Go provides a pseudo package called C to interface with C libraries.
* Its not very straightforward how to do this though.
* In this tutorial, well go over creating a simple C function,
* and calling it from go. After that, well move on to a slightly
* more complex example involving C structs.
*
* See https://karthikkaranth.me/blog/calling-c-code-from-go
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <gos/forgo.h>
int gos_for_go_greet(char* buffer, size_t size, const char* name, int year) {
int result;
result = snprintf(
buffer,
size,
"Greetings, %s from %d! We come in peace :)",
name,
year);
return result;
}
int gos_for_go_greet_st(struct GosForGoGreetee* greetee) {
int result;
result = snprintf(
greetee->buffer,
greetee->size,
"Greetings, %s from %d! We come in peace with structures :)",
greetee->name,
greetee->year);
}
|
C
|
#include <nc_tests.h>
#include "err_macros.h"
#include <stdio.h>
#include <stdlib.h>
#include <netcdf.h>
#define FILECLASSIC "tst_dimsize_classic.nc"
#define FILE64OFFSET "tst_dimsize_64offset.nc"
#define FILE64DATA "tst_dimsize_64data.nc"
#define DIMMAXCLASSIC (NC_MAX_INT - 3)
#define DIMMAX64OFFSET (NC_MAX_UINT - 3)
#define DIMMAX64DATA (NC_MAX_UINT64 - 3)
/*
Test that at least the meta-data works
for dimension sizes X modes.
NC_CLASSIC => NC_INT_MAX - 3
NC_64BIT_OFFSET => NC_UINT_MAX - 3
NC_64BIT_DATA => NC_UINT64_MAX - 3
Note that this will not test the last case when
|size_t| == 4.
Also, leave the files around so we can test with ncdump.
*/
int
main(int argc, char **argv)
{
int ncid;
size_t dimsize;
int dimid;
int stat = NC_NOERR;
nc_set_log_level(5);
printf("\n*** Testing Max Dimension Sizes\n");
printf("\n|size_t|=%lu\n",(unsigned long)sizeof(size_t));
printf("\n*** Writing Max Dimension Size (%d) For NC_CLASSIC\n",DIMMAXCLASSIC);
if ((stat=nc_create(FILECLASSIC, NC_CLOBBER, &ncid))) ERRSTAT(stat);
dimsize = DIMMAXCLASSIC;
if ((stat=nc_def_dim(ncid, "testdim", dimsize, &dimid))) ERRSTAT(stat);
if ((stat=nc_close(ncid))) ERRSTAT(stat);
printf("\n*** Reading Max Dimension Size For NC_CLASSIC\n");
if ((stat=nc_open(FILECLASSIC, NC_NOCLOBBER, &ncid))) ERRSTAT(stat);
if ((stat=nc_inq_dimid(ncid, "testdim", &dimid))) ERRSTAT(stat);
if ((stat=nc_inq_dimlen(ncid, dimid, &dimsize))) ERRSTAT(stat);
if(dimsize != DIMMAXCLASSIC) ERR;
if ((stat=nc_close(ncid))) ERRSTAT(stat);
printf("\n*** Writing Max Dimension Size (%u) For NC_64BIT_OFFSET\n",DIMMAX64OFFSET);
if ((stat=nc_create(FILE64OFFSET, NC_CLOBBER | NC_64BIT_OFFSET, &ncid))) ERRSTAT(stat);
dimsize = DIMMAX64OFFSET;
if ((stat=nc_def_dim(ncid, "testdim", dimsize, &dimid))) ERRSTAT(stat);
if ((stat=nc_enddef(ncid))) ERRSTAT(stat);
if ((stat=nc_close(ncid))) ERRSTAT(stat);
printf("\n*** Reading Max Dimension Size For NC_64BIT_OFFSET\n");
if ((stat=nc_open(FILE64OFFSET, NC_NOCLOBBER|NC_64BIT_OFFSET, &ncid))) ERRSTAT(stat);
if ((stat=nc_inq_dimid(ncid, "testdim", &dimid))) ERRSTAT(stat);
if ((stat=nc_inq_dimlen(ncid, dimid, &dimsize))) ERRSTAT(stat);
if(dimsize != DIMMAX64OFFSET) ERR;
if ((stat=nc_close(ncid))) ERRSTAT(stat);
if(sizeof(size_t) == 8) {
printf("\n*** Writing Max Dimension Size (%llu) For NC_64BIT_DATA\n",DIMMAX64DATA);
if ((stat=nc_create(FILE64DATA, NC_CLOBBER | NC_64BIT_DATA, &ncid))) ERRSTAT(stat);
dimsize = (size_t)DIMMAX64DATA;
if ((stat=nc_def_dim(ncid, "testdim", dimsize, &dimid))) ERRSTAT(stat);
if ((stat=nc_close(ncid))) ERRSTAT(stat);
printf("\n*** Reading Max Dimension Size For NC_64BIT_DATA\n");
if ((stat=nc_open(FILE64DATA, NC_NOCLOBBER|NC_64BIT_DATA, &ncid))) ERRSTAT(stat);
if ((stat=nc_inq_dimid(ncid, "testdim", &dimid))) ERRSTAT(stat);
if ((stat=nc_inq_dimlen(ncid, dimid, &dimsize))) ERRSTAT(stat);
if(dimsize != DIMMAX64DATA) ERR;
if ((stat=nc_close(ncid))) ERRSTAT(stat);
}
SUMMARIZE_ERR;
FINAL_RESULTS;
}
|
C
|
#include <stdio.h>
int main(void)
{
int row, line, space, num;
printf("Enter the number of row to print the number pyramid pattern: ");
scanf("%d", &row);
for (line = 1; line <= row; line++)
{
for(num = 1; num <= line; num++)
printf("%d", num);
for(space = 1; space <= ((row - line) * 2); space++)
printf(" ");
for(num = 1; num <= line; num++)
printf("%d", num);
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])
{
FILE *fp,*f1;
char c,s[10];
int i;
clrscr();
f1=fopen("real","w");
for(i=0;i<argc;i++)
fprintf(f1,"%s ",argv[i]);
fclose(f1);
f1=fopen("real","r");
fp=fopen("copy","w");
for(i=0;i<argc;i++)
{
fscanf(f1,"%s",s);
fprintf(fp,"%s ",s);
}
fclose(f1);
fclose(fp);
fp=fopen("copy","r");
for(i=0;i<argc;i++)
{
fscanf(fp,"%s",s);
printf(" %s ",s);
}
fclose(fp);
getch();
}
|
C
|
#include "helloLib.h"
#include <stdio.h>
void printResult(int res)
{
printf("The result is: %d.\n", res);
}
int addNumbers(int a, int b)
{
return a+b;
}
void printFirstNumber(int num)
{
printf("The first number is: %d.\n", num);
}
void printSecondNumber(int num)
{
printf("The second number is: %d.\n", num);
}
|
C
|
#include <stdio.h>
int main()
{
int A[100][100];
int B[100][100];
int N, M;
int N2, M2;
//L� as dimens�es de cada matriz
printf("Dimensoes Matriz A, separadas por espaco: \n");
scanf("%d %d", &N, &M);
printf("Dimensoes Matriz B, separadas por espaco: \n");
scanf("%d %d", &N2, &M2);
//Caso o n�mero de colunas de A seja diferente do n�mero de linhas de B, informa que � imposs�vel realizar o produto das matrizes.
if (M != N2) printf("Impossivel realizar o c�lculo do produto \n");
else {
//Le A.
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
printf("A%dx%d: ", i+ 1, j + 1);
scanf("%d", &A[i][j]);
}
}
//Le B.
for (int i = 0; i < N2; i++) {
for (int j = 0; j < M2; j++) {
printf("B%dx%d: ", i+ 1, j + 1);
scanf("%d", &B[i][j]);
}
}
//Inicializando os elementos da matriz multiplica�o C.
int C[100][100];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M2; j++) {
C[i][j] = 0;
}
}
// Multiplicando os elementos de A e B e armazenando em C.
for(int i = 0; i < N; ++i) {
for(int j = 0; j < M2; ++j) {
for(int k = 0; k < M; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M2; j++) {
printf("%d ", C[i][j]);
if (j == M2 - 1) printf("\n");
}
}
}
}
|
C
|
#include "help.h"
int is_nat(char* a)
{
int n = strlen(a), num = 0, sign, i = 0;
if(a[0] == '-' || a[0] == '+')
i = 1;
else
if(!(a[0] > '0' && a[0] < '9'))
return -1;
for(;i < n;i++)
{
if(!(a[i] >= '0' && a[i] <= '9'))
return -1;
if(num >= 2000000000 && a[i] != '\0')
return -1;
num = num * 10 + a[i] - '0';
}
return num;
}
string_struct input(string_struct lst)
{
char *str = NULL;//Текущая строка
int n = 0;//Текущий символ
char c;
int N = input_size, i = 0;//N - макс размер текущей строки, i - размер текущей строки
str = (char*)malloc(N*sizeof(char));//Выделяем память
n = read(0, &c, 1);
while(n > 0)
{
while(n > 0 && c != '\n')
{
if(i+2 == N)//Если считанная строка не укладывается в нашу строку то перевыделяем память увеличивая в 2 раза место
{
N*=2;
str = (char*)realloc(str, N*sizeof(char));
}
str[i++] = c;
n = read(0,&c, 1);
}
if(c == '\n')
str[i++] = c;
// if((n = read(0, &c, 1)) = 0)
// str[i++] = '\n';
if(i > 0)
{
str[i] = '\0';
lst = add_string_list(lst,str,i+1);
}
free(str);
N = input_size;
i = 0;
str = (char*)malloc(N*sizeof(char));
n = read(0, &c, 1);
}
free(str);//Отчистка памяти выделенной под строку
return lst;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* perebor.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dstracke <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/19 15:06:05 by dstracke #+# #+# */
/* Updated: 2019/05/16 05:02:18 by dstracke ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
char *errfree(char *str)
{
write(1, "error\n", 6);
free(str);
return (NULL);
}
char *buf19(ssize_t ret, char *str, char *buf, char *c)
{
char *tmp;
if (ret == 20)
{
buf[ret] = '\0';
if (ft_validate(buf, ret))
{
tmp = ft_strjoin(str, ft_cuttetr(ft_cup(buf, c)));
free(str);
str = tmp;
}
else
str = errfree(str);
}
else
str = errfree(str);
return (str);
}
char *ft_tet(int fd, char *buf)
{
char *tmp;
static char c = '@';
char *str;
ssize_t ret;
str = ft_strnew(0);
while ((ret = read(fd, buf, 21)) == 21)
{
if (!(buf[ret] = '\0') && ft_validate(buf, ret))
{
tmp = ft_strjoin(str, ft_cuttetr(ft_cup(buf, &c)));
free(str);
str = tmp;
}
else
{
str = errfree(str);
break ;
}
}
if (str && (ft_strlen(str) > 233))
str = errfree(str);
if (str && (ret < 21))
str = buf19(ret, str, buf, &c);
return (str);
}
void mapper(size_t cmp_sd, char *map)
{
size_t fill;
fill = 0;
while (fill < (cmp_sd * (cmp_sd + 1) - 1))
{
if ((fill + 1) % (cmp_sd + 1) != 0 || fill == 0)
{
map[fill] = '.';
fill++;
}
else
{
map[fill] = '\n';
fill++;
}
}
fill++;
map[fill] = '\0';
}
int main(int argc, char **argv)
{
int fd;
char buf[22];
char *str;
char *tmp;
t_tetr *tetr;
tetr = NULL;
if (argc == 2)
{
fd = open(argv[1], O_RDONLY);
if ((str = ft_tet(fd, buf)))
{
tetr = tlist(str);
tmp = str;
str = solve(tetr, ft_sqrt(str));
free(tmp);
write(1, str, ft_strlen(str));
write(1, "\n", 1);
free(str);
}
}
else
write(1, "usage: ./fillit source_file\n", 28);
freetlist(tetr);
return (0);
}
|
C
|
#include<stdio.h>
int main(){
float a1,b1,a2,b2,X,Y;
scanf("%f%f%f%f",&a1,&b1,&a2,&b2);
if ((a1/a2)==b1/b2)
{
printf("INF");
}
else
{
Y=(a2-a1)/(a2*b1-b2*a1);
X=(b2-b1)/(b2*a1-b1*a2);
printf("(%.3f,%.3f)",X,Y);
}
return 0;
}
|
C
|
#include "bilist.h"
int main()
{
struct node head;
list_create(&head,10);
list_operation(&head,node_show);
printf("\n");
node_insert1(&head,20);
list_operation(&head,node_show);
printf("\n");
list_reverse(&head);
list_operation(&head,node_show);
printf("\n");
list_operation(&head,node_free);
list_operation(&head,node_show);
printf("\n");
return 0;
}
|
C
|
//copied from private directory
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<fcntl.h>
#define DELIMITERS " \t\r\n\a"
int numRedirect = 0;
//method declearations
int execute(char* args[], char* retArgs[]);
//path for binary files
typedef struct Node {
char* data;
struct Node *next;
} pathNode;
pathNode *head = NULL;
//insert link at the first location
void insertFirst(char* data) {
//create a link
pathNode *link = (pathNode*) malloc(sizeof(pathNode));
link->data = data;
//point it to old first node
link->next = head;
//point first to new first node
head = link;
}
pathNode* deleteNode(char* data) {
//start from the first link
pathNode* current = head;
pathNode* previous = NULL;
//if list is empty
if(head == NULL) {
return NULL;
}
//navigate through list
while(strcmp(current-> data, data) != 0) {
//if it is last node
if(current->next == NULL) {
return NULL;
} else {
//store reference to current link
previous = current;
//move to next link
current = current->next;
}
}
//found a match, update the link
if(current == head) {
//change first to point to next link
head = head->next;
} else {
//bypass the current link
previous->next = current->next;
}
return current;
}
//clear list
void clearList(){
pathNode* curr = head;
pathNode* next;
while(curr != NULL){
next = curr -> next;
free(curr);
curr = next;
}
head = NULL;
}
//checks if path has / concatenated to it eg. /bin/ return 1 if true, otherwise return false
int checkBackslash(char *str){
if(str[ strlen(str) - 1] == '/'){
return 1;
} else{
return 0;
}
}
void error_msg(){
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
}
int command_cd(char* args[], int numArgs){
if (numArgs != 2) {
error_msg();
return 1;
}
if (chdir(args[1]) == -1){
error_msg();
return 1;
}
return 0;
}
void printPath(){
if(head == NULL){
return;
}
pathNode* current = head;
while(current != NULL){
printf("%s\n", current -> data);
current = current -> next;
}
}
int command_path(char* args[], int numArgs){
if(strcmp(args[1] , "add") == 0 ){
//if array is full resize by twice the size
if(checkBackslash(args[2]) == 1){
args[2][strlen(args[2]) -1] = '\0';
insertFirst(args[2]);
} else{
insertFirst(args[2]);
}
} else if(strcmp(args[1] , "remove") == 0 ){
// printf("args[2] : %s\n", args[2]);
deleteNode(args[2]);
} else if(strcmp(args[1] , "clear") == 0){
clearList();
}
// printPath();
return 0;
}
int lineSeperate(char* line, char* args[], char* delim) {
char *save;
int argsIndex = 0;
if (!args){
args = malloc(100*sizeof(char));
}
args[argsIndex] = strtok_r(line, delim, &save);
argsIndex++;
while(1){
if (!(args + argsIndex)){
char* temp = (char*)(args + argsIndex);
temp = malloc(100*sizeof(char));
temp++;
}
args[argsIndex] = strtok_r(NULL, delim,&save);
if (args[argsIndex] == NULL){
break;
}
argsIndex++;
}
if (args[0] == NULL) return 0;
return argsIndex;
}
int redirect(char* ret, char* line) {
char* progArgs[100];
char* retArgs[100];
ret[0] = '\0';
ret = ret + 1;
int argsNum = lineSeperate(line, progArgs, DELIMITERS);
if (argsNum == 0){
error_msg();
return 1;
}
int retArgc = lineSeperate(ret, retArgs, DELIMITERS);
if (retArgc != 1){
error_msg();
return 1;
}
execute(progArgs, retArgs);
return 0;
}
int parallel(char* ret, char* line){
char** commands = malloc(100*sizeof(char*));
int numCommands = lineSeperate(line, commands,"&");
char** arguments = malloc(50*sizeof(char*));
char* retRedir = malloc(100*sizeof(char));
for (int i = 0; i < numCommands; i++) {
if ((retRedir = strchr(commands[i], '>'))){
redirect(retRedir, commands[i]);
continue;
}
lineSeperate(commands[i], arguments, DELIMITERS);
execute(arguments, NULL);
}
free(arguments);
free(commands);
return 0;
}
int multiple(char* ret, char* line){
//store parsed commands
char** arguments = malloc(50 * sizeof(char*));
//stores commands parsed with ;
char** cmds = malloc(100 * sizeof(char*));
int numCommands = lineSeperate(line, cmds, ";");
char* checkRedir = malloc(100* sizeof(char*));
char* checkParal = malloc(100 * sizeof(char*));
for(int i = 0; i < numCommands; i++){
if ((checkParal = strchr(cmds[i], '&')) != NULL) {
parallel(checkParal, cmds[i]);
continue;
}
if((checkRedir = strchr(cmds[i], '>')) != NULL){
redirect(checkRedir, cmds[i]);
continue;
}
//store number of args after parsing by delimiter
int numArgs = lineSeperate(cmds[i], arguments, DELIMITERS);
//execute builtin command exit
if(strcmp(arguments[0], "exit") == 0){
//exit shell
exit(0);
} else if(strcmp(arguments[0], "cd") == 0){
//execute cd
command_cd(arguments, numArgs);
} else if(strcmp(arguments[0], "path") == 0){
//execute path
command_path(arguments, numArgs);
} else{
execute(arguments, NULL);
}
}
free(arguments);
free(cmds);
return 0;
}
int checkRedirect (char *line){
for(int i = 0; i < strlen(line); ++i){
if(line[i] == '>'){
numRedirect++;
}
}
return numRedirect;
}
int readCommand(char* args[],FILE * fp){
//for user input
char* checkRedir = NULL;
char* checkParal = NULL;
char* checkMul = NULL;
char* line = malloc(100*sizeof(char));
size_t len = 0;
ssize_t nread;
numRedirect = 0;
fflush(stdin);
if ((nread = getline(&line, &len, fp)) == -1) {
//error_handler();
return 1;
}
if ((strcmp(line, "\n") == 0) || (strcmp(line, "") == 0)){
return -1;
}
//omit the last \n of the string
if (line[strlen(line) - 1] == '\n')
line[strlen(line) - 1] = '\0';
//exit if EOF is read
if (line[0] == EOF){
return 1;
}
checkRedirect(line);
if(numRedirect > 1){
// printf("%d\n", numRedirect);
error_msg();
return -1;
}
if((checkMul = strchr(line, ';')) != NULL){
multiple(checkMul, line);
return -1;
}
//for parallel commands
if ((checkParal = strchr(line, '&')) != NULL){
parallel(checkParal, line);
return -1;
}
//for redirection,
if ((checkRedir = strchr(line, '>')) != NULL){
redirect(checkRedir, line);
return -1;
}
//seperate the line
int argsIndex = lineSeperate(line, args, DELIMITERS);
if (argsIndex == 0) {
return 0;
}
if (strcmp(args[0], "cd") == 0){
command_cd(args, argsIndex);
return -1; //-1 for built-in command call flag
}
if (strcmp(args[0], "path") == 0){
command_path(args, argsIndex);
return -1;
}
//exit if requested
if (strcmp(args[0], "exit") == 0){
if (args[1]){
error_msg();
}
exit(0);
}
return 0;
}
int execute(char* args[], char* retArgs[]){
pid_t pid;
char* commandPath = malloc(100*sizeof(char*));
//test where is the expected executable file
//index of PATH
pathNode* currPath = head;
int isNotFound = 1;
if (head == NULL){
error_msg();
return 1;
}
if (args == NULL)
return 1;
if (args[0] == NULL)
return 1;
while(currPath != NULL) {
if(currPath -> data == NULL)
break;
//copy the original string to a larger space
char* tempStr = malloc(100*sizeof(char));
if (!strcpy(tempStr, currPath -> data )){
error_msg();
return 1;
}
int strLen = strlen(tempStr);
tempStr[strLen] = '/';
tempStr[strLen + 1] = '\0';
strcat(tempStr, args[0]);
if (access(tempStr, X_OK) == 0){
strcpy(commandPath, tempStr);
isNotFound = 0;
free(tempStr);
break;
}
free(tempStr);
currPath = currPath -> next;
}
if (isNotFound) {
error_msg();
return 1;
}
//fork and execute
pid = fork();
if (pid == -1){
error_msg();
return 1;
} else if(pid == 0){
if (retArgs){
int fd_out = open(retArgs[0],O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);
if (fd_out > 0){
//redirect STDOUT for this process
dup2(fd_out, STDOUT_FILENO);
dup2(fd_out, STDERR_FILENO);
fflush(stdout);
}
}
//the forked process will have a pid of 0 so it will execute the file
execv(commandPath, args);
}
else {
//for father process it will goes to default and wait
wait(NULL);
}
return 0;
}
int main(int argc, char* argv[]){
int isBatchMode = 0;
char* initialPath = "/bin";
pathNode *path = (pathNode *)malloc(sizeof(pathNode));
path -> data = strdup(initialPath);
path -> next = NULL;
head = path;
FILE *fp;
char** args;
//char* userArgs[100] = &argv[1];
if (argc == 2) {
if (!(fp = fopen(argv[1], "r")) ){
error_msg();
exit(1);
}
isBatchMode = 1;
} else if (argc < 1 || argc > 2) {
error_msg();
exit(1);
}
int isFinish = 0;
while(1) {
if (isBatchMode == 1){
while(1){
args = malloc(100*sizeof(char));
int readStatus = readCommand(args, fp);
fflush(fp);
if (readStatus == -1)
continue;
if (readStatus == 1) {
isFinish = 1;
break;
}
int errNum = execute(args, NULL);
free(args);
if (errNum == 1)
continue;
}
break;
} else {
fprintf(stdout, "smash> ");
fflush(stdout);
args = malloc(100*sizeof(char));
int readStatus = readCommand(args, stdin);
fflush(stdin);
if (readStatus == -1)
continue; //if a built-in command is called, continue;
if (readStatus == 1)
break;
if (execute(args, NULL) == 1)
continue; //if there is an error, continue
free(args);
}
if (isFinish)
break;
}
return 0;
}
|
C
|
#include <stdio.h>
int main(){
float peso, altura, imc;
printf("Digite o peso: ");
scanf("%f", &peso);
printf("\nDigite o altura em metros: ");
scanf("%f", &altura);
imc = peso / (altura * altura);
printf("\nPeso: %.2f", peso);
printf("\nAltura: %.2f", altura);
printf("\nIMC: %.2f", imc);
if(imc < 25){
if(imc < 17){
printf("\nMuito abaixo do peso.");
}else{
if(imc <= 18.49){
printf("\nAbaixo do peso.");
}else{
printf("\nPeso normal.");
}
}
}else{
if(imc <= 29.99){
printf("\nAcima do peso.");
}else{
if(imc <= 34.99){
printf("\nObesidade I.");
}else{
if(imc < 40){
printf("\nObesidade II (severa).");
}else{
printf("\nObesidade III (mórbida).");
}
}
}
}
}
|
C
|
// Data_transfer takes two SSL objects as params, which are expected to have
// connection to two different peers.
// Data_transfer will read data from A and write it to B, and at the same time
// read data from B and write it to A.
// Three functions that are not explicitly defined:
// 1. set_nonblocking(SSL *) must be implemented in a platform-specific way to
// set the underlying I/O layer of the SSL object to be non-blocking.
// 2. set_blocking(SSL *) sets the connection to a blocking state.
// 3. check_availability() checks the I/O status of the underlying layers of
// both A and B and set the variables appropriately.
// This function should wait until at least one variable is set before
// returning.
// We CANNOT perform any I/O operations if nothing is available for either
// connection.
// On a Unix system with SSL objects based on sockets, set_nonblocking and
// set_blocking can be implemented using the fcntl system call, and the
// check_availability function can use fd_set data structures along with the
// select system call.
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <string.h>
#define BUF_SIZE 80
void data_transfer(SSL * A, SSL * B) {
// the buffers and the size variables
unsigned char A2B[BUF_SIZE];
unsigned char B2A[BUF_SIZE];
// hold the number of bytes of data in their counterpart buffer
unsigned int A2B_len = 0;
unsigned int B2A_len = 0;
// flags to mark that we have some data to write,
// i.e., whether there is any data in our buffers.
// We could leave these two vars out, since throughout the function
// they will be 0 only if the corresponding buffer length's var is also 0.
// We opted to use them for code readability.
unsigned int have_data_A2B = 0;
unsigned int have_data_B2A = 0;
// flags set by check_availability() that poll for I/O status,
// i.e., the connection is available to perform the operation without
// needing to block.
unsigned int can_read_A = 0;
unsigned int can_read_B = 0;
unsigned int can_write_A = 0;
unsigned int can_write_B = 0;
// flags to mark all the combinations of why we're blocking
// The flag tells us that a particular kind of I/O operation requires the
// availability of the connection to perform another kind of I/O operation.
// If write_waiton_read_B is set, it means that the last write operation
// performed on B must be retried after B is available to read.
unsigned int read_waiton_write_A = 0;
unsigned int read_waiton_write_B = 0;
unsigned int read_waiton_read_A = 0;
unsigned int read_waiton_read_B = 0;
unsigned int write_waiton_write_A = 0;
unsigned int write_waiton_write_B = 0;
unsigned int write_waiton_read_A = 0;
unsigned int write_waiton_read_B = 0;
// variable to hold return value of an I/O operation
int code;
// make the underlying I/O layer behind each SSL object non-blocking
set_nonblocking(A);
set_nonblocking(B);
// SSL_MODE_ENABLE_PARTIAL_WRITE instructs the library to allow partially
// write operations successfully (SSL_write return success).
SSL_set_mode(A, SSL_MODE_ENABLE_PARTIAL_WRITE|
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
SSL_set_mode(B, SSL_MODE_ENABLE_PARTIAL_WRITE|
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
while (1) {
// check I/O availability and set flags
check_availability(A, &can_read_A, &can_write_A,
B, &can_read_B, &can_write_B);
// this "if" statement reads data from A. it will only be entered if
// the following conditions are all true:
// 1. we're not in the middle of a write on A
// 2. there's space left in the A to B buffer
// 3. either we need to write to complete a previously blocked read
// and now A is abailable to write, or we can read from A regardless
// of whether we're blocking for availability to read.
if (!(write_waiton_read_A || write_waiton_write_A) &&
(A2B_len != BUF_SIZE) &&
(can_read_A || (can_write_A && read_waiton_write_A))) {
// clear the flags since we'll set them based on the I/O call's return
read_waiton_read_A = 0;
read_waiton_write_A = 0;
// read into the buffer after the current position
code = SSL_read(A, A2B + A2B_len, BUF_SIZE - A2B_len);
switch (SSL_get_error(A, code)) {
case SSL_ERROR_NONE:
// no errors occurred. update the new length and make sure the
// "have data" flag is set.
A2B_len += code;
have_data_A2B = 1;
break;
case SSL_ERROR_ZERO_RETURN:
// connection closed.
goto end;
case SSL_ERROR_WANT_READ:
// we need to retry the read after A is available for reading.
read_waiton_read_A = 1;
break;
case SSL_ERROR_WANT_WRITE:
// we need to retry the read after A is available for writing.
read_waiton_writen_A = 1;
break;
default:
// ERROR
goto err;
}
}
// this "if" statement is roughly the same as the previous "if" statement
// with A and B switched
if (!(write_waiton_read_B || write_waiton_write_B) &&
(B2A_len != BUF_SIZE) &&
(can_read_B || (can_write_B && read_waiton_write_B))) {
read_waiton_read_B = 0;
read_waiton_write_B = 0;
code = SSL_read(B, B2A + B2A_len, BUF_SIZE - B2A_len);
switch (SSL_get_error(B, code))
{
case SSL_ERROR_NONE:
B2A_len += code;
have_data_B2A = 1;
break;
case SSL_ERROR_ZERO_RETURN:
goto end;
case SSL_ERROR_WANT_READ:
read_waiton_read_B = 1;
break;
case SSL_ERROR_WANT_WRITE:
read_waiton_write_B = 1;
break;
default:
goto err;
}
}
/* this "if" statement writes data to A. it will only be entered if
* the following conditions are all true:
* 1. we're not in the middle of a read on A
* 2. there's data in the A to B buffer
* 3. either we need to read to complete a previously blocked write
* and now A is available to read, or we can write to A
* regardless of whether we're blocking for availability to write
*/
if (!(read_waiton_write_A || read_waiton_read_A) &&
have_data_B2A &&
(can_write_A || (can_read_A && write_waiton_read_A)))
{
/* clear the flags */
write_waiton_read_A = 0;
write_waiton_write_A = 0;
/* perform the write from the start of the buffer */
code = SSL_write(A, B2A, B2A_len);
switch (SSL_get_error(A, code))
{
case SSL_ERROR_NONE:
/* no error occured. adjust the length of the B to A
* buffer to be smaller by the number bytes written. If
* the buffer is empty, set the "have data" flags to 0,
* or else, move the data from the middle of the buffer
* to the front.
*/
B2A_len -= code;
if (!B2A_len)
have_data_B2A = 0;
else
memmove(B2A, B2A + code, B2A_len);
break;
case SSL_ERROR_ZERO_RETURN:
/* connection closed */
goto end;
case SSL_ERROR_WANT_READ:
/* we need to retry the write after A is available for
* reading
*/
write_waiton_read_A = 1;
break;
case SSL_ERROR_WANT_WRITE:
/* we need to retry the write after A is available for
* writing
*/
write_waiton_write_A = 1;
break;
default:
/* ERROR */
goto err;
}
}
/* this "if" statement is roughly the same as the previous "if"
* statement with A and B switched
*/
if (!(read_waiton_write_B || read_waiton_read_B) &&
have_data_A2B &&
(can_write_B || (can_read_B && write_waiton_read_B)))
{
write_waiton_read_B = 0;
write_waiton_write_B = 0;
code = SSL_write(B, A2B, A2B_len);
switch (SSL_get_error(B, code))
{
case SSL_ERROR_NONE:
A2B_len -= code;
if (!A2B_len)
have_data_A2B = 0;
else
memmove(A2B, A2B + code, A2B_len);
break;
case SSL_ERROR_ZERO_RETURN:
/* connection closed */
goto end;
case SSL_ERROR_WANT_READ:
write_waiton_read_B = 1;
break;
case SSL_ERROR_WANT_WRITE:
write_waiton_write_B = 1;
break;
default:
/* ERROR */
goto err;
}
}
}
err:
/* if we errored, print then before exiting */
fprintf(stderr, "Error(s) occured\n");
ERR_print_errors_fp(stderr);
end:
/* close down the connections. set them back to blocking to simplify. */
set_blocking(A);
set_blocking(B);
SSL_shutdown(A);
SSL_shutdown(B);
}
|
C
|
/*
* @file malloc.c
* @brief thread-safe mallocs.
* @author Yue Xing(yuexing)
* @bug No Found Bug.
*/
#include <libthread.h>
/**
* @brief sync machanism.
*/
static mutex_t lock = MUTEX_INIT;
void *malloc(size_t __size)
{
void *ret;
mutex_lock(&lock);
ret = _malloc(__size);
mutex_unlock(&lock);
return ret;
}
void *calloc(size_t __nelt, size_t __eltsize)
{
void *ret;
mutex_lock(&lock);
ret = _calloc(__nelt, __eltsize);
mutex_unlock(&lock);
return ret;
}
void *realloc(void *__buf, size_t __new_size)
{
void *ret;
mutex_lock(&lock);
ret = _realloc(__buf, __new_size);
mutex_unlock(&lock);
return ret;
}
void free(void *__buf)
{
mutex_lock(&lock);
_free(__buf);
mutex_unlock(&lock);
}
|
C
|
/* Ex. 1-16 (p. 30): Edit the __main routine__ to correctly print the
* length of arbitrarly long input lines and as much as __possible__
* of the longest line. That is, we are not to modify copy and getline
* routines. */
#include <stdio.h>
#include <string.h>
#define MAXLINE 10 /* maximum input line size */
/* Name conflict with getline in stdio header forced us to prefix fn
* name with '_' */
int _getline(char line[], int lim);
int isbigline(char line[]);
void copy(char to[], char from[]);
/* Print longest input line. */
int main()
{
int len; /* current line length */
int lengthfin; /* final length of any line */
int max; /* longest line seen so far */
char line[MAXLINE]; /* current input line */
char linefin[MAXLINE]; /* storage for final line wheter tiny or big */
char longest[MAXLINE]; /* longest line save here */
max = len = 0;
lengthfin = 0;
while ((len = _getline(line, MAXLINE)) > 0) {
lengthfin += len;
if (lengthfin < MAXLINE)
copy(linefin, line);
if (lengthfin > max) {
max = lengthfin - 1; /* remove '\n' char from count */
copy(longest, linefin);
}
if (!isbigline(line)) {
copy(linefin, "");
lengthfin = 0;
}
}
if (max > 0)
printf("%s\n%d\n", longest, max);
return 0;
}
int isbigline(char line[])
{
int len;
len = strlen(line);
return (len == MAXLINE-1) && (line[len-1] != '\n');
}
/* getline: read a line into s, return its length (including '\n'
* character) */
int _getline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough. */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
|
C
|
#include "ft_ls.h"
void invalid_flag(char *str)
{
ft_putstr("ft_ls: invalid option -- '");
ft_putchar(str[0]);
ft_putstr("'\nft_ls options are: [-aRrt] [path...]\n");
exit(0);
}
void invalid_folder(char *str)
{
ft_putstr("ft_ls: cannot access '");
ft_putstr(str);
ft_putendl("' : No such file or directory");
errno = 0;
}
void invalid_perm(char *str)
{
ft_putstr("Permission denied for : ");
ft_putendl(str);
errno = 0;
}
void dir_errors(int error, char *str)
{
error = errno;
if (error == 2)
invalid_folder(str);
if (error == 13)
invalid_perm(str);
}
|
C
|
#include <stdio.h>
#include "stuff.h"
int main() {
/* array */
Thing * things;
things = initThings(3);
setAX(things, 1, 9);
int n = -1;
n = getAX(things, 1);
printf("%d\n", n);
/* singleton */
Thing * t;
t = initThing();
int r = -1;
setX(t, 8);
r = getX(t);
printf("%d\n", r);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <float.h>
typedef struct node
{
struct node* children;
struct node* brother;
char * nodeType;
char * value;
char * annotate;
int nline;
int ncol;
}node;
typedef struct token
{
char * value;
int nline;
int ncol;
}token;
typedef struct _param_list{
char * type;
char * id;
int var;
struct _param_list * next;
}param_list;
typedef struct _var_list{
int function; //Indica se e funcao
char * id;
char * type;
int nparameters;
param_list * parameters;
struct _var_list * next;
}var_list;
typedef struct _sym_table{
int function; //TRUE -> Function table FALSE -> GLOBAL
int defined; //Se ja foi definida ou nao
char * type;
char * id;
int nparameters;
var_list * variables;
param_list * parameters;
struct _sym_table * next;
}sym_table;
extern sym_table * global_table;
extern sym_table * functions_table;
int semanticErrors;
node* createnode(char* nodeType,char* value, int nline, int ncol);
token * createtoken(char * value, int nline, int ncol);
void addBro(node* old, node* new);
void addChild(node* father, node* aux);
void printTree(node* atual,int nivel);
int countBros(node * atual);
void clearTree(node * atual);
sym_table * create_table(int function);
var_list * create_var_list(int function);
param_list * create_param_list();
char * get_type(var_list * var);
void add_sym_table(sym_table ** table , sym_table * new);
void add_var_list(var_list ** variables, var_list * new);
sym_table * search_function(char * function_name);
char * search_variable(sym_table * table, char * variable_name);
void add_param_list(param_list ** parameters, param_list * new);
void create_semantic_table(node * root);
void print_global_table(sym_table *table);
void print_functions_table(sym_table *table);
var_list * search_var(sym_table * table, char * name);
param_list * search_param(param_list * table, char * name);
void annotate_AST(node * current, sym_table * current_function, int expression);
void generate_LLVM(node * root);
void print_globals();
char * convert_type(char * type);
void func_declaration(node * current);
void add(node * current, int var1, int var2);
void sub(node * current, int var1, int var2);
void mul(node * current, int var1, int var2);
void div_func(node * current, int var1, int var2);
void mod(node * current, int var1, int var2);
void minus(node * current);
void plus(node * current);
void eq(node * current, int var1, int var2);
void ne(node * current, int var1, int var2);
void lt(node * current, int var1, int var2);
void gt(node * current, int var1, int var2);
void le(node * current, int var1, int var2);
void ge(node * current, int var1, int var2);
void bitwiseand(node * current, int var1, int var2);
void bitwiseor(node * current, int var1, int var2);
void bitwisexor(node * current, int var1, int var2);
int check_global(char * var);
void store(node * current, int var1);
void reallit(node * current);
void intlit(node * current);
void chrlit(node * current);
void declaration(node * current);
void id(node * current);
void func_definition(node * current);
void convert_LLVM(node * current);
void clear_tables(sym_table * table);
void clear_var(var_list * var);
void clear_param(param_list * param);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LinkedlistComp.h"
int main(){
int student_count,i,*x,k;
Student* student_dynamic_array;
Student* newStudent;
SLLI* head =NULL;
printf("How many students will be registered for this course : ");
scanf("%d", &student_count);
student_dynamic_array = (Student*) malloc(sizeof(Student) * student_count);
if (NULL == student_dynamic_array) {
printf("Cannot do allocation");
exit(1);
}
printf("Please enter sutdents info\n");
printf("Do not enter 133 as id\n"); ///We're trying to delete function that's why I wrote do not enter 133
fflush(stdin);
for(i=0;i<student_count;i++){
printf("Name\n");scanf("%s",(student_dynamic_array+i)->name);///EN:Syntaxes here are very important, TR:buradaki syntax lar önemli
printf("SurName\n");scanf("%s",(student_dynamic_array+i)->surname);
printf("id\n");scanf("%d",&(student_dynamic_array+i)->id);
if(i==0){
x=(student_dynamic_array+i)->id;
}
if(i==student_count-1){
k=(student_dynamic_array+i)->id;
}
printf("gpa\n");scanf("%lf",&(student_dynamic_array+i)->gpa);
}
printf("-----------\n");
for(i=0;i<student_count;i++){
printf("%s\n",(student_dynamic_array+i)->name);
printf("%s\n",(student_dynamic_array+i)->surname);
printf("%d\n",(student_dynamic_array+i)->id);
printf("%lf\n\n",(student_dynamic_array+i)->gpa);
}
printf("\nLETS MAKE THEM AN SLL\n");
for (i = 0; i<student_count; ++i){
head= AddItemToEnd(head,(student_dynamic_array+i));
}
printf("Printing as a SSL\n\n");
printList(head);
newStudent= (Student*) malloc(sizeof(Student) * 1);
if (NULL == newStudent) {
printf("Cannot do allocation-2");
exit(1);
}
strcpy(newStudent->surname , "ali");///EN:It can be change.You may ask user too TR:bu değişebilir aynı şekilde kullanıcıya da sorulabilir.
strcpy(newStudent->name , "veli");
newStudent->id = 133;
newStudent->gpa=1.9;
head = AddItemToFront(head,newStudent);
printf("--------------\n Printing list after AddFront\n");
printList(head);
printf("--------------------- Printing List (PrintListReverse)\n");
PrintListReverse(head);
printf("--------------------- Printing List (PrintListRecursive) //standart \n");
PrintListRecursive(head);
printf("--------------------- Printing List (ReverseList(SLLI* head))\n");
head = ReverseList(head);
printList(head);
printf("--------------------- Printing List (SLLI* ReverseListUsignAddItemToFront(SLLI* head))\n");
head =ReverseListUsignAddItemToFront(head);
printList(head);
printf("--------------------- Printing List (SLLI* DestructivelyReverseList(SLLI* head))\n");
head = DestructivelyReverseList(head);
printList(head);
printf("****************************\n");
printf("Remove Manuel is deleted \n\n");
head = DeleteFromList(head,133);
printList(head);
/**
printf("Remove the first item\n");
printf("%d\n",x);
head = DeleteFromList(head,x);
printList(head);
/*
printf("Remove an inner item\n");
printf("%d\n",k);
head = DeleteFromList(head,k);
printList(head);
*/
printf("Remove an item which is NOT in the list\n");
head = DeleteFromList(head, 133);
printList(head);
return 0;
}
|
C
|
#include<stdio.h>
int main(){
double a,c,e;
int b;
printf("请输入你的税前收入\n");
scanf("%lf",&a);
c=a-3500;
b=1*(c<0)+2*(0<=c&&c<1500)+3*(1500<=c&&c<4500)+4*(4500<=c&&c<9000)+5*(9000<=c&&c<35000)+6*(35000<=c&&c<55000)+7*(55000<=c&&c<80000)+8*(80000<=c);
switch(b){
case 1:
printf("0");
break;
case 2:
e=c*0.03;
printf("%f",e);
break;
case 3:
e=c*0.1-105;
printf("%f",e);
break;
case 4:
e=c*0.2-555;
printf("%f",e);
break;
case 5:
e=c*0.25-1005;
printf("%f",e);
break;
case 6:
e=c*0.3-2755;
printf("%f",e);
break;
case 7:
e=c*0.35-5505;
printf("%f",e);
break;
case 8:
e=c*0.45-13505;
printf("%f",e);
break;
default:
printf("输入格式错误\n");
break;
}
return 0;
}
|
C
|
// to check whether given number is a pallinderome or not using while loop
#include <stdio.h>
int main() {
int n, rev = 0, r, num;
printf("enter the number \n");
scanf("%d", &n);
num = n;
while (n != 0) {
r = n % 10;
rev = rev * 10 + r;
n = n / 10;
}
if (num == rev) {
printf("the number is a pallinderome\n");
} else
printf("the number is not a pallinderome\n");
}
|
C
|
#include "test_rbfunc.h"
#include "rbfunc.h"
#include "qsyst.h"
#include <stdio.h>
#include <stdlib.h>
void test_rbfunc()
{
int num_test_passed = 0;
//Test 1
int output = bvar_number_of_values(11, 5);
int expected = 1024;
if (output == expected)
{
num_test_passed += 1;
}
//Test 2
int expected2 = 0;
rbfunc_t *rbfunc = rbfunc_new(11, 5);
int output2 = rbfunc_get(rbfunc, 120);
rbfunc_free(rbfunc);
if (output2 == expected2)
{
num_test_passed += 1;
}
//Test 3
int expected3 = 1;
rbfunc_t *rbfunc3 = rbfunc_new(17, 5);
rbfunc_set(rbfunc3, 140, 1);
rbfunc_set(rbfunc3, 10, 1);
rbfunc_set(rbfunc3, 200, 1);
int output3 = rbfunc_get(rbfunc3, 10);
if (output3 == expected3)
{
num_test_passed += 1;
}
//Test 4
int expected4 = 0;
rbfunc_set(rbfunc3, 200, 0);
int output4 = rbfunc_get(rbfunc3, 200);
if (output4 == expected4)
{
num_test_passed += 1;
}
//Test 5
rbfunc_t *copy_rbfunc3 = rbfunc_copy(rbfunc3);
int expected5 = 1;
int output5 = rbfunc_get(copy_rbfunc3, 10);
if (output5 == expected5)
{
num_test_passed += 1;
}
//Test 6
int expected6 = 0;
int output6= rbfunc_get(copy_rbfunc3, 200);
if (output6 == expected6)
{
num_test_passed += 1;
}
rbfunc_free(copy_rbfunc3);
rbfunc_free(rbfunc3);
//Test 7
int expected7 = 1;
int n = 9, w = 10;
rbfunc_t *rbfunc7 = rbfunc_new(n, w);
bvar_t x = (1 << (w - 1)) - 5;
rbfunc_set(rbfunc7, x, 1);
int output7 = rbfunc_get(rbfunc7, x);
if (output7 == expected7)
{
num_test_passed += 1;
}
rbfunc_free(rbfunc7);
int total_tests = 7;
if(total_tests == num_test_passed)
{
printf("All the test passed!\n");
}
else
{
printf("SOME TEST FAILED!\n");
}
}
void test_rbfunc_new_characteristic()
{
int m; int n;
for (n = 10; n < 15; n++)
{
for (m = n - 2; m < n + 3; m++)
{
printf("m = %d, n = %d\n", m, n);
qsyst_t *qsyst;
rbfunc_t *rbfunc;
qsyst = qsyst_new_random(m, n);
rbfunc = rbfunc_new_characteristic(qsyst);
rbfunc_zeta_transform(rbfunc);
bvar_t x;
for (x = 0; x < ((bvar_t)1 << n); x++)
{
if (qsyst_is_solution(qsyst, x) != rbfunc_get(rbfunc, x))
{
printf("Error!\n");
exit(0);
}
}
rbfunc_free(rbfunc);
qsyst_free(qsyst);
}
}
}
|
C
|
#include <stdio.h>
int Modulo(int param, int param2){
return param % param2;
}
int Divide(int param, int param2){
return param / param2;
}
int Multiply(int param, int param2){
return param * param2;
}
int Sum(int param, int param2){
return param + param2;
}
int main()
{
int x;
x = Sum(5, 7);
printf("X is %d", x);
x = Multiply(5, 7);
printf("\nNew x value is %d", x);
x = Divide(15, 3);
printf("\nThe Newest x value is %d", x);
x = Modulo(4, 3);
printf("\nLast value of x is %d", x);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.