language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/**
*包含对控制台的一些基本操作
*/
#ifndef INCLUDE_CONSOLE_H
#define INCLUDE_CONSOLE_H
#include "types.h"
// 定义颜色(可用于前景色或者背景色)
typedef enum real_color
{
rc_black=0,
rc_blue=1,
rc_green=2,
rc_cyan=3,
rc_red=4,
rc_magenta=5,
rc_brown=6,
rc_light_grey=7,
rc_dark_grey=8,
rc_light_blue=9,
rc_light_green=10,
rc_light_cyan=11,
rc_light_red=12,
rc_light_magenta=13,
rc_light_brown=14,
rc_white=15
}real_color_t;
// 清屏操作
void console_clear();
// 输出一个带颜色的字符
void console_putc_color(char c,real_color_t fore,real_color_t back);
// 输出一个以'\0'结尾,黑色背景,白色前景色的字符串
void console_write(char *cstr);
// 输出一个以'\0'结尾,自定义前景色和背景色的字符串
void console_write_color(char *cstr,real_color_t fore,real_color_t back);
// 以16进制的形式输出一个自定义前景色和背景色的无符号整数,假设该整数是符合条件的整数
void console_write_hex(uint32_t n,real_color_t fore,real_color_t back);
// 以10进制形式输出一个自定义前景色和背景色的无符号整数,假设该整数是符合条件的整数
void console_write_dec(uint32_t n,real_color_t fore,real_color_t back);
// 以10进制形式输出一个自定义前景色和背景色的有符号整数,假设该整数是符合条件的整数
void console_write_dec_sign(int32_t n,real_color_t fore,real_color_t back);
// 打印一个浮点数f,小数点后保留len位.
void console_write_float(float f,int len,real_color_t fore,real_color_t back);
#endif
|
C
|
#include <stdio.h>
int main(){
int a = 10;
printf("a - %08X\n~a = %08X\n", a, ~a);
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int i;
char vChar[5];
int vInt[5];
double vDouble[5];
printf("\n endereco de vChar = %ld", (long int)vChar);
for (i = 0; i < 5; i++){
printf("\n endereco de vChar[%d] = %ld", i, (long int)&vChar[i]);
}
printf("\n\n endereco de vInt = %ld", (long int)vInt);
for (i = 0; i < 5; i++){
printf("\n endereco de vInt[%d] = %ld", i, (long int)&vInt[i]);
}
printf("\n\n endereco de vDouble = %ld", (long int)vDouble);
for (i = 0; i < 5; i++){
printf("\n endereco de vDouble[%d] = %ld", i, (long int)&vDouble[i]);
}
return 0;
}
|
C
|
#include "Translator.h"
void translateReg (char* reg, char* out) {
if (!strcmp(reg,"A0")) {
strcpy(out, "00");
}
else if (!strcmp(reg,"A1")) {
strcpy(out, "01");
}
else if (!strcmp(reg,"A2")) {
strcpy(out, "10");
}
else if (!strcmp(reg,"A3")) {
strcpy(out, "11");
}
else {
printf("[ERROR] The provided register name, namely \"%s\", is not part of this machine.\n", reg);
exit(1);
}
}
void processSymbols (char* line, int* addr, SymbolsTable* t) {
// First token: label or instruction name.
char* token = strtok(line, " ");
char symbol[MAXSYMBOLSIZE];
if (token[0] == '_') { // It's a label.
strcpy(symbol, token);
token = strtok(NULL, " "); // Gets the instruction.
if (!strcmp(token, ".data")) {
/* Gets the number of allocated bytes. */
token = strtok(NULL, " ");
int allocatedBytes = atoi(token);
token = strtok(symbol, ":"); // Strips ':' character from symbol
insertSymbolToTable(token, (*addr), t); // and inserts it on the table.
(*addr) = (*addr) + allocatedBytes; // Computes the address of the next symbol.
return;
}
token = strtok(symbol, ":"); // Strips ':' character from symbol
insertSymbolToTable(token, (*addr), t); // and inserts it on the table.
}
(*addr) = (*addr) + 2; // Computes the address of the next symbol.
}
void translateLine (char* line, char* out, SymbolsTable* t) {
char* token = strtok(line, " \n");
if (token[0] == '_') { // It's a label. Ignore it.
token = strtok(NULL, " "); // Gets the instruction name.
}
/* Tries to match a single-word instruction first. */
if (!strcmp(token, "stop")) {
strncpy(out, "0000000000000000", 17);
}
else if (!strcmp(token, "return")) {
strncpy(out,"1000000000000000", 17);
}
/* From now on, deals with non single-word instructions. */
else if (!strcmp(token, ".data")) {
int allocatedBytes;
int value;
token = strtok(NULL, " "); // Gets the number of allocated bytes.
allocatedBytes = atoi(token);
token = strtok(NULL, "; \n"); // Gets the initial value.
value = atoi(token);
constantToNbitString(value, 8*allocatedBytes, out);
}
else if (!strcmp(token, "load")) {
strncpy(out,"00001", 6);
token = strtok(NULL, " "); // Gets dst register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
token = strtok(NULL, "; \n"); // Gets dst label.
/* If the first character is a letter, I'm assuming it's a
label name, otherwhise I assume it's a constant.
*/
if (!isdigit(token[0])) {
strncpy(out+7, getAddress(token, t), 10);
}
else {
constantTo9bitString(atoi(token), out+7);
}
}
else if (!strcmp(token, "store")) {
strncpy(out,"00010", 6);
token = strtok(NULL, " "); // Gets dst register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
token = strtok(NULL, "; \n"); // Gets dst label.
/* If the first character is a letter, I'm assuming it's a
label name, otherwhise I assume it's a constant.
*/
if (!isdigit(token[0])) {
strncpy(out+7, getAddress(token, t), 10);
}
else {
constantTo9bitString(atoi(token), out+7);
}
}
else if (!strcmp(token, "read")) {
strncpy(out,"00011", 6);
strncpy(out+5,"000000000", 10);
token = strtok(NULL, "; \n"); // Gets dst register.
char reg[3];
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "write")) {
strncpy(out,"00100", 6);
strncpy(out+5,"000000000", 10);
token = strtok(NULL, "; \n"); // Gets dst register.
char reg[3];
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "add")) {
strncpy(out,"00101", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
strncpy(out+7,"0000000", 8);
token = strtok(NULL, "; \n"); // Gets second register.
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "subtract")) {
strncpy(out,"00110", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
strncpy(out+7,"0000000", 8);
token = strtok(NULL, "; \n"); // Gets second register.
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "multiply")) {
strncpy(out,"00111", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
strncpy(out+7,"0000000", 8);
token = strtok(NULL, "; \n"); // Gets second register.
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "divide")) {
strncpy(out,"01000", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
strncpy(out+7,"0000000", 8);
token = strtok(NULL, "; \n"); // Gets second register.
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "jump")) {
strncpy(out,"01001", 6);
strncpy(out+5, "00", 3);
token = strtok(NULL, "; \n"); // Gets address label.
/* If the first character is a letter, I'm assuming it's a
label name, otherwhise I assume it's a constant.
*/
if (!isdigit(token[0])) {
strncpy(out+7, getAddress(token, t), 9);
}
else {
constantTo9bitString(atoi(token), out+7);
}
}
else if (!strcmp(token, "jmpz")) {
strncpy(out,"01010", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
token = strtok(NULL, "; \n"); // Gets address label.
/* If the first character is a letter, I'm assuming it's a
label name, otherwhise I assume it's a constant.
*/
if (!isdigit(token[0])) {
strncpy(out+7, getAddress(token, t), 9);
}
else {
constantTo9bitString(atoi(token), out+7);
}
}
else if (!strcmp(token, "jmpn")) {
strncpy(out,"01011", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
token = strtok(NULL, "; \n"); // Gets address label.
/* If the first character is a letter, I'm assuming it's a
label name, otherwhise I assume it's a constant.
*/
if (!isdigit(token[0])) {
strncpy(out+7, getAddress(token, t), 9);
}
else {
constantTo9bitString(atoi(token), out+7);
}
}
else if (!strcmp(token, "move")) {
strncpy(out,"01100", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
strncpy(out+7,"0000000", 8);
token = strtok(NULL, "; \n"); // Gets second register.
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "push")) {
strncpy(out,"01101", 6);
strncpy(out+5,"000000000", 10);
token = strtok(NULL, "; \n"); // Gets dst register.
char reg[3];
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "pop")) {
strncpy(out,"01110", 6);
strncpy(out+5,"000000000", 10);
token = strtok(NULL, "; \n"); // Gets dst register.
char reg[3];
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "call")) {
strncpy(out,"01111", 6);
strncpy(out+5, "00", 3);
token = strtok(NULL, "; \n"); // Gets address label.
strncpy(out+7, getAddress(token, t), 10);
}
else if (!strcmp(token, "load_s")) {
strncpy(out,"10001", 6);
token = strtok(NULL, " "); // Gets dst register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
token = strtok(NULL, "; \n"); // Gets dst label.
/* If the first character is a letter, I'm assuming it's a
label name, otherwhise I assume it's a constant.
*/
if (!isdigit(token[0])) {
strncpy(out+7, getAddress(token, t), 10);
}
else {
constantTo9bitString(atoi(token), out+7);
}
}
else if (!strcmp(token, "store_s")) {
strncpy(out,"10010", 6);
token = strtok(NULL, " "); // Gets dst register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
token = strtok(NULL, "; \n"); // Gets dst label.
/* If the first character is a letter, I'm assuming it's a
label name, otherwhise I assume it's a constant.
*/
if (!isdigit(token[0])) {
strncpy(out+7, getAddress(token, t), 10);
}
else {
constantTo9bitString(atoi(token), out+7);
}
}
else if (!strcmp(token, "load_c")) {
strncpy(out,"10011", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
token = strtok(NULL, "; \n"); // Gets constant.
constantTo9bitString(atoi(token), out+7);
}
else if (!strcmp(token, "load_i")) {
strncpy(out,"10100", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
strncpy(out+7,"0000000", 8);
token = strtok(NULL, "; \n"); // Gets second register.
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "store_i")) {
strncpy(out,"10101", 6);
token = strtok(NULL, " "); // Gets first register.
char reg[3];
translateReg(token, reg);
strncpy(out+5, reg, 3);
strncpy(out+7,"0000000", 8);
token = strtok(NULL, "; \n"); // Gets second register.
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
else if (!strcmp(token, "copytop")) {
strncpy(out,"10110", 6);
strncpy(out+5,"000000000", 10);
token = strtok(NULL, "; \n"); // Gets register.
char reg[3];
translateReg(token, reg);
strncpy(out+14, reg, 3);
}
}
|
C
|
#include <stdio.h>
// Compiling C program -> gcc name_of_file.c -o name_of_exe
// ls -al name_of_exe -> see info about the file (size etc)
// int -> return value is a integer
// Void -> no arguments
int main(void) {
printf("Hello World!\n");
}
|
C
|
#include "steepest_descent.h"
#include <string.h>
#define EPSILON 1e-6
/*
* These functions are necessary for the software. They must be
* implemented in a separate file by the user.
*/
void cutest_ufn_ (my_integer *, my_integer * n, my_doublereal * x, my_doublereal * f);
void cutest_uofg_ (my_integer *, my_integer * n, my_doublereal * x, my_doublereal * f,
my_doublereal * g, my_logical * grad);
my_doublereal NormInf (my_doublereal * x, my_integer n) {
my_integer i;
my_doublereal s = 0.0;
for (i = 0; i < n; i++) {
my_doublereal absxi = fabs(x[i]);
if (absxi > s)
s = absxi;
}
return s;
}
my_doublereal Norm (my_doublereal * x, my_integer n) {
my_integer i;
my_doublereal s = 0.0;
for (i = 0; i < n; i++)
s += x[i]*x[i];
return sqrt(s);
}
my_doublereal NormSqr (my_doublereal * x, my_integer n) {
my_integer i;
my_doublereal s = 0.0;
for (i = 0; i < n; i++)
s += x[i]*x[i];
return s;
}
void SteepestDescent (my_doublereal * x, my_integer n, Status *status, Param *param) {
my_doublereal * g, f, fp;
my_doublereal * xp, lambda, ng_sqr;
my_doublereal alpha = param->alpha;
my_integer i, maxiter = param->maxiter;
my_integer st;
my_logical one = 1;
if ( (x == 0) || (status == 0) )
return;
g = (my_doublereal *) malloc(n * sizeof(my_doublereal) );
xp = (my_doublereal *) malloc(n * sizeof(my_doublereal) );
status->iter = 0;
status->n_objfun = 0;
status->n_gradfun = 0;
status->exitflag = 0;
cutest_uofg_(&st, &n, x, &f, g, &one);
status->n_objfun++;
status->n_gradfun++;
status->ng = NormInf(g, n);
while (status->ng > EPSILON) {
lambda = 1;
for (i = 0; i < n; i++) {
xp[i] = x[i] - g[i];
}
cutest_ufn_(&st, &n, xp, &fp);
status->n_objfun++;
ng_sqr = status->ng*status->ng;
while (fp > f - alpha * lambda * ng_sqr) {
for (i = 0; i < n; i++) {
xp[i] = x[i] - lambda*g[i];
}
lambda = lambda/2;
cutest_ufn_(&st, &n, xp, &fp);
status->n_objfun++;
}
for (i = 0; i < n; i++)
x[i] = xp[i];
cutest_uofg_(&st, &n, x, &f, g, &one);
status->n_objfun++;
status->n_gradfun++;
status->ng = NormInf(g, n);
status->iter++;
if (status->iter >= maxiter) {
status->exitflag = 1;
break;
}
}
status->f = f;
free(xp);
free(g);
}
void SD_Print (my_doublereal * x, my_integer n, Status * status) {
my_integer i;
if ( (x == 0) || (status == 0) )
return;
if (status->exitflag == 0) {
printf("Converged to solution\n");
} else if (status->exitflag == 1) {
printf("Maximum iterations reached\n");
}
printf("x = (%lf", x[0]);
for (i = 1; i < n; i++)
printf(",%lf", x[i]);
printf(")\n");
printf("Iter = %d\n", status->iter);
printf("f(x) = %lf\n", status->f);
printf("|g(x)| = %lf\n", status->ng);
printf("objfun calls = %d\n", status->n_objfun);
printf("gradfun calls = %d\n", status->n_gradfun);
printf("exitflag = %d\n", status->exitflag);
printf("\n");
}
void DefaultParam (Param *param) {
param->alpha = 1e-4;
param->maxiter = 1e4;
}
void ReadParam (Param *param) {
FILE *f = fopen("param.spc","r");
char name[64];
if (f == NULL) {
printf("param.spc not found. Skipping\n");
return;
}
while (fscanf(f, "%s", name) != EOF) {
if (strcmp(name, "alpha") == 0) {
fscanf(f, "%lf", ¶m->alpha);
} else if (strcmp(name, "maxiter") == 0) {
fscanf(f, "%d", ¶m->maxiter);
} else {
printf("Error '%s' is not a valid parameter\n", name);
break;
}
}
fclose(f);
}
|
C
|
/*
* printf_test.c
*
* Created on: 2018-2-20
* Author: virusv
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "smartocd.h"
#include "Library/misc/misc.h"
char* itoa(int num, char *str, int radix) {
/*索引表*/
char index[] = "0123456789ABCDEF";
unsigned unum;/*中间变量*/
int i = 0, j, k;
/*确定unum的值*/
if (radix == 10 && num < 0)/*十进制负数*/
{
unum = (unsigned) -num;
str[i++] = '-';
} else
unum = (unsigned) num;/*其他情况*/
/*转换*/
do {
str[i++] = index[unum % (unsigned) radix];
unum /= radix;
} while (unum);
str[i] = '\0';
/*逆序*/
if (str[0] == '-')
k = 1;/*十进制负数*/
else k = 0;
char temp;
for (j = k; j <= (i - 1) / 2; j++) {
temp = str[j];
str[j] = str[i - 1 + k - j];
str[i - 1 + k - j] = temp;
}
return str;
}
#define BIT2BYTE(bitCnt) ({ \
int byteCnt = 0; \
int tmp = (bitCnt) >> 6; \
byteCnt = tmp + (tmp << 3); \
tmp = bitCnt & 0x3f; \
byteCnt += tmp ? ((tmp + 7) >> 3) + 1 : 0; \
})
#define SET_Nth_BIT(data,n,val) do{ \
uint8_t tmp_data = *(CAST(uint8_t *, (data)) + ((n)>>3)); \
tmp_data &= ~(1 << ((n) & 0x7)); \
tmp_data |= ((val) & 0x1) << ((n) & 0x7); \
*(CAST(uint8_t *, (data)) + ((n)>>3)) = tmp_data; \
}while(0);
int test_main(int argc, const char *argv[]){
uint8_t sdad[5];
memset(sdad, 0, 5);
for(int i=0;i<40;i++){
SET_Nth_BIT(sdad, i, 1);
misc_PrintBulk(sdad, 5, 5);
}
for(int i=0;i<40;i++){
SET_Nth_BIT(sdad, i, 0);
misc_PrintBulk(sdad, 5, 5);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main() {
double r;
double surface;
double volume;
double perimeter;
printf("%s: ", "Enter radius");
scanf("%lf", &r);
perimeter = 2 * M_PI * r;
surface = 4 * M_PI * (r * r);
volume = (4.0 / 3.0) * M_PI *(r * r * r);
printf("Perimeter: %lf\n", perimeter);
printf("Surface: %lf\n", surface);
printf("Volume: %lf\n", volume);
return 0;
}
|
C
|
/*
* RCS info
* $Author: steves $
* $Locker: $
* $Date: 2009/03/12 17:06:46 $
* $Id: rpg_itc.c,v 1.13 2009/03/12 17:06:46 steves Exp $
* $Revision: 1.13 $
* $State: Exp $
*/
/********************************************************************
This module contains the functions that support
Inter-Task Common block (ITC) based interprocess communication.
********************************************************************/
#include <rpg.h>
#define MAXN_ITCS 32
enum {ITC_READ, ITC_WRITE}; /* values for Itc_t.access */
typedef struct { /* data structure for ITC common blocks */
int id; /* ITC common block id */
int access; /* access method: ITC_READ or ITC_WRITE */
char *name; /* LB_name for the ITC */
int data_id; /* Data ID for LB. */
LB_id_t msgid; /* LB message id of the ITC */
int fd; /* File descriptor for ITC. */
char *ptr; /* pointer to the common block */
int len; /* length of the ITC */
int sync_prd; /* syncronization product id (or ITC_ON_CALL, ITC_ON_EVENT) */
en_t event_id; /* associated event id (for ON_EVENT only) */
int updated; /* updated flag (for all timing values except ITC_ON_EVENT) */
int (*callback) (); /* callback function */
} Itc_t;
static Itc_t Itc [MAXN_ITCS];
/* list of all ITC */
static int N_itcs = 0; /* number of ITCs */
static int Events_registered = 0;
/* flag indicating that events have been registered
with ITC updates */
/* local functions */
void Report_itc( int ind );
void ITC_update_callback( int fd, LB_id_t msgid, int msg_info, void *arg );
/***********************************************************************
Description:
This function registers an input ITC common block.
Inputs:
itc_id - id number of the ITC. It is a combination of
major an minor id code. The major code is used
for the LB name and the minor code is for the
LB message id of the ITC.
first - address of the first element of the ITC.
last - address after the last element of the ITC.
sync_prd - the syncronization product id. ITC_ON_CALL means
no automatic syncronized update is performed.
ITC_ON_EVENT means automatic update performed when
event triggered. ITC_WITH_EVENT means the event
is triggered upon reading the ITC (assumes
explicit read).
event_id - the syncronization event id. (optional)
Return:
Return value is never used.
Notes:
When an error due to coding or incorrect run time
configuration is detected, this function aborts the task.
This function can be called multiplically to associate
an input ITC with multiple input products.
***********************************************************************/
int RPG_itc_in( fint *itc_id, void *first, void *last, fint *sync_prd, ... ){
int i;
va_list ap;
/*
Do for all registered ITCs.
*/
for (i = 0; i < N_itcs; i++) {
/*
Check for duplicate registration. Duplicates are not registered.
*/
if( (*itc_id == Itc [i].id)
&&
(*sync_prd == Itc [i].sync_prd)
&&
(Itc [i].access == ITC_READ) )
return (0);
}
/*
Too many ITCs registered.
*/
if (N_itcs >= MAXN_ITCS){
/*
This will cause a later abort.
*/
LE_send_msg ( GL_INFO, "Too many ITC specified\n");
return (0);
}
/*
Register ITC id and product synchronized with ITC read.
*/
Itc [N_itcs].id = *itc_id;
Itc [N_itcs].data_id = (*itc_id / ITC_IDRANGE) * ITC_IDRANGE;
Itc [N_itcs].msgid = *itc_id % ITC_IDRANGE;
Itc [N_itcs].sync_prd = *sync_prd;
/*
If ITC update synchronized with an event.
*/
if( (*sync_prd == ITC_ON_EVENT) || (*sync_prd == ITC_WITH_EVENT) ){
/*
Register event id.
*/
va_start( ap, sync_prd );
Itc [N_itcs].event_id = (en_t) *(va_arg(ap, int *));
va_end(ap);
if( *sync_prd == ITC_ON_EVENT )
Events_registered = 1;
}
else
Itc [N_itcs].event_id = -1;
/*
Register all other ITC information.
*/
Itc [N_itcs].ptr = (char *) first;
Itc [N_itcs].access = ITC_READ;
Itc [N_itcs].name = NULL;
Itc [N_itcs].len = (char *) last - (char *) first;
Itc [N_itcs].callback = NULL;
Itc [N_itcs].updated = -1;
Itc [N_itcs].fd = ORPGDA_open( Itc [N_itcs].data_id, LB_WRITE );
/* Tell user about the ITC. */
Report_itc( N_itcs );
/*
Increment the number of registered ITCs.
*/
N_itcs++;
return (0);
/* End of RPG_itc_in */
}
/***********************************************************************
Description:
This function registers an output ITC common block.
Inputs:
itc_id - id number of the ITC. It is a combination of
major an minor id code. The major code is used
for the LB name and the minor code is for the
LB message id of the ITC.
first - address of the first element of the ITC.
last - address after the last element of the ITC.
sync_prd - the syncronization product id. ITC_ON_CALL means
no automatic syncronized update is performed.
ITC_ON_EVENT means automatic update performed when
event triggered. ITC_WITH_EVENT means the event
is triggered upon writing the ITC (assumes
explicit write).
event_id - the syncronization event id. (optional)
Return:
Return value is never used.
Notes:
When an error due to coding or incorrect run time
configuration is detected, this function aborts the task.
This function can be called multiplically to associate
an input ITC with multiple output products.
***********************************************************************/
int RPG_itc_out( fint *itc_id, void *first, void *last, fint *sync_prd, ... ){
int i;
va_list ap;
/*
Do for all registered ITCs.
*/
for (i = 0; i < N_itcs; i++) {
/*
Check for duplicate ITC registration. Duplicates are not
registered.
*/
if( (*itc_id == Itc [i].id)
&&
(*sync_prd == Itc [i].sync_prd)
&&
(Itc [i].access == ITC_WRITE) )
return (0);
}
/*
Too many ITCs registered.
*/
if (N_itcs >= MAXN_ITCS) {
/*
This will cause a later abort.
*/
LE_send_msg( GL_INFO, "Too many ITC specified\n" );
return (0);
}
/*
Register the ITC id and product the ITC is synchronized with.
*/
Itc [N_itcs].id = *itc_id;
Itc [N_itcs].data_id = (*itc_id / ITC_IDRANGE) * ITC_IDRANGE;
Itc [N_itcs].msgid = *itc_id % ITC_IDRANGE;
Itc [N_itcs].sync_prd = *sync_prd;
/*
If ITC update syncronized to event, then ...
*/
if( *sync_prd == ITC_ON_EVENT || *sync_prd == ITC_WITH_EVENT ){
/*
Register the event id.
*/
va_start( ap, sync_prd );
Itc [N_itcs].event_id = (en_t) *(va_arg(ap, int *));
va_end(ap);
if( *sync_prd == ITC_ON_EVENT )
Events_registered = 1;
}
else
Itc [N_itcs].event_id = -1;
/*
Register all other information.
*/
Itc [N_itcs].ptr = (char *) first;
Itc [N_itcs].access = ITC_WRITE;
Itc [N_itcs].name = NULL;
Itc [N_itcs].len = (char *) last - (char *) first;
Itc [N_itcs].callback = NULL;
Itc [N_itcs].updated = -1;
/* For output ITC, open the ITC with write permission. */
Itc [N_itcs].fd = ORPGDA_open( Itc [N_itcs].data_id, LB_WRITE );
/* Tell user about the ITC. */
Report_itc( N_itcs );
/*
Increment the number of ITCs registered.
*/
N_itcs++;
return (0);
/* End of RPG_itc_out */
}
/***********************************************************************
Description:
This function registers an callback function for the ITC "itc_id".
Inputs:
itc_id - id number of the ITC. It is a combination of
major an minor id code. The major code is used
for the LB name and the minor code is for the
LB message id of the ITC.
func - the callback function for the ITC.
Return:
Return value is never used.
Notes:
If "itc_id" is not registered, this function aborts the task.
***********************************************************************/
int RPG_itc_callback( fint *itc_id, fint (*func)() ){
int i, itc_registered;
/*
Initialize the ITC registered flag to "not registered".
*/
itc_registered = 0;
/*
Do for all registered ITCs.
*/
for (i = 0; i < N_itcs; i++) {
/*
If ITC id match, then ...
*/
if (*itc_id == Itc [i].id){
/*
Register the ITC callback function, and set ITC
registered flag.
*/
Itc [i].callback = func;
itc_registered = 1;
}
}
/*
Terminate if ITC is not registered.
*/
if (!itc_registered) {
PS_task_abort ("unregistered ITC specified in RPG_itc_callback\n");
return (0);
}
return (0);
/* End of RPG_itc_callback */
}
/***********************************************************************
Description:
Register read-access ITCs for LB notification.
***********************************************************************/
void ITC_initialize(){
int ret, i;
/*
Do for all registered ITCs ....
*/
for (i = 0; i < N_itcs; i++) {
/*
If not updated by event and access is read ...
*/
if( (Itc [i].sync_prd != ITC_ON_EVENT)
&&
(Itc [i].access == ITC_READ) ){
/*
Register the ITC for LB Notification.
*/
if( (ret = ORPGDA_UN_register( Itc [i].data_id, Itc [i].msgid,
ITC_update_callback )) < 0 )
LE_send_msg( GL_INFO, "ORPGDA_UN_register Failed (%d)\n", ret );
else
Itc [i].updated = 1;
}
}
/* End of ITC_initialize() */
}
/***********************************************************************
Description:
This function reads in all ITC messages associated
with input product inp_prod.
Inputs:
inp_prod - an input product id (buffer type) that some
of the ITCs are associated.
Notes:
When an error due to coding or incorrect run time
configuration is detected, this function aborts the task.
This function is called internally when product "inp_prod"
is read from its buffer.
***********************************************************************/
void ITC_read_all (int inp_prod){
int i;
int status;
/*
Do for all registered ITCs.
*/
for (i = 0; i < N_itcs; i++) {
/*
If ITC associated with input product and ITC access is read.
*/
if( (Itc [i].sync_prd == inp_prod) && (Itc [i].access == ITC_READ) ){
/*
Read the ITC.
*/
RPG_itc_read (&(Itc [i].id), &status);
if (status != NORMAL)
PS_task_abort ("ITC read failed\n");
}
}
return;
/* End of ITC_read_all */
}
/***********************************************************************
Description:
This function writes out all ITC messages associated
with output product out_prod.
Inputs:
out_prod - an output product id (buffer type) that some
of the ITCs are associated.
Notes:
when an error due to coding or incorrect run time
configuration is detected, this function aborts the task.
This function is called internally when product "out_prod"
is written to its buffer.
***********************************************************************/
void ITC_write_all (int out_prod){
int i;
int status;
/*
Do for all ITCs.
*/
for (i = 0; i < N_itcs; i++) {
/*
If ITC associated with output product and ITC access is write.
*/
if( (Itc [i].sync_prd == out_prod) && (Itc [i].access == ITC_WRITE) ){
/*
Write the ITC.
*/
RPG_itc_write (&(Itc [i].id), &status);
if (status != NORMAL)
PS_task_abort ("ITC write failed\n");
}
}
return;
/* End of ITC_write_all */
}
/***********************************************************************
Description:
This function reads in the ITC "itc_id".
Inputs:
itc_id - the id of the ITC to update.
status - pointer to int to store ITC read status.
Return:
Return value is never used.
Notes:
When an error due to coding or incorrect run time
configuration is detected, this function aborts the task.
***********************************************************************/
int RPG_itc_read( fint *itc_id, fint *status ){
int len, ret;
int i;
/*
Initialize the status return value to ok (NORMAL).
*/
*status = NORMAL;
/*
Do for all registered ITCs.
*/
for (i = 0; i < N_itcs; i++) {
/*
If ITC matchand access mode is read, break out of loop.
*/
if( (Itc [i].id == *itc_id) && (Itc [i].access == ITC_READ) )
break;
}
/*
ITC not registered.
*/
if (i >= N_itcs)
PS_task_abort ("itc_id (%d) not registered\n", *itc_id);
/*
Read the ITC if the ITC has been updated or if the LB_notification
failed (so we don't know whether or not the LB was updated.
*/
if( Itc [i].updated != 0 ){
/* If the updated flag is less than 0, this indicates the LB_notification
failed. In this case, we always want to read the LB. */
if( Itc [i].updated > 0 )
Itc [i].updated = 0;
len = ORPGDA_read (Itc [i].data_id, Itc [i].ptr, Itc [i].len,
Itc [i].msgid);
if (len != Itc [i].len){
LE_send_msg( GL_INFO, "ITC READ FAILED: Itc[%d].data_id %d, Itc[%d].msgid %d\n",
i, Itc[i].data_id, i, Itc[i].msgid );
LE_send_msg( GL_INFO, "--->Returned len %d != ITc[%d].len %d\n", len, i, Itc[i].len );
*status = NO_DATA;
}
/*
If callback function associated with ITC read, call it now.
*/
else if (Itc [i].callback != NULL)
Itc [i].callback (&(Itc [i].id), &(Itc [i].access));
}
/*
If event associated with read, post it now.
*/
if( (Itc [i].event_id < 0)
||
(Itc [i].sync_prd == ITC_ON_EVENT) )
return (0);
if( ( ret = EN_post( Itc [i].event_id, NULL, 0,
EN_POST_FLAG_DONT_NTFY_SENDER ) ) < 0 )
LE_send_msg( GL_INFO, "EN_post Of %d Failed\n", Itc [i].event_id );
else
LE_send_msg( GL_INFO, "Event %d Posted\n", Itc [i].event_id );
return (0);
/* End of RPG_itc_read */
}
/***********************************************************************
Description:
This function writes out the ITC "itc_id" to its LB.
Inputs:
itc_id - the id of the ITC to output.
status - pointer to int where status of write operation
is stored.
Return:
Return value is never used.
Notes:
When an error due to coding or incorrect run time configuration
is detected, this function aborts the task.
***********************************************************************/
int RPG_itc_write( fint *itc_id, fint *status ){
int len, ret;
int i;
/*
Initialize the status return value to ok (NORMAL).
*/
*status = NORMAL;
/*
Do for registered ITCs.
*/
for (i = 0; i < N_itcs; i++) {
/*
If ITC match and access mode is write, break out of
loop.
*/
if (Itc [i].id == *itc_id && Itc [i].access == ITC_WRITE)
break;
}
/*
ITC not registered.
*/
if (i >= N_itcs)
PS_task_abort ("itc_id (%d) Not Registered\n", *itc_id);
/*
If callback function registered with ITC, call it now.
*/
if (Itc [i].callback != NULL)
Itc [i].callback (&(Itc [i].id), &(Itc [i].access));
/*
Write the ITC.
*/
len = ORPGDA_write (Itc [i].data_id, Itc [i].ptr, Itc [i].len,
Itc [i].msgid);
if (len < 0){
LE_send_msg( GL_INFO, "ITC WRITE FAILED (%d): Itc[%d].data_id %d, Itc[i].msgid %d\n",
len, i, Itc[i].data_id, i, Itc[i].msgid );
*status = NO_DATA;
}
/*
If event associated with write, post it now.
*/
if( (Itc [i].event_id < 0)
||
(Itc [i].sync_prd == ITC_ON_EVENT) )
return (0);
if( ( ret = EN_post( Itc [i].event_id, NULL, 0,
EN_POST_FLAG_DONT_NTFY_SENDER ) ) < 0 )
LE_send_msg( GL_INFO, "EN_post Of %d Failed\n", Itc [i].event_id );
else
LE_send_msg( GL_INFO, "Event %d Posted\n", Itc [i].event_id );
return (0);
/* End of RPG_itc_write */
}
/***********************************************************************
Description:
This function updates ITC that are attached to the data time.
Inputs:
new_vol - flag, if set, indicates beginning of a volume scan.
Return:
There is no return value defined for this function.
Notes:
On fatal error this function aborts the task.
***********************************************************************/
void ITC_update (int new_vol){
int i;
int status;
/*
Do for all ITCs ...
*/
for (i = 0; i < N_itcs; i++) {
/*
If ITC registered for write access, then ...
*/
if (Itc [i].access == ITC_WRITE) {
/*
If new volume scan and ITC update synchronized to beginning
of volume, or if ITC update synchronized to beginning of elevation,
then ....
*/
if ((Itc [i].sync_prd == ITC_BEGIN_VOLUME && new_vol) ||
Itc [i].sync_prd == ITC_BEGIN_ELEVATION) {
/*
Write the ITC.
*/
RPG_itc_write (&(Itc [i].id), &status);
if (status != NORMAL ){
if( !AP_abort_flag( UNKNOWN ) )
PS_task_abort ("ITC write failed in ITC_update. Status = %d\n",
status);
else
LE_send_msg ( GL_INFO, "ITC write failed in ITC_update. Status = %d\n",
status);
}
}
}
/*
If ITC registered for read access, then ...
*/
if (Itc [i].access == ITC_READ) {
/*
If new volume scan and ITC update synchronized to beginning
of volume, or if ITC update synchronized to beginning of elevation,
then ....
*/
if ((Itc [i].sync_prd == ITC_BEGIN_VOLUME && new_vol) ||
Itc [i].sync_prd == ITC_BEGIN_ELEVATION) {
/*
Read ITC.
*/
RPG_itc_read (&(Itc [i].id), &status);
if (status != NORMAL){
if(!AP_abort_flag( UNKNOWN ) )
PS_task_abort ("ITC read failed in ITC_update. Status = %d\n",
status);
else
LE_send_msg (GL_INFO, "ITC read failed in ITC_update. Status = %d\n",
status);
}
}
}
}
return;
/* End of ITC_update */
}
/***********************************************************************
Description:
This function updates ITC that are associatged with an event.
Inputs:
event_id - event id which triggers ITC update.
Return:
There is no return value defined for this function.
Notes:
On fatal error this function aborts the task.
***********************************************************************/
void ITC_update_by_event ( en_t event_id ){
int i;
int status;
/*
If no events registered, no point in continuing.
*/
if( !Events_registered )
return;
/*
Do for all registered ITCs.
*/
for (i = 0; i < N_itcs; i++) {
/*
If ITC access is write, then ...
*/
if (Itc [i].access == ITC_WRITE) {
/*
If ITC update associated with event and event_id matches
ITC event id, then ....
*/
if ((Itc [i].sync_prd == ITC_ON_EVENT)
&&
(Itc [i].event_id == event_id)){
/*
Write ITC.
*/
RPG_itc_write (&(Itc [i].id), &status);
if (status != NORMAL)
PS_task_abort ("ITC Write Failed In ITC_update_by_event. Status = %d\n",
status);
}
}
/*
If ITC access is write, then ...
*/
if (Itc [i].access == ITC_READ) {
/*
If ITC update associated with event and event_id matches
ITC event id, then ....
*/
if ((Itc [i].sync_prd == ITC_ON_EVENT)
&&
(Itc [i].event_id == event_id)){
/*
Read the ITC.
*/
RPG_itc_read (&(Itc [i].id), &status);
if (status != NORMAL)
PS_task_abort ("ITC Read Failed in ITC_update_by_event. Status = %d\n",
status);
}
}
}
return;
/* End of ITC_update_by_event */
}
/******************************************************************************
Description:
Given the ITC id, returns pointer to start of the ITC data buffer.
Inputs:
itc_id - id of ITC
Returns:
Pointer to start of ITC data buffer, or NULL if ITC not defined.
******************************************************************************/
void* ITC_get_data( int itc_id ){
int i;
for( i = 0; i < N_itcs; i++ ){
if( Itc[i].id == itc_id )
return ( (void *) Itc[i].ptr);
}
return (NULL);
/* End of ITC_get_data */
}
/*****************************************************************************
Description:
Sends to the log error file, information about the registered ITC.
Inputs:
ind - index of the registered ITC.
Outputs:
Returns:
Notes:
*****************************************************************************/
void Report_itc( int ind ){
int sync_prod = Itc[ind].sync_prd;
switch( sync_prod ){
case ITC_BEGIN_VOLUME:
{
if( Itc[ind].access == ITC_READ )
LE_send_msg( GL_INFO, "Itc %d Read At Beginning Of Volume\n",
Itc[ind].id );
if( Itc[ind].access == ITC_WRITE )
LE_send_msg( GL_INFO, "Itc %d Written At Beginning Of Volume\n",
Itc[ind].id );
break;
}
case ITC_BEGIN_ELEVATION:
{
if( Itc[ind].access == ITC_READ )
LE_send_msg( GL_INFO, "Itc %d Read At Beginning Of Elevation\n",
Itc[ind].id );
if( Itc[ind].access == ITC_WRITE )
LE_send_msg( GL_INFO, "Itc %d Written At Beginning Of Elevation\n",
Itc[ind].id );
break;
}
case ITC_ON_EVENT:
{
if( Itc[ind].access == ITC_READ )
LE_send_msg( GL_INFO, "Itc %d Read On Event %d\n",
Itc[ind].id, Itc[ind].event_id );
if( Itc[ind].access == ITC_WRITE )
LE_send_msg( GL_INFO, "Itc %d Written On Event %d\n",
Itc[ind].id, Itc[ind].event_id );
break;
}
case ITC_WITH_EVENT:
{
if( Itc[ind].access == ITC_READ )
LE_send_msg( GL_INFO, "Itc %d Read With Event %d\n",
Itc[ind].id, Itc[ind].event_id );
if( Itc[ind].access == ITC_WRITE )
LE_send_msg( GL_INFO, "Itc %d Written With Event %d\n",
Itc[ind].id, Itc[ind].event_id );
break;
}
case ITC_ON_CALL:
{
if( Itc[ind].access == ITC_READ )
LE_send_msg( GL_INFO, "Itc %d Read With Call\n",
Itc[ind].id );
if( Itc[ind].access == ITC_WRITE )
LE_send_msg( GL_INFO, "Itc %d Written With Call\n",
Itc[ind].id );
break;
}
default:
{
if( Itc[ind].access == ITC_READ )
LE_send_msg( GL_INFO, "Itc %d Read With Receipt Of Product %d\n",
Itc[ind].id, sync_prod );
if( Itc[ind].access == ITC_WRITE )
LE_send_msg( GL_INFO, "Itc %d Written With Release Of Product %d\n",
Itc[ind].id, sync_prod );
break;
}
/* End of "switch" */
}
/* End of Report_itc() */
}
/*****************************************************************************
Description:
LB Notification for ITCs not updated by Event.
Inputs:
See orpgda man page for details.
Outputs:
Returns:
Notes:
*****************************************************************************/
void ITC_update_callback( int fd, LB_id_t msgid, int msg_info, void *arg ){
int i;
for( i = 0; i < N_itcs; i++ ){
if( (Itc[i].fd == fd)
&&
(Itc[i].msgid == msgid)
&&
(Itc[i].access == ITC_READ) ){
Itc[i].updated = 1;
}
}
/* End of ITC_update_callback() */
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
void init(char str[],int length) {
for (int i = 0; i <= length; i++) {
str[i] = 0;
}
}
int main() {
int n = 0;
int cnt = 0;
int i = 0;
int j = 0;
int k = 0;
int start = 0;
int end = 0;
int len = 0;
char str[100] = { 0, };
char* same = 0;
scanf("%d", &n);
cnt = n;
for (i = 0; i < n; i++) {
//printf("=========================\n");
//printf("=========================\n");
scanf("%s", str);
len = strlen(str);
/*for (j = 0; j < len; j++) {
printf("[%d]%c ", j, str[j]);
}
printf("\n");
*/
for (j = len - 1; j > 0; j--) {
//printf("=-=-=-=-=-=-=-=-=-=-=-=-=\n");
//printf("[%d] test : %c\n",j, str[j]);
for (k = 0; k < j; k++) {
if (str[j] == str[k]) {
//printf("[%d] %c same!!\n",k, str[k]);
same = str[k];
end = j;
for (start = k + 1; start < end; start++) {
//printf("------------------------\n");
//printf("%s : [%d] %c\n", str, k + 1, str[k + 1]);
if (str[start] != same) {
//printf("minus!!\n");
cnt--;
j = -1;
break;
}
}
}
else {
//printf("[%d] not same %c\n",k, str[k]);
}
}
}
init(str, len);
}
printf("%d\n", cnt);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int isreverse(int tab1[], int tab2[], int taille){
if(*tab1 == tab2[taille-1]){
if(taille-1 == 0)
return 1;
return isreverse(tab1+1,tab2,taille-1);
}
return 0;
}
void main(){
int tab1[4]={4,1,2,3};
int tab2[4]={3,1,1,4};
printf("%d\n", isreverse(tab1,tab2,4));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Elena <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/17 16:57:22 by Elena #+# #+# */
/* Updated: 2019/06/19 14:53:20 by Elena ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int main(void)
{
int fd;
int fd1;
char *line;
fd = open("file.txt", O_RDONLY);
fd1 = open("file1.txt", O_RDONLY);
printf("%d\n", get_next_line(fd, &line));
printf("%s\n", line);
free(line);
printf("%d\n", get_next_line(fd1, &line));
printf("%s\n", line);
free(line);
printf("%d\n", get_next_line(fd, &line));
printf("%s\n", line);
free(line);
printf("%d\n", get_next_line(fd1, &line));
printf("%s\n", line);
free(line);
printf("%d\n", get_next_line(fd, &line));
printf("%s\n", line);
free(line);
/*
while ((fd1 = get_next_line(fd, &line)) == 1)
{
printf("%d\n", fd1);
printf("%s\n", line);
free(line);
}
printf("%d\n", fd1);
printf("%s\n", line);
free(line);
*/
close(fd);
close(fd1);
return (0);
}
|
C
|
//
// main.c
// hash_function
//
// Created by Raquel Alvarez on 11/18/15.
// Copyright (c) 2015 R. All rights reserved.
//
#include <stdio.h>
#define HASHMAP_RANGE 8192
int hash_function (int disk, int block) {
int temp = disk * 10000;
temp = temp + block;
return (temp%HASHMAP_RANGE);
}
int main(int argc, const char * argv[]) {
// Variables
int hashtable [HASHMAP_RANGE] = { 0 };
int hash_value = 0;
int worst_case = -100000;
//int accesses = 10000;
// Generate hash values for all possible blocks
for (int disk = 0; disk < 9; disk++) {
for (int block = 0; block < 4096; block++) {
hash_value = hash_function(disk, block);
hashtable[hash_value]++;
// update worst case time
if (hashtable[hash_value] > worst_case) {
worst_case = hashtable[hash_value];
}
}
}
// Print the distribution of the hash values
// For every hash_value: for every hash_function(d,b) = hash_value, print *
for (int val = 0; val < HASHMAP_RANGE; val++) {
printf("%4d |", val);
for (int star = 0; star < hashtable[val]; star++) {
printf("*");
}
printf("\n");
}
printf("STATISTICS -> Worst Case %d\n", worst_case);
return(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int minimum(int apples,int oranges)
{
if (apples > oranges)
{
return oranges ;
}
else
{
return apples ;
}
}
int maximum (int apples,int oranges)
{
if(apples > oranges)
{
return apples ;
}
else
{
return oranges ;
}
}
int main()
{
int test;
scanf("%d",&test);
while(test > 0)
{
int apples,oranges,gold ;
scanf("%d %d %d",&apples,&oranges,&gold);
if(minimum(apples, oranges) + gold >= maximum(apples, oranges))
{
printf("0");
}
else
{
printf("%d",maximum(apples, oranges) - minimum(apples, oranges) - gold);
}
test --;
printf("\n");
}
return 0;
}
|
C
|
#include "ArrayEmployees.h"
static int Employee_incrementalID = 0;
static int Sector_incrementalID = 0;
int employee_getID(void)
{
return Employee_incrementalID += 1;
}
int sector_getID(void)
{
return Sector_incrementalID += 1;
}
int initEmployees(Employee list[], int len)
{
int i;
if(list != NULL && len > 0)
{
for(i = 0; i < len; i++)
{
list[i].isEmpty = EMPTY;
}
}
return 0;
}
int getEmptyIndex(Employee list[], int len)
{
int returnValue = -1;
int i;
if(list != NULL && len > 0)
{
for(i = 0; i < len; i++)
{
if(list[i].isEmpty == EMPTY)
{
returnValue = i;
break;
}
}
}
return returnValue;
}
int addEmployees(Employee list[], int len, Sector listOfSector[], int lenSector)
{
int returnValue = -1;
int i;
i = getEmptyIndex(list, len);
if(i != -1)
{
list[i] = requestEmployeeData(list, len, listOfSector, lenSector);
list[i].id = employee_getID();
list[i].idSector = sector_getID();
list[i].isEmpty = FULL;
returnValue = 0;
}
return returnValue;
}
Employee requestEmployeeData(Employee list[], int len, Sector listSector[], int lenSector)
{
Employee myEmployee;
printf("Enter a name: ");
fflush(stdin);
scanf("%[^\n]", myEmployee.name);
printf("Enter a last name: ");
fflush(stdin);
scanf("%[^\n]", myEmployee.lastName);
printf("Enter a salary: ");
scanf("%f", &myEmployee.salary);
printf("Enter a sector: ");
fflush(stdin);
scanf("%[^\n]", myEmployee.description);
return myEmployee;
}
int Employee_modify(Employee list[], int len)
{
int returnValue = -1;
int auxiliary;
int option;
int i;
printEmployees(list, len);
printf("Enter your ID");
scanf("%d", &auxiliary);
for(i = 0; i < len; i++)
{
if(auxiliary == list[i].id)
{
if(list[i].isEmpty == EMPTY)
{
puts("The employee is unsubscribed");
break;
}
else
{
printf("Enter an option:\n1- Name\n2- Last name\n3- Salary\n4- Sector");
scanf("%d", &option);
switch(option)
{
case 1:
printf("Enter a name: ");
fflush(stdin);
scanf("%[^\n]", list[i].name);
break;
case 2:
printf("Enter a last name: ");
fflush(stdin);
scanf("%[^\n]", list[i].lastName);
break;
case 3:
printf("Enter a salary: ");
scanf("%f", &list[i].salary);
break;
case 4:
printf("Enter a sector: ");
fflush(stdin);
scanf("%[^\n]", list[i].description);
break;
}
returnValue = 0;
}
break;
}
}
return returnValue;
}
int findEmployeeById(Employee list[], int len, int ID)
{
int returnValue = -1;
int i;
if(list != NULL && len > 0)
{
for(i = 0; i < len; i++)
{
if(list[i].id == ID && list[i].isEmpty == FULL)
{
returnValue = i;
break;
}
}
}
return returnValue;
}
int removeEmployee(Employee list[], int len)
{
int returnValue = -1;
int idEmployee;
int index;
int flag = 0;
if(printEmployees(list, len))
{
flag = 1;
}
if(flag)
{
printf("Enter an ID to remove an employee: ");
scanf("%d", &idEmployee);
while(findEmployeeById(list, len, idEmployee) == -1)
{
puts("The ID does not exist");
printf("Re-enter the ID: ");
scanf("%d", &idEmployee);
}
index = findEmployeeById(list, len, idEmployee);
list[index].isEmpty = REMOVED;
returnValue = 0;
}
return returnValue;
}
void printOneEmployee(Employee myEmployee)
{
printf("|%6d|%13s|%16s|%12.2f|%11d|%22s|\n", myEmployee.id,
myEmployee.name,
myEmployee.lastName,
myEmployee.salary,
myEmployee.idSector,
myEmployee.description
);
printf("|_____________________________________________________________________________________|\n");
}
int printEmployees(Employee list[], int len)
{
int i;
int returnValue = -1;
int counter = 0;
printf("| ID | Name | Last name | Salary | ID Sector | Sector |\n");
printf("|_____________________________________________________________________________________|\n");
for(i = 0; i < len; i++)
{
if(list != NULL && len > 0)
{
if(list[i].isEmpty == FULL)
{
printOneEmployee(list[i]);
counter++;
}
}
}
if(counter > 0)
{
returnValue = 1;
}
return returnValue;
}
int sortEmployees(Employee list[], int len, int order)
{
Employee auxiliary;
int returnValue = -1;
int i;
int j;
if(list != NULL && len > 0)
{
switch(order)
{
case 1:
for(i = 0; i < len - 1; i++)
{
for(j = i + 1; j < len; j++)
{
if(list[i].isEmpty == FULL && list[j].isEmpty == FULL)
{
if(strcmp(list[i].lastName, list[j].lastName) < 0 && strcmp(list[i].description, list[j].description) > 0)
{
auxiliary = list[i];
list[i] = list[j];
list[j] = auxiliary;
}
}
}
}
returnValue = 0;
break;
case 0:
for(i = 0; i < len - 1; i++)
{
for(j = i + 1; j < len; j++)
{
if(list[i].isEmpty == FULL && list[j].isEmpty == FULL)
{
if(strcmp(list[i].lastName, list[j].lastName) < 0 && strcmp(list[i].description, list[j].description) < 0)
{
auxiliary = list[i];
list[i] = list[j];
list[j] = auxiliary;
}
}
}
}
returnValue = 0;
break;
}
}
return returnValue;
}
int calculateAverageSalary(Employee list[], int len)
{
int returnValue = -1;
int i;
float accumulatorSalary = 0;
int aboveAverageCounter = 0;
float averageSalary;
int counter = 0;
if(list != NULL && len > 0)
{
for(i = 0; i < len; i++)
{
if(list[i].isEmpty == FULL)
{
accumulatorSalary += list[i].salary;
counter++;
}
}
averageSalary = accumulatorSalary / counter;
for(i = 0; i < len; i++)
{
if(list[i].isEmpty == FULL && list[i].salary > averageSalary)
{
aboveAverageCounter++;
}
}
returnValue = 0;
}
printf("Total salaries are: %.2f\n", accumulatorSalary);
printf("The average salary is: %.2f\n", averageSalary);
printf("The number of employees above the average salary is: %d\n", aboveAverageCounter);
return returnValue;
}
|
C
|
#ifndef NODE_H
#define NODE_H
#include "cmm-type.h"
#include "cmm-symtab.h"
typedef struct Node_ *Node;
typedef struct Operand_ *Operand;
struct Node_ {
enum ProductionTag tag;
int lineno;
union {
int i;
float f;
const char *s;
void *p;
const char *operator;
} val;
Node child, sibling;
/////////////////////////////////////////////////////////////////
// Used for syntax-directed analysis
/////////////////////////////////////////////////////////////////
// For semantic analysis
struct {
Type *type;
const char *name;
int lineno;
Symbol **symtab;
} sema;
// For intermediate code translation
Operand dst; // 一个表达式可能需要上层提供的目标地址, 值类型可能会将这个字段的值替换 [Feature]
Operand base; // Used for array to locate the initial address
Operand label_true;
Operand label_false;
};
Node new_node();
void free_node(Node nd);
void puts_tree(Node nd);
void analyze_program(Node program);
#endif // NODE_H
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* equalizer_check_file3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bnoufel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/18 15:59:59 by bnoufel #+# #+# */
/* Updated: 2018/10/18 16:01:39 by bnoufel ### ########.fr */
/* */
/* ************************************************************************** */
#include "mysh.h"
/*
** @brief
** -ef : le file f1 et le file f2 sont des liens physiques vers le même file
** @param cmp
** @param f1
** @param f2
** @return
*/
static bool check_modification_file2(t_cmp *cmp)
{
char *dest;
t_stat f1;
t_stat f2;
if (!ft_strcmp(cmp->cmp, "-ef"))
{
if (stat(cmp->str, &f1) == -1 || stat(cmp->str1, &f2) == -1)
return (false);
if (!(dest = ft_strnew(256)))
malloc_failed("check_modification_file");
if (readlink(cmp->str1, dest, 256))
{
if (!ft_strcmp(dest, ft_return_home(cmp->str)))
{
free(dest);
return (true);
}
}
free(dest);
return (false);
}
return (false);
}
/*
** @brief
** -nt : le fichier f1 est plus récent que le fichier f2
** -ot : le fichier f1 est plus ancien que le fichier f2
** @param cmp
** @param f1
** @param f2
** @return
*/
bool check_modification_file(t_cmp *cmp)
{
t_stat f1;
t_stat f2;
if (!ft_strcmp(cmp->cmp, "-nt"))
{
if (stat(cmp->str, &f1) == -1 || stat(cmp->str1, &f2) == -1)
return (false);
if (f1.st_ctime > f2.st_ctime)
return (true);
}
else if (!ft_strcmp(cmp->cmp, "-ot"))
{
if (stat(cmp->str, &f1) == -1 || stat(cmp->str1, &f2) == -1)
return (false);
if (f1.st_ctime < f2.st_ctime)
return (true);
}
else
return (check_modification_file2(cmp));
return (false);
}
|
C
|
#include "lcd.h"
#include "io_ports.h"
#include "system.h"
#define LCD_CONTROL_SIGNAL(EN,RW,RS) ( (EN*(LCD_EN)) | (RW*(LCD_RW)) | (RS*(~LCD_RS)))
#define LCD_DATA_WRITE_SIGNAL LCD_CONTROL_SIGNAL(1,0,1)
#define LCD_INST_WRITE_SIGNAL LCD_CONTROL_SIGNAL(1,0,0)
#define LCD_CLEAR 0b00000001
#define LCD_HOME 0b00000010
#define LCD_SHIFT_CUR_LEFT 0b00010000
#define LCD_SHIFT_CUR_RIGHT 0b00010100
#define LCD_SHIFT_DISP_LEFT 0b00011000
#define LCD_SHIFT_DISP_RIGHT 0b00011100
#define LCD_BYTES_PER_LINE 16
#define LCD_START_ADDRESS_LINE2 0x40
#define LCD_END_ADDRESS_LINE2 0x67
void lcd_nibble_write(char nibble,char ctrl_signal);
void lcd_data_write(char data, char address);
void lcd_set_cursor_address(char address);
char lcd_get_cursor_address(char line);
char lcd_get_cursor_line(char position);
char lcd_cursor_position = 0;
char lcd_shift_offset = 0;
void init_lcd(void)
{
lcd_nibble_write(0b0011, LCD_INST_WRITE_SIGNAL);
delay_ms(2);
lcd_nibble_write(0b0011, LCD_INST_WRITE_SIGNAL);
delay_ms(2);
lcd_nibble_write(0b0011, LCD_INST_WRITE_SIGNAL);
delay_ms(2);
lcd_nibble_write(0b0010, LCD_INST_WRITE_SIGNAL);
delay_ms(2);
lcd_nibble_write(0b0010, LCD_INST_WRITE_SIGNAL);
delay_ms(2);
lcd_nibble_write(0b1000, LCD_INST_WRITE_SIGNAL); // Function Set ( 0 0 - 0 0 1 DL N F * * )
delay_ms(2);
lcd_nibble_write(0b1110, LCD_INST_WRITE_SIGNAL); // Display ON/OFF control ( 0 0 - 0 0 0 0 1 D C B )
delay_ms(2);
lcd_instruction_write(LCD_CLEAR); // Clear display
delay_ms(2);
lcd_instruction_write(0b00000110); // Entry Mode Set ( 0 0 0 0 0 0 0 1 I/D S )
delay_ms(2);
lcd_cursor_position = 0;
lcd_shift_offset = 0;
}
void lcd_nibble_write(char nibble,char ctrl_signal)
{
char lcd_out;
lcd_out = nibble & (~LCD_NIBBLE_MASK);
lcd_out |= ctrl_signal;
write_sreg2(LCD_CONTROL_MASK&LCD_NIBBLE_MASK, lcd_out);
bit_clr_reg2(LCD_EN);
}
/* writes a charcter to the LCD and increments the cursor position */
void lcd_character_write(char character)
{
char address_line_0, address_line_1;
address_line_0 = lcd_get_cursor_address(0);
address_line_1 = lcd_get_cursor_address(1);
if (lcd_get_cursor_line(lcd_cursor_position + 1) == 0)
{
lcd_data_write(character, address_line_1);
lcd_data_write(character, address_line_0);
}
else
{
lcd_data_write(character, address_line_0);
lcd_data_write(character, address_line_1);
}
}
void lcd_data_write(char data, char address)
{
if((address & 0b0111111) < 40)
{
lcd_set_cursor_address(address);
lcd_nibble_write(data >> 4, LCD_DATA_WRITE_SIGNAL);
lcd_nibble_write(data , LCD_DATA_WRITE_SIGNAL);
lcd_cursor_position++;
}
}
void lcd_set_cursor_address(char address)
{
lcd_nibble_write(0b1000 | (address >> 4), LCD_INST_WRITE_SIGNAL);
lcd_nibble_write(address , LCD_INST_WRITE_SIGNAL);
if (address & 0b1000000) // In second line.
{
address &= 0b0111111;
if(address > 19)
{
lcd_cursor_position = address + LCD_BYTES_PER_LINE - 40;
}
else
{
lcd_cursor_position = address + LCD_BYTES_PER_LINE;
}
}
else // In first line.
{
if(address > 19)
{
lcd_cursor_position = address - 40;
}
else
{
lcd_cursor_position = address;
}
}
}
void lcd_set_position (signed char position)
{
char address;
lcd_cursor_position = position;
address = lcd_get_cursor_address(lcd_get_cursor_line(position));
lcd_set_cursor_address(address);
}
char lcd_get_cursor_address(char line)
{
if(line == 0)
{
if(lcd_cursor_position < 0)
{
return 40 + lcd_cursor_position;
}
else
{
return lcd_cursor_position;
}
}
else
{
if(lcd_cursor_position < LCD_BYTES_PER_LINE)
{
return (40 + lcd_cursor_position - LCD_BYTES_PER_LINE) | 0b1000000;
}
else
{
return (lcd_cursor_position - LCD_BYTES_PER_LINE) | 0b1000000;
}
}
}
char lcd_get_cursor_line(char position)
{
signed char position_on_screen = (position + lcd_shift_offset);
return ( position_on_screen < LCD_BYTES_PER_LINE)? 0 : 1;
}
/* writes an instruction to the LCD */
void lcd_instruction_write(char instruction)
{
lcd_nibble_write(instruction>>4, LCD_INST_WRITE_SIGNAL);
lcd_nibble_write(instruction, LCD_INST_WRITE_SIGNAL);
}
/* scrolls the chatacters on the LCD one position to the left */
void lcd_left_scroll(void)
{
lcd_instruction_write(LCD_SHIFT_DISP_LEFT);
lcd_shift_offset--;
}
/* scrolls the chatacters on the LCD one position to the right */
void lcd_right_scroll(void)
{
lcd_instruction_write(LCD_SHIFT_DISP_RIGHT);
lcd_shift_offset++;
}
void lcd_shift_cursor_left(void)
{
lcd_instruction_write(LCD_SHIFT_CUR_LEFT);
lcd_cursor_position--;
}
void lcd_shift_cursor_right(void)
{
lcd_instruction_write(LCD_SHIFT_CUR_RIGHT);
lcd_cursor_position++;
}
/* clears the LCD and moves the cursor to the start position */
void lcd_scrn_clear(void)
{
lcd_instruction_write(LCD_CLEAR);
lcd_cursor_position = 0;
lcd_shift_offset = 0;
}
void lcd_backspace (void)
{
lcd_shift_cursor_left();
delay_us(37);
lcd_character_write(' ');
delay_us(37);
lcd_shift_cursor_left();
}
void lcd_print_str(char* str)
{
while( (*str) != '\0' ){
lcd_character_write(*str);
str++;
delay_us(37);
}
}
|
C
|
/*
* Exercise 7-7.
*
* Modify the pattern finding program of Chapter 5 to take its input from a set
* of named files or, if no files are named as arguments, from the standard
* input. Should the file name be printed when a matching line is found?
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 1000
struct options {
int except;
int number;
int filename;
char *pattern;
int pathargs;
};
static int findpattern(FILE *file, char *path, struct options *);
static void parseargs(int argc, char **argv, struct options *);
static FILE *chkfopen(char *path, char *modes);
static char *chkfgets(char *s, int n, FILE *iop, char *path);
static char errormsg[MAXLINE];
int main(int argc, char *argv[])
{
struct options options;
int i, found = 0;
FILE *file;
char *path;
parseargs(argc, argv, &options);
if (options.pathargs < argc)
for (i = options.pathargs; i < argc; i++) {
path = argv[i];
file = chkfopen(path, "r");
found += findpattern(file, path, &options);
fclose(file);
}
else
found = findpattern(stdin, "<stdin>", &options);
return 0;
}
void parseargs(int argc, char **argv, struct options *options)
{
int c, i;
char *arg;
options->except = options->number = options->filename = 0;
for (i = 1; i < argc && (arg = argv[i])[0] == '-'; i++)
while (c = *++arg)
switch(c) {
case 'x':
options->except = 1;
break;
case 'n':
options->number = 1;
break;
case 'f':
options->filename = 1;
break;
default:
fprintf(stderr, "find: illegal option %c\n", c);
exit(1);
}
if (i == argc) {
fprintf(stderr, "Usage: find -x -n -f pattern\n");
exit(1);
} else {
options->pattern = argv[i++];
options->pathargs = i;
}
}
int findpattern(FILE *file, char *path, struct options *options)
{
char line[MAXLINE];
long lineno = 0, found = 0;
while (chkfgets(line, MAXLINE, file, path) != NULL) {
lineno++;
if ((strstr(line, options->pattern) != NULL) != options->except) {
if (options->filename)
printf("%s:", path);
if (options->number)
printf("%ld:", lineno);
printf("%s", line);
found++;
}
}
return found;
}
FILE *chkfopen(char *path, char *modes)
{
FILE *fp = fopen(path, modes);
if (fp != NULL)
return fp;
sprintf(errormsg, "error: Failed to open file: '%s'", path);
perror(errormsg);
exit(1);
}
char *chkfgets(char *s, int n, FILE *iop, char *path)
{
char *r = fgets(s, n, iop);
if (!ferror(iop))
return r;
sprintf(errormsg, "error: Failed to read file: '%s'", path);
perror(errormsg);
fclose(iop);
exit(1);
}
|
C
|
#include "libft.h"
#include <stdio.h>
int main(void)
{
char *s="lorem \n ipsum \t dolor \n sit \t amet";
printf("en entre ; \n XXX%sXXX\nensortie \nXXX%sXXX\n",s,ft_strtrim(s));
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <ctype.h>
//////////////////////////Structs////////////////////////
typedef struct threadBuffer{
char** buffer; // dynamic buffer
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
} ThreadBuffer;
typedef struct node {
char* data;
int freq;
struct node *next;
struct node* prev;
} Node;
typedef struct list {
Node *start;
Node *end;
} List;
//////////////////////Function Prototypes//////////////////
void initializeBuffer (ThreadBuffer *buf, int numberOfLines);
static void reader (ThreadBuffer *buf);
static void counter (ThreadBuffer *buf, char* name);
static void * readCall(void* data);
static void * countCall (void* data);
int initializeList(List *sList, char* data);
int printList(List *sList);
void insertWord(List *sList, char * oneWord);
void createNewThread(char* name);
/////////////////////////Global Variables////////////////////////
char *finalLine, **fileNames, *threadName = "a", newName = 'b';
int numberOfLines, maxCounters, listCount = 0, EOFFlag = 0, stopCounter = 0,
threadCount = 0, fileCount = 0, oneFile = 1, bufferFull = 0,
numLinesSet = 0, maxCounterSet = 0, fileDelaySet = 0, threadDelaySet = 0;
long fileDelay, threadDelay;
FILE* file;
ThreadBuffer buffy;
List oddWordsList, evenWordsList;
struct timespec fileWait, threadWait;
pthread_t thread1, thread2, newThread, *threadNames;
void* returnValue;
///////////////////////////Main/////////////////////////////////
int main(int argc, char *argv[]){
int i, numberOfFiles;
// needs 10 commandline arguments
if (argc < 10){
printf("Error. Please enter correct arguments\n");
exit(1);
}
for (i = 1; i < argc; i++){
if (strcmp(argv[i], "-b") == 0){
numberOfLines = atoi(argv[i+1]);
if (numberOfLines <= 0){
fprintf(stderr, "Enter a positive integer for numlines.\n");
exit(1);
}
numLinesSet = 1;
}
if (strcmp(argv[i], "-t") == 0){
maxCounters = atoi(argv[i+1]);
if (maxCounters > 26 || maxCounters < 1){
fprintf(stderr, "Can only have up to 26 maxcounters.\n");
exit(1);
}
maxCounterSet = 1;
}
if (strcmp(argv[i], "-d") == 0){
fileDelay = atoi(argv[i+1]);
if (fileDelay < 0){
fprintf(stderr, "The filedelay must be zero or greater.\n");
exit(1);
}
fileDelaySet = 1;
}
if (strcmp(argv[i], "-D") == 0){
threadDelay = atoi(argv[i+1]);
if (threadDelay < 0){
fprintf(stderr, "The threaddelay must be zero or greater.\n");
exit(1);
}
threadDelaySet = 1;
}
}
threadNames = malloc(sizeof(pthread_t) * maxCounters+1);
fileNames = malloc(sizeof(char) * argc + 1);
finalLine = malloc((LINE_MAX * sizeof(char))+1);
finalLine = "\n";
// get correct time values
if (fileDelay <= 999)
fileWait.tv_nsec = fileDelay*1000000;
else
fileWait.tv_sec = fileDelay/1000;
if (threadDelay <= 999)
threadWait.tv_nsec = threadDelay*1000000;
else
threadWait.tv_sec = threadDelay/1000;
numberOfFiles = argc - 9;
//stick file names in file array
while(numberOfFiles > 0){
char* fileToOpen = argv[8+numberOfFiles];
fileNames[fileCount] = fileToOpen;
fileCount++;
numberOfFiles--;
}
initializeBuffer(&buffy, numberOfLines);
initializeList(&oddWordsList, "0");
initializeList(&evenWordsList, "0");
//if the buffersize is 1, set numberOfLines to 2 to fix empty checks
if (numberOfLines == 1){
numberOfLines++;
}
// create all the threads
pthread_create (&thread1, NULL, readCall, 0);
pthread_create (&thread2, NULL, countCall, (void*) threadName);
// wait until all threads finish
pthread_join (thread1, &returnValue);
pthread_join (thread2, &returnValue);
// get rid of the zeros at the front of the lists
oddWordsList.start = oddWordsList.start->next;
evenWordsList.start = evenWordsList.start->next;
printf("\nODD WORDS\n");
printf("---------\n");
if (oddWordsList.start != NULL){
printList(&oddWordsList);
}
else{
printf("No Odd Words Found\n\n");
}
printf("\nEVEN WORDS\n");
printf("----------\n");
if (evenWordsList.start != NULL){
printList(&evenWordsList);
}
else{
printf("No Even Words Found\n");
}
return 0;
}
/////////////////////////Methods////////////////////////////////
void createNewThread(char* name){
threadName = name;
pthread_t newThread;
threadNames[threadCount] = newThread;
threadCount++;
maxCounters--;
pthread_create (&newThread, NULL, countCall, (void*) threadName);
int j;
for (j = 0; j < threadCount-25; j++){
pthread_join (threadNames[j], &returnValue);
}
}
////////////////////////////////////////////////////////////////
void* readCall (void* data){
while (EOFFlag == 0){
reader (&buffy);
nanosleep(&fileWait, NULL);
}
return NULL;
}
////////////////////////////////////////////////////////////////
static void reader (ThreadBuffer *buf){
char *oneLine = malloc((LINE_MAX * sizeof(char))+1);;
pthread_mutex_lock(&buf->lock);
//wait until buffer is not full
while ((buf->writepos+1) % numberOfLines == buf->readpos){
pthread_cond_wait (&buf->notfull, &buf->lock);
}
memset(oneLine, 0, sizeof(LINE_MAX * sizeof(char))+1);
//if its the first time entering or other file has been closed
if (oneFile == 1){
while(1){
file = fopen(fileNames[fileCount-1], "r");
if (file == NULL){
fprintf(stderr, "File %s could not be opened. Continuing with rest of files...\n", fileNames[fileCount-1]);
fileCount--;
if (fileCount <= 0){
break;
}
}
else
break;
}
}
if (fileCount != 0){
oneFile = 0;
fgets(oneLine, LINE_MAX, file);
//if end of one file
if (feof(file)){
oneFile = 1;
fclose(file);
fileCount--;
}
//if end of all files
if (fileCount == 0){
EOFFlag = 1;
}
// if it is the last line, set finalLine so counter knows when to stop
if (EOFFlag == 1){
finalLine = oneLine;
}
// write line from file to buffer and continue
buf->buffer[buf->writepos] = oneLine;
buf->writepos++;
if (buf->writepos >= numberOfLines){
buf->writepos = 0;
bufferFull = 1;
if (maxCounters > 1){
char* str = malloc(sizeof(char));
str[0] = newName;
createNewThread(str);
newName++;
}
}
// signal that the buffer now isn't empty
pthread_cond_signal (&buf->notempty);
pthread_mutex_unlock (&buf->lock);
}
//final file could not be opened
else{
EOFFlag = 1;
pthread_cond_signal (&buf->notempty);
stopCounter = 1;
pthread_mutex_unlock (&buf->lock);
}
}
////////////////////////////////////////////////////////////////
void* countCall (void* data){
char* name = (char*) data;
while (stopCounter == 0){
counter (&buffy, name);
}
return NULL;
}
////////////////////////////////////////////////////////////////
static void counter (ThreadBuffer *buf, char* name){
//local val so we know which thread stopped it
int thisStop = 0, j = 0, k = 0;
char c = '\0', *data, *oneWord;
data = malloc((LINE_MAX * sizeof(char)) + 1);
memset(data, 0, sizeof(LINE_MAX * sizeof(char)) + 1);
pthread_mutex_lock (&buf->lock);
while (buf->writepos == buf->readpos){
if (stopCounter == 1){
break;
}
pthread_cond_wait (&buf->notempty, &buf->lock);
}
// if counts are done, other threads should skip this
if (stopCounter == 0){
/* Read the data from buffer and advance read pointer */
data = buf->buffer[buf->readpos];
nanosleep(&threadWait, NULL);
if (strcmp(data, finalLine) == 0 && EOFFlag == 1){
stopCounter = 1;
thisStop = 1;
}
// for EOF checks
strcat(data,"\n");
//loop through data to split words
while (c != '\n'){
oneWord = malloc((LINE_MAX* sizeof(char))+1);
memset(oneWord, 0, sizeof(LINE_MAX * sizeof(char)) + 1);
c = data[j];
while (!isspace(c)){
oneWord[k] = c;
j++;
k++;
c = data[j];
}
j++;
//if oneWord isn't empty:
if (strcmp(oneWord, "") != 0){
//check if odd or even and insert into list alphabetically
if (strlen(oneWord) % 2 == 0){
insertWord(&evenWordsList, oneWord);
}
else{
insertWord(&oddWordsList, oneWord);
}
printf("%s", name);
fflush(stdout);
}
}
}
buf->readpos++;
if (buf->readpos >= numberOfLines)
buf->readpos = 0;
/* Signal that the buffer is now not full */
pthread_cond_signal (&buf->notfull);
pthread_mutex_unlock (&buf->lock);
//cancel all remaning threads
if (thisStop == 1){
int y = 0;
for (y = 0; y < threadCount-25; y++){
pthread_cancel(threadNames[y]);
}
pthread_cancel(thread2);
pthread_cancel(thread1);
}
}
////////////////////////////////////////////////////////////////
void initializeBuffer (ThreadBuffer *buf, int numberOfLines){
buf->buffer = malloc((sizeof(char*)+1)*numberOfLines);
memset(buf->buffer, 0, sizeof(buf->buffer));
pthread_mutex_init (&buf->lock, NULL);
pthread_cond_init (&buf->notempty, NULL);
pthread_cond_init (&buf->notfull, NULL);
buf->readpos = 0;
buf->writepos = 0;
}
////////////////////////////////////////////////////////////////
int initializeList(List *sList, char* data){
Node *newNode;
newNode = malloc(sizeof(Node));
newNode->data = data;
newNode->freq = 1;
newNode->next = NULL;
newNode->prev = NULL;
sList->start = newNode;
sList->end = newNode;
return 0;
}
////////////////////////////////////////////////////////////////
int printList(List *sList){
Node *current = sList->start;
while(current != sList->end) {
fprintf(stderr, "%s %d\n", current->data, current->freq);
current = current->next;
}
fprintf(stderr, "%s %d\n", current->data, current->freq);
return 0;
}
////////////////////////////////////////////////////////////////
void insertWord(List *sList, char* oneWord){
Node *current = sList->start;
if (current != sList->end)
current = current->next;
while (current != sList->end && (strcmp(oneWord, current->data) > 0)){
current = current->next;
}
if (strcmp(oneWord, current->data) == 0){
current->freq = current->freq + 1;
}
else if (current == sList->end){
Node *new = malloc(sizeof(Node));
new->data = oneWord;
new->freq = 1;
if (strcmp(oneWord, current->data) > 0 || current == sList->start){
new->next = NULL;
new->prev = current;
current->next = new;
sList->end = new;
listCount++;
}
else{
new->next = current;
new->prev = current->prev;
current->prev->next = new;
current->prev = new;
listCount++;
}
}
else{
Node *new;
new = malloc(sizeof(Node));
new->data = oneWord;
new->freq = 1;
new->next = current;
new->prev = current->prev;
current->prev->next = new;
current->prev = new;
listCount++;
}
}
|
C
|
#include<stdio.h>
main()
{
long int p;
int n;
double q;
printf("----------\n");
printf("2 to power n n 2 to power -n\n");
printf("----------\n");
p = 1;
for(n = 0; n < 21; ++n)
{
if(n==0)
p = 1;
else
p = p*2;
q = 1.0/(double)p;
printf("%10ld%10d%20.12lf\n",p,n,q);
}
printf("----------\n");
}
|
C
|
#include <git2.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/param.h>
#include <libgen.h>
#include <stdio.h>
/*
* Blogpit is a set of simple functions to access a dictionary
*
*
* - open(path)
* - close()
* - version()
* - sections(path)
* - get_article(path)
* - articles(path)
* - set_article(path, content)
*
* Dictionary keys are a 2 level structure "section1/section2/articles"
* i.e. sections are folders and articles are files
*/
#include "util.h"
#include "structs.h"
struct blogpit*
blogpit_open(const char *path, const char *name)
{
assert(path); assert(name);
git_repository *repo;
int len = strnlen(name, MAX_BRANCHNAME_LENGTH);
if ( len == MAX_BRANCHNAME_LENGTH ) {
return NULL;
}
char *s = calloc(1,len+1);
strlcpy(s, name, len+1);
struct blogpit *b = calloc(1, sizeof(struct blogpit));
if ( b == NULL ) {
return NULL;
}
int err = git_repository_open(&repo, path);
if ( err != 0 ) {
repo = util_create_repo( path );
if ( repo == NULL ) {
goto fail_repo;
}
}
b->repo = repo;
b->branch = s;
return b;
fail_repo:
free(s);
free(b);
return NULL;
}
void
blogpit_close(struct blogpit *b)
{
if (!b) {
return;
}
git_repository_free(b->repo);
free(b->branch);
free(b);
}
char *
blogpit_version(struct blogpit *b)
{
assert(b);
char *s = util_resolve_name(b->repo, b->branch);
if ( s == NULL ) {
s = malloc(1);
s[0] = '\0';
}
return s;
}
void *
blogpit_getarticle(struct blogpit *b, const char *path, size_t *buflen)
{
assert(b); assert(path); assert(buflen);
size_t len;
git_blob *blob = util_get_blob( b->repo, b->branch, path);
if ( blob == NULL ) {
return NULL;
}
len = git_blob_rawsize(blob);
void *data = calloc( 1, len );
if ( data == NULL ) {
return NULL;
}
memcpy( data, git_blob_rawcontent(blob), len);
*buflen = len;
git_blob_free(blob);
return data;
}
int
blogpit_setarticle(struct blogpit *b, const char *path, void *data, size_t len, const char *msg)
{
int rvalue = -1;
char *cp1 = strdup(path);
char *cp2 = strdup(path);
char *filename = basename(cp1);
char *dir = dirname(cp2);
if ( strcmp(filename, "") == 0 ) {
goto empty_filename;
}
rvalue = util_commit_file(b->repo, b->branch,
dir, filename, data, len, msg);
empty_filename:
free(cp1);
free(cp2);
return rvalue;
}
char**
blogpit_sections(struct blogpit *b, const char *path)
{
assert(b); assert(path);
return util_get_tree_names( b->repo, b->branch, path, GIT_OBJ_TREE);
}
char**
blogpit_articles(struct blogpit *b, const char *path)
{
assert(b); assert(path);
return util_get_tree_names( b->repo, b->branch, path, GIT_OBJ_BLOB);
}
|
C
|
/*
* CONCURRENCY EXPERIMENT WITH REAL TIME LINUX THREADS (XENOMAI)
*
* ANALYSIS:
The yappy thread ran first.
It is possible to use printf in main. However, printf uses linux syscalls and this
significantly slows down the real-time thread. The rt_printf is preferred because it is
a cheaper printing call (no syscalls or locks).
What was the pattern of the numbers printed out?
'yyyyyyyyyyyyyyyyyyyyyyyyysyyyysyyyysyy'. Unlike partB, yappy threads keeps outputting to the
console for a while before both threads eventually start interleaving.
Run your program several more times. Is the same thread always run first?
Yes, but the number of outputs are not consistent.
Run your program several more times, changing the sleep time and the spin time. What
changes do you see?
Reducing the spin time causes the yappy thread to output to the console more frequently.
By increasing the sleep time, the sleepy thread prints to the console less frequently.
*
* Author: OSAZUWA OMIGIE (100764733)
*/
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/mman.h>
#include <native/task.h>
#include <native/timer.h>
RT_TASK yappy_task;
RT_TASK sleepy_task;
#define MAX_OUTPUT 1000
static char log[MAX_OUTPUT]; //shared memory with child thread
static int log_index = 0;
typedef struct{
int count; //used to indicate sleep time (in nanoseconds) or spin count
char output;
} Data;
void yappyRun(void *arg){
while(log_index < (MAX_OUTPUT-1)){
Data * data = (Data *) arg;
log[log_index++] = data->output;
/*spinning*/
int var;
for(var=2;var<data->count;var++){
var *=1;
var /=1;
}
}
}
void sleepyRun(void *arg){
while(log_index < (MAX_OUTPUT-1)){
Data * data = (Data *) arg;
log[log_index++] = data->output; //write to log variable
rt_task_sleep(data->count); //sleep
}
}
void cleanUp(){
rt_task_delete(&yappy_task);
rt_task_delete(&sleepy_task);
}
void catch_signal(int sig)
{
cleanUp();
return;
}
int main(int argc, char* argv[])
{
signal(SIGTERM, catch_signal);
signal(SIGINT, catch_signal);
rt_print_auto_init(1);
/* Avoids memory swapping for this program */
mlockall(MCL_CURRENT|MCL_FUTURE);
if(rt_task_create(&yappy_task, NULL, 0, 0, T_JOINABLE)==0){
}else{
printf("error creating yappy thread");
return -1;
}
if(rt_task_create(&sleepy_task, "sleepy", 0, 0, T_JOINABLE)==0){}
else{
printf("error creating sleepy thread");
return -1;
}
Data yappyData;
yappyData.output = 'y';
yappyData.count = 100000; //set the spin count
Data sleepyData;
sleepyData.output = 's';
sleepyData.count = 1000000; //set the sleep time
if(rt_task_start(&yappy_task, &yappyRun, &yappyData)==0){}
else{
printf("error starting yappy thread");
return -1;
}
if(rt_task_start(&sleepy_task, &sleepyRun, &sleepyData)==0){}
else {
printf("error starting sleepy thread");
return -1;
}
//wait for the children thread to terminate
rt_task_join(&yappy_task);
rt_task_join(&sleepy_task);
log[MAX_OUTPUT] = '\0'; //null ending character
rt_printf("%s",log);
return 0;
}
|
C
|
#ifndef LIST_H_
#define LIST_H_
#include "main.h"
typedef UINT8 LSTATUS;
/*------------------------------------------
NULL<-- [Head] <--> [Instance A ] <--> [Instance B] <--> [Tail] -- Null
| |
| |
———————— ————————
Define Data Struct Define Data Struct
------------------------------------------*/
typedef struct _NODE{
struct _NODE *pPre;
struct _NODE *pNext;
void *Instance;
INT8 *IdName;
}NODE,*pNODE;
pNODE CreatLinkList(void);
LSTATUS IsEmptyLinkList(IN pNODE pHead);
UINT8 GetLengthLinkList(IN pNODE pHead);
LSTATUS InsertNodeLinkList(IN pNODE pHead,IN UINT16 pos,IN void * Instance,IN UINT8 *idname);
LSTATUS DelNodeLinkList(IN pNODE pHead,IN UINT16 pos);
LSTATUS FreeMemory(IN pNODE *ppHead);
#endif
|
C
|
#include "fmod/fmod.h"
#include <stdlib.h>
#include <stdio.h>
#include "fonctions.h"
void ADMIN(){
printf("\e[1;1H\e[2J");
printf("---ADMIN CONTROL PANEL---\n");
printf("1) RETOUR\n");
printf("CHOIX : ");
scanf("%d",&choix);
if(choix != 1)
{
printf("Choix impossible. Choisissez une option entre 1 et 1");
}
else
{
MENU_PRINCIPAL();
}
}
void USER (){
printf("\e[1;1H\e[2J");
printf("---USER CONTROL PANEL---\n");
printf("1) RETOUR\n");
printf("CHOIX : ");
scanf("%d",&choix);
if(choix != 1)
{
printf("Choix impossible. Choisissez une option entre 1 et 1");
}
else
{
MENU_PRINCIPAL();
}
}
void CONFIGURATION() {
printf("\e[1;1H\e[2J");
printf("---CONFIGURATION CONTROL PANEL---\n");
printf("1) RETOUR\n");
printf("CHOIX : ");
scanf("%d",&choix);
if(choix != 1)
{
printf("Choix impossible. Choisissez une option entre 1 et 1");
}
else
{
MENU_PRINCIPAL();
}
}
void ECOUTER_SON() {
FMOD_System_PlaySound(fmodsys, sound, NULL, 0, NULL);
while(choix2 != 3){
printf("\e[1;1H\e[2J");
printf("---PLAY SOUND---\n");
printf("1) PLAY/PAUSE\n");
printf("2) STOP\n");
printf("3) RETOUR\n");
printf("CHOIX DU MENU : ");
scanf("%d",&choix2);
switch (choix2) {
case 1:
FMOD_Channel_GetPaused(0, &etat);
if (etat == 1) // Si la chanson est en pause
FMOD_Channel_SetPaused(0, 0); // On enlève la pause
else // Sinon, elle est en cours de lecture
FMOD_Channel_SetPaused(0, 1); // On met en pause
break;
case 2 :
FMOD_System_PlaySound(fmodsys,sound ,NULL, 1, NULL);
break;
}
MENU_PRINCIPAL();
}
}
void MENU_PRINCIPAL () {
while(1){
printf("\e[1;1H\e[2J");
printf("---MENU---\n");
printf("1) ADMIN\n");
printf("2) USER\n");
printf("3) CONFIGURATION\n");
printf("4) ECOUTER UN SON\n");
printf("5) QUITTER\n");
printf("CHOIX DU MENU : ");
scanf("%d",&choix);
/*if(choix != 1 || choix != 2 || choix != 3 || choix != 4 || choix != 5)
{
printf("Choix impossible. Choisissez une option entre 1 et 4");
}*/
//else{
switch (choix){
case 1 :
ADMIN();
break;
case 2 :
USER();
break;
case 3:
CONFIGURATION();
break;
case 4 :
ECOUTER_SON();
break;
case 5:
printf("\e[1;1H\e[2J");
exit(0);
break;
//}
}
}
}
|
C
|
e/*
** EPITECH PROJECT, 2017
** my_put_nbr
** File description:
**
*/
int my_put_nbr(int nb)
{
int n = abs(nb);
int e = abs(nb);
int x = 1000000000;
if (nb == 0)
my_putchar(48);
if (nb < 0)
my_putchar(45);
while (x > abs(nb))
x = x / 10;
while (x != 1 && x != 0) {
n = n / x;
if (n < 10)
my_putchar(n + 48);
e = e % x;
x = x / 10;
n = e;
}
if (n != 0)
my_putchar(n + 48);
}
|
C
|
//233 "ѹα" о ϴ α ۼϼ.
#include <stdio.h>
void main(void) {
FILE* fp;
char buff[100];
fopen_s(&fp, "file6.txt", "r");
if (fp != NULL) {
while (!feof(fp)) {
fgets(buff, 100, fp);
printf(buff);
}
fclose(fp);
}
}
//feof ̿ нϴ.
// fgets ƹ͵ о ʽϴ.
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Employee
{
char name[25];
int sapID;
};
struct node
{
void *data;
struct node *next;
};
int integerComp(int *p1,int *p2)
{
if(*p1==*p2)
return 1;
else
return 0;
}
int doubleComp(double *p1,double* p2)
{
if(*p1==*p2)
return 1;
else
return 0;
}
int characterComp(char *p1,char *p2)
{
if(!strcmp(p1,p2))
return 1;
else
return 0;
return EXIT_SUCCESS;
}
int (*compare[])()={integerComp,doubleComp,characterComp};
//void (*allocation[])(void**,int)={allocateInt,allocateDouble,allocateChar};
int insert_into_list(struct node**,void *);
int search_data(struct node *);
int insert_into_list(struct node **ptr,void *data)
{
if(*ptr)
insert_into_list(&(*ptr)->next,data);
if(!*ptr)
{
*ptr=malloc(sizeof(struct node));
if(!*ptr)
{
perror("Error while allocating memory\n");
return EXIT_FAILURE;
}
(*ptr)->data=data;
printf("Data inserted!\n");
return EXIT_SUCCESS;
}
return EXIT_SUCCESS;
}
int search_data(struct node *ptr)
{
char name[25];
int sapCode,iType,count=1;
struct Employee *emp;
printf("Search by\n\n\t1. Employee Name\n\t2. SAP ID\n\t_____Anyother key to exit_____\n\t>");
scanf("%d",&iType);
// 0 - int; 1 - double; 2 - char;
switch(iType)
{
case 1 :
printf("Name : ");
scanf("%s",name);
while(ptr)
{
emp = ptr->data;
if((*compare[2])(emp->name,name))
{
printf("\nRecord found at index : %d\n",count);
return 1;
}
count++;
ptr=ptr->next;
}
return 0;
break;
case 2 :
printf("SAP ID : ");
scanf("%d",&sapCode);
while(ptr)
{
emp = ptr->data;
printf("Iter : %d",emp->sapID);
if((*compare[0])(&emp->sapID,&sapCode))
{
printf("\nRecord found at index : %d\n",count);
return 1;
}
count++;
ptr=ptr->next;
}
return 0;
break;
}
return EXIT_SUCCESS;
}
int Print(struct node *ptr)
{
struct Employee *emp;
while(ptr)
{
emp=ptr->data;
printf("\tName : %s\n",emp->name);
printf("\tSAP ID : %d\n",emp->sapID);
ptr=ptr->next;
}
return EXIT_SUCCESS;
}
int DeleteName(struct node **ptr,struct node **prev,char *name)
{
struct node *temp=(struct node*)*ptr;
struct Employee *emp=temp->data;
if((*compare[2])(emp->name,name) && (*ptr)->next!=NULL)
{
if(prev==NULL && (*ptr)->next!=NULL)
*ptr=temp->next;
else if(prev!=NULL && (*ptr)->next!=NULL)
(*prev)->next=(struct node*)(*ptr)->next;
else if(prev==NULL && (*ptr)->next==NULL)
{
free(emp);
free(temp);
}
else
(*prev)->next=NULL;
printf("\n Deleted Record : %s\n",emp->name);
free(emp);
if(temp->next)
temp->next=NULL;
free(temp);
return EXIT_SUCCESS;
}
else
DeleteName(&(*ptr)->next,ptr,name);
return EXIT_FAILURE;
}
int DeleteSap(struct node **ptr,struct node **prev,int sapCode)
{
struct node *temp=*ptr;
struct Employee *emp=temp->data;
printf("\n Current Record : %s\n",emp->name);
if((*compare[0])(&emp->sapID,&sapCode))
{
if(prev==NULL && (*ptr)->next!=NULL)
*ptr=temp->next;
else if(prev!=NULL && (*ptr)->next!=NULL)
(*prev)->next=(struct node*)(*ptr)->next;
else if(prev==NULL && (*ptr)->next==NULL)
{
free(emp);
free(temp);
}
else
(*prev)->next=NULL;
printf("\n Deleted Record : %s\n",emp->name);
free(emp);
if(temp->next)
temp->next=NULL;
free(temp);
return EXIT_SUCCESS;
}
else
DeleteSap(&(*ptr)->next,ptr,sapCode);
return EXIT_FAILURE;
}
int remove_element(void **ptr)
{
char name[25];
int iType,sapCode;
do
{
printf("Remove Record by\n\t1. Name\n\t2. SAP ID\n\t >");
scanf("%d",&iType);
if(iType==1)
{
printf("Name : ");
scanf("%s",name);
DeleteName((struct node **)ptr,NULL,name);
}
else if(iType==2)
{
printf("SAP ID : ");
scanf("%d",&sapCode);
DeleteSap((struct node **)ptr,NULL,sapCode);
}
}while(iType == 1 || iType == 2);
return EXIT_SUCCESS;
}
int allocateMem(void **ptr)
{
*ptr = malloc(sizeof(struct Employee));
if(!*ptr)
{
perror("Error in Allocating memory!\n");
exit(-1);
}
return EXIT_SUCCESS;
}
int main()
{
void *data;
struct node *start=NULL;
allocateMem(&data);
strcpy(((struct Employee*)data)->name,"Arun");
((struct Employee*)data)->sapID = 21;
insert_into_list(&start,data);
allocateMem(&data);
strcpy(((struct Employee*)data)->name,"Balaji");
((struct Employee*)data)->sapID = 22;
insert_into_list(&start,data);
allocateMem(&data);
strcpy(((struct Employee*)data)->name,"Karthik");
((struct Employee*)data)->sapID = 23;
insert_into_list(&start,data);
puts("\n");
Print(start);
puts("\n");
search_data(start);
remove_element((void**)&start);
puts("\n");
Print(start);
puts("\n");
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include "bstree.h"
int main()
{
struct BSTree* t;
printf("testing tree create...");
if ((t = tree_create()) == NULL)
goto fail;
printf("[ok]\n");
int arr[10], count, ref[10] = { 1, 3, 2, 5, 7, 6, 4 };
int i;
printf("testing insert...");
add(t,4);
add(t,2);
add(t,6);
add(t,1);
add(t,3);
add(t,5);
add(t,7);
printf("[ok]\n");
printf("testing search...");
if (!search(t,1) || !search(t,2) || !search(t,3) ||
!search(t,4) || !search(t,5) || !search(t,6) || !search(t,7))
goto fail;
if (search(t,8) || search(t,9))
goto fail;
printf("[ok]\n");
printf("testing get_postorder...");
get_postorder(t, arr, &count);
if (count != 7)
goto fail;
for (i = 0; i < 7; i++) {
if (arr[i] != ref[i])
goto fail;
}
printf("[ok]\n");
return 0;
fail:
printf("[failed]\n");
return -1;
}
|
C
|
/***************************
* AddData.c
*
*
*
*
***************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "../MAIN/movie.h"
#include "../movieValidate/movieValidate.h"
#include "../codeGen/codeGen.h"
#include "../writeData/writeData.h"
#include "addData.h"
void getTitle(char *movieCode, char *titleInput)
{
char stringInput[256];
do
{
printf("Please enter movie name\n");
printf("Enter here : ");
fgets(stringInput, sizeof(stringInput), stdin);
strcpy(titleInput, stringInput);
}while(strlen(titleInput) == 0);
generateCode(titleInput, movieCode);
}
void getActor(char *actorName)
{
char stringInput[256];
do
{
printf("Please enter actor(s) name\n");
printf("Example : 'Robert Downey Jr. , Tony Jaa'");
printf("Enter here : ");
fgets(stringInput, sizeof(stringInput), stdin);
strcpy(actorName, stringInput);
}while(checkName(actorName) == 1);
}
void getCategory(char *category)
{
char stringInput[256];
int i = 0;
do
{
printf("Please enter category\n");
printf("Category list : DRAMA , COMEDY , ACTION , ROMANCE , HORROR , CARTOON , OTHER\n");
printf("Enter here : ");
fgets(stringInput, sizeof(stringInput), stdin);
strcpy(category, stringInput);
for(i = 0 ; i < strlen(category) ; i++)
{
category[i] = toupper(category[i]);
}
}while(checkCategory(category) == 1);
}
void getLanguage(char *language)
{
char stringInput[256];
int i = 0;
do
{
printf("Please enter langauge of this movie\n");
printf("Language list : ENGLISH , THAI , OTHER\n");
printf("Enter here : ");
fgets(stringInput, sizeof(stringInput), stdin);
strcpy(language, stringInput);
for(i = 0 ; i < strlen(language) ; i++)
{
language[i] = toupper(language[i]);
}
}while(checkLanguage(language) == 1);
}
void getReleaseDate(char *releaseDate)
{
char stringInput[256];
do
{
printf("Please enter the release date here(YYYY-MM-DD)\n");
printf("Enter here:");
fgets(stringInput,sizeof(stringInput),stdin);
strcpy(releaseDate,stringInput);
}while(checkDate(releaseDate) == 1);
}
int getSeenDate(char *seenDate)
{
char stringInput[256];
int status = 0;
do
{
printf("Please enter the date you watched the movie(YYYY-MM-DD)\n");
printf("Enter here(Leave blank if haven't seen yet):");
fgets(stringInput,sizeof(stringInput),stdin);
strcpy(seenDate,stringInput);
if(strcmp(seenDate,"\n") == 0)
{
printf("You haven't watch the movie\n");
status = 1;
}
}while(checkSeenDate(seenDate) == 1);
return status;
}
void getMethod(char *method)
{
char stringInput[256];
int i;
do
{
printf("Please enter your viewing method here\n");
printf("Enter here:");
fgets(stringInput,sizeof(stringInput),stdin);
strcpy(method,stringInput);
for(i = 0; i < strlen(method); i++)
{
method[i] = toupper(method[i]);
}
}while(checkMethod(method) == 1);
}
void getRating(int* rating)
{
char stringInput[256];
do
{
printf("Please enter the rating for the movie here(1-10)\n");
printf("Enter here:");
fgets(stringInput, sizeof(stringInput), stdin);
sscanf(stringInput,"%d",rating);
}while(checkRating(rating) == 1);
}
void addData(MOVIE_NT* movie[])
{
char stringInput[256];
char title[256];
char movieCode[16];
char actor[256];
char category[100];
char language[100];
char releaseDate[20];
char seenDate[20];
char viewMethod[100];
int rating;
char yesNo;
int watched = 0;
int i = 0;
do
{
/*Copy movie title and movie code to structure*/
getTitle(movieCode, title);
strcpy(movie[i].code, movieCode);
strcpy(movie[i].title, title);
/*Copy actor name to structure*/
getActor(actor);
strcpy(movie[i].actor, actor);
/*Copy category to structure*/
getCategory(category);
strcpy(movie[i].category, category);
/*Copy language to structure*/
getLanguage(language);
strcpy(movie[i].language, language);
/*Copy release date to stucture*/
getReleaseDate(releaseDate);
strcpy(movie[i].releaseDate, releaseDate);
/*Copy seen date to structure*/
watched = getSeenDate(seenDate);
strcpy(movie[i].releaseDate, releaseDate);
if(watched == 1) /*If user input seen date*/
{
/*Copy view method to structure*/
getMethod(viewMethod);
strcpy(movie[i].viewMethod, viewMethod);
/*Copy rating to structure*/
getRating(&rating);
movie[i].Rating = rating;
}
do
{
printf("Do you want to add other movie? (y/n) : ");
fgets(stringInput, sizeof(stringInput), stdin);
sscanf(stringInput, "%c", &yesNo);
if(yesNo = 'n')
{
break;
}
}while((yesNo != 'y') || (yesNo != 'n'));
i++;
}while(yesNo == 'y');
}
int main()
{
printf("hello world\n");
return 0;
}
|
C
|
#include <stdio.h>
extern int yylex(void);
void yyparse();
extern FILE* yyin;
int main(int argc, char **argv) {
if (argc > 1) {
yyin = fopen(argv[1], "r");
if (yyin == NULL){
printf("syntax: %s filename\n", argv[0]);
}//end if
}//end if
yyparse(); // Calls yylex() for tokens.
return 0;
}
|
C
|
#include "dna_hasher.h"
uint64_t hashDNAstringtonum(std::string dna)
{
uint64_t result = 0;
for(std::string::iterator it = dna.begin(); it != dna.end(); ++it)
{
result = result << 2;
switch(*it)
{
case 'c':
case 'C':
result |= 1;
break;
case 'g':
case 'G':
result |= 2;
break;
case 't':
case 'T':
result |= 3;
break;
default:
break;
}
}
return result;
}
std::string hashDNAnumtostring(uint64_t dna_num, const uint8_t length)
{
const char lookuptable[4] = {'A','C','G','T'};
std::string dna = "";
for(uint8_t i = length; i > 0; i--)
{
dna.push_back(lookuptable[dna_num & 3]);
dna_num = dna_num >> 2;
}
std::reverse(dna.begin(), dna.end());
return dna;
}
std::string dnaReverseComplement(std::string dna)
{
auto lambda = [](const char c)
{
switch(c)
{
case 'a':
case 'A':
return 'T';
case 'g':
case 'G':
return 'C';
case 'c':
case 'C':
return 'G';
case 't':
case 'T':
return 'A';
default:
return 'N'; //gracefully return N for other bases
}
};
std::transform(dna.cbegin(), dna.cend(), dna.begin(), lambda);
std::reverse(dna.begin(), dna.end());
return dna;
}
|
C
|
#include "common.h"
#include "client.h"
#include "map.h"
#include "network.h"
void client_net_block_set(map_t *map, s32 x, s32 y, tile_t tile)
{
printf("client_net_block_set: %d,%d\n", x, y);
if(net_player.sockfd != FD_LOCAL_IMMEDIATE)
{
net_pack(NULL, PKT_BLOCK_SET,
x, y,
tile.type, tile.col, tile.chr);
} else {
map_set_tile(map, x, y, tile);
}
}
void client_net_block_push(map_t *map, s32 x, s32 y, tile_t tile)
{
printf("client_net_block_push: %d,%d\n", x, y);
if(net_player.sockfd != FD_LOCAL_IMMEDIATE)
{
net_pack(NULL, PKT_BLOCK_PUSH,
x, y,
tile.type, tile.col, tile.chr);
} else {
map_push_tile(map, x, y, tile);
}
}
void client_net_block_pop(map_t *map, s32 x, s32 y)
{
printf("client_net_block_pop: %d,%d\n", x, y);
if(net_player.sockfd != FD_LOCAL_IMMEDIATE)
{
net_pack(NULL, PKT_BLOCK_POP,
x, y);
} else {
map_pop_tile(map, x, y);
}
}
void client_load_chunk(map_t *map, s32 x, s32 y)
{
s32 px = divneg(x,LAYER_WIDTH);
s32 py = divneg(y,LAYER_HEIGHT);
if(!map_get_existing_layer(map, px,py))
map_get_net_layer(map, px,py);
}
void client_set_tile(map_t *map, s32 x, s32 y, tile_t tile)
{
client_load_chunk(map, x, y);
client_net_block_set(map, x, y, tile);
}
void client_set_tile_ext(map_t *map, s32 x, s32 y, u8 uidx, tile_t tile, int sendflag)
{
client_load_chunk(map, x, y);
if(sendflag)
/* TODO! */;
else
map_set_tile_ext(map, x, y, uidx, tile);
}
void client_alloc_tile_data(map_t *map, s32 x, s32 y, u8 uidx, u16 datalen, int sendflag)
{
client_load_chunk(map, x, y);
if(sendflag)
/* TODO! */;
else
map_alloc_tile_data(map, x, y, uidx, datalen);
}
void client_set_tile_data(map_t *map, s32 x, s32 y, u8 uidx, u8 datalen, u16 datapos, u8 *data, int sendflag)
{
client_load_chunk(map, x, y);
if(sendflag)
/* TODO! */;
else
map_set_tile_data(map, x, y, uidx, datalen, datapos, data);
}
tile_t client_get_tile(map_t *map, s32 x, s32 y)
{
client_load_chunk(map, x, y);
return map_get_tile(map, x, y);
}
void client_push_tile(map_t *map, s32 x, s32 y, tile_t tile)
{
client_load_chunk(map, x, y);
client_net_block_push(map, x, y, tile);
}
void client_pop_tile(map_t *map, s32 x, s32 y)
{
client_load_chunk(map, x, y);
client_net_block_pop(map, x, y);
}
u8 client_get_next_update(map_t *map, int *lidx, s32 *x, s32 *y)
{
return map_get_next_update(map, lidx, x, y);
}
void client_set_update(map_t *map, s32 x, s32 y, u8 tonew)
{
client_load_chunk(map, x, y);
map_set_update(map, x,y, tonew);
}
void client_set_update_n(map_t *map, s32 x, s32 y, u8 tonew)
{
client_set_update(map,x,y,tonew);
client_set_update(map,x-1,y,tonew);
client_set_update(map,x+1,y,tonew);
client_set_update(map,x,y-1,tonew);
client_set_update(map,x,y+1,tonew);
}
|
C
|
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include "log.h"
#include "utils.h"
#include "mem.h"
#include "icy_mem.h"
#include "icy_vector.h"
size_t icy_vector_capacity(icy_vector * table){
return table->area->size / table->element_size - 4;
}
size_t icy_vector_count(icy_vector * table){
return ((size_t *) table->area->ptr)[0];
}
void icy_vector_count_set(icy_vector * table, unsigned int newcount){
((size_t *) table->area->ptr)[0] = newcount;
}
size_t _icy_vector_free_index_count(icy_vector * table){
return ((size_t *) table->free_indexes->ptr)[0];
}
void _icy_vector_free_index_count_set(icy_vector * table, size_t cnt){
((size_t *) table->free_indexes->ptr)[0] = cnt;
}
void icy_vector_check_sanity(icy_vector * table){
size_t cnt = _icy_vector_free_index_count(table);
ASSERT(table->free_indexes->size / sizeof(size_t) > cnt);
}
void * icy_vector_all(icy_vector * table, size_t * cnt){
// return count -1 and a pointer from the placeholder element.
*cnt = icy_vector_count(table) - 1;
return table->area->ptr + table->element_size * 5;
}
void icy_vector_clear(icy_vector * table){
icy_vector_count_set(table, 1);
_icy_vector_free_index_count_set(table, 0);
icy_mem_realloc(table->free_indexes, sizeof(size_t));
}
size_t _icy_vector_alloc(icy_vector * table){
size_t freeindexcnt = _icy_vector_free_index_count(table);
if(freeindexcnt > 0){
size_t idx = ((size_t *) table->free_indexes->ptr)[freeindexcnt];
_icy_vector_free_index_count_set(table, freeindexcnt - 1);
ASSERT(idx != 0);
void * p = icy_vector_lookup(table, (icy_index){idx});
memset(p, 0, table->element_size);
return idx;
}
while(icy_vector_capacity(table) <= icy_vector_count(table)){
size_t prevsize = table->area->size;
ASSERT((prevsize % table->element_size) == 0);
size_t newsize = MAX(prevsize * 2, 8 * table->element_size);
icy_mem_realloc(table->area, newsize);
memset(table->area->ptr + prevsize, 0, newsize - prevsize);
}
size_t idx = icy_vector_count(table);
icy_vector_count_set(table,idx + 1);
return idx;
}
icy_index icy_vector_alloc(icy_vector * table){
auto index = _icy_vector_alloc(table);
ASSERT(index > 0);
return (icy_index){index};
}
void icy_vector_remove(icy_vector * table, icy_index index){
ASSERT(index.index < icy_vector_count(table));
ASSERT(index.index > 0);
size_t cnt = _icy_vector_free_index_count(table);
icy_mem_realloc(table->free_indexes, table->free_indexes->size + sizeof(size_t));
((size_t *)table->free_indexes->ptr)[cnt + 1] = 0;
//ASSERT(memmem(table->free_indexes->ptr + sizeof(size_t), (cnt + 1) * sizeof(size_t), &index, sizeof(index)) == NULL);
((size_t *)table->free_indexes->ptr)[cnt + 1] = index.index;
((size_t *) table->free_indexes->ptr)[0] += 1;
}
void icy_vector_resize_sequence(icy_vector * table, icy_vector_sequence * seq, size_t new_count){
icy_vector_check_sanity(table);
icy_vector_sequence nseq = {0};
if(new_count == 0){
icy_vector_remove_sequence(table, seq);
*seq = nseq;
return;
}
nseq = icy_vector_alloc_sequence(table, new_count);
if(seq->index.index != 0 && seq->count != 0 ){
if(new_count > 0){
void * src = icy_vector_lookup_sequence(table, *seq);
void * dst = icy_vector_lookup_sequence(table, nseq);
memmove(dst, src, MIN(seq->count, nseq.count) * table->element_size);
}
icy_vector_remove_sequence(table, seq);
}
*seq = nseq;
icy_vector_check_sanity(table);
}
icy_vector_sequence icy_vector_alloc_sequence(icy_vector * table, size_t count){
size_t freeindexcnt = _icy_vector_free_index_count(table);
if(freeindexcnt > 0){
size_t start = 0;
size_t cnt = 0;
for(size_t i = 0; i < freeindexcnt; i++){
size_t idx = ((size_t *) table->free_indexes->ptr)[i + 1];
if(start == 0){
start = idx;
cnt = 1;
}else if(idx == start + cnt){
cnt += 1;
}else if(idx == start + cnt - 1){
ASSERT(false); // it seems that some bug can appear here.
}else{
start = idx;
cnt = 1;
}
if(cnt == count){
// pop it from the indexex.
_icy_vector_free_index_count_set(table, freeindexcnt - cnt);
size_t * ptr = table->free_indexes->ptr;
for(size_t j = i - cnt + 1; j < freeindexcnt - cnt; j++)
ptr[j + 1] = ptr[j + cnt + 1];
ASSERT(start != 0);
void * p = icy_vector_lookup(table, (icy_index){start});
memset(p, 0, cnt * table->element_size);
return (icy_vector_sequence){.index = (icy_index){start}, .count = cnt};
}
}
}
while(icy_vector_capacity(table) <= (icy_vector_count(table) + count)){
size_t prevsize = table->area->size;
ASSERT((prevsize % table->element_size) == 0);
size_t newsize = MAX(prevsize * 2, 8 * table->element_size);
icy_mem_realloc(table->area, newsize);
memset(table->area->ptr + prevsize, 0, newsize - prevsize);
}
size_t idx = icy_vector_count(table);
icy_vector_count_set(table,idx + count);
return (icy_vector_sequence){.index = (icy_index){idx}, .count = count};
}
void icy_vector_remove_sequence(icy_vector * table, icy_vector_sequence * seq){
size_t cnt = _icy_vector_free_index_count(table);
icy_mem_realloc(table->free_indexes, table->free_indexes->size + seq->count * sizeof(size_t));
//ASSERT(memmem(table->free_indexes->ptr + sizeof(size_t), cnt * sizeof(size_t), &index, sizeof(index)) == NULL);
for(size_t i = 0; i < seq->count; i++)
((size_t *)table->free_indexes->ptr)[cnt + i + 1] = seq->index.index + i;
((size_t *) table->free_indexes->ptr)[0] += seq->count;
memset(seq, 0, sizeof(*seq));
icy_vector_optimize(table);
}
void * icy_vector_lookup_sequence(icy_vector * table, icy_vector_sequence seq){
if(seq.index.index == 0)
return NULL;
return icy_vector_lookup(table, seq.index);
}
icy_vector * icy_vector_create(const char * name, size_t element_size){
ASSERT(element_size > 0);
icy_vector table = {.area = NULL, .free_indexes = NULL, .element_size = element_size};
if(name != NULL){
table.area = icy_mem_create(name);
char name2[128] = {0};
sprintf(name2, "%s.free", name);
table.free_indexes = icy_mem_create(name2);
}else{
table.area = icy_mem_create3();
table.free_indexes = icy_mem_create3();
}
if(table.free_indexes->size < sizeof(size_t)){
icy_mem_realloc(table.free_indexes, sizeof(size_t));
((size_t *)table.free_indexes->ptr)[0] = 0;
}
if(table.area->size < element_size){
icy_mem_realloc(table.area, element_size * 4);
memset(table.area->ptr, 0, table.area->size);
_icy_vector_alloc(&table);
}
ASSERT((table.area->size % table.element_size) == 0);
ASSERT(icy_vector_count(&table) > 0);
return iron_clone(&table, sizeof(table));
}
void icy_vector_destroy(icy_vector ** _table){
icy_vector * table = *_table;
*_table = NULL;
icy_mem_free(table->area);
icy_mem_free(table->free_indexes);
}
void * icy_vector_lookup(icy_vector * table, icy_index index){
ASSERT(index.index < icy_vector_count(table));
ASSERT(index.index > 0);
return table->area->ptr + (4 + index.index) * table->element_size;
}
bool icy_vector_contains(icy_vector * table, icy_index index){
if(index.index == 0)
return false;
if (index.index >= icy_vector_count(table))
return false;
size_t freecnt = _icy_vector_free_index_count(table);
size_t * start = table->free_indexes->ptr + sizeof(size_t);
for(size_t i = 0; i < freecnt; i++){
if(start[i] == index.index)
return false;
}
return true;
}
static int cmpfunc (const size_t * a, const size_t * b)
{
return ( *(int*)a - *(int*)b );
}
void icy_vector_optimize(icy_vector * table){
// the index table is optimized by sorting and removing excess elements
//
size_t free_cnt = _icy_vector_free_index_count(table);
if(table->free_indexes->ptr == NULL || free_cnt == 0)
return; // nothing to optimize.
size_t * p = table->free_indexes->ptr;
qsort(p + 1,free_cnt , sizeof(size_t), (void *) cmpfunc);
size_t table_cnt = icy_vector_count(table);
// remove all elements that are bigger than the table. note: how did these enter?
while(p[free_cnt] >= table_cnt && free_cnt != 0){
free_cnt -= 1;
}
// remove all elements that are freed from the end of the table
while(table_cnt > 0 && p[free_cnt] == table_cnt - 1 && free_cnt != 0){
table_cnt -= 1;
free_cnt -= 1;
}
_icy_vector_free_index_count_set(table, free_cnt);
icy_vector_count_set(table, table_cnt);
size_t newsize = table_cnt * table->element_size + table->element_size * 5;
icy_mem_realloc(table->area, newsize);
size_t newsize2 = (1 + free_cnt) * sizeof(size_t);
icy_mem_realloc(table->free_indexes, newsize2);
icy_vector_check_sanity(table);
}
|
C
|
#ifndef __BPT_H__
#define __BPT_H__
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
// page properties
#define PAGE_SIZE 4096
#define OFF(pagenum) ((pagenum) * PAGE_SIZE)
#define INTERNAL_ORDER 249
#define LEAF_ORDER 32
#define VALUE_SIZE 120
#define QUEUE_SIZE 1000
// err numbers
#define BAD_REQUEST -400
#define NOT_FOUND -404
#define CONFLICT -409
#define INTERNAL_ERR -500
// type definitions
typedef uint64_t pagenum_t;
typedef struct key_value_t key_value_t;
typedef struct key_page_t key_page_t;
typedef struct header_page_t header_page_t;
typedef struct free_page_t free_page_t;
typedef struct node_page_t node_page_t;
typedef struct page_t page_t;
typedef struct Queue Queue;
/* key, value type for leaf node
*/
struct key_value_t {
int64_t key;
char value[VALUE_SIZE];
};
/* key, page_number type for internal node
*/
struct key_page_t {
int64_t key;
uint64_t page_number;
};
/* first page (offset 0-4095) of a data file
* contains metadata.
*/
struct header_page_t {
uint64_t free_page_number;
uint64_t root_page_number;
uint64_t number_of_pages;
int8_t reserved[4072];
};
/* free page layout
* linked and allocation is managed by the free page list.
*/
struct free_page_t {
uint64_t next_free_page_number;
int8_t not_used[4088];
};
/* Internal/Leaf page
*/
struct node_page_t {
uint64_t parent_page_number;
uint32_t is_leaf;
uint32_t number_of_keys;
int8_t reserved[104];
/* right_sibling_page_number for leaf node,
* one_more_page_number for internal node
*/
union {
uint64_t right_sibling_page_number;
uint64_t one_more_page_number;
};
/* key_values for leaf node,
* key_page_numbers for internal node
*/
union {
key_value_t key_values[31];
key_page_t key_page_numbers[248];
};
};
/* in-memory page structure
*/
struct page_t {
union{
header_page_t header;
free_page_t free;
node_page_t node;
};
};
struct Queue {
int front, rear;
int item_count;
pagenum_t pages[QUEUE_SIZE];
};
// file manager
pagenum_t file_alloc_page();
void file_free_page(pagenum_t pagenum);
void file_read_page(pagenum_t pagenum, page_t* dest);
void file_write_page(pagenum_t pagenum, const page_t* src);
// open
int open_table(char* pathname);
// util
int cut(int len);
// find
pagenum_t find_leaf(pagenum_t root, int64_t key);
int db_find(int64_t key, char* ret_val);
// insert
pagenum_t make_node(page_t* node);
pagenum_t start_new_tree(int64_t key, char* value);
pagenum_t insert_into_new_root(pagenum_t left_num, page_t* left,
int64_t key, pagenum_t right_num, page_t* right);
int get_left_index(page_t* parent, pagenum_t left_num);
void insert_into_node(page_t* parent, int left_index, int64_t key, pagenum_t right_num);
pagenum_t insert_into_node_after_splitting(pagenum_t root_num,
pagenum_t parent_num, page_t* parent,
int left_index, int64_t key, pagenum_t right_num);
pagenum_t insert_into_parent(pagenum_t root_num, pagenum_t left_num, page_t* left,
int64_t key, pagenum_t right_num, page_t* right);
void insert_into_leaf(pagenum_t leaf_num, page_t* leaf, int64_t key, char* value);
pagenum_t insert_into_leaf_after_splitting(pagenum_t root_num, pagenum_t leaf_num, page_t* leaf,
int64_t key, char* value);
int db_insert(int64_t key, char* value);
// delete
void remove_entry_from_leaf(page_t* node, int64_t key);
void remove_entry_from_node(page_t* node, int64_t key);
pagenum_t adjust_root(pagenum_t root_num);
int get_neighbor_index(page_t* parent, pagenum_t node_num);
pagenum_t coalesce_nodes(pagenum_t root_num, pagenum_t node_num, page_t* node,
pagenum_t neighbor_num, page_t* neighbor, int neighbor_index,
int64_t k_prime);
void redistribute_nodes(pagenum_t node_num, page_t* node, pagenum_t neighbor_num, page_t* neighbor,
int neighbor_index, int k_prime_index, int64_t k_prime);
pagenum_t delete_entry(pagenum_t root_num, pagenum_t node_num, int64_t key);
int db_delete(int64_t key);
// print
void enqueue(Queue* q, pagenum_t data);
pagenum_t dequeue(Queue* q);
void print_tree();
extern int fd;
extern page_t header_page;
#endif
|
C
|
#include "heap.h"
static void heap_up(heap_t *heap) {
int element_index = heap->length; //Last element in the Heap
while(element_index != 1){
//Get Parent.
int parent_index = (element_index/2);
// Swap if parent is greater
if (heap->store[parent_index-1] > heap->store[element_index-1]){
swap_heap_elements(heap, parent_index-1, element_index-1);
} else {
break;
}
element_index = parent_index;
}
}
static void heap_down(heap_t *heap) {
int element_index = 1;
int first_child_index = element_index *2;
while (heap->length >= first_child_index+1){
//2 Children
if (heap->store[element_index-1] > heap->store[first_child_index-1] || heap->store[element_index-1] > heap->store[(first_child_index+1)-1]){
// parent is bigger than either of its children then swap with the smallest
if (heap->store[first_child_index-1] <= heap->store[first_child_index+1]){
swap_heap_elements(heap, element_index-1, first_child_index-1);
element_index = first_child_index;
} else {
swap_heap_elements(heap, element_index-1, first_child_index+1-1);
element_index = first_child_index+1;
}
} else {
break; // No smaller child
}
first_child_index = element_index *2;
}
// For odd number of elements in the heap.
if (heap->length == first_child_index){
if (heap->store[element_index-1] < heap->store[first_child_index-1]){
swap_heap_elements(heap, element_index-1, first_child_index-1);
}
}
}
void swap_heap_elements(heap_t *heap, int const first, int const second){
int temp = heap->store[first];
heap->store[first] = heap->store[second];
heap->store[second] = temp;
}
void heap_init(heap_t *heap, int *store) {
heap->store = store;
heap->length = 0;
}
void heap_insert(heap_t *heap, int value) {
// The new element is always added to the end of a heap
heap->store[(heap->length)++] = value;
heap_up(heap);
}
int heap_extract(heap_t *heap) {
// The root value is extracted, and the space filled by the value from the end
// If the heap is empty, this will fail horribly...
int value = heap->store[0];
heap->store[0] = heap->store[--(heap->length)];
heap_down(heap);
return value;
}
int heap_isEmpty(heap_t *heap) {
return !(heap->length);
}
|
C
|
#define SYSCALL "mprotect"
#include "common.h"
int run() {
// TODO
return 0;
}
/*
MPROTECT(2) Linux Programmer's Manual MPROTECT(2)
NAME
mprotect - set protection on a region of memory
SYNOPSIS
#include <sys/mman.h>
int mprotect(void *addr, size_t len, int prot);
DESCRIPTION
mprotect() changes protection for the calling process's memory page(s)
containing any part of the address range in the interval
[addr, addr+len-1]. addr must be aligned to a page boundary.
If the calling process tries to access memory in a manner that violates
the protection, then the kernel generates a SIGSEGV signal for the
process.
prot is either PROT_NONE or a bitwise-or of the other values in the
following list:
PROT_NONE The memory cannot be accessed at all.
PROT_READ The memory can be read.
PROT_WRITE The memory can be modified.
PROT_EXEC The memory can be executed.
RETURN VALUE
On success, mprotect() returns zero. On error, -1 is returned, and
errno is set appropriately.
ERRORS
EACCES The memory cannot be given the specified access. This can hap‐
pen, for example, if you mmap(2) a file to which you have read-
only access, then ask mprotect() to mark it PROT_WRITE.
EINVAL addr is not a valid pointer, or not a multiple of the system
page size.
ENOMEM Internal kernel structures could not be allocated.
ENOMEM Addresses in the range [addr, addr+len-1] are invalid for the
address space of the process, or specify one or more pages that
are not mapped. (Before kernel 2.4.19, the error EFAULT was
incorrectly produced for these cases.)
ENOMEM Changing the protection of a memory region would result in the
total number of mappings with distinct attributes (e.g., read
versus read/write protection) exceeding the allowed maximum.
(For example, making the protection of a range PROT_READ in the
middle of a region currently protected as PROT_READ|PROT_WRITE
would result in three mappings: two read/write mappings at each
end and a read-only mapping in the middle.)
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4. POSIX says that the behavior of
mprotect() is unspecified if it is applied to a region of memory that
was not obtained via mmap(2).
NOTES
On Linux it is always permissible to call mprotect() on any address in
a process's address space (except for the kernel vsyscall area). In
particular it can be used to change existing code mappings to be
writable.
Whether PROT_EXEC has any effect different from PROT_READ depends on
processor architecture, kernel version, and process state. If
READ_IMPLIES_EXEC is set in the process's personality flags (see per‐
sonality(2)), specifying PROT_READ will implicitly add PROT_EXEC.
On some hardware architectures (e.g., i386), PROT_WRITE implies
PROT_READ.
POSIX.1 says that an implementation may permit access other than that
specified in prot, but at a minimum can allow write access only if
PROT_WRITE has been set, and must not allow any access if PROT_NONE has
been set.
EXAMPLE
The program below allocates four pages of memory, makes the third of
these pages read-only, and then executes a loop that walks upward
through the allocated region modifying bytes.
An example of what we might see when running the program is the follow‐
ing:
$ ./a.out
Start of region: 0x804c000
Got SIGSEGV at address: 0x804e000
Program source
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)
static char *buffer;
static void
handler(int sig, siginfo_t *si, void *unused)
{
printf("Got SIGSEGV at address: 0x%lx\n",
(long) si->si_addr);
exit(EXIT_FAILURE);
}
int
main(int argc, char *argv[])
{
char *p;
int pagesize;
struct sigaction sa;
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = handler;
if (sigaction(SIGSEGV, &sa, NULL) == -1)
handle_error("sigaction");
pagesize = sysconf(_SC_PAGE_SIZE);
if (pagesize == -1)
handle_error("sysconf");
/* Allocate a buffer aligned on a page boundary;
initial protection is PROT_READ | PROT_WRITE *|
buffer = memalign(pagesize, 4 * pagesize);
if (buffer == NULL)
handle_error("memalign");
printf("Start of region: 0x%lx\n", (long) buffer);
if (mprotect(buffer + pagesize * 2, pagesize,
PROT_READ) == -1)
handle_error("mprotect");
for (p = buffer ; ; )
*(p++) = 'a';
printf("Loop completed\n"); /* Should never happen *|
exit(EXIT_SUCCESS);
}
SEE ALSO
mmap(2), sysconf(3)
COLOPHON
This page is part of release 4.04 of the Linux man-pages project. A
description of the project, information about reporting bugs, and the
latest version of this page, can be found at
http://www.kernel.org/doc/man-pages/.
Linux 2015-07-23 MPROTECT(2)
*/
|
C
|
#include<stdio.h>
int main()
{
long long n,i,a[1000],flag,j;
scanf("%lld",&n);
for(i=0;i<n;i++)
scanf("%lld",&a[i]);
for(i=0;i<n;i++)
{
flag=0;
for(j=0;j<n;j++)
{
if(i!=j&&a[i]==a[j])
{
flag=1;
break;
}
}
if(flag==0)
{
printf("%lld",a[i]);
break;
}
}
}
|
C
|
/*!
* @file queue.h
* @author Tyler Holmes
*
* @date 20-May-2017
* @brief Simple circular buffer handler.
*/
#pragma once
#include <stdint.h>
//! The structure to track all pertinant variables for the circular buffer.
typedef struct {
volatile uint8_t head_ind; //!< Tracks the front of the buffer (where new info gets pushed)
volatile uint8_t tail_ind; //!< Tracks the back of the buffer (where data is read from)
volatile uint8_t unread_items; //!< Number of un-popped items
volatile uint32_t overwrite_count; //!< Number of items that were lost to overwrite
} queue_t;
void queue_init(volatile queue_t *queue_admin_ptr);
void queue_increment_tail(volatile queue_t *queue_admin_ptr, const uint8_t queue_size);
void queue_increment_head(volatile queue_t *queue_admin_ptr, const uint8_t queue_size);
|
C
|
/**
@file schedule.h
@brief Definitions, data structues and prototypes for generic scheduling mechanisms
@author Joe Brown
*/
#ifndef SCHEDULE_H
#define SCHEDULE_H
/** @brief timing multiplier to allow regular interval scheduling with varying
clock speeds */
extern volatile uint8_t g_timing_multiplier;
// Timing divisors for scheduling
// The base time millisecond will always be 1.024ms due to the watchdog timer
// divisors. For that reason we will multiply _SECOND by slightly less than 1000
// to account for it and make subsequent multipliers slightly more accurate
#define _MILLISECOND g_timing_multiplier
/** @brief function pointer to a callback*/
typedef void (*CallbackFn)(void);
/** @brief function pointer to a callout*/
typedef void (*CalloutFn)(void);
/** @brief Configuration for callback which holds the function pointer,
run time (period), next time it will run, and whether or not it is enabled*/
typedef struct
{
CallbackFn func;
uint8_t enabled;
uint32_t run_time;
uint32_t next_run_time;
} CallbackEvent;
enum ScheduleMode
{
ENABLED = 1,
DISABLED = 0
};
/** @brief global time accessible by everyone */
extern volatile uint32_t g_now;
/**
@brief Initialize the schedule timer used to check callouts and callbacks
@details
Configure the watchdog timer to periodically wake up and service the scheduler
tasks. We currently use a 0.5 ms period and save the multiplier to
g_timing_multiplier. This is used in the definition of _MILLISECOND to give
flexible timing.
*/
extern void ScheduleTimerInit(void);
/**
@brief Add a callback to the store for periodic execution
@details
Take the function and run time and store them in the callback store. Intially
set the enabled flag to false to keep us from accidentally calling a function
before it is expected.
@param[in] func function pointer registered to callback
@param[in] run_time period on which to run the callback function
@return SUCCESS if callback registered successfully, FAILURE otherwise
*/
extern int8_t CallbackRegister(CallbackFn func, uint32_t run_time);
/**
@brief Enable or disable a function callback
@details
Search the callback store for the specified function and enable or disable it
based on the mode passed in.
@param[in] func callback function to configure
@param[in] mode enabled or disabled
*/
extern void CallbackMode(CallbackFn func, enum ScheduleMode mode);
/**
@brief Add a callout to the store for one-time execution
@details
Take the function and run time and store them in the callout store. For callouts
we maintain a "map" of callouts in a bit array. When we store a new function we
find an empty slot (0 in the bit array) and set it. That bit corresponds to the
index of the callout store the function pointer is stored at.
@param[in] func function pointer registered to callout slot
@param[in] run_time Specific time in which to run the function
@return SUCCESS if callback registered successfully, FAILURE otherwise
*/
extern int8_t CalloutRegister(CalloutFn func, uint32_t run_time);
/**
@brief Disable a function callout before it has run
@details
Search the callout store for the specific function. If we find it go clear the
map to indicate the slot is vacant.
@param[in] func function pointer to search for and cancel
*/
extern void CalloutCancel(CalloutFn func);
#endif // SCHEDULE_H
|
C
|
#include<stdio.h>
#include<time.h>
int a[1000],b[1000],c[1000],A[1000],ac[1000];
int n,m,i,j,ch,m,temp,num;
FILE *f;
double t;
clock_t t1,t2;
void display()
{
printf("\n\nBubble Sort:");
for(int k=0;k<n;k++)
printf(" %d ",a[k]);
printf("\n");
printf("\nInsertion Sort:");
for(int k=0;k<n;k++)
printf(" %d ",b[k]);
printf("\n");
printf("\nSelection Sort:");
for(int k=0;k<n;k++)
printf(" %d ",c[k]);
printf("\n");
printf("\nQuick Sort:");
for(int k=0;k<n;k++)
printf(" %d ",A[k]);
printf("\n");
}
void bubble()
{t1=clock();
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}t2=clock();
}
void insertion()
{t1=clock();
for(i=0;i<n;i++)
{
temp=b[i];
for(j=i-1;(j>=0&&temp<b[j]);j--)
b[j+1]=b[j];
b[j+1]=temp;
}t2=clock();
}
void selection()
{t1=clock();
int min;
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(c[min]>c[j])
min=j;
}
temp=c[i];
c[i]=c[min];
c[min]=temp;
}t2=clock();
}
int Partition(int A[100],int beg,int end)
{
int loc=beg;
while(1)
{
while(A[loc]<=A[end]&&loc!=end)
end=end-1;
if(loc==end)
return loc;
int temp=A[loc];
A[loc]=A[end];
A[end]=temp;
loc=end;
while(A[loc]>=A[beg]&&loc!=beg)
beg=beg+1;
if(loc==beg)
return loc;
temp=A[loc];
A[loc]=A[beg];
A[beg]=temp;
loc=beg;
}
}
void QuickSort(int A[100],int beg,int end)
{
if(beg<end)
{
int x=Partition(A,beg,end);
QuickSort(A,beg,x-1);
QuickSort(A,x+1,end);
}
}
void main()
{
printf("Enter Number of terms:");
scanf("%d",&n);m=n;
f=fopen("ins.dat","a");
fprintf(f,"\n%d\t",n);
fclose(f);
f=fopen("bub.dat","a");
fprintf(f,"\n%d\t",n);
fclose(f);
f=fopen("sel.dat","a");
fprintf(f,"\n%d\t",n);
fclose(f);
f=fopen("qk.dat","a");
fprintf(f,"\n%d\t",n);
fclose(f);
for(ch=1;ch<4;ch++)
{
if(ch==1)
{
printf("\nRandom\n");
for(i=0;i<n;i++)
{
b[i]=c[i]=A[i]=a[i]=(rand()%n);
}
}
if(ch==2)
{
printf("\nAscending\n");
for(i=0;i<n;i++)
{
ac[i]=b[i]=c[i]=A[i]=a[i]=a[i];
}
}
if(ch==3)
{
printf("\nDescending\n");
for(i=0;i<n;i++)
{
b[i]=c[i]=A[i]=a[i]=ac[n-i-1];
}
}
insertion();
printf("Insertion Sort=%f\n",((double) (t2 - t1)) / CLOCKS_PER_SEC);
f=fopen("ins.dat","a");
fprintf(f,"\t%f\t",((double) (t2 - t1)) / CLOCKS_PER_SEC);
fclose(f);
bubble();
printf("Bubble Sort=%f\n",((double) (t2 - t1)) / CLOCKS_PER_SEC);
f=fopen("bub.dat","a");
fprintf(f,"\t%f\t",((double) (t2 - t1)) / CLOCKS_PER_SEC);
fclose(f);
selection();
printf("Selection Sort=%f\n",((double) (t2 - t1)) / CLOCKS_PER_SEC);
f=fopen("sel.dat","a");
fprintf(f,"\t%f\t",((double) (t2 - t1)) / CLOCKS_PER_SEC);
fclose(f);
t1=clock();
QuickSort(A,0,n-1);
t2=clock();
printf("Quick Sort=%f\n",((double) (t2 - t1)) / CLOCKS_PER_SEC);
f=fopen("qk.dat","a");
fprintf(f,"\t%f\t",((double) (t2 - t1)) / CLOCKS_PER_SEC);
fclose(f);
//display();
}
}
|
C
|
//#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
//#include "pthreadbarrier.h"
#define num_thrds 4
pthread_barrier_t mybarrier;
void* threadFn(void *id_ptr) {
long thread_id = (long) id_ptr;
int wait_sec = 1 + rand() % 4;
printf("thread %ld: Wait for %d seconds.\n", thread_id, wait_sec);
sleep(wait_sec);
printf("thread %ld: I'm ready \n", thread_id);
pthread_barrier_wait(&mybarrier);
printf("thread %ld left the barrier\n", thread_id);
pthread_exit(NULL);
}
int main() {
long i;
pthread_t ids[num_thrds];
int short_ids[num_thrds];
srand(time(NULL));
pthread_barrier_init(&mybarrier, NULL, num_thrds + 1);
for (i=0; i < num_thrds; i++) {
pthread_create(&ids[i], NULL, threadFn, (void*) i);
}
printf("main() is ready.\n");
sleep(1);
pthread_barrier_wait(&mybarrier);
printf("main() left the barrier.\n");
for (i=0; i < num_thrds; i++) {
pthread_join(ids[i], NULL);
}
pthread_barrier_destroy(&mybarrier);
return 0;
}
|
C
|
/* SPDX-License-Identifier: BSD-2-Clause */
/*
* Copyright (c) 2017, Intel Corporation
* All rights reserved.
*/
#include <glib.h>
#include <stdlib.h>
#include <stdio.h>
#include <setjmp.h>
#include <cmocka.h>
#include "tpm2-header.h"
#include "tpm2-response.h"
#include "util.h"
#define HANDLE_TEST 0xdeadbeef
#define HANDLE_TYPE 0xde
typedef struct {
Tpm2Response *response;
guint8 *buffer;
size_t buffer_size;
Connection *connection;
} test_data_t;
/*
* This function does all of the setup required to run a test *except*
* for instantiating the Tpm2Response object.
*/
static int
tpm2_response_setup_base (void **state)
{
test_data_t *data = NULL;
gint client_fd;
HandleMap *handle_map;
GIOStream *iostream;
data = calloc (1, sizeof (test_data_t));
/* allocate a buffer large enough to hold a TPM2 header and a handle */
data->buffer_size = TPM_RESPONSE_HEADER_SIZE + sizeof (TPM2_HANDLE);
data->buffer = calloc (1, data->buffer_size);
handle_map = handle_map_new (TPM2_HT_TRANSIENT, MAX_ENTRIES_DEFAULT);
iostream = create_connection_iostream (&client_fd);
data->connection = connection_new (iostream, 0, handle_map);
g_object_unref (handle_map);
g_object_unref (iostream);
*state = data;
return 0;
}
/*
* This function sets up all required test data with a Tpm2Response
* object that has no attributes set.
*/
static int
tpm2_response_setup (void **state)
{
test_data_t *data;
tpm2_response_setup_base (state);
data = (test_data_t*)*state;
data->response = tpm2_response_new (data->connection,
data->buffer,
data->buffer_size,
(TPMA_CC){ 0, });
return 0;
}
/*
* This function sets up all required test data with a Tpm2Response
* object that has attributes indicating the response has a handle
* in it.
*/
static int
tpm2_response_setup_with_handle (void **state)
{
test_data_t *data;
TPMA_CC attributes = 1 << 28;
tpm2_response_setup_base (state);
data = (test_data_t*)*state;
data->buffer_size = TPM_RESPONSE_HEADER_SIZE + sizeof (TPM2_HANDLE);
data->response = tpm2_response_new (data->connection,
data->buffer,
data->buffer_size,
attributes);
set_response_size (data->buffer, data->buffer_size);
data->buffer [TPM_RESPONSE_HEADER_SIZE] = 0xde;
data->buffer [TPM_RESPONSE_HEADER_SIZE + 1] = 0xad;
data->buffer [TPM_RESPONSE_HEADER_SIZE + 2] = 0xbe;
data->buffer [TPM_RESPONSE_HEADER_SIZE + 3] = 0xef;
return 0;
}
/**
* Tear down all of the data from the setup function. We don't have to
* free the data buffer (data->buffer) since the Tpm2Response frees it as
* part of its finalize function.
*/
static int
tpm2_response_teardown (void **state)
{
test_data_t *data = (test_data_t*)*state;
g_object_unref (data->connection);
g_object_unref (data->response);
free (data);
return 0;
}
/**
* Here we check to be sure that the object instantiated in the setup
* function is actually the type that we expect. This is a test to be sure
* the type is registered properly with the type system.
*/
static void
tpm2_response_type_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
assert_true (G_IS_OBJECT (data->response));
assert_true (IS_TPM2_RESPONSE (data->response));
}
/**
* In the setup function we save a reference to the Connection object
* instantiated as well as passing it into the Tpm2Response object. Here we
* check to be sure that the Connection object returned by the Tpm2Response
* object is the same one that we passed it.
*/
static void
tpm2_response_get_connection_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
Connection *connection;
connection = tpm2_response_get_connection (data->response);
assert_int_equal (data->connection, connection);
g_object_unref (connection);
}
/**
* In the setup function we passed the Tpm2Response object a data buffer.
* Here we check to be sure it passes the same one back to us when we ask
* for it.
*/
static void
tpm2_response_get_buffer_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
assert_int_equal (data->buffer, tpm2_response_get_buffer (data->response));
}
/**
* Here we retrieve the data buffer from the Tpm2Response and manually set
* the tag part of the response buffer to TPM2_ST_SESSIONS in network byte
* order (aka big endian). We then use the tpm2_response_get_tag function
* to retrieve this data and we compare it to TPM2_ST_SESSIONS to be sure we
* got the value in host byte order.
*/
static void
tpm2_response_get_tag_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
guint8 *buffer = tpm2_response_get_buffer (data->response);
TPM2_ST tag_ret;
/* this is TPM2_ST_SESSIONS in network byte order */
buffer[0] = 0x80;
buffer[1] = 0x02;
tag_ret = tpm2_response_get_tag (data->response);
assert_int_equal (tag_ret, TPM2_ST_SESSIONS);
}
/**
* Again we're getting the response buffer from the Tpm2Response object
* but this time we're setting the additional size field (uint32) to 0x6
* in big endian format. We then use the tpm2_response_get_size function
* to get this value back and we compare it to 0x6 to be sure it's returned
* in host byte order.
*/
static void
tpm2_response_get_size_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
guint8 *buffer = tpm2_response_get_buffer (data->response);
guint32 size_ret = 0;
/* this is TPM2_ST_SESSIONS in network byte order */
buffer[0] = 0x80;
buffer[1] = 0x02;
buffer[2] = 0x00;
buffer[3] = 0x00;
buffer[4] = 0x00;
buffer[5] = 0x06;
size_ret = tpm2_response_get_size (data->response);
assert_int_equal (0x6, size_ret);
}
/**
* Again we're getting the response buffer from the Tpm2Response object
* but this time we're setting the additional response code field (TPM_RC)
* to a known value in big endian format. We then use tpm2_response_get_code
* to retrieve the RC and compare it to the appropriate constant to be sure
* it's sent back to us in host byte order.
*/
static void
tpm2_response_get_code_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
guint8 *buffer = tpm2_response_get_buffer (data->response);
TPM2_CC response_code;
/**
* This is TPM2_ST_SESSIONS + a size of 0x0a + the response code for
* GetCapability in network byte order
*/
buffer[0] = 0x80;
buffer[1] = 0x02;
buffer[2] = 0x00;
buffer[3] = 0x00;
buffer[4] = 0x00;
buffer[5] = 0x0a;
buffer[6] = 0x00;
buffer[7] = 0x00;
buffer[8] = 0x01;
buffer[9] = 0x00;
response_code = tpm2_response_get_code (data->response);
assert_int_equal (response_code, TPM2_RC_INITIALIZE);
}
/**
* This is a setup function for testing the "short-cut" constructor for the
* Tpm2Response object that creates the response buffer with the provided RC.
*/
static int
tpm2_response_new_rc_setup (void **state)
{
test_data_t *data = NULL;
gint client_fd;
GIOStream *iostream;
HandleMap *handle_map;
data = calloc (1, sizeof (test_data_t));
/* allocate a buffer large enough to hold a TPM2 header */
handle_map = handle_map_new (TPM2_HT_TRANSIENT, MAX_ENTRIES_DEFAULT);
iostream = create_connection_iostream (&client_fd);
data->connection = connection_new (iostream, 0, handle_map);
g_object_unref (handle_map);
g_object_unref (iostream);
data->response = tpm2_response_new_rc (data->connection, TPM2_RC_BINDING);
*state = data;
return 0;
}
/**
* The tpm2_response_new_rc sets the TPM2_ST_NO_SESSIONS tag for us since
* it's just returning an RC and cannot have connections. Here we check to be
* sure we can retrieve this tag and that's it's returned in host byte order.
*/
static void
tpm2_response_new_rc_tag_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TPM2_ST tag = 0;
tag = tpm2_response_get_tag (data->response);
assert_int_equal (tag, TPM2_ST_NO_SESSIONS);
}
/**
* The tpm2_response_new_rc sets the size to the appropriate
* TPM_RESPONSE_HEADER size (which is 10 bytes) for us since the response
* buffer is just a header. Here we check to be sure that we get this value
* back in the proper host byte order.
*/
static void
tpm2_response_new_rc_size_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
guint32 size = 0;
size = tpm2_response_get_size (data->response);
assert_int_equal (size, TPM_RESPONSE_HEADER_SIZE);
}
/**
* The tpm2_response_new_rc sets the response code to whatever RC is passed
* as a parameter. In the paired setup function we passed it TPM2_RC_BINDING.
* This function ensures that we get the same value back from the
* tpm2_response_get_code function in the proper host byte order.
*/
static void
tpm2_response_new_rc_code_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TSS2_RC rc = TPM2_RC_SUCCESS;
rc = tpm2_response_get_code (data->response);
assert_int_equal (rc, TPM2_RC_BINDING);
}
/**
* The tpm2_response_new_rc takes a connection as a parameter. We save a
* reference to this in the test_data_t structure. Here we ensure that the
* tpm2_response_get_connection function returns the same connection to us.
*/
static void
tpm2_response_new_rc_connection_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
Connection *connection = data->connection;
assert_int_equal (connection, tpm2_response_get_connection (data->response));
}
/*
* This test ensures that a tpm2_response_has_handle reports the
* actual value in the TPMA_CC attributes field when the rHandle bit
* in the attributes is *not* set.
*/
static void
tpm2_response_no_handle_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
gboolean has_handle;
has_handle = tpm2_response_has_handle (data->response);
assert_false (has_handle);
}
/*
* This test ensures that a tpm2_response_has_handle reports the
* actual value in the TPMA_CC attributes field when the rHandle bit
* in the attributes *is* set.
*/
static void
tpm2_response_has_handle_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
gboolean has_handle = FALSE;
has_handle = tpm2_response_has_handle (data->response);
assert_true (has_handle);
}
/*
* This tests the Tpm2Response objects ability to return the handle that
* we set in the setup function.
*/
static void
tpm2_response_get_handle_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TPM2_HANDLE handle;
handle = tpm2_response_get_handle (data->response);
assert_int_equal (handle, HANDLE_TEST);
}
/*
* This tests the Tpm2Response object's ability detect an attempt to read
* beyond the end of its internal buffer. We fake this by changing the
* buffer_size field manually and then trying to access the handle.
*/
static void
tpm2_response_get_handle_no_handle_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TPM2_HANDLE handle;
data->response->buffer_size = TPM_HEADER_SIZE;
handle = tpm2_response_get_handle (data->response);
assert_int_equal (handle, 0);
}
/*
* This tests the Tpm2Response objects ability to return the handle type
* from the handle we set in the setup function.
*/
static void
tpm2_response_get_handle_type_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TPM2_HT handle_type;
handle_type = tpm2_response_get_handle_type (data->response);
assert_int_equal (handle_type, HANDLE_TYPE);
}
/*
* This tests the Tpm2Response objects ability to set the response handle
* field. We do this by first setting the handle to some value and then
* querying the Tpm2Response object for the handle. The value returned
* should be the handle that we set in the previous call.
*/
static void
tpm2_response_set_handle_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TPM2_HANDLE handle_in = 0x80fffffe, handle_out = 0;
tpm2_response_set_handle (data->response, handle_in);
handle_out = tpm2_response_get_handle (data->response);
assert_int_equal (handle_in, handle_out);
}
/*
* This tests the Tpm2Response object's ability detect an attempt to write
* beyond the end of its internal buffer. We fake this by changing the
* buffer_size field manually and then trying to set the handle.
*/
static void
tpm2_response_set_handle_no_handle_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TPM2_HANDLE handle_in = 0x80fffffe, handle_out = 0;
data->response->buffer_size = TPM_HEADER_SIZE;
tpm2_response_set_handle (data->response, handle_in);
handle_out = tpm2_response_get_handle (data->response);
assert_int_equal (handle_out, 0);
}
gint
main (void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test_setup_teardown (tpm2_response_type_test,
tpm2_response_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_get_connection_test,
tpm2_response_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_get_buffer_test,
tpm2_response_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_get_tag_test,
tpm2_response_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_get_size_test,
tpm2_response_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_get_code_test,
tpm2_response_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_new_rc_tag_test,
tpm2_response_new_rc_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_new_rc_size_test,
tpm2_response_new_rc_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_new_rc_code_test,
tpm2_response_new_rc_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_new_rc_connection_test,
tpm2_response_new_rc_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_no_handle_test,
tpm2_response_setup,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_has_handle_test,
tpm2_response_setup_with_handle,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_get_handle_test,
tpm2_response_setup_with_handle,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_get_handle_no_handle_test,
tpm2_response_setup_with_handle,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_get_handle_type_test,
tpm2_response_setup_with_handle,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_set_handle_test,
tpm2_response_setup_with_handle,
tpm2_response_teardown),
cmocka_unit_test_setup_teardown (tpm2_response_set_handle_no_handle_test,
tpm2_response_setup_with_handle,
tpm2_response_teardown),
};
return cmocka_run_group_tests (tests, NULL, NULL);
}
|
C
|
/*
* Programmer: Hermes Obiang
* CptS 360 - Fall 2019
* Project Level 1
*/
/************* level 1 file **************/
/**** globals defined in main.c file ****/
extern MINODE minode[NMINODE];
extern MINODE *root;
extern PROC proc[NPROC], *running;
extern char gpath[256];
extern char *name[64];
extern int n;
extern int fd, dev;
extern int nblocks, ninodes, bmap, imap, inode_start;
extern char line[256], cmd[32], pathname[256];
char *cp,myname[256], buf[1024];
MINODE *pip, *mip;
int myino, parentino;
#define OWNER 000700
#define GROUP 000070
#define OTHER 000007
change_dir()
{
int ino;
MINODE *mip;
if (strcmp(pathname,"") == 0) //check if there is a pathname
{
running->cwd = root;
return;
}
ino = getino(pathname); // get ino of pathname
mip = iget(dev,ino); // get the MINODE structure of the ino
int temp = &(mip->INODE).i_mode;
if(S_ISDIR(temp)) // check if it is a directory
{
iput(running->cwd = mip);
running->cwd = mip;
}
iput(running->cwd = mip);
running->cwd = mip;
}
int list_file()
{
if (strlen(pathname) == 0) // check if there is a pathname
{
mip = running->cwd; // if no path provided, set mip to the cwd
ip = &(mip->INODE);
}
else
{
myino = getino(pathname);
mip = iget(dev,myino);
ip = &(mip->INODE);
}
if(S_ISDIR(ip->i_mode)) // check if it is a directory
{
ls_dir(ip);
}
else
{
ls_file(myino,name[n-1]);
}
}
int ls_dir(INODE *s)
{
char nam[32];
get_block(dev,s->i_block[0],buf);
dp = (DIR*)buf;
cp = buf;
while(cp < buf + BLKSIZE)
{
strncpy(nam,dp->name,dp->name_len);
nam[dp->name_len] = 0;
ls_file(dp->inode,nam);
cp += dp->rec_len;
dp = (DIR *)cp;
}
}
int ls_file(MINODE *inno, char *n)
{
char buff[516];
char ftime[64];
mip = iget(dev,inno);
ip = &(mip->INODE);
if(S_ISDIR(ip->i_mode))
{
printf("d");
}
if(S_ISLNK(ip->i_mode))
{
printf("l");
}
if(S_ISREG(ip->i_mode))
{
printf("-");
}
for (int i = 8; i >= 0; i--)
{
if (ip->i_mode & (1 << i)) // print r|w|x
{
printf("%c", t1[i]);
}
else
{
printf("%c", t2[i]); // or print -
}
}
printf("%4d ",ip->i_links_count); // link count
printf("%4d ",ip->i_gid); // gid
printf("%4d ",ip->i_uid); // uid
printf("%8d ",ip->i_size); // file size
// print time
strcpy(ftime, ctime(&ip->i_mtime)); // print time in calendar form
ftime[strlen(ftime)-1] = 0; // kill \n at end
printf("%s ",ftime);
printf("%s",n);
if(ip->i_mode == 0120000)
{
//char *l = myreadlink(n);
//printf("-> %s", l);
printf("-> %s", ip->i_block);
}
printf("\n");
}
int pwd(MINODE *wd)
{
if (wd == root)
{
printf("/");
}
else
{
rpwd(wd);
}
printf("\n");
}
void rpwd(MINODE *wd)
{
char myname[256];
if(wd == root)
{
return;
}
// get the block
get_block(dev,wd->INODE.i_block[0],buf); // from i_block[0] get myino and parentino
dp = (DIR *)buf;
myino = dp->inode;
cp = buf;
cp = cp + dp->rec_len; // add to get the next dir
dp = (DIR *)cp;
parentino = dp->inode; // get parent ino
pip = iget(dev,parentino);
get_block(dev, pip->INODE.i_block[0],buf);
dp = (DIR*)buf;
cp = buf;
while(cp < buf + BLKSIZE)
{
if(myino == dp->inode)
{
strncpy(myname,dp->name,dp->name_len);
myname[dp->name_len] = 0;
break;
}
cp += dp->rec_len;
dp = (DIR *)cp;
}
rpwd(pip);
printf("/%s",myname);
}
int make_dir()
{
char parent[128], child[64];
MINODE *start;
int isdir = 0;
if(pathname[0]== '/')
{
start = root;
dev = root->dev;
}
else
{
start = running->cwd;
dev = running->cwd->dev;
}
// since basename and dirname destroys the path
// we make a copy of the path and operate on it
strcpy(parent,dirname(gpath));
// since basename and dirname destroys the path
// we make a copy of the path and operate on it
strcpy(gpath,pathname);
strcpy(child,basename(gpath));
//Get the In_MEMORY minode of parent:
int pino = getino(parent);
if(pino == 0)
{
printf("mkdir failed: %s does not exist\n",parent);
return 1;
}
pip = iget(dev, pino);
//Verify : (1). parent INODE is a DIR (HOW?)
if(S_ISDIR(pip->INODE.i_mode))
{
iput(pip);
isdir = 1;
}
else
{
iput(pip);
isdir = 0;
}
//(2). child does NOT exists in the parent directory (HOW?);
int exists = search(pip,child);
if(isdir == 1 && exists == 0)
{
//4. call mymkdir(pip, child);
mymkdir(pip,child);
//increment parent inodes's link count by 1;
//touch its atime and mark it DIRTY
pip->INODE.i_links_count++;
pip->dirty = 1;
pip->INODE.i_atime = time(0L);
iput(pip);
return 1;
}
iput(pip);
return 0;
}
int mymkdir(MINODE *pip, char *name)
{
MINODE *mip;
int ino,bno;
char buf[BLKSIZE];
//allocate an inode and a disk block for the new directory;
ino = ialloc(dev);
bno = balloc(dev);
printf("ino = %d bno = %d\n",ino,bno);
mip = iget(dev, ino); //load the inode into a minode[] (in order to wirte contents to the INODE in memory.
//iput(mip); //Write contents to mip->INODE to make it as a DIR INODE.
ip = &mip->INODE;
ip->i_mode = 0x41ED; // OR 040755: DIR type and permissions
ip->i_uid = running->uid; // Owner uid
ip->i_gid = running->gid; // Group Id
ip->i_size = BLKSIZE; // Size in bytes
ip->i_links_count = 2; // Links count=2 because of . and ..
ip->i_atime = time(0L);// set to current time
ip->i_ctime = time(0L);// set to current time
ip->i_mtime = time(0L); // set to current time
ip->i_blocks = 2; // LINUX: Blocks count in 512-byte chunks
ip->i_block[0] = bno; // new DIR has one data block
for(int i = 1; i<=14;i++){ ip->i_block[i] = 0;} //i_block[1] to i_block[14] = 0;
mip->dirty = 1; // mark minode dirty
iput(mip); // write INODE to disk
//***** create data block for new DIR containing . and .. entries ******
get_block(dev,bno,buf);
dp = (DIR*)buf;
cp = buf;
//Write . entry into a buf[ ] of BLKSIZE
dp->file_type = (u8)EXT2_FT_DIR;
dp->inode = (u32)ino;
dp->name[0] = '.';
dp->name_len = (u8) 1;
dp->rec_len = (u16) 12;
//Write .. entry into a buf[ ] of BLKSIZE
cp += dp->rec_len;
dp = (DIR*)cp;
dp->file_type = (u8)EXT2_FT_DIR;
dp->inode = (u32)pip->ino;
dp->name[0] = '.';
dp->name[1] = '.';
dp->name_len = (u8) 2;
dp->rec_len = (u16) 1012;
//Then, write buf[ ] to the disk block bno;
put_block(dev,bno,buf);
//Finally, enter name ENTRY into parent's directory by
enter_name(pip,ino,name);
return 0;
}
int enter_name(MINODE *pip, int myino, char *myname)
{
char buf[BLKSIZE];
for(int i = 0; i<12; i++)
{
if(pip->INODE.i_block[i] == 0){break;}
//get parent's data block into a buf[];
get_block(dev,pip->INODE.i_block[i],buf);
dp = (DIR*)buf;
cp = buf;
// step to LAST entry in block: int blk = parent->INODE.i_block[i];
int blk = pip->INODE.i_block[i];
printf("step to LAST entry in data block %d\n", blk);
//Step to the last entry in a data block (HOW?).
while(cp + dp->rec_len < buf + BLKSIZE)
{
cp += dp->rec_len;
dp = (DIR*)cp;
}
int IDEAL_LEN = 4*((8 + dp->name_len + 3)/4);
int need_length = 4*((8 + strlen(myname) + 3)/4);
int remain = dp->rec_len - IDEAL_LEN;
if(remain >= need_length)
{
dp->rec_len = IDEAL_LEN;
cp += dp->rec_len;
dp = (DIR*)cp;
dp->file_type = (u8)EXT2_FT_DIR;
dp->inode = (u32)myino;
strcpy(dp->name,myname);
dp->name_len = (u8) strlen(myname);
dp->rec_len = (u16) remain;
//Write data block to disk;
put_block(dev,pip->INODE.i_block[i],buf);
return 0;
}
// Reach here means: NO space in existing data block(s)
//Allocate a new data block; INC parent's isze by BLKSIZE;
int temp_bno = balloc(dev); //Allocate a new data block;
pip->INODE.i_block[i] = temp_bno;
pip->INODE.i_size += BLKSIZE; //INC parent's isze by BLKSIZE;
pip->dirty = 1; // mark pip->dirty
get_block(dev,temp_bno, buf); // get the new block
//Enter new entry as the first entry in the new data block with rec_len=BLKSIZE.
cp = buf;
dp = (DIR*)buf;
dp->file_type = (u8)EXT2_FT_DIR;
dp->inode = (u32)myino;
strcpy(dp->name,myname);
dp->name_len = (u8) strlen(myname);
dp->rec_len = (u16) BLKSIZE;
put_block(dev,temp_bno,buf);
}
}
int creat_file()
{
char parent[128], child[64];
MINODE *start;
int isdir = 0;
if(pathname[0]== '/')
{
start = root;
dev = root->dev;
}
else
{
start = running->cwd;
dev = running->cwd->dev;
}
// since basename and dirname destroys the path
// we make a copy of the path and operate on it
strcpy(parent,dirname(gpath));
// since basename and dirname destroys the path
// we make a copy of the path and operate on it
strcpy(gpath,pathname);
strcpy(child,basename(gpath));
//Get the In_MEMORY minode of parent:
int pino = getino(parent);
pip = iget(dev, pino);
//Verify : (1). parent INODE is a DIR (HOW?)
if(pip->mounted && pip->ino != root->ino)
{
pip = start;
dev = pip->dev;
}
if(S_ISDIR(pip->INODE.i_mode))
{
iput(pip);
isdir = 1;
}
else
{
iput(pip);
isdir = 0;
}
//(2). child does NOT exists in the parent directory (HOW?);
int exists = search(pip,child);
if(isdir == 1 && exists == 0)
{
//4. call mymkdir(pip, child);
my_creat(pip,child);
pip->dirty = 1;
pip->INODE.i_atime = time(0L);
iput(pip);
return 1;
}
iput(pip);
return 0;
}
int my_creat(MINODE *pip, char *name)
{
MINODE *mip;
int ino,bno;
char buf[BLKSIZE];
//allocate an inode and a disk block for the new directory;
ino = ialloc(dev);
//bno = balloc(dev);
printf("ino = %d \n",ino);
mip = iget(dev, ino); //load the inode into a minode[] (in order to wirte contents to the INODE in memory.
//iput(mip); //Write contents to mip->INODE to make it as a DIR INODE.
ip = &mip->INODE;
ip->i_mode = 0x81A4; // OR 040755: DIR type and permissions
ip->i_uid = running->uid; // Owner uid
ip->i_gid = running->gid; // Group Id
ip->i_size = 0; // Size in bytes
ip->i_links_count = 1; // Links count=2 because of . and ..
ip->i_atime = time(0L);// set to current time
ip->i_ctime = time(0L);// set to current time
ip->i_mtime = time(0L); // set to current time
ip->i_blocks = 2; // LINUX: Blocks count in 512-byte chunks
//ip->i_block[0] = bno; // new DIR has one data block
for(int i = 1; i<=14;i++){ ip->i_block[i] = 0;} //i_block[1] to i_block[14] = 0;
mip->dirty = 1; // mark minode dirty
iput(mip); // write INODE to disk
//Finally, enter name ENTRY into parent's directory by
enter_name(pip,ino,name);
return 0;
}
int rmdir()
{
char parent[128], child[64];
//2. get inumber of pathname:
int ino = getino(pathname);
// verify the pathname is valid
if(ino == 0)
{
printf("rmdir failed: %s does not exist\n",pathname);
return 1;
}
//3. get its minode[ ] pointer:
mip = iget(dev, ino);
//4. check ownership. super user : OK. not super user: uid must match
if(running->uid != 0)
{
if(running->uid != mip->INODE.i_uid)
{
printf("cannot remove directory : Permission denied.\n");
return -1;
}
}
// check if it is a directory
if(!S_ISDIR(mip->INODE.i_mode))
{
printf("rmdir: failed to remove %s: Not a directory\n",pathname);
return -1;
}
// ckeck if the directory is empty
if(isEmpty(mip) == -1)
{
return -1;
}
// since basename and dirname destroys the path
// we make a copy of the path and operate on it
strcpy(parent,dirname(gpath));
// since basename and dirname destroys the path
// we make a copy of the path and operate on it
strcpy(gpath,pathname);
strcpy(child,basename(gpath));
//Get the In_MEMORY minode of parent:
int pino = getino(parent);
pip = iget(mip->dev, pino);
//Deallocate its block and inode
for (int i=0; i<12; i++)
{
if (mip->INODE.i_block[i]==0){continue;}
bdealloc(mip->dev, mip->INODE.i_block[i]);
}
idealloc(mip->dev, mip->ino);
iput(mip); //(which clears mip->refCount = 0);
rm_child(pip, child);
pip->INODE.i_links_count -= 1;
//pip->refCount -= 1;
pip->dirty = 1;
pip->INODE.i_mtime = time(0L);
pip->INODE.i_atime = time(0L);
iput(pip);
return 0;
}
int rm_child(MINODE *parent, char *name)
{
DIR *last_dir, *last_dir2;
char temp[128], buf[BLKSIZE];
char *cp2, *cp;
//Search parent INODE's data block(s) for the entry of name
for(int i = 0; i<12; i++)
{
if(parent->INODE.i_block[i] == 0) {break;}
get_block(parent->dev,parent->INODE.i_block[i],buf);
cp = buf;
dp = (DIR*)buf;
while(cp < buf + BLKSIZE)
{
strncpy(temp, dp->name,dp->name_len);
temp[dp->name_len] = 0;
// found name
if(strcmp(temp,name) == 0)
{
if(cp + dp->rec_len == buf + BLKSIZE)
{
last_dir->rec_len += dp->rec_len;
put_block(dev,parent->INODE.i_block[i],buf);
return 0;
}
else
{
last_dir2 = (DIR*)buf;
cp2 = buf;
while(cp2 + last_dir2->rec_len < buf + BLKSIZE)
{
cp2 += last_dir2->rec_len;
last_dir2 = (DIR*)cp2;
}
last_dir2->rec_len += dp->rec_len;
int start = cp + dp->rec_len;
int end = buf + BLKSIZE;
memmove(cp,start,end-start);
put_block(dev,parent->INODE.i_block[i],buf);
}
}
cp += dp->rec_len;
last_dir = dp;
dp = (DIR*)cp;
}
}
}
int link()
{
char old_file[256], new_file[256],filename[256], path[256];
int ino,new_ino;
strcpy(new_file,pathname2);
strcpy(old_file,pathname);
//(1).get the INODE of /a/b/c into memory: mip->minode[ ]
ino = getino(old_file);
mip = iget(dev,ino);
//(2). check /a/b/c is a REG or LNK file (link to DIR is NOT allowed).
if(S_ISREG(mip->INODE.i_mode) || S_ISLNK(mip->INODE.i_mode))
{
strcpy(path,dirname(new_file));
strcpy(new_file,pathname2);
strcpy(filename,basename(new_file));
//(3). check /x/y exists and is a DIR but 'z' does not yet exist in /x/y/
new_ino = getino(path);
if(new_ino == 0)
{
return 1;
}
pip = iget(dev,new_ino);
strcpy(new_file,pathname2);
if(search(pip,filename) != 0)
{
printf("Path to %s already exist",path);
return 1;
}
enter_name(pip,ino,filename);
//(5). increment the i_links_count of INODE by 1
mip->INODE.i_links_count++;
iput(mip);
return 0;
}
else
{
printf("link to DIR is NOT allowed\n");
return 1;
}
}
int unlink()
{
char path[256], *parent,*child;
strcpy(path,pathname);
int ino = getino(path);
if(ino == 0)
{
return 1;
}
mip = iget(dev,ino);
if(S_ISREG(mip->INODE.i_mode) || S_ISLNK(mip->INODE.i_mode))
{
mip->INODE.i_links_count--;
//if i_links_count == 0 ==> rm pathname by
if(mip->INODE.i_links_count == 0)
{
for(int i = 0; i<12; i++)
{
if(mip->INODE.i_block[i] == 0){break;}
bdealloc(dev,mip->INODE.i_block[i]);
}
idealloc(dev,ino);
}
strcpy(path,pathname);
parent = dirname(path);
strcpy(path,pathname);
child = basename(path);
ino = getino(parent);
pip = iget(dev,ino);
rm_child(pip,child);
return 0;
}
else
{
printf("link to DIR is NOT allowed\n");
return 1;
}
}
int symlink()
{
char old_file[256], new_file[256],*filename, parent[256],child[256];
strcpy(old_file,pathname);
strcpy(new_file,pathname2);
//(1). check: old_file exist
if(getino(old_file) == 0)
{
printf("%s does not exist",old_file);
return 1;
}
//(2). check: new_file does not exist
if(getino(new_file) != 0)
{
printf("%s already exist",new_file);
return 1;
}
strcpy(parent,dirname(new_file));
strcpy(new_file,pathname2);
strcpy(child,basename(new_file));
int pino = getino(parent);
pip = iget(dev,pino);
strcpy(new_file,pathname2);
//(2). creat new_file; change new_file to LNK type;
my_creat(pip,child);
//(3). assume length of old_file name <= 60 chars
myino = search(pip,child);
mip = iget(dev,myino);
if(strlen(new_file) <= 60)
{
//store old_file name in newfile’s INODE.i_block[ ] area.
strcpy((char*)mip->INODE.i_block,basename(pathname));
//set file size to length of old_file name
mip->INODE.i_size = strlen(basename(old_file));
//mark new_file’s minode dirty;
mip->dirty = 1;
mip->INODE.i_mode = 0120000;
iput(mip);
}
}
|
C
|
#include "mb_log.h"
#include "packet.h"
#include <arpa/inet.h>
#include <linux/if_ether.h>
#include <linux/tcp.h>
#include <linux/ip.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
int process_packet(struct pair_entry *p, struct iphdr *iph, int ipl, struct tcphdr *tcph, int tl, uint8_t *reply, int *len)
{
return _process_packet(p, iph, ipl, tcph, tl, reply, len);
}
int _process_packet(struct pair_entry *p, struct iphdr *iph, int ipl, struct tcphdr *tcph, int tl, uint8_t *reply, int *len)
{
*len = 0;
if (tcph->syn)
{
MB_LOG1x("SYN packet", tcph->syn);
MB_LOG1x("ACK packet", tcph->ack);
iph->ihl = 5;
iph->version = 4;
iph->protocol = IPPROTO_TCP;
iph->ttl = 255;
iph->saddr = p->daddr;
iph->daddr = p->saddr;
iph->tot_len = ipl + tl;
iph->check = 0x0;
iph->check = _ip_checksum(iph, ipl);
tcph->source = htons(p->dport);
tcph->dest = htons(p->sport);
tcph->ack_seq = htonl(p->seq + 1);
tcph->seq = htonl(p->ack);
tcph->syn = 1;
tcph->ack = 1;
tcph->check = 0x0;
tcph->check = _tcp_checksum(iph, tcph, tl);
memcpy(reply, iph, ipl);
memcpy(reply + ipl, tcph, tl);
*len = ipl + tl;
}
return 1;
}
int check_checksum(uint8_t *header, int len)
{
MB_LOG("Check Checksum");
int ret;
struct iphdr *iph = (struct iphdr *) (header);
int ihl = iph->ihl * 4;
MB_LOG1d("IP header length", ihl);
MB_LOG1d("IP packet length", ntohs(iph->tot_len));
ret = _ip_checksum(iph, ihl);
if (ret < 0 || ret > 0)
return -1;
MB_LOG("IP Checksum verification success");
struct tcphdr *tcph = (struct tcphdr *) (header + ihl);
int tl = ntohs(iph->tot_len) - ihl;
int thl = tcph->doff * 4;
int pl = tl - thl;
MB_LOG1d("TCP Segment Length", tl);
MB_LOG1d("TCP Header Length", thl);
MB_LOG1d("TCP Payload Length", pl);
ret = _tcp_checksum(iph, tcph, tl);
if (ret < 0 || ret > 0)
return -1;
MB_LOG("TCP Checksum verification success");
return 1;
}
int _ip_checksum(struct iphdr *iph, int ihl)
{
return make_checksum((uint8_t *)iph, ihl);
}
int _tcp_checksum(struct iphdr *iph, struct tcphdr *tcph, int tl)
{
int ret;
struct pseudo_tcp *ptcph = (struct pseudo_tcp *)malloc(sizeof(struct pseudo_tcp));
ptcph->saddr = iph->saddr;
MB_LOG1x("IP source addr", iph->saddr);
MB_LOG1x("Pseudo TCP Header", ptcph->saddr);
ptcph->daddr = iph->daddr;
ptcph->reserved = 0;
ptcph->protocol = iph->protocol;
ptcph->len = htons(tl); // Caution!
unsigned char check[sizeof(struct pseudo_tcp) + tl];
memset(check, 0x00, sizeof(struct pseudo_tcp) + tl);
memcpy(check, ptcph, sizeof(struct pseudo_tcp));
memcpy(check + sizeof(struct pseudo_tcp), tcph, tl);
ret = make_checksum((uint8_t *)check, sizeof(struct pseudo_tcp) + tl);
if (ret < 0)
return -1;
free(ptcph);
return ret;
}
int make_checksum(uint8_t *header, int len)
{
int i, tmp1, tmp2;
int checksum = 0;
if (len == 0)
return 1;
for (i=0; i<len; i+=2)
{
tmp1 = header[i];
if (i+1 >= len)
{
checksum = checksum + (int)((tmp1 & 0xFF) << 8);
}
else
{
tmp2 = header[i+1];
checksum = checksum + (int)(((tmp1 & 0xFF) << 8) | (tmp2 & 0xFF));
}
}
checksum = (checksum & 0xFFFF) + (checksum >> 16);
checksum = ~checksum & 0xFFFF;
MB_LOG1x("Checksum Result", checksum);
return checksum;
}
int parse_entry(struct pair_entry *tmp, uint8_t *buf, int len)
{
struct ethhdr *eh = (struct ethhdr *) buf;
struct iphdr *iph = (struct iphdr *) (buf + sizeof(struct ethhdr));
struct tcphdr *tcph = (struct tcphdr *)(iph + iph->ihl * 4);
tmp->saddr = iph->saddr;
tmp->daddr = iph->daddr;
tmp->sport = ntohs(tcph->source);
tmp->dport = ntohs(tcph->dest);
tmp->seq = ntohl(tcph->seq);
if (tcph->ack_seq == 0)
{
srand(time(NULL));
tmp->ack = rand() % INT_MAX;
}
else
tmp->ack = tcph->ack_seq;
return 1;
}
|
C
|
#include <stdio.h>
int main(){
int x,y;
scanf("%d%d", &x, &y);
int month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int totalDays = 0;
for(int i = 1; i < x; i++){
totalDays += month[i-1];
}
totalDays += y;
totalDays = totalDays % 7;
switch(totalDays){
case 1: printf("MON");
break;
case 2: printf("TUE");
break;
case 3: printf("WED");
break;
case 4: printf("THU");
break;
case 5: printf("FRI");
break;
case 6: printf("SAT");
break;
default: printf("SUN");
break;
}
}
|
C
|
#include<stdio.h>
int add(int,int);
int sub(int,int);
int main(int argc,char const *argv[])
{
printf("Addition:%d\n",add(10,20));
printf("Difference:%d\n",sub(10,20));
return 0;
}
|
C
|
#include <stdio.h>
int main(){
char s1[] = "Now is the time for all good programmers";
int i;
printf("s1 is : %s\n", s1);
printf("Printing one char at a time: ");
for (i=0; s1[i] != '\0'; i++ ) {
printf("%c ", s1[i]);
}
printf("\n");
char s2[100];
printf("Enter a string: ");
scanf("%100[^\n]", s2);
printf("s2 is: %s\n", s2);
return 0;
}
/*
*
*
*
*
*
printf("s1 os : %s\n", s1);
scanf("%s", s1);
printf("s1 is %s\ns2 is : %s\n",s1,s2);
for(i = 0; s1[i] != '\0';i++){
printf("%c ", s1[i]);
}
printf("s1 is %s\ns2 is : %s\n",s1,s2);
printf("Printing s1 one character at a time not looking for the null character:");
for(i = 0; i<10000;i++){
printf("%c", s1[i]);
}
printf("\n");
*/
|
C
|
/*
* motorControl.c
*
* Control module for the main and tail motors of the helicopter.
*
* Author: J. Shaw and M. Rattner
*/
#include "globals.h"
#include "motorControl.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/sysctl.h"
#include "driverlib/pwm.h"
#include "driverlib/gpio.h"
/**
* Initialise the PWM generators. Should be called after the associated
* GPIO pins have been enabled for output.
* PWM generator 0: Controls PWM1 (Main rotor)
* PWM generator 2: Controls PWM4 (Tail rotor)
*/
void initPWMchan (void) {
if (initialised) {
return;
}
unsigned long period;
SysCtlPeripheralReset(SYSCTL_PERIPH_PWM);
SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM);
// Configure both PWM generators' counting mode and synchronisation mode
PWMGenConfigure(PWM_BASE, PWM_GEN_0,
PWM_GEN_MODE_UP_DOWN | PWM_GEN_MODE_NO_SYNC);
PWMGenConfigure(PWM_BASE, PWM_GEN_2,
PWM_GEN_MODE_UP_DOWN | PWM_GEN_MODE_NO_SYNC);
// Compute the PWM period based on the system clock.
SysCtlPWMClockSet(SYSCTL_PWMDIV_4);
// We set the PWM clock to be 1/4 the system clock, so set the period
// to be 1/4 the system clock divided by the desired frequency.
period = SysCtlClockGet() / 4 / PWM_RATE_HZ;
// Generator 0
PWMGenPeriodSet(PWM_BASE, PWM_GEN_0, period);
PWMPulseWidthSet(PWM_BASE, PWM_OUT_1, period * MAIN_INITIAL_DUTY100 / 10000);
// Generator 2
PWMGenPeriodSet(PWM_BASE, PWM_GEN_2, period);
PWMPulseWidthSet(PWM_BASE, PWM_OUT_4, period * TAIL_INITIAL_DUTY100 / 10000);
// Disable the PWM output signals until we want the heli to take off.
PWMOutputState(PWM_BASE, PWM_OUT_1_BIT | PWM_OUT_4_BIT, false);
// Enable the PWM generators.
PWMGenEnable(PWM_BASE, PWM_GEN_0);
PWMGenEnable(PWM_BASE, PWM_GEN_2);
initialised = 1;
}
/**
* If the helicopter is at a low enough altitude, turn off the motors.
*/
void powerDown (void) {
_desiredAltitude = 0;
unsigned int mainDuty = getDutyCycle100(MAIN_ROTOR);
// Check that the heli is close to the ground and that the main rotor
// has a low duty cycle before shutting off.
if (_avgAltitude < 5 && mainDuty <= MIN_DUTY100) {
PWMOutputState(PWM_BASE, PWM_OUT_1_BIT | PWM_OUT_4_BIT, false);
setDutyCycle100(MAIN_ROTOR, MAIN_INITIAL_DUTY100);
setDutyCycle100(TAIL_ROTOR, TAIL_INITIAL_DUTY100);
_heliState = HELI_OFF;
}
}
/**
* Turns on the motors and sets duty cycle of both to the initial amount.
*/
void powerUp (void) {
if (!initialised) {
return;
}
setDutyCycle100(MAIN_ROTOR, MAIN_INITIAL_DUTY100);
setDutyCycle100(TAIL_ROTOR, TAIL_INITIAL_DUTY100);
PWMOutputState(PWM_BASE, PWM_OUT_1_BIT | PWM_OUT_4_BIT, true);
_heliState = HELI_ON;
}
/**
* Sets the PWM duty cycle to be the duty cycle %. Has built in
* safety at 5% or 95% if dutyCycle set above 95% or below 5%.
* @param rotor Either MAIN_ROTOR or TAIL_ROTOR
* @param dutyCycle100 The desired duty cycle % times 100
*/
void setDutyCycle100 (unsigned long rotor, unsigned int dutyCycle100) {
if (!initialised) {
return;
}
unsigned long period = (rotor == MAIN_ROTOR) ?
PWMGenPeriodGet(PWM_BASE, PWM_GEN_0) // main rotor PWM
: PWMGenPeriodGet(PWM_BASE, PWM_GEN_2); // tail rotor PWM
// If the desired duty cycle is below 5% or above 95%, hold.
if (dutyCycle100 < MIN_DUTY100) {
dutyCycle100 = MIN_DUTY100;
} else if (dutyCycle100 > MAX_DUTY100) {
dutyCycle100 = MAX_DUTY100;
}
unsigned long newPulseWidth = (dutyCycle100 * period + 5000) / 10000;
// Set the pulse width according to the desired duty cycle
PWMPulseWidthSet(PWM_BASE, rotor, newPulseWidth);
}
/**
* Get the current duty cycle of the specified rotor PWM.
* @param rotor Either MAIN_ROTOR or TAIL_ROTOR
* @return The current duty cycle % of that rotor's PWM channel, * 100
*/
unsigned int getDutyCycle100 (unsigned long rotor) {
unsigned long pulseWidth = PWMPulseWidthGet(PWM_BASE, rotor);
unsigned long period = (rotor == MAIN_ROTOR) ?
PWMGenPeriodGet(PWM_BASE, PWM_GEN_0) // main rotor PWM
: PWMGenPeriodGet(PWM_BASE, PWM_GEN_2); // tail rotor PWM
return (10000 * pulseWidth + period / 2) / period;
}
/**
* Adjusts duty cycle from current duty cycle.
* Used for testing the open loop response of the helicopter motors.
* @param rotor Either MAIN_ROTOR or TAIL_ROTOR
* @param amount Percentage * 100 to adjust the duty cycle
*/
void changeDutyCycle (unsigned long rotor, signed int amount) {
unsigned long currentPulseWidth = PWMPulseWidthGet(PWM_BASE, rotor);
unsigned long period = (rotor == MAIN_ROTOR) ?
PWMGenPeriodGet(PWM_BASE, PWM_GEN_0) // main rotor PWM
: PWMGenPeriodGet(PWM_BASE, PWM_GEN_2); // tail rotor PWM
// Don't allow the duty cycle to change too much at once
if (amount > MAX_DUTY_CHANGE100) {
amount = MAX_DUTY_CHANGE100;
} else if (amount < -MAX_DUTY_CHANGE100) {
amount = -MAX_DUTY_CHANGE100;
}
signed long pulseWidthChange = (amount * (signed long)period + 5000) / 10000;
signed long newPulseWidth = currentPulseWidth + pulseWidthChange;
unsigned long minPulseWidth = (MIN_DUTY100 * period + 5000) / 10000;
unsigned long maxPulseWidth = (MAX_DUTY100 * period + 5000) / 10000;
// Don't allow the duty cycle to be <5% or >95%
if (newPulseWidth < minPulseWidth) {
newPulseWidth = minPulseWidth;
} else if (newPulseWidth > maxPulseWidth) {
newPulseWidth = maxPulseWidth;
}
PWMPulseWidthSet(PWM_BASE, rotor, newPulseWidth);
}
/**
* Adjusts the PWM duty cycle of the main rotor to control the altitude.
*/
void altitudeControl (void) {
if (!initialised) {
return;
}
unsigned int mainDuty100 = getDutyCycle100(MAIN_ROTOR);
static signed long errorIntegrated = 200;
int error = _desiredAltitude - _avgAltitude;
// Bypass normal altitude control if the heli is landing
if (_heliState == HELI_STOPPING && mainDuty100 > MIN_DUTY100) {
changeDutyCycle(MAIN_ROTOR, -MAX_DUTY_CHANGE100);
errorIntegrated = 0;
return;
}
// bias = 1500; Kp = 25; Ki = 25/2
int newDuty100 = 1500 + error * 25 + errorIntegrated * 25 / 2;
// Don't allow duty cycle to change too much at once
if (newDuty100 > (signed int)mainDuty100 + MAX_DUTY_CHANGE100) {
newDuty100 = mainDuty100 + MAX_DUTY_CHANGE100;
} else if (newDuty100 < (signed int)mainDuty100 - MAX_DUTY_CHANGE100) {
newDuty100 = mainDuty100 - MAX_DUTY_CHANGE100;
}
// Don't set to a negative duty cycle
if (newDuty100 < 0) {
newDuty100 = MIN_DUTY100;
}
setDutyCycle100(MAIN_ROTOR, newDuty100);
// If we are at saturation (5% and we want to go lower, or 95%
// and we want to go higher), don't integrate any further
if ((mainDuty100 <= MIN_DUTY100 && error < 0) ||
(mainDuty100 >= MAX_DUTY100 && error > 0)) {
return;
}
// delta t = 0.5 seconds
errorIntegrated += error / 2;
}
/**
* Adjusts the PWM duty cycle of the tail rotor to control the yaw.
*/
void yawControl (void) {
if (!initialised) {
return;
}
static signed long errorIntegrated = 0;
unsigned int tailDuty100 = getDutyCycle100(TAIL_ROTOR);
int error = _desiredYaw100 - _yaw100;
// bias = 1500; Kp = 1/4; Ki = 1/4
int newDuty100 = 1500 + (error / 4) + (errorIntegrated / 4);
// Don't allow duty cycle to change too much at once
if (newDuty100 > (signed int)tailDuty100 + MAX_DUTY_CHANGE100) {
newDuty100 = tailDuty100 + MAX_DUTY_CHANGE100;
} else if (newDuty100 < (signed int)tailDuty100 - MAX_DUTY_CHANGE100) {
newDuty100 = tailDuty100 - MAX_DUTY_CHANGE100;
}
// Don't set to a negative duty cycle
if (newDuty100 < 0) {
newDuty100 = MIN_DUTY100;
}
setDutyCycle100(TAIL_ROTOR, newDuty100);
// If we are at saturation (5% and we want to go lower, or 95%
// and we want to go higher), don't integrate any further
if ((tailDuty100 <= MIN_DUTY100 && error < 0) ||
(tailDuty100 >= MAX_DUTY100 && error > 0)) {
return;
}
// delta t = 0.5 seconds
errorIntegrated += error / 2;
}
|
C
|
#include <linux/input.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include "libfahw.h"
#define IR_PATH "/dev/input/event2"
#define IR_EVENT_TIMES (20)
void IRHandler(int signNum)
{
if (signNum == SIGINT) {
printf("Quit waiting IR event\n");
}
exit(0);
}
int main(int argc, char ** argv)
{
int devFD;
char *devName = IR_PATH;
if (argc != 2) {
printf("Using default IR device:%s\n", devName);
} else {
devName = argv[1];
printf("Using IR device:%s\n", devName);
}
struct input_event evKey;
devFD = openHW(devName, O_RDWR);
if (devFD < 0) {
printf("Fail to open IR device.\n");
return -1;
}
int i = 0;
int j = 0;
int retSize = -1;;
signal(SIGINT, IRHandler);
printf("Waiting IR event %d times\n", IR_EVENT_TIMES);
for (i = 0; i < IR_EVENT_TIMES; ) {
if (selectHW(devFD, 0, 0) == 1) {
retSize = readHW(devFD, &evKey, sizeof(struct input_event));
for (j = 0; j < (int) retSize / sizeof(struct input_event); j++) {
if (evKey.type == EV_KEY) {
i++;
switch ( evKey.code ) {
case KEY_POWER:
printf("KEY_POWER:%d\n", evKey.value);
break;
case KEY_UP:
printf("KEY_UP:%d\n", evKey.value);
break;
case KEY_DOWN:
printf("KEY_DOWN:%d\n", evKey.value);
break;
case KEY_LEFT:
printf("KEY_LEFT:%d\n", evKey.value);
break;
case KEY_RIGHT:
printf("KEY_RIGHT:%d\n", evKey.value);
break;
case KEY_BACK:
printf("KEY_BACK:%d\n", evKey.value);
break;
case KEY_ENTER:
printf("KEY_ENTER:%d\n", evKey.value);
break;
case KEY_HOMEPAGE:
printf("KEY_HOMEPAGE:%d\n", evKey.value);
break;
case KEY_MENU:
printf("KEY_MENU:%d\n", evKey.value);
break;
case KEY_1:
printf("KEY_1:%d\n", evKey.value);
break;
case KEY_2:
printf("KEY_2:%d\n", evKey.value);
break;
case KEY_3:
printf("KEY_3:%d\n", evKey.value);
break;
case KEY_4:
printf("KEY_4:%d\n", evKey.value);
break;
case KEY_5:
printf("KEY_5:%d\n", evKey.value);
break;
case KEY_6:
printf("KEY_6:%d\n", evKey.value);
break;
case KEY_7:
printf("KEY_7:%d\n", evKey.value);
break;
case KEY_8:
printf("KEY_8:%d\n", evKey.value);
break;
case KEY_9:
printf("KEY_9:%d\n", evKey.value);
break;
case KEY_0:
printf("KEY_0:%d\n", evKey.value);
break;
case KEY_VOLUMEDOWN:
printf("KEY_VOLUMEDOWN:%d\n", evKey.value);
break;
case KEY_VOLUMEUP:
printf("KEY_VOLUMEUP:%d\n", evKey.value);
break;
default:
printf("Unsuppoted IR key\n");
break;
}
}
}
}
}
closeHW(devFD);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
double X, Y, res;
int N, i;
scanf("%d",&N);
for(i=1; i<=N; i=i+1)
{
scanf("%lf %lf",&X,&Y);
if(Y!=0)
{
res=X/Y;
printf("%0.1lf\n",res);
}
else
{
printf("disisao impossivel\n");
}
}
system("PAUSE");
return 0;
}
|
C
|
#include<conio.h>
void main()
{
int bt[20],p[20],ct[20],at[20]={0},tat[20],wt[20],temp,n,i,j;
float avgwt=0,avgtat=0;
clrscr();
printf("Enter no of processes: ");
scanf("%d",&n);
printf("Enter burst time of procceses: ");
bt[0]=0;
p[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&bt[i]);
p[i]=i;
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(bt[i]>bt[j])
{
temp=bt[i];
bt[i]=bt[j];
bt[j]=temp;
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
wt[0]=0;
wt[1]=0;
for(i=1;i<=n;i++)
{
wt[i+1]=wt[i]+bt[i];
avgwt=avgwt+wt[i];
}
for(i=1;i<=n;i++)
{
tat[i]=wt[i]+bt[i];
avgtat=avgtat+tat[i];
}
printf("\nProcess\t BurstTime \t WaitingTime\t TAT");
for(i=1;i<=n;i++)
{
printf("\np%d\t\t%d\t\t%d\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avgtat=avgtat/n;
avgwt=avgwt/n;
printf("Avg TAT: %f \n Avg WT: %f",avgtat,avgwt);
getch();
}
|
C
|
/*
CELLULAR AUTOMATON IN C - automata.c
AC21009 COURSEWORK 2, TEAM 21
AUTHORS: Daniel Kevin Blackley (160007728)
Esther Bolik (170010779)
Michael Wamarema (150024823)
LAST MODIFIED: 2018-11-08
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "automata.h"
#include "automata-menu.h"
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/* global variables for the current automaton */
// The current rule (0..255). Only used for 1D automata.
unsigned char rule = 30;
// The output of the automaton, as a 2-dimensional array.
// Note that for 1D automata, each row of this array is an individual
// generation, advancing downwards. On the other hand, for the Game of Life, the
// array represents the entire current generation (and only the current
// generation).
char **output = NULL;
// The dimensions of the output array.
// rows represents rows of cells in the Game of Life, but represents generations
// in 1D automata. columns always represents columns of cells.
size_t rows = 5;
size_t columns = 9;
// Whether or not to wrap the automaton on the x axis (if false, OOB parents will be treated as 0)
bool xWrap = false;
// Whether or not to wrap on the y axis (ONLY USED FOR GAME OF LIFE)
bool yWrap = false;
// Characters to use when displaying the automaton's output
char cTrue = 'X';
char cFalse = ' ';
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// NOTE: All function descriptions are located in the relevant header files,
// rather than in the source files.
int main(int argc, char const *argv[]) {
menu();
return 0;
}
|
C
|
/**
* Name : log.c
* Author : Jrgen Ryther Hoem
* Lab : Lab 4 (ET014G)
* Description : Log functions, uses FAT service and SD/MMC driver
*/
#include <asf.h>
#include <string.h>
#include "log.h"
/***** VARIABLES ****************************************************/
// Sets the active memory slot
volatile uint8_t active_drive = 0;
// Active logfile that is used
volatile char logfile[MAX_FILE_PATH_LENGTH];
// Tells whether the logfile is open or not
volatile bool logfile_open = false;
/***** PRIVATE PROTOTYPES *******************************************/
// Reset navigator priv prototype
void reset_navigator(void);
/***** FUNCTIONS ****************************************************/
/*
* Log initialization
*
* This function checks if any drives exists
* and tries to mount it. Returns true if successful
* or false otherwise.
*/
bool log_init(uint8_t slot)
{
// Set drive/disk slot
active_drive = slot;
// Check if drive(s) exists
if (!nav_drive_nb() || slot > nav_drive_nb()-1) {
printf("\r\nMemory slots not found (%d)\r\n", active_drive);
return false;
}
// Try to mount drive if possible
printf("\r\nTrying to mount drive %d\r\n", active_drive);
if (mount_drive()) {
printf("Try to format the drive using 'format'\r\n");
return false;
}
// Return true if ok
return true;
}
/*
* Log set file
*
* Selects (creates if necessary) logfile
*/
void log_set_file(char *filename)
{
uint8_t i;
uint8_t len = strlen(filename);
// Make sure length of filename does not exceed limit
if (len > MAX_FILE_PATH_LENGTH-1) len = MAX_FILE_PATH_LENGTH-1;
// Copy filename to memory
for (i=0; i < len; i++)
{
logfile[i] = filename[i];
}
logfile[i] = '\0';
// Create new logfile
reset_navigator();
nav_file_create((FS_STRING)logfile);
}
/*
* Log Start
*
* Tries to open logfile in append mode for writing
*/
bool log_start(void)
{
logfile_open = false;
// Reset navigator just in case
reset_navigator();
// Try to navigate to logfile
if (!nav_setcwd((FS_STRING)logfile, true, true))
{
printf("Error: Could not open logfile (err: %d)\r\n", fs_g_status);
}
else
{
// Open logfile
file_open(FOPEN_MODE_APPEND);
logfile_open = true;
}
return logfile_open;
}
/*
* Log write ADC
*
* This function writes the system cycle count and
* ADC value (uint16 argument) to the logfile as comma separated
* values if the file is open.
*/
void log_write_adc(uint32_t cy_count, uint16_t value)
{
if (logfile_open)
{
// Convert data to string
char buffer[24];
sprintf(buffer, "%lu, %u", cy_count, value);
// Write data to file
file_write_buf((uint8_t*)buffer, strlen(buffer));
file_putc('\r');
file_putc('\n');
}
else printf("Error: Logfile not open\r\n");
}
/*
* Log Stop
*
* Closes the logfile
*/
void log_stop(void)
{
// Close logfile
file_close();
logfile_open = false;
}
/*
* Format drive
*
* Format current drive to FAT16
* Returns true if successful
*/
bool format_drive(void)
{
// Reset navigator
reset_navigator();
// Format drive to FAT16
if (!nav_drive_format(FS_FORMAT_FAT))
{
return false;
}
return true;
}
/*
* Mount drive
*
* Drive/disk mount with user friendly error messages.
* Returns a FAT error or 0 if mounting is successful.
*/
uint8_t mount_drive(void)
{
// Reset navigator
reset_navigator();
// Try to mount, print error message if not
if (!nav_partition_mount())
{
printf("Error: ");
switch (fs_g_status)
{
case FS_ERR_HW_NO_PRESENT:
printf("Disk not present\r\n");
break;
case FS_ERR_HW:
printf("Disk access error\r\n");
break;
case FS_ERR_NO_FORMAT:
printf("Disk not formated\r\n");
break;
case FS_ERR_NO_PART:
printf("No partition available on disk\r\n");
break;
case FS_ERR_NO_SUPPORT_PART:
printf("Partition not supported\r\n");
break;
default :
printf("Unknown system error\r\n");
break;
}
return fs_g_status;
}
else printf("Partition mounted\r\n");
return 0;
}
/*
* Reset FAT navigator
*
* This function resets the FAT navigator and
* set the drive/disk active
*/
void reset_navigator(void)
{
// Reset navigator
nav_reset();
// Set drive
nav_drive_set(active_drive);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <assert.h>
#include "QBDI.h"
int fibonacci(int n) {
if(n <= 2)
return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
VMAction showInstruction(VMInstanceRef vm, GPRState *gprState, FPRState *fprState, void *data) {
// Obtain an analysis of the instruction from the VM
const InstAnalysis* instAnalysis = qbdi_getInstAnalysis(vm, QBDI_ANALYSIS_INSTRUCTION | QBDI_ANALYSIS_DISASSEMBLY);
// Printing disassembly
printf("0x%" PRIRWORD ": %s\n", instAnalysis->address, instAnalysis->disassembly);
return QBDI_CONTINUE;
}
VMAction countIteration(VMInstanceRef vm, GPRState *gprState, FPRState *fprState, void *data) {
(*((int*) data))++;
return QBDI_CONTINUE;
}
static const size_t STACK_SIZE = 0x100000; // 1MB
int main(int argc, char **argv) {
int n = 0;
int iterationCount = 0;
uint8_t *fakestack;
VMInstanceRef vm;
GPRState *state;
rword retvalue;
if(argc >= 2) {
n = atoi(argv[1]);
}
if(n < 1) {
n = 1;
}
// Constructing a new QBDI VM
qbdi_initVM(&vm, NULL, NULL, 0);
// Get a pointer to the GPR state of the VM
state = qbdi_getGPRState(vm);
assert(state != NULL);
// Setup initial GPR state,
qbdi_allocateVirtualStack(state, STACK_SIZE, &fakestack);
// Registering showInstruction() callback to print a trace of the execution
uint32_t cid = qbdi_addCodeCB(vm, QBDI_PREINST, showInstruction, NULL);
assert(cid != QBDI_INVALID_EVENTID);
// Registering countIteration() callback
qbdi_addMnemonicCB(vm, "CALL*", QBDI_PREINST, countIteration, &iterationCount);
// Setup Instrumentation Range
bool res = qbdi_addInstrumentedModuleFromAddr(vm, (rword) &fibonacci);
assert(res == true);
// Running DBI execution
printf("Running fibonacci(%d) ...\n", n);
res = qbdi_call(vm, &retvalue, (rword) fibonacci, 1, n);
assert(res == true);
printf("fibonnaci(%d) returns %ld after %d recursions\n",
n, retvalue, iterationCount);
// cleanup
qbdi_alignedFree(fakestack);
qbdi_terminateVM(vm);
return 0;
}
|
C
|
#include "myarraylib.h"
#include <stdio.h>
#include <stdlib.h>
#include "time.h"
float *creatVector(int n) {
float *v = (float *) malloc(n * sizeof (float));
return v;
}
void fillArray(float *v, int n) {
int i;
srand(time(0));
for (i = 0; i < n; i++) {
v[i] = (rand() % 10) + 1;
}
}
void printArray(float *v, int n) {
int i;
for (i = 0; i < n; i++)
printf("sayi: %.2f\n", v[i]);
puts("");
}
float topla(float *v, int n) {
int i;
float toplam = 0;
for (i = 0; i < n; i++) {
toplam += v[i];
printf("toplam: %f\n", toplam);
}
return toplam;
}
|
C
|
Purpose: This program displays a menu
to the user containing information
about a politician. If the menu item is
unknown, the user is allowed to enter
that information.
Assumptions: It is assumed that the user
knows what they can and cannot input from
the given directions provides. The program
accepts characted and integer inputs.
Bugs: When the user enters something invalid,
sometimes the program gets stuck in the while
loop and the user is not allowed to input
anything else.
Please compile with the -lm link.*/
// Header File
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void menu();
int check();
// This function prints the menu to the user
void menu() {
printf("(1) Enter Name\t\t\t\t\t(6) Display the Data\n");
printf("(2) Enter Years, Party, Office, and State\t");
printf("(7) Clear all Data\n");
printf("(3) Enter Age and Sex\t\t\t\t(8) Quit\n");
printf("(4) Enter Contacts\n(5) Enter Contributions and Lies\n");
printf("Select a menu option: ");
}
// This function allows the user to select a menu option
// and checks to make sure the input is a valid selection.
int check() {
int choice, invalid;
// User Selection
invalid = 0;
scanf("%d", &choice);
while (invalid == 0) {
if (choice < 1 || choice > 8) {
printf("Not a valid selection. Please try again: ");
scanf("%d", &choice);
invalid = 0;
}
else {
invalid = 1;
}
}
return choice;
}
int main() {
// Variables
int choice, i, invalid = 0, partyNum = 0;
// Menu
menu();
choice = check();
// Input
char firstName[33] = "?????";
char middleName = '?';
char lastName[34] = "?????";
char suffix[3] = "???";
char years[2] = "??";
char office[33] = "?????";
char state[2] = "??";
char age[2] = "??";
int ageD[1];
char sex = '?';
char twitter[15] = "?????";
char phone[10] = "??????????";
float contributions = 0;
float lies = 0;
int loop = 0;
float ratio = 0;
while (loop == 0) {
switch (choice) {
case 1: {
// First Name
invalid = 0;
printf("Please enter a first name: ");
// Loops until a valid first name is input
while (invalid == 0) {
scanf("%32s",firstName);
for (i=0; i<32; i++) {
if (firstName[i] == '\0') {
invalid = 1;
break;
}
if (firstName[31] != '\0') {
printf("Your input has too many characters. ");
printf("Please try again: ");
invalid = 0;
break;
}
}
}
// Middle Initial
printf("Please enter a middle initial. If there is no middle");
printf(" initial, enter '?': ");
scanf(" %c", &middleName);
// Last Name
invalid = 0;
printf("Please enter a last name: ");
while (invalid == 0) {
scanf("%s",lastName);
for (i=0; i<32; i++) {
if (lastName[i] == '\0') {
invalid = 1;
break;
}
if (lastName[31] != '\0') {
printf("Your input has too many characters. ");
printf("Please try again: ");
invalid = 0;
break;
}
}
}
// Suffix
invalid = 0;
printf("Please enter a suffix. If you wish to not enter a suffix,");
printf(" then enter ""???"": ");
while (invalid == 0) {
scanf("%s", suffix);
if (suffix[3] != '\0') {
printf("Your input has too many characters. ");
printf("Please try again: ");
invalid = 0;
}
else {
invalid = 1;
}
}
printf("\n");
// Display menu
menu();
choice = check();
loop = 0;
break;
}
case 2: { // Years, Party, Office, and State
// Years
invalid = 0;
printf("Enter the number of years served (0 to 99): ");
while (invalid == 0) {
scanf("%s", years);
for(i = 0; i<=2; i++) {
if (years[i] == '\0') {
invalid = 1;
break;
}
}
// checks if it is a two digit input
if (years[2] == '\0'){
// digit[0] = years[0] - '0';
// digit[1] = years[1] - '0';
invalid = 1;
}
else {
printf("You did not enter a two digit number. Please try again: ");
invalid = 0;
}
}
// Political Party
printf("\n1 - Constitution\t\t2 - Democrat\n3 - Green\t\t\t4 - Libertarian\n");
printf("5 - Republican");
printf("\nPlease select a party affiliation: ");
invalid = 0;
while (invalid == 0){
scanf("%d%*c", &partyNum);
if (partyNum < 1 || partyNum > 5) {
printf("Invalid selection. Please try again: ");
invalid = 0;
}
else {
invalid = 1;
}
}
// Office Held
printf("Please enter the political office held: ");
invalid = 0;
while (invalid == 0){
fgets(office, 34, stdin);
if (office[33] == '\0') {
printf("You entered too many characters. Please try again: ");
invalid = 0;
}
else {
invalid = 1;
}
}
// State
printf("AL\tAK\tAZ\tAR\tCA\nCO\tCT\tDE\tFL\tGA\nHI\tID\tIL\tIN\tIA");
printf("\nKS\tKY\tLA\tME\tMD\nMA\tMI\tMN\tMS\tMO\nMT\tNE\tNV\tNH\tNJ");
printf("\nNM\tNY\tNC\tND\tOH\nOK\tOR\tPA\tRI\tSC\nSD\tTN\tTX\tUT\tVT");
printf("\nVA\tWA\tWV\tWI\tWY");
printf("\nPlease select a home state: ");
invalid = 0;
// loops until 2 characters are entered
while (invalid == 0) {
fgets(state, 3, stdin);
if (state[2] == '\0') {
invalid = 1;
}
else {
printf("Invalid selection. Please try again: ");
}
}
// show menu
menu();
choice = check();
loop = 0;
break;
}
case 3: { //Age and Sex
//Age
invalid = 0;
printf("Enter age: ");
while (invalid == 0) {
scanf("%s", age);
for(i = 0; i<=2; i++) {
if (age[i] == '\0') {
invalid = 1;
break;
}
}
// checks if it is a two digit input
if (age[2] == '\0'){
ageD[0] = age[0] - '0';
ageD[1] = age[1] - '0';
}
else{
printf("You did not enter a two digit number between");
printf(" 21 and 99. Please try again: ");
invalid = 0;
}
if ((ageD[0] == 2 && ageD[1] == 0)|| ageD[0] < 2) {
printf("You did not enter a two digit number between");
printf(" 21 and 99. Please try again: ");
invalid = 0;
}
}
//Sex
invalid = 0;
printf("Enter sex with either M or F: ");
// loops until F or M is entered
while (invalid == 0) {
scanf(" %c%*c", &sex);
if (sex == 'F' || sex == 'M') {
invalid = 1;
}
else {
printf("Not a valid input. Please try again: ");
invalid = 0;
}
}
// Display Menu
menu();
choice = check();
loop = 0;
break;
}
case 4: {
// Phone Number
printf("Please enter a phone number in the form XXXXXXXXXX: ");
scanf("%s",phone);
// Twitter Account
printf("Please enter a twitter account: ");
invalid = 0;
while (invalid == 0) {
scanf("%s", twitter);
for (i=0; i<=15; i++) {
if (twitter[i] == '\0') {
invalid = 1;
break;
}
if (twitter[15] != '\0') {
printf("Your input has too many characters. ");
printf("Please try again: ");
invalid = 0;
break;
}
}
}
// Display Menu
menu();
choice = check();
loop = 0;
break;
}
case 5: { // Contributions and Lies
// Contributions
printf("Please enter the amount of contributions received (MAX: 10^50): ");
invalid = 0;
float max1 = pow(10,50);
while (invalid == 0) {
scanf("%f", &contributions);
if (contributions >= 0 && contributions <= max1){
invalid = 1;
}
else {
printf("Invalid input. Please try again: ");
invalid = 0;
}
}
// Number of Lies Told
printf("Please enter the number of lies told (MAX: 10^100): ");
invalid = 0;
float max2 = pow(10,100);
while (invalid == 0) {
scanf("%f", &lies);
if (lies >= 0 && lies <= max2) {
invalid = 1;
}
else {
printf("Invalid input. Please try again: ");
invalid = 0;
}
}
// Ratio
ratio = contributions/lies;
// Display Menu
menu();
choice = check();
loop = 0;
break;
}
case 6: { // Display the Data
// Name
printf("\nName: %s %s %c %s", suffix, firstName,middleName,lastName);
// Years Served
printf("\nYears Served: %c%c\n", years[0], years[1]);
// Party Affiliation
switch(partyNum) {
case 0: {
printf("Party Affiliation: Unknown\n");
break;
}
case 1: {
printf("Party Affiliation: Constitution\n");
break;
}
case 2: {
printf("Party Affiliation: Democrat\n");
break;
}
case 3: {
printf("Party Affiliation: Green\n");
break;
}
case 4: {
printf("Party Affiliation: Libertarian\n");
break;
}
case 5: {
printf("Party Affiliation: Republican\n");
break;
}
}
// Office Held
printf("Office Held: %s", office);
// Home State
printf("\nHome State: %c%c", state[0],state[1]);
// Age
printf("\nAge: %c%c\n",age[0], age[1]);
// Sex
if (sex == 'M'){
printf("Sex: Male\n");
}
else if (sex == 'F'){
printf("Sex: Female\n");
}
else {
printf("Sex: ?\n");
}
// Phone Number
printf("Phone Number: (%c%c%c)",phone[0], phone[1], phone[2]);
printf(" %c%c%c", phone[3], phone[4], phone[5]);
printf("-%c%c%c%c\n", phone[6], phone[7], phone[8], phone[9]);
// Twitter
printf("Twitter: @%s\n", twitter);
// Contributions
printf("US Dollars Received: $%.2f\n", contributions);
// Lies Told
printf("Number of Lies Told: %.2f\n", lies);
// Ratio of contributions to lies told
printf("Ratio of contributions to lies told: %.2f:1\n", ratio);
// Menu
menu();
choice = check();
loop = 0;
break;
}
case 7: { // Clear Data
memset(firstName,0,34);
middleName = '?';
memset(lastName,0,35);
memset(suffix, 0, 4);
memset(office,0, 34);
memset(years, 0, 3);
memset(state, 0 , 3);
memset(age, 0 , 3);
sex = '?';
memset(twitter, 0 , 16);
memset(phone, 0, 11);
contributions = 0;
lies = 0;
ratio = 0;
partyNum = 0;
// Display Menu
menu();
choice = check();
loop = 0;
break;
}
case 8: { // Exit program
exit(1);
}
}
}
return 0;
}
|
C
|
/*
печать таблицы температур по Фаренгейту
и Цельсию для fahr = 0, 20, ..., 300
Ref:
C Kerigan Richi 2001.pdf
1.2. Переменные и арифметические выражения
*/
#include <stdio.h>
main()
{
int fahr, celsius;
int lower, upper, step;
lower = 0; /* нижняя граница таблицы температур */
upper = 300; /* верхняя граница */
step = 20; /* шаг */
fahr = lower;
printf("This is INTEGER conversation of F to C\n\n");
while (fahr <= upper)
{
celsius = 5 * (fahr-32) / 9;
printf ("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
printf("\n\nThis is FLOAT conversation of F to C\n");
float celsiusF;
float fahrF = lower;
while (fahrF <= upper)
{
celsiusF = (5.0/9.0) * (fahrF-32.0);
printf ("%3.0f\t%6.1f\n", fahrF, celsiusF);
fahrF = fahrF + step;
}
printf("\n\nThis is FLOAT conversation of C to F\n");
celsiusF = lower;
fahrF;
while (celsiusF <= upper)
{
fahrF = (celsiusF / (5.0/9.0)) + 32.0;
printf ("%f\t%f\n", celsiusF, fahrF);
celsiusF = celsiusF + step;
}
}
|
C
|
/*MIT License
Copyright (c) 2021 Michał Bazan
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "i2c.h"
void I2C_start(void){
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while (!(TWCR & (1<<TWINT))) { continue; }
}
void I2C_send_byte(uint8_t byte){
TWDR = byte;
TWCR = (1<<TWINT) | (1<<TWEN);
while (!(TWCR & (1<<TWINT))) { continue; }
}
uint8_t I2C_read_byte(uint8_t ack_bit){
TWCR = (1 << TWINT) | (1 << TWEN) | (ack_bit << TWEA);
while(!(TWCR & (1 << TWINT))) { continue; }
return TWDR;
}
void I2C_stop(void){
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWSTO);
}
void I2C_send_buffer(uint8_t slave_adr, const uint8_t* buffer, uint8_t buffer_len){
I2C_start();
I2C_send_byte(slave_adr);
for(const uint8_t* buff_iter = buffer; buff_iter < buffer + buffer_len; ++buff_iter){
I2C_send_byte(*buff_iter);
}
I2C_stop();
}
void I2C_read_buffer(uint8_t slave_adr, uint8_t read_adr, uint8_t* buffer, uint8_t buffer_len){
I2C_start();
I2C_send_byte(slave_adr);
I2C_send_byte(read_adr);
I2C_start();
I2C_send_byte(slave_adr + 1);
while(buffer_len--){
*buffer++ = I2C_read_byte(buffer_len != 0? 1 : 0);
}
I2C_stop();
}
|
C
|
//SPDX-License-Identifier: LGPL-2.0-or-later
/*
Copyright (c) 2014-2020 Cyril Hrubis <[email protected]>
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/inotify.h>
#include <core/gp_debug.h>
#include <utils/gp_block_alloc.h>
#include <gp_dir_cache.h>
static gp_dir_entry *new_entry(gp_dir_cache *self, size_t size,
const char *name, mode_t mode, time_t mtime)
{
size_t name_len = strlen(name);
size_t entry_size;
int is_dir = 0;
gp_dir_entry *entry;
if ((mode & S_IFMT) == S_IFDIR)
is_dir = 1;
entry_size = sizeof(gp_dir_entry) + name_len + is_dir + 1;
entry = gp_block_alloc(&self->allocator, entry_size);
if (!entry)
return NULL;
entry->size = size;
entry->is_dir = is_dir;
sprintf(entry->name, "%s%s", name, is_dir ? "/" : "");
entry->mtime = mtime;
GP_DEBUG(3, "Dir Cache %p new entry '%s'", self, entry->name);
return entry;
}
static void put_entry(gp_dir_cache *self, gp_dir_entry *entry)
{
if (self->used >= self->size) {
size_t new_size = self->size + 50;
void *entries;
entries = realloc(self->entries, new_size * sizeof(void*));
if (!entries) {
GP_DEBUG(1, "Realloc failed :-(");
return;
}
self->size = new_size;
self->entries = entries;
}
self->entries[self->used++] = entry;
}
static void add_entry(gp_dir_cache *self, const char *name)
{
gp_dir_entry *entry;
struct stat buf;
if (fstatat(self->dirfd, name, &buf, 0)) {
GP_DEBUG(3, "stat(%s): %s", name, strerror(errno));
return;
}
entry = new_entry(self, buf.st_size, name,
buf.st_mode, buf.st_mtim.tv_sec);
if (!entry)
return;
put_entry(self, entry);
}
static int rem_entry_by_name(gp_dir_cache *self, const char *name)
{
unsigned int i;
for (i = 0; i < self->used; i++) {
if (!strcmp(self->entries[i]->name, name)) {
self->entries[i] = self->entries[--self->used];
return 0;
}
}
return 1;
}
static void populate(gp_dir_cache *self)
{
for (;;) {
struct dirent *ent;
ent = readdir(self->dir);
if (!ent)
return;
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
add_entry(self, ent->d_name);
}
}
static int cmp_asc_name(const void *a, const void *b)
{
const gp_dir_entry *const *ea = a;
const gp_dir_entry *const *eb = b;
return strcmp((*ea)->name, (*eb)->name);
}
static int cmp_desc_name(const void *a, const void *b)
{
const gp_dir_entry *const *ea = a;
const gp_dir_entry *const *eb = b;
return strcmp((*eb)->name, (*ea)->name);
}
static int cmp_asc_size(const void *a, const void *b)
{
const gp_dir_entry *const *ea = a;
const gp_dir_entry *const *eb = b;
if ((*ea)->size == (*eb)->size)
return 0;
return (*ea)->size > (*eb)->size;
}
static int cmp_desc_size(const void *a, const void *b)
{
const gp_dir_entry *const *ea = a;
const gp_dir_entry *const *eb = b;
if ((*ea)->size == (*eb)->size)
return 0;
return (*ea)->size < (*eb)->size;
}
static int cmp_asc_time(const void *a, const void *b)
{
const gp_dir_entry *const *ea = a;
const gp_dir_entry *const *eb = b;
if ((*ea)->mtime == (*eb)->mtime)
return 0;
return (*ea)->mtime > (*eb)->mtime;
}
static int cmp_desc_time(const void *a, const void *b)
{
const gp_dir_entry *const *ea = a;
const gp_dir_entry *const *eb = b;
if ((*ea)->mtime == (*eb)->mtime)
return 0;
return (*ea)->mtime < (*eb)->mtime;
}
static int (*cmp_funcs[])(const void *, const void *) = {
[GP_DIR_SORT_ASC | GP_DIR_SORT_BY_NAME] = cmp_asc_name,
[GP_DIR_SORT_DESC | GP_DIR_SORT_BY_NAME] = cmp_desc_name,
[GP_DIR_SORT_ASC | GP_DIR_SORT_BY_SIZE] = cmp_asc_size,
[GP_DIR_SORT_DESC | GP_DIR_SORT_BY_SIZE] = cmp_desc_size,
[GP_DIR_SORT_ASC | GP_DIR_SORT_BY_MTIME] = cmp_asc_time,
[GP_DIR_SORT_DESC | GP_DIR_SORT_BY_MTIME] = cmp_desc_time,
};
void gp_dir_cache_sort(gp_dir_cache *self, int sort_type)
{
int (*cmp_func)(const void *, const void *) = cmp_funcs[sort_type];
if (!cmp_func)
return;
self->sort_type = sort_type;
qsort(self->entries+1, self->used-1, sizeof(void*), cmp_func);
}
static void open_inotify(gp_dir_cache *self, const char *path)
{
self->inotify_fd = inotify_init1(IN_NONBLOCK);
if (self->inotify_fd < 0) {
GP_DEBUG(1, "inotify_init(): %s", strerror(errno));
return;
}
int watch = inotify_add_watch(self->inotify_fd, path, IN_CREATE | IN_DELETE);
if (watch < 0) {
GP_DEBUG(1, "inotify_add_watch(): %s", strerror(errno));
close(self->inotify_fd);
self->inotify_fd = -1;
return;
}
}
static void close_inotify(gp_dir_cache *self)
{
if (self->inotify_fd > 0)
close(self->inotify_fd);
}
static void append_slash(struct inotify_event *ev)
{
size_t len = strlen(ev->name);
if (ev->name[len] == '/')
return;
if (len + 1 >= ev->len)
return;
ev->name[len] = '/';
ev->name[len+1] = 0;
}
int gp_dir_cache_inotify(gp_dir_cache *self)
{
long buf[1024];
struct inotify_event *ev = (void*)buf;
int sort = 0;
if (self->inotify_fd <= 0)
return 0;
while (read(self->inotify_fd, &buf, sizeof(buf)) > 0) {
switch (ev->mask) {
case IN_DELETE:
if (!rem_entry_by_name(self, ev->name)) {
GP_DEBUG(1, "Deleted '%s'", ev->name);
sort = 1;
break;
}
/*
* We have to try both since symlink to directory does not
* contain IN_ISDIR but appears to be directory for us.
*/
/* fallthrough */
case IN_DELETE | IN_ISDIR:
append_slash(ev);
GP_DEBUG(1, "Deleted '%s'", ev->name);
if (rem_entry_by_name(self, ev->name))
GP_WARN("Failed to remove '%s'", ev->name);
sort = 1;
break;
case IN_CREATE:
case IN_CREATE | IN_ISDIR:
GP_DEBUG(1, "Created '%s'", ev->name);
add_entry(self, ev->name);
sort = 1;
break;
}
}
if (sort)
gp_dir_cache_sort(self, self->sort_type);
return sort;
}
#define MIN_SIZE 25
gp_dir_cache *gp_dir_cache_new(const char *path)
{
DIR *dir;
int dirfd;
gp_dir_cache *ret;
gp_dir_entry **entries;
GP_DEBUG(1, "Creating dir cache for '%s'", path);
ret = malloc(sizeof(gp_dir_cache));
entries = malloc(MIN_SIZE * sizeof(void*));
if (!ret || !entries) {
GP_DEBUG(1, "Malloc failed :(");
return NULL;
}
ret->entries = entries;
open_inotify(ret, path);
dirfd = open(path, O_DIRECTORY);
if (!dirfd) {
GP_DEBUG(1, "open(%s, O_DIRECTORY): %s", path, strerror(errno));
goto err0;
}
dir = opendir(path);
if (!dir) {
GP_DEBUG(1, "opendir(%s) failed: %s", path, strerror(errno));
goto err1;
}
ret->dir = dir;
ret->dirfd = dirfd;
ret->size = MIN_SIZE;
ret->used = 0;
ret->allocator = NULL;
ret->sort_type = 0;
add_entry(ret, "..");
populate(ret);
gp_dir_cache_sort(ret, ret->sort_type);
return ret;
err1:
close(dirfd);
err0:
close_inotify(ret);
free(ret->entries);
free(ret);
return NULL;
}
void gp_dir_cache_free(gp_dir_cache *self)
{
GP_DEBUG(1, "Destroying dir cache %p", self);
close_inotify(self);
closedir(self->dir);
close(self->dirfd);
gp_block_free(&self->allocator);
free(self->entries);
free(self);
}
gp_dir_entry *gp_dir_cache_get_filtered(gp_dir_cache *self, unsigned int pos)
{
unsigned int n, cur_pos = 0;
for (n = 0; n < self->used; n++) {
if (self->entries[n]->filtered)
continue;
if (cur_pos++ == pos)
return self->entries[n];
}
return NULL;
}
|
C
|
/*
* mfile.c
*
* This file is part of zeroskip.
*
* zeroskip is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*
*/
#define _XOPEN_SOURCE 500 /* For ftruncate() see `man ftruncate` */
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <libzeroskip/crc32c.h>
#include <libzeroskip/mfile.h>
#include <libzeroskip/util.h>
static struct mfile mf_init = {NULL, -1, MAP_FAILED, 0, 0, 0, 0, 0, 0, 0, 0, 0};
#define OPEN_MODE 0644
/*
mfile_open():
* Return:
- On Success: returns 0
- On Failure: returns non 0
*/
int mfile_open(const char *fname, uint32_t flags, struct mfile **mfp)
{
struct mfile *mf;
int mflags, oflags;
struct stat st;
int ret = 0;
if (!fname) {
fprintf(stderr, "Need a valid filename\n");
return -1;
}
mf = xcalloc(1, sizeof(struct mfile));
mf->filename = xstrdup(fname);
mf->flags = flags;
mf->fd = -1;
if (mf->ptr != MAP_FAILED) {
if (mf->ptr)
munmap(mf->ptr, mf->size);
mf->ptr = MAP_FAILED;
}
/* Flags */
if (flags & MFILE_RW) {
mflags = PROT_READ | PROT_WRITE;
oflags = O_RDWR;
} else if (flags & MFILE_WR) {
mflags = PROT_READ | PROT_WRITE;
oflags = O_WRONLY;
} else if (flags & MFILE_RD) {
mflags = PROT_READ;
oflags = O_RDONLY;
} else { /* defaults to RDONLY */
mflags = PROT_READ;
oflags = O_RDONLY;
}
if (flags & MFILE_CREATE)
oflags |= O_CREAT;
if (flags & MFILE_EXCL)
oflags |= O_EXCL;
mf->fd = open(fname, oflags, OPEN_MODE);
if (mf->fd < 0) {
perror("mfile_open:open");
return errno;
}
if (fstat(mf->fd, &st) != 0) {
int err = errno;
close(mf->fd);
perror("mfile_open:fstat");
return err;
}
mf->size = st.st_size;
if (mf->size) {
mf->ptr = mmap(0, mf->size, mflags, MAP_SHARED, mf->fd, 0);
if (mf->ptr == MAP_FAILED) {
int err = errno;
close(mf->fd);
return err;
}
} else
mf->ptr = NULL;
mf->mflags = mflags;
*mfp = mf;
return ret;
}
/*
XXX: At a later point in time, mfile_open() will be split into 2
operations. The first one would be to open() the file and get a valid fd.
And then the mfile_map() to actually map it in memory.
*/
#if 0
/*
* mfile_map()
*
*/
int mfile_map(struct mfile **mfp)
{
if (mfp && *mfp) {
struct mfile *mf = *mfp;
if (mf == &mf_init)
return 0;
if (mf->size) {
mf->ptr = mmap(0, mf->size, mf->mflags,
MAP_SHARED, mf->fd, 0);
if (mf->ptr == MAP_FAILED) {
int err = errno;
close(mf->fd);
return err;
}
} else
mf->ptr = NULL;
}
return 0;
}
#endif
/*
* mfile_close()
*
*/
int mfile_close(struct mfile **mfp)
{
if (mfp && *mfp) {
struct mfile *mf = *mfp;
if (mf == &mf_init)
return 0;
xfree(mf->filename);
if (mf->ptr != MAP_FAILED && mf->ptr) {
munmap(mf->ptr, mf->size);
mf->ptr = MAP_FAILED;
}
if (mf->fd) {
close(mf->fd);
mf->fd = -1;
}
xfree(mf);
*mfp = &mf_init;
}
return 0;
}
/*
* mapfile_read():
*
* mfp - a pointer to a struct mfile object
* obuf - buffer to read into
* osize - bize of the buffer being read into
* nbytes - total number of bytes read
*
* Return:
* Success : 0
* Failre : non zero
*/
int mfile_read(struct mfile **mfp, void *obuf,
uint64_t obufsize, uint64_t *nbytes)
{
struct mfile *mf = *mfp;
uint64_t n = 0;
if (!mf)
return EINVAL;
if (mf == &mf_init || mf->ptr == MAP_FAILED)
return EINVAL;
if (mf->offset < mf->size) {
n = ((mf->offset + obufsize) > mf->size) ?
mf->size - mf->offset : obufsize;
memcpy(obuf, mf->ptr + mf->offset, n);
mf->offset += n;
}
if (nbytes)
*nbytes = n;
return 0;
}
/*
* mapfile_write():
*
* mfp - a pointer to a struct mfile object
* ibuf - buffer to write from
* ibufsize - size of the buffer written
* nbytes - total number of bytes written
*
* Return:
* Success : 0
* Failre : non zero
*/
int mfile_write(struct mfile **mfp, void *ibuf, uint64_t ibufsize,
uint64_t *nbytes)
{
struct mfile *mf = *mfp;
if (!mf)
return EINVAL;
if (mf == &mf_init || mf->ptr == MAP_FAILED)
return EINVAL;
if (!(mf->flags & MFILE_WR) ||
!(mf->flags & MFILE_WR_CR) ||
!(mf->flags & MFILE_RW) ||
!(mf->flags & MFILE_RW_CR))
return EACCES;
if (mf->size < (mf->offset + ibufsize)) {
/* If the input buffer's size is bigger, we overwrite. */
if (mf->ptr && munmap(mf->ptr, mf->size) != 0) {
int err = errno;
mf->ptr = MAP_FAILED;
close(mf->fd);
return err;
}
if (ftruncate(mf->fd, mf->offset + ibufsize) != 0)
return errno;
mf->ptr = mmap(0, mf->offset + ibufsize, mf->flags,
MAP_SHARED, mf->fd, 0);
if (mf->ptr == MAP_FAILED) {
int err = errno;
close(mf->fd);
return err;
}
mf->size = mf->offset + ibufsize;
}
if (ibufsize) {
memcpy(mf->ptr + mf->offset, ibuf, ibufsize);
mf->offset += ibufsize;
}
if (nbytes)
*nbytes = ibufsize;
/* compute CRC32 */
if (mf->compute_crc) {
mf->crc32_data_len += ibufsize;
}
return 0;
}
/*
* mfile_write_iov():
*
* Return:
* Success : 0
* Failre : non zero
*/
int mfile_write_iov(struct mfile **mfp, const struct iovec *iov,
unsigned int iov_cnt, uint64_t *nbytes)
{
struct mfile *mf = *mfp;
unsigned int i;
uint64_t total_bytes = 0;
if (!mf)
return EINVAL;
if (mf == &mf_init || mf->ptr == MAP_FAILED)
return EINVAL;
if (!(mf->flags & MFILE_WR) ||
!(mf->flags & MFILE_WR_CR) ||
!(mf->flags & MFILE_RW) ||
!(mf->flags & MFILE_RW_CR))
return EACCES;
for (i = 0; i < iov_cnt; i++) {
total_bytes += iov[i].iov_len;
}
if (mf->size < (mf->offset + total_bytes)) {
/* If the input buffer's size is bigger, we overwrite. */
if (mf->ptr && munmap(mf->ptr, mf->size) != 0) {
int err = errno;
mf->ptr = MAP_FAILED;
close(mf->fd);
return err;
}
if (ftruncate(mf->fd, mf->offset + total_bytes) != 0)
return 0;
mf->ptr = mmap(0, mf->offset + total_bytes, mf->flags,
MAP_SHARED, mf->fd, 0);
if (mf->ptr == MAP_FAILED) {
int err = errno;
close(mf->fd);
return err;
}
mf->size = mf->offset + total_bytes;
}
if (total_bytes) {
for (i = 0; i < iov_cnt; i++) {
memcpy(mf->ptr + mf->offset, iov[i].iov_base,
iov[i].iov_len);
mf->offset += iov[i].iov_len;
}
}
if (nbytes)
*nbytes = total_bytes;
return 0;
}
/*
mfile_size():
* Return:
- On Success: returns 0
- On Failure: returns non 0
*/
int mfile_size(struct mfile **mfp, uint64_t *psize)
{
struct mfile *mf = *mfp;
struct stat stbuf;
int err = 0;
memset(&stbuf, 0, sizeof(struct stat));
if (!mf)
return EINVAL;
if (mf == &mf_init || mf->ptr == MAP_FAILED)
return EINVAL;
if (mf->ptr && (mf->flags & PROT_WRITE))
msync(mf->ptr, mf->size, MS_SYNC);
if (fstat(mf->fd, &stbuf) != 0)
return errno;
if (mf->size != (uint64_t) stbuf.st_size) {
if (mf->ptr)
err = munmap(mf->ptr, mf->size);
if (err != 0)
err = errno;
else {
mf->size = stbuf.st_size;
if (mf->size) {
mf->ptr = mmap(0, mf->size, mf->flags,
MAP_SHARED, mf->fd, 0);
if (mf->ptr == MAP_FAILED)
err = errno;
} else
mf->ptr = NULL;
}
}
if (err != 0) {
mf->ptr = MAP_FAILED;
close(mf->fd);
mf->fd = -1;
} else {
if (psize)
*psize = stbuf.st_size;
}
return err;
}
/*
mfile_stat():
* Return:
- On Success: returns 0
- On Failure: returns non 0
*/
int mfile_stat(struct mfile **mfp, struct stat *stbuf)
{
struct mfile *mf = *mfp;
if (!mf)
return EINVAL;
if (mf == &mf_init || mf->ptr == MAP_FAILED)
return EINVAL;
if (mf->ptr && (mf->flags & PROT_WRITE))
msync(mf->ptr, mf->size, MS_SYNC);
if (fstat(mf->fd, stbuf) != 0)
return errno;
return 0;
}
/*
mfile_truncate()
* Return:
- On Success: returns 0
- On Failure: returns non 0
*/
int mfile_truncate(struct mfile **mfp, uint64_t len)
{
struct mfile *mf = *mfp;
int err = 0;
if (!mf)
return EINVAL;
if (mf == &mf_init || mf->ptr == MAP_FAILED || mf->ptr == NULL)
return EINVAL;
if (munmap(mf->ptr, mf->size) != 0) {
err = errno;
mf->ptr = MAP_FAILED;
close(mf->fd);
return err;
}
if (ftruncate(mf->fd, len) != 0)
return errno;
mf->ptr = len ? mmap(0, len, mf->flags, MAP_SHARED, mf->fd, 0) : NULL;
if (mf->ptr == MAP_FAILED) {
err = errno;
close(mf->fd);
return err;
}
mf->size = len;
return 0;
}
/*
mfile_flush()
* Return:
- On Success: returns 0
- On Failure: returns non 0
*/
int mfile_flush(struct mfile **mfp)
{
struct mfile *mf = *mfp;
if (!mf)
return EINVAL;
if (mf == &mf_init || mf->ptr == MAP_FAILED || mf->ptr == NULL)
return EINVAL;
if (mf->flags & PROT_WRITE)
return msync(mf->ptr, mf->size, MS_SYNC);
return 0;
}
/*
mfile_seek()
* Return:
- On Success: returns 0
- On Failure: returns non 0
*/
int mfile_seek(struct mfile **mfp, uint64_t offset, uint64_t *newoffset)
{
struct mfile *mf = *mfp;
if (!mf)
return EINVAL;
if (mf == &mf_init || mf->ptr == MAP_FAILED || mf->ptr == NULL)
return EINVAL;
if (offset > mf->size)
return ESPIPE;
mf->offset = offset;
if (newoffset)
*newoffset = offset;
return 0;
}
void crc32_begin(struct mfile **mfp)
{
(*mfp)->crc32 = crc32c(0, 0, 0);
(*mfp)->compute_crc = 1;
(*mfp)->crc32_begin_offset = (*mfp)->offset;
(*mfp)->crc32_data_len = 0;
}
uint32_t crc32_end(struct mfile **mfp)
{
if ((*mfp)->compute_crc) {
(*mfp)->crc32_data_len = (*mfp)->offset - (*mfp)->crc32_begin_offset;
(*mfp)->crc32 = crc32c_hw((*mfp)->crc32,
((*mfp)->ptr + (*mfp)->crc32_begin_offset),
(*mfp)->crc32_data_len);
(*mfp)->compute_crc = 0;
(*mfp)->crc32_data_len = 0;
}
return (*mfp)->crc32;
}
|
C
|
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include "unittest.h"
#include "bs_tree_map.h"
int tree_str_traverse_count = 0;
void bs_tree_map_str_free_cb(void *key, void *value)
{
if (key) {
// nothing to free here
}
if (value) {
// nothing to free here
}
}
void bs_tree_map_str_traverse_cb(void *key, void *value)
{
tree_str_traverse_count++;
printf("key:%s - val:%s\n", (char*)key, (char*)value);
if (key) {
// nothing to do here
}
if (value) {
// nothing to do here
}
}
int bs_tree_map_str_cmp(void *a, void *b)
{
return strcmp((char*)a, (char*)b);
}
char *test_new()
{
bs_tree_map *tree = bs_tree_map_new(NULL);
assert(tree != NULL, "Failed to create tree");
return NULL;
}
char *test_free()
{
bs_tree_map *tree = bs_tree_map_new(NULL);
bs_tree_map_free(tree, bs_tree_map_str_free_cb);
return NULL;
}
char *test_insert_strs()
{
char *s1_k = "key1";
char *s2_k = "key2";
char *s3_k = "key3";
char *s4_k = "key4";
char *s1_v = "val1";
char *s2_v = "val2";
char *s3_v = "val3";
char *s4_v = "val4";
bs_tree_map *tree = bs_tree_map_new(bs_tree_map_str_cmp);
bs_tree_map_insert(tree, s1_k, s1_v);
bs_tree_map_insert(tree, s2_k, s2_v);
assert(tree->len == 2, "Len of tree should be 2");
bs_tree_map_insert(tree, s3_k, s3_v);
bs_tree_map_insert(tree, s4_k, s4_v);
assert(tree->len == 4, "Len of tree should be 4");
bs_tree_map_free(tree, bs_tree_map_str_free_cb);
return NULL;
}
char *test_insert_and_delete_strs()
{
char *s1_k = "key1";
char *s2_k = "key2";
char *s3_k = "key3";
char *s4_k = "key4";
char *s5_k = "key5";
char *s1_v = "val1";
char *s2_v = "val2";
char *s3_v = "val3";
char *s5_v = "val5";
bs_tree_map *tree = bs_tree_map_new(bs_tree_map_str_cmp);
bs_tree_map_insert(tree, s1_k, s1_v);
bs_tree_map_insert(tree, s2_k, s2_v);
bs_tree_map_insert(tree, s3_k, s3_v);
assert(tree->len == 3, "Len of tree should be 3");
bs_tree_map_delete(tree, s2_k, bs_tree_map_str_free_cb);
assert(tree->len == 2, "Len of tree should be 2");
bs_tree_map_delete(tree, s1_k, bs_tree_map_str_free_cb);
assert(tree->len == 1, "Len of tree should be 1");
bs_tree_map_delete(tree, s4_k, bs_tree_map_str_free_cb);
assert(tree->len == 1, "Len of tree should be 1");
bs_tree_map_insert(tree, s5_k, s5_v);
assert(tree->len == 2, "Len of tree should be 2");
bs_tree_map_delete(tree, s5_k, bs_tree_map_str_free_cb);
assert(tree->len == 1, "Len of tree should be 1");
bs_tree_map_free(tree, bs_tree_map_str_free_cb);
return NULL;
}
char *test_traverse()
{
char *s1_k = "key1";
char *s2_k = "key2";
char *s3_k = "key3";
char *s4_k = "key4";
char *s1_v = "val1";
char *s2_v = "val2";
char *s3_v = "val3";
char *s4_v = "val4";
bs_tree_map *tree = bs_tree_map_new(bs_tree_map_str_cmp);
bs_tree_map_insert(tree, s1_k, s1_v);
bs_tree_map_insert(tree, s2_k, s2_v);
bs_tree_map_insert(tree, s3_k, s3_v);
bs_tree_map_insert(tree, s4_k, s4_v);
assert(tree_str_traverse_count == 0, "Traverse count should be 0");
bs_tree_map_traverse(tree, bs_tree_map_str_traverse_cb);
assert(tree_str_traverse_count == 4, "Traverse count should be 4");
return NULL;
}
int main()
{
start_tests("bs_tree_map tests");
run_test(test_new);
run_test(test_free);
run_test(test_insert_strs);
run_test(test_insert_and_delete_strs);
run_test(test_traverse);
end_tests();
return 0;
}
|
C
|
// Shared via Compiler App https://g633x.app.goo.gl/TPlw
#include<stdio.h>
void main()
{
int i,j;
printf("i j i&j");
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf("\n%d %d %d",i,j,i&&j);
}
}
}
|
C
|
#include <stdio.h>
int main()
{
int broj, temp, pom = 1;
scanf("%d", &broj);
temp = broj;
while(temp) {
temp /= 10;
pom *= 10;
}
while(pom > 1) {
pom /= 10;
printf("%d ", broj / pom);
broj %= pom;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _node{
int key;
struct _node *left;
struct _node *right;
} Node;
typedef Node* Tree;
void print_t(Tree t){
if(t != NULL){
print_t(t->left);
printf("%d\n", t->key);
print_t(t->right);
}
}
int get_int();
void mem_err();
void abr_insert(Tree* t_ptr, int val);
int abr_query(Tree t);
void free_tree(Tree* t_ptr);
int main(){
Tree t = NULL;
/*LEGGI N*/
int N = get_int();
/*INSERISCI N INTERI NELL'ALBERO*/
int i;
for(i = 0; i < N; i++)
abr_insert(&t, get_int());
/*TROVA IL SECONDO EL. PIU' GRANDE NELL'ALBERO*/
/*E STAMPALO*/
printf("%d\n", abr_query(t));
/*DEALLOCA ALBERO*/
free_tree(&t);
return 0;
}
int abr_query(Tree t){
if(t->left == NULL && (t->right->left == NULL && t->right->right == NULL))
return t->key;
else if(t->right == NULL && (t->left->left == NULL && t->left->right == NULL))
return t->left->key;
Node* prec;
Node* curr;
if(t->right == NULL){
prec = t->left;
curr = t;
}
else{
prec = t;
curr = t->right;
}
while(curr->right != NULL){
prec = curr;
curr = curr->right;
}
if(curr->left != NULL){
prec = curr->left;
while(prec->right != NULL)
prec = prec->right;
}
return prec->key;
}
void abr_insert(Tree* t_ptr, int val){
if(t_ptr != NULL){
if(*t_ptr == NULL){
Node *new_node = calloc(1, sizeof(Node));
if(new_node == NULL)
mem_err();
new_node->key = val;
*t_ptr = new_node;
return;
}
if(val < (*t_ptr)->key)
abr_insert(&((*t_ptr)->left), val);
else
abr_insert(&((*t_ptr)->right), val);
}
}
void free_tree(Tree* tree_ptr){
if(tree_ptr != NULL && *tree_ptr != NULL){
free_tree(&((*tree_ptr)->left));
free_tree(&((*tree_ptr)->right));
free(*tree_ptr);
*tree_ptr = NULL;
}
}
int get_int(){
int tmp;
scanf("%d", &tmp);
scanf("%*[^\n]");
scanf("%*c");
return tmp;
}
void mem_err(){
puts("memoria heap esaurita");
exit(EXIT_FAILURE);
}
|
C
|
#include <stddef.h>
#include <ctype.h>
#include<stdio.h>
getwords(char *line, char *words[], int maxwords)
{
char *p = line;
int nwords = 0;
while(1)
{
while(isspace(*p))
p++;
if(*p == '\0')
return nwords;
words[nwords++] = p;
while(!isspace(*p) && *p != '\0')
p++;
if(*p == '\0')
return nwords;
*p++ = '\0';
if(nwords >= maxwords)
return nwords;
}
}
int main()
{
// char line[] = "this is a test";
char line[20];
int i,nwords;
char *words[20];
fgets(line,20,stdin);
nwords = getwords(line, words,20);
for(i = 0; i < nwords; i++)
printf("%s\n", words[i]);
return 0;
}
|
C
|
#include<stdio.h>
int isprime( long num ){
long i=2;
while( i<num ){
if( num%i++==0 ) return 0;
}
return 1;
}
int main(){
printf( "%d\n", isprime(715827883) );
}
|
C
|
//逗号运算符
#include <stdio.h>
int main()
{
int a=1;int b=2;int c=3;
a++,b++,c++;//逗号表达式
a=(a+1,b+1,c+1);//赋值表达式,输出最大的数。
printf("a=%d,b=%d,c=%d",a,b,c);
return 0;
}
|
C
|
/**
* @file calorie.h
*
* @brief Libreria per la gestione delle calorie.
*
* La libreria calorie.h stata implementata per permettere all'utente
* la gestione delle proprie assunzioni con il corrispettivo valore
* calorico.
*
* @authors Alessandro Scarcia, Davide Quatela, Michela Salvemini
*/
#ifndef CALORIE_LIB
#define CALORIE_LIB
#ifndef STD_LIB
#define STD_LIB
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#endif
//Inclusione della libreria matematica
#ifndef MATH_LIB
#define MATH_LIB
#include <math.h>
#endif
// Inclusione delle librerie per la manipolazione di stringhe e caratteri
#ifndef STRING_LIB
#define STRING_LIB
#include <string.h>
#include <ctype.h>
#endif
#define FLAG_INPUT_LIBERO 3 /// flag che identifica che lassunzione frutto di un input libero, ovvero che non ne un alimento, ne una ricetta presente nei database
#define KCAL_MEDIE_GIORNALIERE 2000 /// kcal medie giornaliere che un utente dovrebbe assumere
#define CAMPIONE_ISTOGRAMMI 200 /// kcal a cui equivale un * negli istogrammi
/// Costanti per i nome del file assunzione
#define PREFIX_FILE_ASSUNZIONI "../assunzioni_" /// Parte iniziale del nome di un file assunzioni
#define SUFFIX_FILE_ASSUNZIONI ".dat" /// Parte finale del nome di un file assunzioni
#define LUNG_FILE_ASSUNZIONI 50 /// Lunghezza massima in caratteri del nome del file assunzioni
#define LUNG_NOME_ASSUNZIONE 21 /// Lunghezza massima in caratteri del nome di un assunzione
#define MIN_KCAL 0 /// Valore minimo per le kcal usate nel calcolo relativo ad un assunzione
#define MAX_KCAL 5000 /// Valore minimo per le kcal usate nel calcolo relativo ad un assunzione
#include "pulizia_flussi.h"
#include "alimenti.h"
#include "ricette.h"
/**
* @typedef assunzione
*
* Il tipo di dato "assunzione" serve a memorizzare un assunzione della giornata corrente di un utente.
* E' basato su di una struct i cui membri sono: nome, quantita, kcal, e flag (per identificare se si tratta di una ricetta o aliment).
*
*/
typedef struct struct_assunzione{
char nome[LUNG_NOME_ASSUNZIONE]; ///stringa che contiene il nome dell'assunzione
float quantita; /// quantit assunta
unsigned short int kcal; /// kcal per la quantita assunta
int flag; /// flag che indica se una ricetta, un input libero o un alimento
} assunzione;
/**
* Questa funzione ha il compito di richiedere all'utente di inserire il nome relativo ad un assunzione.
* Il valore inserito dall'utente viene controllato, verificando che sia della lunghezza massima stabilita.
* Se corretto, viene restituito il puntatore alla stringa del nome inserito.
*
* @return puntatore alla stringa inserita dall'utente
*/
char* input_nome_assunzione();
/**
* Questa funzione ha il compito di richiedere all'utente il valore di kcal relative ad un assunzione libera.
* Ilvalore viene inserito, controllando che sia significativo nel formato e nel valore.
* Se corretto, lo stesso viene restituito.
*
* @return kcal inserite dall'utente
*/
unsigned short int input_kcal_libere();
/**Questa funzione ha il compito di popolare una struct di tipo assunzione passatagli in ingresso, con i dati
* inseriti dal'utente. Per fare ci chiede all'utente di inserire 0 se ha intenzione di inserire un alimento
* oppure 1 se si tratta di una ricetta. Fatta tale distinzione, vengono chiamate opportune funzioni per
* l'estrazione dal database del tipo di dato che si deve gestire, permettendo il popolamento della struct
* passata in ingresso.
*
* @return -1 se l'utente vuole smettere di inserire alimenti
* @return 1 se tutto avviene in modo corretto
*
*/
int input_alimento_consumato ();
/**La funzione calcolo_kcal_alimento() ha il compito di calcolare le kcal di un alimento basandosi sulla quantit,
* il tutto attraverso una proporzione.
*
* @param kcal numero intero corrispondente alle kcal per un dato campione
* @param campione numero intero che rappresenta la quantit corrispondente alle kcal
* @param q_consumata numero corrispondente alla quantita consumata effettivamente
*
* @return 0 se i dati inseriti non sono validi
* @return risultato_kcal kcal per il quantitativo inserito
*/
unsigned short int calcolo_kcal(unsigned short int kcal, int campione, float q_consumata);
/**La funzione aggiorno_database_calorie() ha il compito di scrive su file assunzioni relativo all'utente,
* il quale nickname viene passato come parametro di ingresso alla fuzione, il cibo assunto.
*
* @param nome_consumo nome dell'alimento consumato
* @param nickname nome con cui creare il nome del file su cui scrivere
* @param flag_consumo flag che indica se si tratta di un alimento, una ricetta o un input libero
* @param quantita_consumo quantita consumata
*
*@return -1 se il file non esiste e non possibile crearne uno
*@return 1 se la funzione riesce a svolgere il suo compito
*/
int aggiorno_database_calorie(char nome_consumo[], int flag_consumo, float quantita_consumo, char nickname[]);
/**La funzione inizializza_file_assunzione() ha il compito di resettare il file e scrivere in prima posizione la data
* odierna.
*
* @param nickname nome con cui creare il nome del file su cui scrivere
*
* @return -1 se non riesce a creare il file
* @return 1 se riesce a svolgere il suo compito
*
*/
int inizializza_file_assunzione(char nickname[]);
/**La funzione apertura_file_assunzioni() ha il compito di aprire il file se l'autenticazioen va a buon fine e
* verificare che la data presente sia quella odierna servendosi di una funzione che calcola la differenza tra le
* due date passategli in ingresso. Se la funzione restituisce zero, si procede all'input dell'alimento consumato,
* altrimenti viene resettato il file e scritta la nuova data, solo dopo si procede all'input degli alimenti.
*
*@return 0 se l'autenticazione non ha successo
*@return -1 se non riesce ad aprire e creare il file
*@return 1 se la funzione riesce a svolgere il suo compito
*/
int apertura_file_assunzioni();
/**La funzione stampa_database_assunzioni() ha il compito di aprire il file tutti i suoi elementi al suo interno
* stampandoli su schermo.
*
*@return -1 se non riesce ad aprire e creare il file
*@return 1 se la funzione riesce a svolgere il suo compito
*/
int stampa_database_assunzioni ();
/**La funzione calcolo_kcal_totali() ha il compito di aprire il file, posizionare il puntatore
* dopo la data e leggere tutti i suoi elementi al suo interno accumulando le kcal di ciauscino in una variabile
* per poi essere stampata su schermo.
*
* @param nomefile stringa utile all'apertura del file
*
*@return -1 se non riesce ad aprire e creare il file
*@return 1 se la funzione riesce a svolgere il suo compito
*/
unsigned short calcolo_kcal_totali(char* nomefile);
/**La funzione creazione_assunzioni() ha il compito di creare il file assunzioni.
*
*
*@return 0 se l'autenticazione non va a buon fine
*@return 1 se la funzione riesce a svolgere il suo compito
*/
int creazione_assunzioni ();
/**La funzione modifica_assunzione() ha il compito di modifcare una delle struct presenti nel file, su richiesta dell'utente.
*
*@return 0 se non riesce ad aprire il file o se l'autenticazione fallisce
*@return 1 se la funzione riesce ad effetturare la modifica correttamente
*/
int modifica_assunzione ();
/**La funzione ricerca_assunzione_database() ha il compito di aprire il file assunzioni legato all'utente il cui nome gli viene passato in
* ingresso grazie alla struct assunzione, cercare nel file una struct di tipo assunzione che abbia la stringa nome uguale alla varibile nome passata in ingresso.
* Se la trova, ritorna la sua posizioen nel file.
*
*
*@param nuova_assunzione struct dove viene inserita la struct se trovata
*@param nickname variabile per aprire il file legato all'utente
*
*@return posizione se trova la struct con nome corrispondente al nome passato in ingresso
*@return 0 se non trova una struct con nome corrispondente al nome passato in ingresso
*/
short int ricerca_assunzione_database (assunzione* nuova_assunzione, char nickname[]);
/**La funzione scrittura_diretta_assunzione() ha il compito di scrivere sul file corrispondente all'utente il quale nickname viene passato
* in ingresso, la struct pasastagli in ingresso.
*
*
*@param nickname variabile per l'apertura del file corrispondente all'utente
*@param cibo struct da scrivere su file
*
*@return 1 se il file viene aggiornato correttamente
*/
int scrittura_diretta_assunzione (assunzione* cibo, char nickname[]);
/**La procedura istogrami() ha il compito di stampare su schermo le calorie che l'utente dovrebbe assumere in base al suo menu di riferimento
* e quelle che effettivamente assunto in base al file assunzioni.
*
*/
void istogrami ();
#endif
|
C
|
#include<stdio.h>
/* ִ빦ܽ飺ԭ */
/* User Code Begin(Limit: lines<=1, lineLen<=50, ڱкӴ롢1Сÿг<=50ַ) */
int deal(char *str);
/* User Code End(Ӵע⣺к͵Ϊһе{}гtab) */
int main(void)
{
int Len;
char String[101];/* = "?????????????????????????????????????????????????????????????"; */
printf("\ninput a string: ");
/* ִ빦ܽ飺ÿԶ庯ʵ */
/* User Code Begin(Limit: lines<=1, lineLen<=50, ڱкӴ롢1Сÿг<=50ַ) */
Len = deal(String);
/* User Code End(Ӵע⣺к͵Ϊһе{}гtab) */
printf("\nThe string lenth is: %d\n", Len);
printf("The string is: %s\n", String);
return 0;
}
/* User Code Begin(ڴ˺Զ庯ƣ) */
int deal(char *str)
{
int i1 = -1, ch;
do
{
i1++;
ch = scanf("%c", &str[i1]);
if (str[i1] == '\n' || str[i1] == '\0' || ch != 1)
{
/* i1 = i1; */
break;
}
} while (i1 < 100);
str[i1] = '\0';
return i1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "NHAL_function.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct{
int msgN;
int cfg;
void *next;
}Search_msg;
typedef enum{
Idle,
RF_on,
Srch_on,
RF_sync
}Scheduler_state;
typedef enum{
normal_off,
forced_off
}Srchoff_state;
int main(void) {
int exit = 0;
Scheduler_state state = Idle;
Srchoff_state srchst;
Search_msg *srch_msg;
int secondsrch;
while(exit == 0){
switch(state){
//IDLE = ƹ͵ ϰ ִ
// RRC command (event triggered) RFon ϰ RFon· Ѿ
case Idle :
if(srch_msg != NULL){
if(0 == NHAL_RFcmd_on()){
state = RF_on;
break;
}
else{
printf("RFon failed!");
break;
}
}
state = Idle;
break;
//RF_on = vRF
// RRC on ϸ Srch on ϰ Srchon· Ѿ
case RF_on :
NHAL_srchcmd_on();
state = Srch_on;
break;
//Srch_on = vSrcher ִ
//vSearcher off (event triggered) ãҴٰ ǴϿ RF_sync· Ѿ
//vSearcher off (event triggered) ġ з ǴϿ RF off ϰ Idle· Ѿ -> RF off µ ־ߵdz?
case Srch_on :
if(srchst == normal_off){
sendResUpper();
state = RF_sync;
break;
}else if(srchst == forced_off ){
sendFailUpper();
state = Idle;
break;
}
state = Srch_on;
break;
//RF_sync = vSrcher ãƳ ֱ timing RF ִ
//ο RRC command (event triggered) RF off ϰ Idle· Ѿ
// ġϴ RRC command (event triggered) Srch on ϰ Srchon· Ѿ
case RF_sync:
if (srch_msg != NULL){
//if(Search_msg.cfg.freq_offset == RF.freq_offset)
if( secondsrch == 1)
{
NHAL_srchcmd_on();
state = Srch_on;
break;
}else{
NHAL_RFcmd_off();
state = Idle;
break;
}
}
state = RF_sync;
break;
default:
exit = 1;
printf("wrong state error! (val : %s)\n",state);
break;
}
}
return 0;
}
|
C
|
#include <stdlib.h>
#include "oeving2.h"
#include "sys/interrupts.h"
//Since this is the file utilizing the extern type-modified pointers below, we initialize them here with the values given in the code supplied to us.
volatile avr32_pio_t *piob = &AVR32_PIOB;
volatile avr32_pio_t *pioc = &AVR32_PIOC;
volatile avr32_pm_t *pm = &AVR32_PM;
volatile avr32_abdac_t *abdac = &AVR32_ABDAC;
/* funksjon for å initialisere maskinvaren, må utvides */
void initHardware(void){
initIntc();
initAudio();
initLeds();
initButtons();
}
//Function of initializing interruptController.
void initIntc(void){
set_interrupts_base((void *)AVR32_INTC_ADDRESS);
init_interrupts();
}
//Function for initalizing buttons
void initButtons(void){
//The below line tells the interruptController to call the button_isr() function when the buttons send an interrupt, with the interrupt priority-level set in a macro given to us in the supplied code.
register_interrupt(button_isr, AVR32_PIOB_IRQ/32, AVR32_PIOB_IRQ % 32, BUTTONS_INT_LEVEL);
//The below line initializes variable 'active' with the combined values of the switches listes on the right hand side of the equals sign.
short active = SW7+SW6+SW5+SW4+/*SW3+SW2+*/SW0; //Commented out SW3 and SW2 because our sampleStructs don't work when genereting tone based on strokes
//Below we activate the switches by writing to the PIOEnableRegister, Pull-upEnableRegister, and InterruptEnableRegister
piob->per = active;
piob->puer = active;
piob->ier = active;
//Below we disable the rest of the switches by sending the inverted value of the 'active' variable to the buttons InterruptDisableRegister
piob->idr = SW1+SW2+SW3;//Same as comment on line 33
}
//Function for initializing LEDs
void initLeds(void){
//Below we initialize all the LEDs by writing the hex-value 0xff to the PIOEnableRegister for the LEDs
pioc->per = 0xff; //0xff == all LEDs
//Below we allow all the LEDs to have an output vale (AKA enabling the LEDs SetOutputData and ClearOutputData Register)
pioc->oer = 0xff;
//Below we first turn all the LEDs off, before we turn on the LED for SW0 (Indicating that we start with silence...)
pioc->codr = 0xff;
pioc->sodr = SW0;
}
//Function for initializing ABDAC (Audio)
void initAudio(void){
//Below we use the PowerManager first to choose which oscillator we want the ABDAC to utilize
pm->GCCTRL[6].oscsel = 0;
//Then below we set the diven (Divide Enable) register to zero to turn it off.
pm->GCCTRL[6].diven = 0;
//Then below we choose which PLL we want to use
pm->GCCTRL[6].pllsel = 0;
//Then finally we turn the cen register (ClockEnable) to one, turning it on.
pm->GCCTRL[6].cen = 1;
//Below we tell the InterruptController to call the abdac_isr function each time the abdac receives an interrupt, and make each interrupt call with the ABDAC_INT_LEVEL as interrupt-priority level
//(Much like the corresponding line in initButtons())
register_interrupt(abdac_isr, AVR32_ABDAC_IRQ/32, AVR32_ABDAC_IRQ % 32, ABDAC_INT_LEVEL);
//Below we setup PIOB to be used by ABDAC (Basically connecting the ABDAC to PIOB)
piob->PDR.p20 = 1;
piob->PDR.p21 = 1;
piob->ASR.p20 = 1;
piob->ASR.p21 = 1;
//Here we call the function setAbdacOnOff with parameter 1 to turn the abdac on
setAbdacOnOff(1);
}
//Function we wrote to easily turn ABDAC on and off
void setAbdacOnOff(int value){
//We read in parameter value, and make sure it is not the same as the value abdac->CR.en and abdac->IER.tx_ready already have
//(Meaning that this function will do nothing when the function is sent parameter zero and the abdac is turned off, or vica versa with parameter equalling 1)
if(value != abdac->CR.en &&
value != abdac->IER.tx_ready){
//If the two values however do differ, set the abddac-members to the new value
abdac->CR.en = value;
abdac->IER.tx_ready = value;
}
}
|
C
|
#include "img_pro.h"
unsigned char **alloc_img(int ncol,int nrow)
{
int i;
unsigned char **img;
/* allocate pointers to rows */
img = (unsigned char **) malloc((size_t)((nrow+1)*sizeof(unsigned char*)));
if (!img)
{
printf("\n\n Cannot allocate memory (1)\n");
exit(0);
}
/* allocate rows and set pointers to them */
img[0] = (unsigned char *) malloc((size_t)((nrow*ncol+1)*sizeof(unsigned char)));
if (!img[0])
{
printf("\nCannot allocate memory (2)\n");
exit(0);
}
for(i=1;i<=nrow;i++)
img[i]=img[i-1] + ncol;
/* return pointer to array of pointers to rows */
return (img);
}
void free_img(unsigned char** img)
{
free( img[0] );
free( img );
}
void show_pgm_file(char *file_name)
{
FILE *xfp;
char command[256]="";
char app[256]="";
strcat(command,view);
sprintf(app," %s",file_name);
/*
xfp=popen((const char *)strcat(command,app),"w");
pclose(xfp);
*/
system((const char *)strcat(command,app));
}
void img_to_pgm_file(unsigned char **img, char *file_name,int NC, int NR)
{
int i,j;
FILE *fp;
fp=fopen(file_name,"w");
#ifdef WIN
_setmode( _fileno(fp), _O_BINARY); /* be sure to write files in binary mode */
#endif
fprintf(fp,"P5\n%d %d\n255\n",NC,NR);
for(i=0;i<NR;i++)
for(j=0;j<NC;j++)
fputc(img[i][j],fp);
fclose(fp);
}
unsigned char **pgm_file_to_img(char *file_name,int *pNC,int *pNR)
#define MAXC 80
{
FILE *fp;
unsigned char **img;
char cline[MAXC];
int i,j,NR,NC;
int maxgray;
if((fp=fopen(file_name,"r")) == NULL) {
/* open image file */
printf("\n *** pgm_file_to_img -- can't open file: %s ****",file_name);
exit(0); }
#ifdef WIN
_setmode( _fileno(fp), _O_BINARY); /* be sure to read files in binary mode */
#endif
comment_loop0: /* skip any comments */
fgets(cline,MAXC,fp); /* get next line from file */
if(cline[0]=='#') goto comment_loop0;
if(cline[0]!='P'||cline[1]!='5')
{
printf("\n **** pgm_file_to_img -- not a pgm file: %s ****",file_name);
exit(0);
}
comment_loop1: /* skip any comments */
fgets(cline,MAXC,fp); /* get next line from file */
if(cline[0]=='#') goto comment_loop1;
sscanf(cline,"%d %d ",&NC,&NR);
comment_loop2: /* skip any comments */
fgets(cline,MAXC,fp); /* get next line from file */
if(cline[0]=='#') goto comment_loop2;
sscanf(cline,"%d ",&maxgray); /* get maxgray */
/* return size of image to caller */
*pNC=NC;
*pNR=NR;
img=alloc_img(NC,NR); /* allocate image array */
for(i=0;i<NR;i++)
for(j=0;j<NC;j++)
{
img[i][j]=fgetc(fp); /* read image data from file */
}
fclose(fp);
return(img);
}
|
C
|
#include <stdio.h>
int main (void)
{
char theCharA = 'A';
char theCharZ = 'Z';
printf("the first char is:%c \n",theCharA);
printf("the second char is:%c\n" ,theCharZ);
printf("the num of chars without A and Z :%d\n", (theCharZ-theCharA-1));
getchar();
}
|
C
|
/*******************************************************************************************
** Name: Peter Moldenhauer
** Date: 12/30/16
** Description: This program demonstrates puts and gets - easier than printf() and scanf().
** Puts() prints a string out to the screen and gets() gets a string from the user. In both
** cases the strings CAN contain spaces. Finally, stringcat() can build a new string piece
** by piece.
********************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h> // used for string functions
#include <math.h>
int main()
{
// scanf() only reads one word strings - once it gets to a space it stops reading in
// gets() allows you to read strings with spaces
char personName[50];
char personFood[25];
char sentence[75] = "";
puts("Whats the person's name?" ); // puts automatically adds a new line to the end of the output
gets(personName);
puts("Whats the person's favorite food?" );
gets(personFood);
strcat(sentence, personName);
strcat(sentence, " loves to eat ");
strcat(sentence, personFood);
puts(sentence);
return 0;
}
|
C
|
#ifndef SORT_H
#define SORT_H
#include <stdio.h>
#include <stdlib.h>
/* DATA STRUCTURES */
/**
* struct listint_s - Doubly linked list node
*
* @n: Integer stored in the node
* @prev: Pointer to the previous element of the list
* @next: Pointer to the next element of the list
*/
typedef struct listint_s
{
const int n;
struct listint_s *prev;
struct listint_s *next;
} listint_t;
/* PROTOTYPES */
void print_array(const int *array, size_t size);
void print_list(const listint_t *list);
void bubble_sort(int *array, size_t size);
void swap(int *a, int *b);
void selection_sort(int *array, size_t size);
void insertion_sort_list(listint_t **list);
int partition(int *array, size_t size, int low, int high);
void my_sort(int *array, size_t size, int low, int high);
void quick_sort(int *array, size_t size);
void merge_sort(int *array, size_t size);
void real_sort(int *array, int *temp, size_t start, size_t end, size_t size);
void merge(int *array, int *temp, size_t start,
size_t mid, size_t end, size_t size);
void shell_sort(int *array, size_t size);
void cocktail_sort_list(listint_t **list);
int listint_len(const listint_t *h);
void swap_node(listint_t *element, listint_t *mover, listint_t **list);
void rev_swap_node(listint_t *element, listint_t *mover, listint_t **list);
int check_sorted(listint_t **list);
int is_sorted(int *array, size_t size);
int find_max(int *array, size_t size);
void counting_sort(int *array, size_t size);
#endif /* SORT_H */
|
C
|
struct stack_record
{
int size;
int top;
int min;
int min_loc;
int *array;
};
typedef struct stack_record *STACK;
#define EMPTY (-1)
#define MIN_STACK_SIZE 4
#define BUFSIZE 10
#define MAX 99999
STACK create_stack(int max_elements)
{
STACK S;
if(max_elements<MIN_STACK_SIZE)
printf("Stack size is too small");
S=(STACK) malloc(sizeof(struct stack_record));
if(S==NULL){
printf("Out of space!");
exit(-1);
}
S->array=(int *) malloc(sizeof(int)*max_elements);
if(S->array==NULL){
printf("Out of space!");
exit(-1);
}
S->top=EMPTY;
S->size=max_elements;
S->min=MAX;
S->min_loc=EMPTY;
return(S);
}
void dispose_stack(STACK S)
{
if(S!=NULL)
{
free(S->array);
free(S);
}
}
int is_empty(STACK S)
{
return (S->top==EMPTY);
}
void make_null(STACK S)
{
S->top=EMPTY;
S->min=MAX;
S->min_loc=EMPTY;
}
void push(int x,STACK S)
{
if(S->top==(S->size-1))
error("Stack is FULL");
else{
S->array[++(S->top)]=x;
if(x<S->min){
S->min=x;
S->min_loc=S->top;
}
}
}
int top(STACK S)
{
if(is_empty(S))
printf("Stack is EMPTY\n");
else
return S->array[S->top];
}
void pop(STACK S)
{
if(is_empty(S))
printf("Stack is EMPTY\n");
else{
int i=S->top;
S->top--;
if(i==S->min_loc){
S->min=MAX;
for(i=0;i<=S->top;i++)
if(S->min>S->array[i]){
S->min=S->array[i];
S->min_loc=i;
}
}
}
}
int find_min(STACK S)
{
return(S->min);
}
|
C
|
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<fcntl.h>
void main(){
int fd = creat("text1.txt", O_RDWR);
char buf[80]="Hello World \nThis is line 1\nLine 2";
int bytes = write(fd, buf, sizeof(buf));
printf("Number of bytes written: %d\n",bytes);
}
|
C
|
//Estructuras de Funciones
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct NODO{
char usuario [21];
char barrio [41];
int tel;
char mail[41];
char password [11];
struct NODO *next;
};
struct LIBRO{
char titulo[41];
struct LIBRO *next;
};
void alta_usuario();
void baja_usuario();
// void buscar(struct NODO *);
// void agregar_libro(char *usuario);//el usuario agrega un libro
// void borrar_libro(char * usuario);// pasa el nombre del txt a abrir para borrar libro
// void listar_mislibros (char *usuario);// muestra los libros del usuario
// void listar_libros(struct NODO *);//muestra todos los libros de todos los usuarios
int validar_usuario(char *us,char *pass);//valida usuario y password
void ordenar_usuario(struct NODO **);
void ordenar_libros();
void alta_usuario(){
struct NODO *aux; //aca esta al pedo por ahora. si no recibiera nada funcionaria igual
//aca tambien esta al pedo
char a[41],b[41]; //estas variables las voy a utilizar para comparar el mail y la contraseña aunque la contraseña tenga un tamaño menor
aux=(struct NODO *)malloc(sizeof(struct NODO)); //reservo memoria del tamaño de la estructura
if(aux==NULL){
printf("Error de memoria al cargar usuario\n");
return; //en caso de que no me pueda reservar el espacio
}else{
aux->next=NULL;
printf("Nombre de usuario:\n"); //carga de usuario, barrio, telfono
scanf("%s",aux->usuario); //puse algun getchar() porque me tomaba un enter sin dejarme cargar el dato siguiente
getchar();
printf("Barrio:\n");
fgets(aux->barrio, 41, stdin); //use el fgets como para poder cargar un string con espacios y de un tamaño determinado
printf("telefono:\n");
scanf("%d",&aux->tel);
getchar();
while(1){ //pide el mail y repetir el mail hasta que lo ingrese correctamente
printf("Ingrese E-Mail:\n");
fgets(a, 41, stdin); //use el fgets como para poder cargar un string con espacios y de un tamaño determinado
printf("Repetir E-Mail:\n");
fgets(b, 41, stdin);
if(strcmp(a,b)==0){ //compara lo ingresado
strcpy(aux->mail,a); //copia en el espacio reservado
break; //una vez que lo ingreso correctamente 2 veces continua
}else{
printf("Error al ingresar E-Mail\n");
printf("primero %s \nsegundo %s \n",a,b);
}
}
while(1){ //pide la contraseña y repetir la misma hasta que la ingrese correctamente
printf("Contraseña hasta 10 caracteres:\n");
scanf("%s",a);
printf("Repetir contraseña:\n");
scanf("%s",b);
if(strcmp(a,b)==0){
strcpy(aux->password,a);
break; //una vez que lo ingreso correctamente 2 veces continua
}else{
printf("Error al ingresar contraseña\n");
}
}
}
strcpy(b,aux->usuario); //Copia el nombre que ingreso el usuario en la variable b para concatenar con un ".txt"
strcat(b,".txt"); //Concatena el nombre ingresado con un ".txt"
FILE *user;
user=fopen(b,"wb"); //abro el archivo en modo escritura, lo crea. Aca deberia validar su existencia o en todo caso cuando recien ingresa el nombre del usuario, hay un error
printf("\n\nUsuario:%s\nBarrio:%s\nTelefono:%d\n\nMail:%s\nContraseña:%s\n\n",aux->usuario,aux->barrio,aux->tel,aux->mail,aux->password); //te muestra todo lo que ingresaste para chequear, debería preguntar si estas de acuerdo o no
fwrite(aux,sizeof(struct NODO),1,user); //escribe el archivo del tamaño de la estructura
fclose(user); //cierra el archivo
free(aux); //libero el espacio antes tomado por la estructura
return;
}
void baja_usuario(){ //aca por ahora es al pedo que me pase el puntero
char usuario[21],password[11];
printf("Ingrese usuario a eliminar:\n");
scanf("%s",usuario);
getchar();
strcat(usuario,".txt"); //le concateno el ".txt" para para comparar con la existencia del archivo
printf("Ingrese contraseña:\n");
scanf("%s",password);
//getchar();
if(validar_usuario(usuario,password)==1){ //esta funcion va adevolver 1 si existe y es correcto el password para ser eliminado o 0 cero en caso contrario
remove(usuario); //funcion del sistema para borrar el archivo, como ya validé que existe lo puedo borrar
printf("El usuario fue eliminado\n");
return;
}else{
printf("La contraseña ' %s ' es incorrecta vuelva a intentar \n",password); //le indico que lo que puso es incorrecto mostrandoselo, esto se puede obviar, falta poner el loop para que vuelva a intentarlo
}
return;
}
int validar_usuario(char *us,char *pass){ //chequea que exista el archivo del usuario y que su contraseña sea la correcta
struct NODO *aux2; //genero puntero del tamaño de struct
int ok=1,err=0; // valores a devolver, solo para que sea mas claro en el resto de la funcion
FILE *user2;
user2=fopen(us,"r"); //abre el archivo en modo lectura
if(user2==NULL){ //comprueba la existencia del archivo y por ende el usuario
printf("no existe\n");
return err; //no existe el archivo retorna 0 para que no elimine nada
}else{
printf("existe archivo\n");
fread(aux2,sizeof(struct NODO),1,user2); //lee una porcion del archivo
printf("su contraseña es %s\n",aux2->password); //muestra la contraseña que tiene realmente, es solo para chequeo, se debe quitar luego
if(strcmp(pass,aux2->password)==0){ //compara la contraseña ingresada por el usuario y la leida del archivo
printf("Coincide la contraseña\n");
fclose(user2); //coincide y cierra el archivo
return ok; //contraseña correcta retorna 1
}else{
printf("No coincide la contraseña\n");
fclose(user2);
return err; //contraseña incorrecta retorna 0
}
}
return err;
}
|
C
|
/// \file constantes.h
/// \brief Implementation file for "CG-N2_HelloWorld".
/// \version $Revision: 1.0 $
/// \author Dalton Reis.
/// \date 05/09/13.
#ifndef CG_N2_HelloWorld_constantes_h
#define CG_N2_HelloWorld_constantes_h
inline void SRU(void) {
// eixo X - Red
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(10.0f, 0.0f, 0.0f);
glEnd();
// eixo Y - Green
glColor3f(0.0f, 1.0f, 0.0f);
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 10.0f, 0.0f);
glEnd();
// eixo Z - Blue
glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 0.0f, 10.0f);
glEnd();
}
#endif
|
C
|
#define TEST_NAME "box_seal"
#include "cmptest.h"
int
main(void)
{
unsigned char pk[crypto_box_PUBLICKEYBYTES];
unsigned char sk[crypto_box_SECRETKEYBYTES];
unsigned char *c;
unsigned char *m;
unsigned char *m2;
size_t m_len;
size_t c_len;
crypto_box_keypair(pk, sk);
m_len = (size_t) randombytes_uniform(1000);
c_len = crypto_box_SEALBYTES + m_len;
m = (unsigned char *) sodium_malloc(m_len);
m2 = (unsigned char *) sodium_malloc(m_len);
c = (unsigned char *) sodium_malloc(c_len);
randombytes_buf(m, m_len);
if (crypto_box_seal(c, m, m_len, pk) != 0) {
printf("crypto_box_seal() failure\n");
return 1;
}
if (crypto_box_seal_open(m2, c, c_len, pk, sk) != 0) {
printf("crypto_box_seal_open() failure\n");
return 1;
}
printf("%d\n", memcmp(m, m2, m_len));
printf("%d\n", crypto_box_seal_open(m, c, 0U, pk, sk));
printf("%d\n", crypto_box_seal_open(m, c, c_len - 1U, pk, sk));
printf("%d\n", crypto_box_seal_open(m, c, c_len, sk, pk));
sodium_free(c);
sodium_free(m);
sodium_free(m2);
assert(crypto_box_sealbytes() == crypto_box_SEALBYTES);
return 0;
}
|
C
|
/*
* This implementation replicates the implicit list implementation
* provided in the textbook
* "Computer Systems - A Programmer's Perspective"
* Blocks are never coalesced or reused.
* Realloc is implemented directly using mm_malloc and mm_free.
*
* NOTE TO STUDENTS: Replace this header comment with your own header
* comment that gives a high level description of your solution.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include "mm.h"
#include "memlib.h"
/*********************************************************
* NOTE TO STUDENTS: Before you do anything else, please
* provide your team information in the following struct.
********************************************************/
team_t team = {
"woozy_koala",
"yanisa khambanonda",
"[email protected]",
/* Second member's full name (do not modify this as this is an individual lab) */
"",
/* Second member's email address (do not modify this as this is an individual lab)*/
""
};
/*************************************************************************
* Basic Constants and Macros
* You are not required to use these macros but may find them helpful.
*************************************************************************/
#define WSIZE sizeof(void *) /* word size (bytes) */
#define DSIZE (2 * WSIZE) /* doubleword size (bytes) */
#define CHUNKSIZE (1<<7) /* initial heap size (bytes) */
#define MAX(x,y) ((x) > (y)?(x) :(y))
/* Pack a size and allocated bit into a word */
#define PACK(size, alloc) ((size) | (alloc))
/* Read and write a word at address p */
#define GET(p) (*(uintptr_t *)(p))
#define PUT(p,val) (*(uintptr_t *)(p) = (val))
/* Read the size and allocated fields from address p */
#define GET_SIZE(p) (GET(p) & ~(DSIZE - 1))
#define GET_ALLOC(p) (GET(p) & 0x1)
/* Given block ptr bp, compute address of its header and footer */
#define HDRP(bp) ((char *)(bp) - WSIZE)
#define FTRP(bp) ((char *)(bp) + GET_SIZE(HDRP(bp)))
/* Given block ptr bp, compute address of next and previous blocks */
#define NEXT_BLKP(bp) ((char *)(bp) + GET_SIZE(((char *)(bp) - WSIZE)) + DSIZE)
#define PREV_BLKP(bp) ((char *)(bp) - GET_SIZE(((char *)(bp) - DSIZE)) - DSIZE)
#define FREE_LIST_NUMBER 8
void* heap_listp = NULL;
typedef struct free_block{
struct free_block* next;
struct free_block* prev;
}free_block;
free_block* free_lists[FREE_LIST_NUMBER];
int find_free_list(int size);
void add_to_freelist(free_block* temp);
void remove_from_freelist(free_block* block);
/**********************************************************
* HEADER = 8 BYTE (1 WORD) FOOTER = 8 BYTE (1 WORD)
*
* FOOTER 8
* | |
* | DATA | DATA MUST BE MULTIPLE OF 16
* | |
* HEADER 8
*
* Free list sizes
* bucket 0 : 16 bytes (1-2 word)
* bucket 1 : 32 bytes (4 word)
* bucket 2 : 64 bytes (5-8 word)
* bucket 3 : 128 (9-16 word)
* bucket 4 : 256 (17-32 word)
* bucket 5 : 512 (33-64 word)
* bucket 6 : 1024
* bucket 7 : 2048
*
*********************************************************/
/**********************************************************
* mm_init
* Initialize the heap, including "allocation" of the
* prologue and epilogue
**********************************************************/
int mm_init(void)
{
if ((heap_listp = mem_sbrk(4*WSIZE)) == (void *)-1)
return -1;
PUT(heap_listp, 0); // alignment padding
PUT(heap_listp + (1 * WSIZE), PACK(DSIZE, 1)); // prologue header
PUT(heap_listp + (2 * WSIZE), PACK(DSIZE, 1)); // prologue footer
PUT(heap_listp + (3 * WSIZE), PACK(0, 1)); // epilogue header
heap_listp += DSIZE;
for (int i = 0; i < FREE_LIST_NUMBER; i ++){
free_lists[i] = NULL;
}
printf("done mm_init \n");
return 0;
}
/**********************************************************
* coalesce
* Covers the 4 cases discussed in the text:
* - both neighbours are allocated
* - the next block is available for coalescing
* - the previous block is available for coalescing
* - both neighbours are available for coalescing
**********************************************************/
void *coalesce(void *bp)
{
size_t prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp)));
size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
size_t size = GET_SIZE(HDRP(bp));
if (prev_alloc && next_alloc) { /* Case 1 */
return bp;
}
else if (prev_alloc && !next_alloc) { /* Case 2 */
free_block* temp = (free_block *)NEXT_BLKP(bp);
remove_from_freelist(temp);
size += GET_SIZE(HDRP(NEXT_BLKP(bp))) + DSIZE;
PUT(HDRP(bp), PACK(size, 0));
PUT(FTRP(bp), PACK(size, 0));
return (bp);
}
else if (!prev_alloc && next_alloc) { /* Case 3 */
remove_from_freelist(bp);
size += GET_SIZE(FTRP(PREV_BLKP(bp))) + DSIZE;
PUT(FTRP(PREV_BLKP(bp)), PACK(size, 0));
PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));
return (PREV_BLKP(bp));
}
else { /* Case 4 */
free_block* temp = (free_block *)NEXT_BLKP(bp);
remove_from_freelist(temp);
remove_from_freelist(bp);
size += GET_SIZE(FTRP(PREV_BLKP(bp))) + GET_SIZE(HDRP(NEXT_BLKP(bp))) + DSIZE*2 ;
PUT(HDRP(PREV_BLKP(bp)), PACK(size,0));
PUT(FTRP(PREV_BLKP(bp)), PACK(size,0));
return (PREV_BLKP(bp));
}
}
/**********************************************************
* extend_heap
* Extend the heap by "words" words, maintaining alignment
* requirements of course. Free the former epilogue block
* and reallocate its new header
**********************************************************/
void *extend_heap(size_t words)
{
printf("Extending the heap and my knowledge...\n");
char *bp;
size_t size = words;
/* Allocate an even number of words to maintain alignments */
if ( (bp = mem_sbrk(size + DSIZE)) == (void *)-1 )
return NULL;
printf("annie's (heap) brain can be extended!\n");
/* Initialize free block header/footer and the epilogue header */
PUT(HDRP(bp), PACK(size, 0)); // free block header
PUT(FTRP(bp), PACK(size, 0)); // free block footer
PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1)); // new epilogue header
/* Coalesce if the previous block was free */
return bp;
//coalesce(bp);
}
/**********************************************************
* find_fit
* Traverse the heap searching for a block to fit asize
* Return NULL if no free blocks can handle that size
* Assumed that asize is aligned
**********************************************************/
void * find_fit(size_t asize){
// void *bp;
printf("fitting into jeans... \n");
int free_list = find_free_list(asize);
int size = asize;
for (int i = free_list; i < FREE_LIST_NUMBER; i++){
printf("checking jean size %d",i);
if (free_lists[i] != NULL){
free_block* temp = free_lists[i];
while (temp !=NULL){
int tsize = GET_SIZE(HDRP(temp));
if (tsize >= size && tsize < (size + DSIZE)){
remove_from_freelist(temp);
return (void*)temp;
}
else if (tsize >= (size + DSIZE)){
printf("cropping jeans: can split block!\n");
remove_from_freelist(temp);
int extra_size = tsize - size;
void* use_ptr = (void*)temp + extra_size;
// Adjust size of the pointed being used
PUT(HDRP(use_ptr), PACK(size,1));
PUT(FTRP(use_ptr), PACK(size,1));
// Adjust size of new split free block
PUT(HDRP(temp), PACK(extra_size,0));
PUT(HDRP(temp), PACK(extra_size,0));
add_to_freelist(temp);
return use_ptr;
}
temp = temp->next;
}
}
}
printf("annie's jeans don't fit\n");
return NULL;
}
/*********************************************************
* find_free_list
* Lookup Index of FreeList
*********************************************************/
int find_free_list(int size){
int cnt = -4;
size --;
while (size != 0){
size = size >> 1;
cnt ++;
}
cnt = MAX(0,cnt);
return cnt >= FREE_LIST_NUMBER ? FREE_LIST_NUMBER -1 : cnt;
}
/**********************************************************
* add_to_freelist
*
*********************************************************/
void add_to_freelist(free_block* temp){
size_t size = GET_SIZE(HDRP(temp));
int free_list = find_free_list(size);
printf("adding to free list...\n");
if (free_lists[free_list] == NULL){
temp->prev = NULL;
temp->next = NULL;
free_lists[free_list] = temp;
}
else{
temp -> next = free_lists[free_list];
temp -> prev = NULL;
free_lists[free_list]->prev = temp;
free_lists[free_list] = temp;
}
return;
}
/**********************************************************
* remove_from_freelist
*
*********************************************************/
void remove_from_freelist(free_block* block){
printf("remove from freelist...\n");
if (block == NULL){
return;
}
size_t size = GET_SIZE(HDRP(block));
int freelist = find_free_list(size);
printf("ok starting shitting prints\n");
if (block-> prev == NULL && block->next == NULL){ // empty list
free_lists[freelist] = NULL;
printf("empty list\n");
return;
}
else if (block->prev==NULL){ // if b is first elem of list
free_lists[freelist] = block->next;
free_lists[freelist]->prev = NULL;
printf("curr is first element\n");
return;
}
else if (block->next == NULL){ // if b is last elem of list
block->prev->next = NULL;
printf("curr is last element\n");
return;
}
else{ // b is in the middle
block->prev->next = block->next;
block->next->prev = block->prev;
printf("curr is in the middle\n");
return;
}
}
/**********************************************************
* place
* Mark the block as allocated
**********************************************************/
void place(void* bp, size_t asize)
{
/* Get the current block size */
size_t bsize = GET_SIZE(HDRP(bp));
PUT(HDRP(bp), PACK(bsize, 1));
PUT(FTRP(bp), PACK(bsize, 1));
}
/**********************************************************
* mm_free
* Free the block and coalesce with neighbouring blocks
**********************************************************/
void mm_free(void *bp)
{
printf("I am free!\n");
printf("I am a joke\n");
if(bp == NULL){
printf("i am null\n");
return NULL;
}
if(GET_ALLOC(HDRP(bp))==0){
printf("get alloc = 0\n");
return NULL;
}
printf("getting size\n");
size_t size = GET_SIZE(HDRP(bp));
printf("size gotten\n");
printf("PUT function %d \n", size);
PUT(HDRP(bp), PACK(size,0));
PUT(FTRP(bp), PACK(size,0));
printf("i am no longer free ): \n");
add_to_freelist(bp);
//add_to_freelist((free_block*)coalesce(bp));
// coalesce(bp);
}
/**********************************************************
* mm_malloc
* Allocate a block of size bytes.
* The type of search is determined by find_fit
* The decision of splitting the block, or not is determined
* in place(..)
* If no block satisfies the request, the heap is extended
**********************************************************/
void *mm_malloc(size_t size)
{
printf("enter mm_malloc with size %d \n", size);
// size_t asize; /* adjusted block size */
char * bp;
/* Ignore spurious requests */
if (size == 0)
return NULL;
if (size < DSIZE ){
size = DSIZE;
}
else if (size <= 2048){
size --;
size |= size >> 1;
size |= size >> 2;
size |= size >> 4;
size |= size >> 8;
size |= size >> 16;
size++;
}
printf("try to fit size %d \n", size);
if ((bp = find_fit(size)) != NULL){
place(bp, size);
return bp;
}
printf("i dont fit in :(\n");
int extendsize = ((size-1)/ DSIZE)*DSIZE + DSIZE; // round to nearest 16 byte
// EXTEND HEAP AND ALLOCATE BLOCK
if ((bp = extend_heap(extendsize))== NULL){
return NULL;
}
printf("placed here\n");
place(bp, extendsize);
//printf("%d\n",bp);
return bp;
}
/**********************************************************
* mm_realloc
* Implemented simply in terms of mm_malloc and mm_free
*********************************************************/
void *mm_realloc(void *ptr, size_t size)
{
printf("doing realloc... \n");
/* If size == 0 then this is just free, and we return NULL. */
if(size == 0){
mm_free(ptr);
return NULL;
}
/* If oldptr is NULL, then this is just malloc. */
if (ptr == NULL)
return (mm_malloc(size));
void *oldptr = ptr;
void *newptr;
size_t old_size = GET_SIZE(HDRP(oldptr));
if (size<DSIZE){
size = DSIZE;
}
else if (size<2048){
size --;
size |= size >> 1;
size |= size >> 2;
size |= size >> 4;
size |= size >> 8;
size |= size >> 16;
size++;
}
else{
size = ((size-1)/ DSIZE)*DSIZE + DSIZE;
}
if (size<=old_size){ // wants less space
printf("wants less of annie\n");
size_t extra = old_size-size;
if (extra >= DSIZE){
newptr = (void *) (oldptr + size + DSIZE);
PUT(HDRP(newptr), PACK(extra,0));
PUT(FTRP(newptr), PACK(extra,0));
add_to_freelist((free_block*)newptr);
PUT(HDRP(oldptr), PACK(size,1));
PUT(FTRP(oldptr), PACK(size,1));
}
return oldptr;
}
else{ // wants more space
printf("wants more of annie\n");
PUT(HDRP(ptr),PACK(old_size, 0));
PUT(FTRP(ptr),PACK(old_size, 0));
// ptr = coalesce(ptr);
size_t coalesced_size = GET_SIZE(HDRP(ptr));
if(coalesced_size >= size){
memmove(ptr, oldptr, old_size);
PUT(HDRP(ptr),PACK(coalesced_size, 1));
PUT(FTRP(ptr),PACK(coalesced_size, 1));
return ptr;
}
newptr = mm_malloc(size);
if (newptr == NULL){
return NULL;
}
memcpy(newptr, oldptr, old_size);
add_to_freelist((free_block * )ptr);
return newptr;
}
}
/**********************************************************
* mm_check
* Check the consistency of the memory heap
* Return nonzero if the heap is consistant.
*********************************************************/
int mm_check(void){
return 1;
}
|
C
|
#include "libmx.h"
t_list *mx_sort_list(t_list *lst, bool (*cmp)(void *, void *)) {
t_list *new = NULL;
while(lst != NULL) {
t_list *node = lst;
lst = lst->next;
if (new == NULL || cmp(node->data, new->data) == 0)
{
node->next = new;
new = node;
}
else {
t_list *current = new;
while(current->next != NULL || !(cmp(node->data, current->next->data))) {
current = current->next;
}
node->next = current->next;
current->next = node;
}
}
return new;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define P_COUNT 7
#define R_COUNT 3
#define RED "\033[31m"
#define GREEN "\033[32m"
#define RESET "\033[0m"
int main(){
int current[P_COUNT][R_COUNT] = {
{1,2,3},
{2,0,4},
{1,1,1},
{3,4,1},
{2,3,2},
{5,2,1},
{2,1,1}
};
int max[P_COUNT][R_COUNT] = {
{3,4,5},
{3,1,5},
{4,3,4},
{5,4,2},
{3,4,4},
{6,3,2},
{4,2,2}
};
int avail[R_COUNT] = {1,1,1};
printf("Currently Allocated: \n");
int i,j;
for (i = 0; i < P_COUNT; ++i)
{
for ( j = 0; j < R_COUNT; ++j)
{
printf(" %d ", current[i][j]);
}
printf("\n");
}
printf("Max Capacity: \n");
for (i = 0; i < P_COUNT; ++i)
{
for ( j = 0; j < R_COUNT; ++j)
{
printf(" %d ", max[i][j]);
}
printf("\n");
}
printf("Remaining : \n");
for ( j = 0; j < R_COUNT; ++j)
{
printf(" %d ", avail[j]);
}
printf("\n");
printf("Total Capacity: \n");
int r[R_COUNT] = {0};
for (i = 0; i < P_COUNT; ++i)
{
r[0] += (current[i][0]);
r[1] += (current[i][1]);
r[2] += (current[i][2]);
}
r[0] += avail[0];
r[1] += avail[1];
r[2] += avail[2];
for ( i = 0; i < R_COUNT; ++i)
{
printf("resource %d = %d \n",i+1 , r[i] );
}
int lim[R_COUNT];
int k;
for ( k = 0; k < P_COUNT; ++k)
{
for (i = 0; i < P_COUNT; ++i)
{
for ( j = 0; j < R_COUNT; ++j)
{
lim[j] = current[i][j] + avail[j];
}
int complete = 1;
for (j = 0; j < R_COUNT; ++j)
{
if (lim[j] < max[i][j])
{
complete = 0;
}
}
if (complete == 1)
{
printf(GREEN"\nProcess %d complete ", i );
printf(RESET"\n");
avail[0] += current[i][0];
avail[1] += current[i][1];
avail[2] += current[i][2];
current[i][0] = -100;
current[i][1] = -100;
current[i][2] = -100;
printf(RED"\nAvail : %d %d %d ", avail[0],avail[1],avail[2]);
printf(RESET"\n");
}
}
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int i = 0;
int num = 0;
int a = 0;
for (i = 100; i <= 200; i++)
{
for (num = 2, a = 0; num <= (i - 1); num++)
{
if (i % num == 0)
a++;
}
if (a == 0)
printf("%d ", i);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include "network.h"
#include "error.h"
// Author: Gordon Gao
// Implements the client of the application layer
int main(int argc, char* argv[])
{
struct timeval start, end;
// File pointer and strings to concatenate to make
FILE *ifp;
char photoFile[255];
// Creates string for file to load
static int id;
#define BUFFER_SIZE 200
int DEBUG = 1;
int i;
// Checks for correct input
if(argc == 4)
{
id = atoi(argv[2]);
int numphotos = atoi(argv[3]);
char filename[20];
sprintf(filename, "client_%d.log", id);
logfile = fopen(filename, "w");
gettimeofday(&start, NULL);
// Initializes handshake between client and server.
net_connect(id,numphotos, argv[1]);
for(i = 0;i < numphotos; i++)
{
strcpy ( photoFile, "photo");
// Appends input into one string for file access
// photoij.jpg
strcat(photoFile, argv[2]);
char photoIndex[5];
sprintf(photoIndex, "%d", i);
strcat(photoFile, photoIndex);
strcat(photoFile, ".jpg");
// Debug to check which file is being opened
if(DEBUG)
printf("Sending %s...\n" , photoFile);
ifp = fopen(photoFile, "r");
// Error Check if cannot open file
if (ifp == NULL)
{
printf("Can't open input file! \n");
exit(1);
}
// Buffer set to 200 bytes
char buffer[200];
int len;
do
{
len = fread(buffer,1,200,ifp);
net_send(buffer, len, len != 200);
} while (len == 200);
} // end of for loop
phy_close();
gettimeofday(&end, NULL);
char message[250];
unsigned long long int startMicros = start.tv_sec * 1000000 + start.tv_usec;
unsigned long long int endMicros = end.tv_sec * 1000000 + end.tv_usec;
sprintf(message, "Total transfer time: %llu seconds and %llu microseconds", (endMicros - startMicros) / 1000000, (endMicros - startMicros) % 1000000);
log_msg(message);
sprintf(message, "Frames sent: %d, frame retransmissions: %d, good ACKs: %d, error ACKs: %d", totalFrames, totalFramesResent, totalAcks, totalAckErrors);
log_msg(message);
fclose(logfile);
}
else
{
printf("Please use the format, ./client servermachine id num_photos");
exit(1);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main()
{
int i, sum = 0;
int n=0;
//allocate space for how many words you want
printf("how many words you want: ");
int words;
n=scanf( "%i", &words );
char *letter[words];
char tep[256]; //placeholder for the words which will be used in letter
int number;
for (i=0;n>i;i++) //gets all the words
{
printf("enter the %i word: ",i);
scanf( "%s", tep );
number= strlen(tep);
letter[i] = (char*)malloc(number * sizeof(char)+1);
strcpy(letter[i], tep); //copy streng, has to arguments strcpy(streng to, from streng)
}
//print all words in letter
for (i=0; n>i;i++)
{
printf("\n %s \n",letter[i]);
free(letter[i]);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
static int controlling = 1;
int esAcotadoI(int num, int minimo){
return(num>=minimo);
}
int esAcotadoM(int num, int maximo){
return(num<=maximo);
}
int esAcotado(int num, int minimo, int maximo){
return(esAcotadoI(num, minimo) && esAcotadoM(num, maximo));
}
int dEsAcotadoI(double num, double minimo, int infimo){
if(num>minimo){
return 1;
}
else if(num==minimo && infimo){
return 1;
}
return 0;
}
int dEsAcotadoM(double num, double maximo, int supremo){
if(num<maximo){
return 1;
}
else if(num==maximo && supremo){
return 1;
}
return 0;
}
int dEsAcotado(double num, double minimo, int infimo, double maximo, int supremo){
return(dEsAcotadoI(num, minimo, infimo) && dEsAcotadoM(num, maximo, supremo));
}
//Ints
int nextInt (){
int controlling = 1;
int resultado;
char a[12];;/*Creo el array de char donde vamos a guardar la entrada,
el tamaño es 10 ya que el int maximo no tiene más digitos,
necesitamos otro más que contiene \0 y otro para contemplar números negativos*/
char pos;//Para saber lo que contiene la posición del array
char pos2;
int ii;//Para tener controlado el indice del array
int cont;//Para que no nos pasemos de los 10 digitos del array
int signo;//Lo necesitaremos para contemplar numeros negativos
char peta[10] = {8, 5, 8, 9, 9, 3, 4, 5, 9, 1};//Si el número que nos da el usuario es mayor que este, desbordará por segunda vez.
while(controlling){
ii = 0;
cont = 13;
signo = 1;
scanf("%s", a);
pos = a[0];//inicializamos con el primer valor del array
if((pos == '-') && esAcotado(a[1], 48, 57)){
signo = -1;
a[0]='0';
pos = a[0];
cont++;
}
while((pos != '\0') && cont){/*Evaluamos cada posición de la cadena, debe estar entre 48 y 57 que son los caracteres de los números.
Si no es un numero o no contiene \0 (han introducido demasiados caracteres), explota y volvemos a pedir.*/
if(!esAcotado(pos, 48, 57)){//Comprobamos que es un numero
cont = 1;//No es un valor valido, salimos el bucle y volvemos a empezar, ponemos 1 porque despues decrementamos
printf("No has introducido un valor valido, prueba otra vez.\n");
}
ii++;
cont--;
pos = a[ii];
}
resultado = atoi(a);//Todo está casi en orden, pasamos la cadena a int y vamos a comprobar que no desborde.
if(cont <= 3 && resultado>=0){
if(signo<0){
ii = 1;
}
else{
ii = 0;
}
while(ii<10){
pos = a[ii];
pos2 = peta[ii];
if(pos <= pos2){
}
else{
cont = 0;//Ha desbordado y ponemos el resultado a -1 para que salga el mensaje
resultado = -1;
}
ii++;
}
}
if(cont && (resultado>=0)){
resultado = resultado*signo;
return resultado;
}
else if(resultado<0){
printf("El valor introducido desborda, prueba otra vez\n");
}
}
return 0;
}
int nextIntAcotadoI(int minimo){//Scanea un int acotado inferiormente siempre coge la cota
int num = 0;
while(controlling){
scanf("%i", &num);
if(esAcotadoI(num, minimo)){
return num;
}
else{
printf("El número esta por debajo de %i, mete un número correcto\n", minimo);
}
}
return num;
}
int nextIntAcotadoM(int maximo){
int num = 0;
while(controlling){
scanf("%i", &num);
if(esAcotadoM(num, maximo)){
return num;
}
else{
printf("El número está por encima de %i, mete un número correcto\n", maximo);
}
}
return num;
}
int nextIntAcotado(int minimo, int maximo){
int num = 0;
while(controlling){
scanf("%i", &num);
if(esAcotadoM(num, maximo) && esAcotadoI(num, minimo)){
return num;
}
else{
printf("El número debe estar comprendido entre %i y %i, mete un número correcto\n", minimo, maximo);
}
}
return num;
}
/*
int nextInt_Intervalo(int min, int max){//Scanea ints en un intervalo
int aux = 0;
while (controlling){
try{
Scanner sc = new Scanner(System.in);
aux = sc.nextInt();
rango(aux, min, max);
return aux;
}
catch(InputMismatchException ex){
System.out.println("Creia que sabias lo que era un número entero");
System.out.println("Intentalo otra vez anda");
}
catch(ExceptionIntervalo ex){
System.out.println("Si tu respuesta esta en el intervalo lógico de mi pregunta estaria genial");
}
}
return aux;
}
*/
/*ROTO
double nextDouble_Intervalo(double min, double max, int infimo, int supremo){//Scanea doubles en un intervalo
double aux = 0;
while (controlling){
try{
Scanner sc = new Scanner(System.in);
aux = sc.nextDouble();
rango(aux, min, max);
return aux;
}
catch(InputMismatchException ex){
System.out.println("Creia que sabias lo que era un número entero");
System.out.println("Intentalo otra vez anda");
}
catch(ExceptionIntervalo ex){
System.out.println("Si tu respuesta esta en el intervalo lógico de mi pregunta estaria genial");
}
}
return aux;
}
*/
//Doubles
/*
double nextDouble(){//Scanea Doubles de forma segura
double num = 0;
while (controlling){
try{
scanf("%i", &num);
return num;
}
catch(InputMismatchException ex){
System.out.println("Creia que sabias lo que era un número real");
System.out.println("Intentalo otra vez anda");
}
}
return num;
}
*/
double nextDoubleAcotadoI(double minimo, int infimo){//Scanea un double acotado inferiormente. HACER PARA SUPERIOr, INTERVALO ACOTADO Y LO MISMO PARA INTS
double num = 0;
while(controlling){
scanf("%lf", &num);
if(dEsAcotadoI(num, minimo, infimo)){
return num;
}
else{
printf("El número esta por debajo de la cota, mete un número correcto\n");
}
}
return num;
}
double nextDoubleAcotadoM(double maximo, int supremo){//Scanea un double acotado inferiormente. HACER PARA SUPERIOr, INTERVALO ACOTADO Y LO MISMO PARA INTS
double num = 0;
while(controlling){
scanf("%lf", &num);
if(dEsAcotadoM(num, maximo, supremo)){
return num;
}
else{
printf("El número esta por debajo de la cota, mete un número correcto\n");
}
}
return num;
}
//Strings
/*
char[] next(){//Recoger un String facilmente
Scanner sc = new Scanner(System.in);
String respuesta = sc.next();
return respuesta;
}
*/
/*
void nextText(char * cadena){//Recoger un texto facilmente
scanf("%[^'\n']s",cadena);
}
*/
/*
char[] nextMultiple(){//Recoger varios Strings. Este metodo puede dar problemas si pretendes usarlo repetidamente en un mismo array
char [] aux = nextText();
String delimitadores= " ";
String[] palabrasSeparadas = aux.split(delimitadores);
return palabrasSeparadas;
}
*/
/* Se rompe en consecuencia
int nextCharConcreto(char a, int importanMayus){
if(importanMayus){
return(next().equals(a));
}
return(next().equalsIgnoreCase(a));
}
*/
|
C
|
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define NUMBER '0'
#define BUFSIZE 100
#define MAXVAL 100
int sp = 0;
double val[MAXVAL];
int getop(char *);
void push(double);
double pop(void);
main(int argc,char *argv[]){
int i,type;
double op2;
for(i=0;i<argc-1&&(type=getop(*++argv))!='\0';i++){
switch(type){
case NUMBER:
push(atof(*argv));
break;
case '+':
push(pop()+pop());
break;
case 'x':
push(pop()*pop());
break;
case '-':
op2 = pop();
push(pop()-op2);
break;
case '/':
op2 = pop();
if(op2!=0.0)
push(pop()/op2);
else
printf("error: zero divisor\n");
break;
default:
printf("error: unknown command %s\n",t);
break;
}
}
printf("\t%.8g\n",pop());
return 0;
}
int getop(char *s){
int c;
if(*s == '\0'){
return '\0';
}
c=*s;
if(!isdigit(c)&&c!='.')
return c;
return NUMBER;
}
void push(double f){
if(sp<MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can't push %g\n",f);
}
double pop(void){
if(sp>0)
return val[--sp];
else{
printf("error: stack empty\n");
return 0.0;
}
}
|
C
|
/*
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/lib"
gcc main.c -o server -lSDL2 -lSDL2_net
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_net.h>
//-----------------------------------------------------------------------------
#define MAX_PACKET 0xFF
#define MAX_SOCKETS 0x04
#define SERVER_SOCKET 0x00
//-----------------------------------------------------------------------------
#define WOOD_WAIT_TIME 5000
//-----------------------------------------------------------------------------
#define FLAG_WOOD_UPDATE 0x0010
//-----------------------------------------------------------------------------
typedef struct {
int in_use;
int questing;
uint8_t amt_wood;
uint32_t timer_wood;
} Client;
//-----------------------------------------------------------------------------
int next_ind = 1;
Client clients[MAX_SOCKETS];
SDLNet_SocketSet socket_set;
TCPsocket sockets[MAX_SOCKETS];
//-----------------------------------------------------------------------------
void CloseSocket(int index) {
if(sockets[index] == NULL) {
fprintf(stderr, "ER: Attempted to delete a NULL socket.\n");
return;
}
if(SDLNet_TCP_DelSocket(socket_set, sockets[index]) == -1) {
fprintf(stderr, "ER: SDLNet_TCP_DelSocket: %s\n", SDLNet_GetError());
exit(-1);
}
memset(&clients[index], 0x00, sizeof(Client));
SDLNet_TCP_Close(sockets[index]);
sockets[index] = NULL;
}
//-----------------------------------------------------------------------------
int AcceptSocket(int index) {
if(sockets[index]) {
fprintf(stderr, "ER: Overriding socket at index %d.\n", index);
CloseSocket(index);
}
sockets[index] = SDLNet_TCP_Accept(sockets[SERVER_SOCKET]);
if(sockets[index] == NULL) return 0;
clients[index].in_use = 1;
if(SDLNet_TCP_AddSocket(socket_set, sockets[index]) == -1) {
fprintf(stderr, "ER: SDLNet_TCP_AddSocket: %s\n", SDLNet_GetError());
exit(-1);
}
return 1;
}
//-----------------------------------------------------------------------------
void SendData(int index, uint8_t* data, uint16_t length, uint16_t flag) {
uint8_t temp_data[MAX_PACKET];
int offset = 0;
memcpy(temp_data+offset, &flag, sizeof(uint16_t));
offset += sizeof(uint16_t);
memcpy(temp_data+offset, data, length);
offset += length;
int num_sent = SDLNet_TCP_Send(sockets[index], temp_data, offset);
if(num_sent < offset) {
fprintf(stderr, "ER: SDLNet_TCP_Send: %s\n", SDLNet_GetError());
CloseSocket(index);
}
}
//-----------------------------------------------------------------------------
uint8_t* RecvData(int index, uint16_t* length, uint16_t* flag) {
uint8_t temp_data[MAX_PACKET];
int num_recv = SDLNet_TCP_Recv(sockets[index], temp_data, MAX_PACKET);
if(num_recv <= 0) {
CloseSocket(index);
const char* err = SDLNet_GetError();
if(strlen(err) == 0) {
printf("DB: client disconnected\n");
} else {
fprintf(stderr, "ER: SDLNet_TCP_Recv: %s\n", err);
}
return NULL;
} else {
int offset = 0;
*flag = *(uint16_t*) &temp_data[offset];
offset += sizeof(uint16_t);
*length = (num_recv-offset);
uint8_t* data = (uint8_t*) malloc((num_recv-offset)*sizeof(uint8_t));
memcpy(data, &temp_data[offset], (num_recv-offset));
return data;
}
}
//-----------------------------------------------------------------------------
int main(int argc, char** argv) {
if(SDL_Init(SDL_INIT_TIMER|SDL_INIT_EVENTS) != 0) {
fprintf(stderr, "ER: SDL_Init: %s\n", SDL_GetError());
exit(-1);
}
if(SDLNet_Init() == -1) {
fprintf(stderr, "ER: SDLNet_Init: %s\n", SDLNet_GetError());
exit(-1);
}
IPaddress ip;
if(SDLNet_ResolveHost(&ip, NULL, 8099) == -1) {
fprintf(stderr, "ER: SDLNet_ResolveHost: %s\n", SDLNet_GetError());
exit(-1);
}
sockets[SERVER_SOCKET] = SDLNet_TCP_Open(&ip);
if(sockets[SERVER_SOCKET] == NULL) {
fprintf(stderr, "ER: SDLNet_TCP_Open: %s\n", SDLNet_GetError());
exit(-1);
}
socket_set = SDLNet_AllocSocketSet(MAX_SOCKETS);
if(socket_set == NULL) {
fprintf(stderr, "ER: SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
exit(-1);
}
if(SDLNet_TCP_AddSocket(socket_set, sockets[SERVER_SOCKET]) == -1) {
fprintf(stderr, "ER: SDLNet_TCP_AddSocket: %s\n", SDLNet_GetError());
exit(-1);
}
int running = 1;
while(running) {
int num_rdy = SDLNet_CheckSockets(socket_set, 1000);
if(num_rdy <= 0) {
// NOTE: none of the sockets are ready
int ind;
for(ind=0; ind<MAX_SOCKETS; ++ind) {
if(!clients[ind].in_use) continue;
/*
if(clients[ind].questing &&
(SDL_GetTicks()-clients[ind].timer_wood)>WOOD_WAIT_TIME
) {
clients[ind].questing = 0;
clients[ind].amt_wood += 4;
char msg[0xFF] = "> quest complete\n\r";
SendData(ind, msg, (strlen(msg)+1));
}
*/
clients[ind].amt_wood += 4;
/*
uint16_t length = 0;
uint8_t data[MAX_PACKET];
memcpy(data+length, &clients[ind].amt_wood, sizeof(uint8_t));
length += sizeof(uint8_t);
SendData(ind, data, length, FLAG_WOOD_UPDATE);
*/
}
} else {
int ind;
for(ind=0; (ind<MAX_SOCKETS) && num_rdy; ++ind) {
if(sockets[ind] == NULL) continue;
if(!SDLNet_SocketReady(sockets[ind])) continue;
if(ind == SERVER_SOCKET) {
int got_socket = AcceptSocket(next_ind);
if(!got_socket) {
num_rdy--;
continue;
}
// NOTE: get a new index
int chk_count;
for(chk_count=0; chk_count<MAX_SOCKETS; ++chk_count) {
if(sockets[(next_ind+chk_count)%MAX_SOCKETS] == NULL) break;
}
next_ind = (next_ind+chk_count)%MAX_SOCKETS;
printf("DB: new connection (next_ind = %d)\n", next_ind);
num_rdy--;
} else {
uint8_t* data;
uint16_t flag;
uint16_t length;
data = RecvData(ind, &length, &flag);
if(data == NULL) {
num_rdy--;
continue;
}
switch(flag) {
case FLAG_WOOD_UPDATE: {
uint16_t offset = 0;
uint8_t send_data[MAX_PACKET];
memcpy(send_data+offset, &clients[ind].amt_wood, sizeof(uint8_t));
offset += sizeof(uint8_t);
SendData(ind, send_data, offset, FLAG_WOOD_UPDATE);
} break;
}
/*
uint8_t* data; int length;
data = RecvData(ind, &length);
if(data == NULL) {
num_rdy--;
continue;
}
int i;
for(i=0; i<length; ++i) {
if(data[i] == '\n') data[i] = '\0';
if(data[i] == '\r') data[i] = '\0';
}
// TEMP: add a NULL terminator
data = (uint8_t*) realloc(data, (length+1));
data[length] = '\0';
int was_processed = 0;
if(!strcmp(data, "exit")) {
was_processed = 1;
running = 0;
} else if(!strcmp(data, "quit")) {
was_processed = 1;
CloseSocket(ind);
} else if(!strcmp(data, "get data")) {
was_processed = 1;
char msg[0xFF] = {};
sprintf(msg, "> wood: %d\n\r", clients[ind].amt_wood);
//SendData(ind, msg, (strlen(msg)+1));
} else if(!strcmp(data, "quest")) {
was_processed = 1;
if(!clients[ind].questing) {
clients[ind].questing = 1;
clients[ind].timer_wood = SDL_GetTicks();
char msg[0xFF] = "> started quest\n\r";
//SendData(ind, msg, (strlen(msg)+1));
} else {
char msg[0xFF] = "> currently running quest\n\r";
//SendData(ind, msg, (strlen(msg)+1));
}
}
if(was_processed) printf("PR: %s\n", data);
free(data);
*/
num_rdy--;
}
}
}
}
int i;
for(i=0; i<MAX_SOCKETS; ++i) {
if(sockets[i] == NULL) continue;
CloseSocket(i);
}
SDLNet_FreeSocketSet(socket_set);
SDLNet_Quit();
SDL_Quit();
return 0;
}
|
C
|
/*
* File: main.c
* Author: George Main IV
*
* Created on August 1, 2017, 7:56 PM
*/
#include "configurationBits.h"
#include "main.h"
#include "device.h"
#include "uart.h"
#include <xc.h>
#include <stdio.h>
#include <libpic30.h>
#include <p33ev256gm102.h>
int main(void) {
// Initialize oscillator
device_initialize();
// Set all TRIS, ANSEL, and PORT to 0
TRISA = ANSELA = PORTA = 0x00;
TRISB = ANSELB = PORTB = 0x00;
// Turn on power LED
POWER = 1;
// Initialize UART
uart_init();
printf("UART Initialized\n");
// Enable interrupts
device_enableInterrupts();
printf("Interrupts Enabled\n");
printf("ID: %i\n", ID);
printf("Starting Loop\n");
while(1) {
// Check UART
if (U1STAbits.FERR == 1) {
continue;
}
/* Must clear the overrun error to keep UART receiving */
if (U1STAbits.OERR == 1) {
U1STAbits.OERR = 0;
continue;
}
}
return 0;
}
|
C
|
#pragma once
/************************************************************************/
//----------------------------------------------------------------------//
/**
* @LCDɕ\B
*
* _adrs : \ꏊ
* _char : \镶
*/
inline void LCD_Write_char (const LcdAdrs _adrs, const char _char)
{
PUT_LCD(_adrs, _char);
}
//----------------------------------------------------------------------//
/**
* @LCDɕ\B
*
* _adrs : \̐擪̏ꏊ
* _str : \镶
*/
inline void LCD_Write_str (const LcdAdrs _adrs, const char _str[])
{
STR_LCD(_adrs, _str);
}
//----------------------------------------------------------------------//
/**
* @lLCDɕ\B
*
* _adrs : \̐擪̏ꏊ
* _number : \鐔l
* _digit : \
* decimal : \i (2 ` 16i܂)
*/
inline void LCD_Write_num
(
const LcdAdrs _adrs,
unsigned long _number,
const Digit _digit,
const Decimal _decimal
)
{
PUT_NUM(_adrs, _number, _digit, _decimal);
}
//----------------------------------------------------------------------//
/************************************************************************/
|
C
|
// cc -std=c99 -D_BSD_SOURCE -Os closure-demo.c -lm
#if (!defined(__unix__) && !defined(__APPLE__)) || !defined(__x86_64__)
# error Requires x86_64 and System V ABI
#endif
/* Closure functions. */
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
static void
closure_set_data(void *closure, void *data)
{
void **p = closure;
p[-2] = data;
}
static void
closure_set_function(void *closure, void *f)
{
void **p = closure;
p[-1] = f;
}
static unsigned char thunk[6][13] = {
{
0x48, 0x8b, 0x3d, 0xe9, 0xff, 0xff, 0xff,
0xff, 0x25, 0xeb, 0xff, 0xff, 0xff
}, {
0x48, 0x8b, 0x35, 0xe9, 0xff, 0xff, 0xff,
0xff, 0x25, 0xeb, 0xff, 0xff, 0xff
}, {
0x48, 0x8b, 0x15, 0xe9, 0xff, 0xff, 0xff,
0xff, 0x25, 0xeb, 0xff, 0xff, 0xff
}, {
0x48, 0x8b, 0x0d, 0xe9, 0xff, 0xff, 0xff,
0xff, 0x25, 0xeb, 0xff, 0xff, 0xff
}, {
0x4C, 0x8b, 0x05, 0xe9, 0xff, 0xff, 0xff,
0xff, 0x25, 0xeb, 0xff, 0xff, 0xff
}, {
0x4C, 0x8b, 0x0d, 0xe9, 0xff, 0xff, 0xff,
0xff, 0x25, 0xeb, 0xff, 0xff, 0xff
},
};
static void *
closure_create(void *f, int nargs, void *userdata)
{
long page_size = sysconf(_SC_PAGESIZE);
int prot = PROT_READ | PROT_WRITE;
int flags = MAP_ANONYMOUS | MAP_PRIVATE;
char *p = mmap(0, page_size * 2, prot, flags, -1, 0);
if (p == MAP_FAILED)
return 0;
void *closure = p + page_size;
memcpy(closure, thunk[nargs - 1], sizeof(thunk[0]));
mprotect(closure, page_size, PROT_READ | PROT_EXEC);
closure_set_function(closure, f);
closure_set_data(closure, userdata);
return closure;
}
static void
closure_destroy(void *closure)
{
long page_size = sysconf(_SC_PAGESIZE);
munmap((char *)closure - page_size, page_size * 2);
}
/* Coordinates */
#include <math.h>
struct coord {
float x;
float y;
};
static inline float
distance(const struct coord *a, const struct coord *b)
{
float dx = a->x - b->x;
float dy = a->y - b->y;
return sqrtf(dx * dx + dy * dy);
}
int
coord_cmp_r(const void *a, const void *b, void *target)
{
float dist_a = distance(a, target);
float dist_b = distance(b, target);
if (dist_a < dist_b)
return -1;
else if (dist_a > dist_b)
return 1;
else
return 0;
}
/* Demo */
#include <stdio.h>
#include <stdlib.h>
#define N 64
int
main(void)
{
/* Create random coordinates. */
size_t ncoords = N;
struct coord coords[N];
struct coord target = {
1000.0f * rand() / (float)RAND_MAX,
1000.0f * rand() / (float)RAND_MAX
};
for (int i = 0; i < N; i++) {
coords[i].x = 1000.0f * rand() / (float)RAND_MAX;
coords[i].y = 1000.0f * rand() / (float)RAND_MAX;
}
/* Sort using a closure. */
int (*closure)(const void *, const void *);
closure = closure_create(coord_cmp_r, 3, &target);
qsort(coords, ncoords, sizeof(coords[0]), closure);
closure_destroy(closure);
/* Print results. */
printf("target =% 7.5g,% 7.5g\n", target.x, target.y);
for (int i = 0; i < N; i++)
printf("% 7.5g,% 7.5g -> %.9g\n",
coords[i].x, coords[i].y,
distance(coords + i, &target));
}
|
C
|
#include <config.h>
#include <file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int MapFile(PT_FileMap ptFileMap)
{
int iFd;
FILE *tFp;
struct stat tStat;
tFp = fopen(ptFileMap->strFileName, "r+");
if (tFp == NULL)
{
DBG_PRINTF("can't open %s\n", ptFileMap->strFileName);
return -1;
}
ptFileMap->tFp = tfp;
iFd = fileno(tFp);
fstat(iFd, &tStat);
ptFileMap->iFileSize = tStat.st_size;
ptFileMap->pucFileMapMem = (unsigned char *)mmap(NULL, tStat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, iFd, 0);
if (ptFileMap->pucFileMapMem == (unsigned char *)-1)
{
DBG_PRINTF("mmap error!\n");
return -1;
}
return 0;
}
void UnMapFile(PT_FileMap ptFileMap)
{
munmap(ptFileMap->pucFileMapMem, ptFileMap->iFileSize);
fclose(ptFileMap->tFp);
}
|
C
|
#include <stdio.h>
#include <assert.h>
/***strspn()函数检索区分大小写***/
int my_strspn(const char *str1, const char *str2)
{
/***从参数str1字符串的开头计算连续的字符,而这些字符都完全是str2所指字符串中的字符。
简单的说,若strspn()返回的数值为n,则代表字符串str1开头连续有n个字符都是属于字符串str2内的字符***/
assert(str1 != NULL && str2 != NULL);
const char *tmp = str1;
const char *str3;
while(*tmp)
{
for(str3 = str2; *str3; ++str3)
{
if(*str3 == *tmp) //判断str1是否存在str2的字符
break;
}
if(*str3 == '\0') //如果str2结束则跳出循环str1++
break;
tmp++;
}
return tmp - str1; //返回差值,即str1共有几个连续的字符是str2中存在的
}
int main()
{
char s1[] = "hello world!";
char s2[] = "i am lihua";
int p = my_strspn(s1, s2);
printf("The result is:%d\n", p);
return 0;
}
|
C
|
/*
* funcionesConsola.c
*
* Created on: 26/5/2016
* Author: utnso
*/
#include <stdio.h>
#include <stdlib.h>
#include <commons/log.h>
#include <commons/collections/list.h>
#include <commons/config.h>
#include "consola.h"
#include <string.h>
void empaquetarYenviarArchivo(t_archivo* archivo){
char* contenido= malloc(sizeof(int)*2 + archivo->tamArchivo + strlen(archivo->ansiSOP)+1);
t_contenido* paquete =malloc(sizeof(t_contenido));
int offset=0;
int tmp_size=sizeof(int)*2;
memcpy(contenido, &(archivo->protocolo), tmp_size);
offset+= tmp_size;
memcpy(contenido + offset, &(archivo->tamArchivo), tmp_size=archivo->tamArchivo);
offset+= tmp_size;
tmp_size=strlen(archivo->ansiSOP);
memcpy(contenido + offset, &(archivo->ansiSOP), tmp_size+1);
paquete->tamanio= offset+ tmp_size;
paquete->contenido= contenido;
send(socket_nucleo,paquete,sizeof(paquete),0);
free(contenido);
free(paquete);
}
int tamArchivo(char * direccionArchivo) {
FILE * fp;
int tamanioArchivo;
fp = fopen(direccionArchivo, "r");
if (fp == NULL)
puts("Error al abrir archivo");
else {
fseek(fp, 0, SEEK_END);
tamanioArchivo = ftell(fp);
fclose(fp);
printf("El tamaño de %s es: %d bytes.\n\n", direccionArchivo, tamanioArchivo);
}
return tamanioArchivo;
}
char* obtenerContenidoAnSISOP(char * direccionArchivo) {
FILE * fp;
fp = fopen(direccionArchivo, "r");
if (fp == NULL){
puts("Error al abrir archivo");
}else {
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buffer = (char *) malloc(fsize + 1);
if(buffer==NULL){
printf("no se pudo reservar memoria para el archivo");
return "";
}
fread(buffer, fsize, 1, fp);
buffer[fsize] = '\0';
fclose(fp);
printf("%s", buffer);
return buffer;
}
return "";
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* calc_effective_letter.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fdexheim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/05/17 14:08:59 by fdexheim #+# #+# */
/* Updated: 2018/10/11 15:23:56 by fdexheim ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/nm.h"
static char get_letter_from_segname(const char *sectname, t_symbol *sym)
{
if (strcmp_ghetto(sectname, SECT_TEXT) == 0)
return ('T');
else if (strcmp_ghetto(sectname, SECT_DATA) == 0)
return ('D');
else if (strcmp_ghetto(sectname, SECT_BSS) == 0)
return ('B');
else if (strcmp_ghetto(sectname, SECT_COMMON) == 0
&& sym->n_type & N_EXT && sym->n_type & N_UNDF && sym->n_value != 0)
return ('C');
else
return ('S');
}
static char get_from_n_sect(const t_obj_ctrl macho_ctrl, t_symbol *sym)
{
struct section_64 *sec64;
struct section *sec;
sec = NULL;
sec64 = NULL;
if (is_64(macho_ctrl.m_num))
{
sec64 = get_section_from_number_64(macho_ctrl, sym->n_sect);
return (get_letter_from_segname(sec64->sectname, sym));
}
else
{
sec = get_section_from_number(macho_ctrl, sym->n_sect);
return (get_letter_from_segname(sec->sectname, sym));
}
return ('?');
}
static char get_from_n_type(t_symbol *sym)
{
uint8_t a;
a = sym->n_type & N_TYPE;
if (a == N_UNDF && sym->n_value != 0)
return ('C');
else if (a == N_UNDF)
return ('U');
else if (a == N_ABS)
return ('A');
else if (a == N_PBUD)
return ('P');
else if (a == N_INDR)
return ('I');
return ('?');
}
char calc_effective_letter(const t_obj_ctrl macho_ctrl,
t_symbol *sym)
{
char ret;
ret = '?';
if (sym->n_type == 0 && sym->n_sect == 0)
return ('?');
if (sym->n_type & N_STAB)
return ('-');
if ((sym->n_type & N_TYPE) != N_SECT)
ret = get_from_n_type(sym);
else if ((sym->n_type & N_TYPE) == N_SECT)
ret = get_from_n_sect(macho_ctrl, sym);
else if (sym->n_type & N_PEXT)
ret = 'E';
else
ret = '?';
if (!(sym->n_type & N_EXT))
ret = lowercase_ghetto(ret);
return (ret);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_utoa2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: qhonore <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/11/29 12:22:07 by qhonore #+# #+# */
/* Updated: 2016/09/23 08:40:46 by qhonore ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int intlen(size_t nbr)
{
int i;
i = 0;
if (nbr == 0)
return (1);
while (nbr)
{
nbr /= 10;
i++;
}
return (i);
}
char *ft_uctoa(unsigned char nbr)
{
char *s;
int i;
unsigned char div;
div = 1;
i = intlen(nbr);
s = (char*)malloc(sizeof(char) * (i + 1));
s[i] = '\0';
while (--i >= 0)
{
s[i] = ((nbr / div) % 10) + '0';
div *= 10;
}
return (s);
}
char *ft_usitoa(unsigned short int nbr)
{
char *s;
int i;
unsigned short int div;
div = 1;
i = intlen(nbr);
s = (char*)malloc(sizeof(char) * (i + 1));
s[i] = '\0';
while (--i >= 0)
{
s[i] = ((nbr / div) % 10) + '0';
div *= 10;
}
return (s);
}
char *ft_uimtoa(uintmax_t nbr)
{
char *s;
int i;
uintmax_t div;
div = 1;
i = intlen(nbr);
s = (char*)malloc(sizeof(char) * (i + 1));
s[i] = '\0';
while (--i >= 0)
{
s[i] = ((nbr / div) % 10) + '0';
div *= 10;
}
return (s);
}
|
C
|
#include "test_match_item.h"
#include <check.h>
#include <stdlib.h>
#include "test_test_helpers.h"
#include "../src/core/match_item.h"
START_TEST (test_get_n_items)
{
MatchItem f1;
MatchItem f2;
MatchItem f3;
MatchItem f4;
f1.next = &f2;
f1.index = 0;
f2.next = &f3;
f2.index = 1;
f3.next = &f4;
f3.index = 2;
f4.next = NULL;
f4.index = 3;
MatchItem * f5 = MatchItem_getNItems(&f1, 3);
ck_assert_int_eq(f5->index, 0);
ck_assert_int_eq(f5->next->index, 1);
ck_assert_int_eq(f5->next->next->index, 2);
ck_assert_ptr_null(f5->next->next->next);
}
END_TEST
START_TEST (test_copy_single)
{
MatchItem f1;
MatchItem f2;
f1.next = &f2;
f1.index = 0;
f1.path = "path1_value";
f2.next = NULL;
f2.index = 1;
f2.path = "path2_value";
MatchItem * f3 = MatchItem_copySingle(&f1);
ck_assert_int_eq(f3->index, 0);
ck_assert_str_eq(f3->path, "path1_value");
ck_assert_ptr_null(f3->next);
ck_assert_ptr_ne(f3, &f1);
}
END_TEST
START_TEST (test_get_item_n)
{
MatchItem f1;
MatchItem f2;
MatchItem f3;
f1.next = &f2;
f1.index = 0;
f1.path = "path1_value";
f2.next = &f3;
f2.index = 1;
f2.path = "path2_value";
f3.next = NULL;
f3.index = 2;
f3.path = "path3_value";
MatchItem * f4 = MatchItem_getItemN(&f1, 1);
ck_assert_ptr_eq(f4, &f2);
}
END_TEST
Suite * test_MatchItem_suite(void)
{
Suite *s;
TCase *tc_core;
s = suite_create("MatchItem");
tc_core = tcase_create("Core");
tcase_add_test(tc_core, test_get_n_items);
tcase_add_test(tc_core, test_copy_single);
tcase_add_test(tc_core, test_get_item_n);
suite_add_tcase(s, tc_core);
return s;
}
int test_MatchItem_getFailed()
{
TEST_HELPERS_GET_FAILED(test_MatchItem_suite);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.