language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>//exit();
#include <pthread.h>
void thread_1(void)
{
int i=0;
for(i=0;i<=6;i++)
{
printf("This is a pthread_1.\n");
if(i==2)
//用pthread_exit()来调用线程的返回值,用来退出线程,但是退出线程所占用的资源不会随着线程的终止而得到释放
pthread_exit(0);
sleep(1);
}
}
void thread_2(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread_2.\n");
//用pthread_exit()来调用线程的返回值,用来退出线程,但是退出线程所占用的资源不会随着线程的终止而得到释放
//pthread_exit(0);
exit(0);
}
int main(void)
{
pthread_t id_1,id_2;
int ret;
ret=pthread_create(&id_1,NULL,(void *) thread_1,NULL);
if(ret!=0)
{
printf("Create pthread error!\n");
return -1;
}
ret=pthread_create(&id_2,NULL,(void *) thread_2,NULL);
if(ret!=0)
{
printf("Create pthread error!\n");
return -1;
}
pthread_join(id_1,NULL);
pthread_join(id_2,NULL);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int a = 10;
int *b = &a;
int **c = &b;
//address of a
printf("%d\n", &a);
printf("%d\n", b);
printf("%d\n", *c);
//value of a
printf("%d\n", a);
printf("%d\n", *b);
printf("%d\n", **c);
//address of b
printf("%d\n", &b);
printf("%d\n", c);
//value of b
printf("%d\n", b);
printf("%d\n", *c);
//address of c
printf("%d\n", &c);
//value of c
printf("%d\n", c);
return 0;
}
|
C
|
/*
* buttons.c
*
* Reads two push buttons as inputs
* to turn on and of two LEDs as outputs.
*
* Created on: 27/07/2016
* Author: doc2
*/
#include <avr/io.h>
#include <util/delay.h>
/*
* delay_ms(delay_in_ms)
*
* Delay the specified number of milliseconds.
*
* _delay_ms uses a floating point datatype if you call
* that function in many places in your code then it becomes
* very fat. An integer is enough for us.
*
*/
void delay_ms(unsigned int xms)
{
while (xms) {
_delay_ms(0.96);
xms--;
}
}
/*
* init_ports()
*
* Initialise the ports to be used
*/
void init_ports(void)
{
/* Make bits 0 and 1 of PORTB inputs and bits 2 to 6 outputs*/
DDRB = 0x3C & 0x03f;
PORTB = 0;
}
/*
* illuminate_leds(leds)
*
* Illuminate the six LEDs connected to bits 0 to 6
* of Port B according to input leds.
*/
void illuminate_leds(int leds)
{
PORTB = leds & 0xc;
}
void main(void)
{
/* Initialise I/O Ports for use. */
init_ports();
/* Do forever... */
/* Shifts two bits of the DDRB register to the left
* to put the inputs from the buttons into
* the output port location and illuminates the leds accordingly.
*/
while (1) {
illuminate_leds(PINB << 2);
}
/* Cannot get here */
}
|
C
|
#include "str.h"
#include "blockify.h"
Sexp* bDo(Sexp *);
Sexp* bIf(Sexp*);
Sexp* bContainer(Sexp*, size_t);
Sexp* bDef(Sexp* s);
void blockify(Sexp* p) {
for (size_t i = 0; i < p->len; ++i) {
if (isDef(p->list[i])) {
p->list[i] = bDef(p->list[i]);
}
}
}
/**
* Turns (def FuncN (params ...) Type Stmt* )
* => (def FuncN (params ...) Type (do ...) )
*/
Sexp* bDef(Sexp* s) {
return bContainer(s, 3);
}
/**
* Turns (if Expr Stmt* )
* => (if Expr (do ...) )
*/
Sexp* bIf(Sexp* s) {
return bContainer(s, 1);
}
/**
* Transforms a Container of statements to have one Do-block instead.
*/
Sexp* bContainer(Sexp* s, size_t si) { // si = starting index
size_t stmt_count = s->len - si;
Sexp* block = makeSexp(copyStr("do"), stmt_count);
for (size_t i = 0; i < stmt_count; ++i) {
block->list[i] = s->list[si + i];
s->list[si + i] = NULL;
}
block = bDo(block);
s->len = si + 1;
s->list[si] = block;
return s;
}
Sexp* bDo(Sexp *b) {
for (size_t i = 0; i < b->len; ++i) {
if (isIf(b->list[i])) {
b->list[i] = bIf(b->list[i]);
} else if (isDo(b->list[i])) {
b->list[i] = bDo(b->list[i]);
}
}
return b;
}
|
C
|
// TODO: right now, the parser ignores all garbage after the ends of lines
#include "parse.h"
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdlib.h>
// error messaging macros
#define ERR "assembler: ERROR: line %u: "
#define WERR(msg, ...) sprintf(err, ERR msg, line, __VA_ARGS__);
#define SERR(msg) sprintf(err, ERR msg, line);
// true iff the given string is a valid label
// TODO: find the spec and make this conform to it
int valid_label(const char *str){
if(!isalpha(str[0])) return 0;
while(str[1] != '\0'){
if(!isalpha(str[1]) && !isdigit(str[1])) return 0;
str++;
}
return 1;
}
// duplicate a string into a new location in memory
char *strdup(const char *str){
char *ret = malloc(strlen(str)+1);
return strcpy(ret, str);
}
// true iff t is in one of the n optional arguments
int isin(int t, int n, ...){
va_list vl;
va_start(vl, n);
for(int i = 0; i < n; i++){
if(t == va_arg(vl, int)) return 1;
}
va_end(vl);
return 0;
}
// true iff the string is entirely whitespace and comment
int isempty(const char *str){
for(int i = 0; str[i] != '\0'; i++){
if(!isspace(str[i])) return 0;
}
return 1;
}
// return 2^n
long int pwr2(int p){
if(p == 0) return 1;
else return 2 * pwr2(p-1);
}
// attempt to parse a signed n-bit integer from the beginning of str
// on success: return the int; put rest of string in *r if r != 0
// on failure: set *t = -1, and write an error message to err
int32_t sint_parse(char *str, int n, type_t *t, char **r, unsigned int line,
char *err){
if(!str){
*t = -1;
WERR("reached end of line; expected %d-bit signed integer\n", n);
return 0;
}
char *ret;
long int i = strtol(str, &ret, 0);
// special case for hex .word input
int ishex = 0;
if(str[0] == '0' && str[1] == 'x'){
//if(i >= pwr2(n-1)) i -= pwr2(n); // convert from unsigned to signed
ishex = 1;
}
if(ret == str){
*t = -1;
WERR("failed to parse %d-bit signed int\n", n);
return 0;
}else if((!ishex) && (i < -pwr2(n-1) || i >= pwr2(n-1))){
if(i > 0 && i < pwr2(n)){
i -= pwr2(n);
}else{
*t = -1;
WERR("%d-bit signed int '%ld' out of range\n", n, i);
return 0;
}
}else if(ishex && (i > pwr2(n) || i < 0)){
*t = -1;
WERR("%d-bit unsigned int '%ld' out of range\n", n, i);
return 0;
}
if(r) *r = ret;
return i;
}
// attempt to parse a register from the beginning of str
// on success: return the int; put rest of string in *r if r != 0
// on failure: set *t = -1, and write an error message to err
uint8_t reg_parse(char *str, type_t *t, char **r, unsigned int line, char *err){
if(!str){
*t = -1;
SERR("reached end of line; expected register\n");
return 0;
}
while(isspace(str[0])) str++;
if(str[0] != '$'){
*t = -1;
SERR("expected '$' before register number\n");
return 0;
}
char *ret;
long int i = strtol(str+1, &ret, 10);
if(ret == str){
*t = -1;
SERR("failed to parse register number\n");
return 0;
}else if(i < 0 || i > 31){
*t = -1;
WERR("register number '%ld' out of range\n", i);
return 0;
}
if(r) *r = ret;
return i;
}
// return the typecode for the string
type_t gettype(const char *str){
if(strcmp(str, ".word") == 0) return 1;
else if(strcmp(str, "add") == 0) return 2;
else if(strcmp(str, "sub") == 0) return 3;
else if(strcmp(str, "mult") == 0) return 4;
else if(strcmp(str, "multu") == 0) return 5;
else if(strcmp(str, "div") == 0) return 6;
else if(strcmp(str, "divu") == 0) return 7;
else if(strcmp(str, "mfhi") == 0) return 8;
else if(strcmp(str, "mflo") == 0) return 9;
else if(strcmp(str, "lis") == 0) return 10;
else if(strcmp(str, "lw") == 0) return 11;
else if(strcmp(str, "sw") == 0) return 12;
else if(strcmp(str, "slt") == 0) return 13;
else if(strcmp(str, "sltu") == 0) return 14;
else if(strcmp(str, "beq") == 0) return 15;
else if(strcmp(str, "bne") == 0) return 16;
else if(strcmp(str, "jr") == 0) return 17;
else if(strcmp(str, "jalr") == 0) return 18;
else return -1;
}
struct inst inst_parse(char *str, unsigned int line, char *err,
long int addr, struct AVLTree *lbls){
struct inst in;
in.lbl = 0;
// parse any labels from the beginning of the line
char *typestr = strtok(str, " \t\n");
while(typestr && typestr[strlen(typestr)-1] == ':'){
typestr[strlen(typestr)-1] = '\0';
if(!valid_label(typestr)){
in.type = -1;
WERR("invalid label '%s' declared\n", typestr);
return in;
}else if(avl_lookup(lbls, typestr)){
in.type = -1;
WERR("duplicate label '%s' declared\n", typestr);
return in;
}
avl_insert(lbls, typestr, addr);
typestr[strlen(typestr)-1] = ':';
typestr = strtok(0, " \t\n");
}
if(!typestr || isempty(typestr)){
in.type = 0;
return in;
}
in.type = gettype(typestr);
if(in.type == -1){
WERR("invalid operation '%s'\n", typestr);
return in;
}
// TODO: does not ensure commas are there right now
if(in.type == 1){ // .word
char *num = strtok(0, " \t\n");
if(num && isalpha(num[0])){ // attempt to parse a label
if(valid_label(num)){
in.lbl = strdup(num);
}else{
in.type = -1;
WERR("invalid label '%s' referenced\n", num);
return in;
}
}else{
in.i = sint_parse(num, 32, &in.type, 0, line, err);
if(in.type == -1) return in;
}
}else if(isin(in.type, 4, 2,3,13,14)){ // add, sub, slt, sltu
in.d = reg_parse(strtok(0, " \t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
in.s = reg_parse(strtok(0, " ,\t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
in.t = reg_parse(strtok(0, " ,\t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
}else if(isin(in.type, 4, 4,5,6,7)){ // mult, multu, div, divu
in.s = reg_parse(strtok(0, " \t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
in.t = reg_parse(strtok(0, " ,\t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
}else if(isin(in.type, 3, 8,9,10)){ // mfhi, mflo, lis
in.d = reg_parse(strtok(0, " \t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
}else if(isin(in.type, 2, 17,18)){ // jr, jalr
in.s = reg_parse(strtok(0, " \t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
}else if(isin(in.type, 2, 11,12)){ // lw, sw
in.t = reg_parse(strtok(0, " \t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
char *next = strtok(0, " \t\n");
in.i = sint_parse(next, 16, &in.type, &next, line, err);
if(in.type == -1) return in;
if(next[0] != '('){
in.type = -1;
SERR("expected '(' before $s register\n");
return in;
}
in.s = reg_parse(next+1, &in.type, &next, line, err);
if(in.type == -1) return in;
if(next[0] != ')'){
in.type = -1;
SERR("expected ')' after $s register\n");
}
// TODO: there is no check for garbage after i
}else if(isin(in.type, 2, 15,16)){ // beq, bne
in.s = reg_parse(strtok(0, " \t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
in.t = reg_parse(strtok(0, " ,\t\n"), &in.type, 0, line, err);
if(in.type == -1) return in;
// parse label or 16-bit signed int
char *next = strtok(0, " \t\n");
if(!next){
in.type = -1;
SERR("reached end of line; expected 16-bit signed int or label\n");
return in;
}else if(isdigit(next[0]) || next[0] == '-'){ // try to parse a number
in.i = sint_parse(next, 16, &in.type, 0, line, err);
if(in.type == -1) return in;
}else{ // try to parse a label
if(!valid_label(next)){
in.type = -1;
WERR("invalid label '%s' referenced\n", next);
return in;
}else{
in.lbl = strdup(next);
}
}
}
char *c = strtok(0, " \t\n");
if(c){
in.type = -1;
WERR("unexpected token '%s' after valid line\n", c);
}
return in;
}
void lbl_replace(struct AVLTree *lbls, struct inst *in, unsigned int line,
long int addr, char *err){
if(in->lbl){
long int *dat = avl_lookup(lbls, in->lbl);
if(!dat){
in->type = -1;
WERR("referenced label '%s' was never defined\n", in->lbl);
}else{
// TODO: are beq, bne, and .word all?
if(isin(in->type, 2, 15,16)){ // beq, bne
long int branch = *dat - addr - 1;
if(branch < -pwr2(15) || branch >= pwr2(15)){
in->type = -1;
WERR("branch to label '%s' out of range (%ld)\n",
in->lbl, branch);
return;
}
in->i = branch;
}else if(in->type == 1){ // .word, yo
if(*dat >= pwr2(31)){
in->type = -1;
WERR(".word of label '%s' out of range (%ld)\n",
in->lbl, *dat);
return;
}
in->i = *dat * 4;
}
free(in->lbl);
in->lbl = 0;
}
}
}
// get the opcode of an instruction type
word get_opcode(type_t t){
if(t == 1) return 0;
else if(t == 2) return 32;
else if(t == 3) return 34;
else if(t == 4) return 24;
else if(t == 5) return 25;
else if(t == 6) return 26;
else if(t == 7) return 27;
else if(t == 8) return 16;
else if(t == 9) return 18;
else if(t == 10) return 20;
else if(t == 11) return 35; // on left
else if(t == 12) return 43; // on left
else if(t == 13) return 42;
else if(t == 14) return 43;
else if(t == 15) return 4; // on left
else if(t == 16) return 5; // on left
else if(t == 17) return 8;
else if(t == 18) return 9;
else return 999999; // wat
}
// inverse of get_opcode; gets the instruction type of an opcode
type_t get_itype(word w){
if(w == 0) return 1;
else if(w == 32) return 2;
else if(w == 34) return 3;
else if(w == 24) return 4;
else if(w == 25) return 5;
else if(w == 26) return 6;
else if(w == 27) return 7;
else if(w == 16) return 8;
else if(w == 18) return 9;
else if(w == 20) return 10;
else if(w == 35) return 11; // on left
else if(w == 43) return 12; // on left
else if(w == 42) return 13;
else if(w == 43) return 14;
else if(w == 4) return 15; // on left
else if(w == 5) return 16; // on left
else if(w == 8) return 17;
else if(w == 9) return 18;
else return -1;
}
// convert a signed two's complement n-bit integer to an unsigned n-bit integer
// with the same bits
word toun(int32_t i, int n){
return i<0 ? i + pwr2(n) : i;
}
// inverse of the above; convert an unsigned int to a bit-equivalent signed int
int32_t tosign(word w, int n){
return w >= pwr2(n-1) ? w - pwr2(n) : w;
}
word inst_encode(struct inst in){
word opc = get_opcode(in.type);
if(in.type == 1){ // .word
return in.i;
}else if(isin(in.type, 4, 2,3,13,14)){ // add, sub, slt, sltu
return opc + (in.d << 11) + (in.t << 16) + (in.s << 21);
}else if(isin(in.type, 4, 4,5,6,7)){ // mult, multu, div, divu
return opc + (in.t << 16) + (in.s << 21);
}else if(isin(in.type, 3, 8,9,10)){ // mfhi, mflo, lis
return opc + (in.d << 11);
}else if(isin(in.type, 4, 11,12,15,16)){ // lw, sw, beq, bne
return toun(in.i, 16) + (in.t << 16) + (in.s << 21) + (opc << 26);
}else if(isin(in.type, 2, 17,18)){ // jr,jalr
return opc + (in.s << 21);
}
return 0; // unreachable
}
struct inst inst_decode(word w){
struct inst in;
in.lbl = 0;
// parse a bunch of regions of the word
word leftop = w >> 26;
word rightop = (w << 26) >> 26;
type_t ltype = get_itype(leftop);
type_t rtype = get_itype(rightop);
in.s = (w << 6) >> 27;
in.t = (w << 11) >> 27;
in.d = (w << 16) >> 27;
in.i = tosign((w << 16) >> 16, 16);
if(isin(ltype, 4, 11,12,15,16)){ // lw, sw, beq, bne
in.type = ltype;
}else if(isin(rtype, 13, 2,3,4,5,6,7,8,9,10,13,14,17,18)){ // all others
in.type = rtype;
}else{ // not valid command
in.type = -1;
}
return in;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
int i, j, pom = n;
int i2 = 2*n - 1;
int j2 = 2*n - 1;
for (i=0;i<i2;i++){
for (j=0;j<j2;j++){
printf("%d ", pom);
if (i >= n){
if (2*n-1-i > j+1) pom--;
else if (j > i-1) pom++;
else continue;
} else {
if (i > j) pom--;
else if (2*n-1-j > i+1) continue;
else pom++;
}
}
printf("\n");
pom = n;
}
return 0;
}
|
C
|
#ifndef _DT_QUEUE_H_INCLUDED_
#define _DT_QUEUE_H_INCLUDED_
#include <stddef.h>
typedef struct dt_queue_s dt_queue_t, dt_list, dt_queue;
struct dt_queue_s {
dt_queue_t *prev;
dt_queue_t *next;
};
#define dt_queue_init(q) \
(q)->prev = q; \
(q)->next = q
#define dt_queue_empty(h) \
(h == (h)->prev)
#define dt_queue_insert_head(h, x) \
(x)->next = (h)->next; \
(x)->next->prev = x; \
(x)->prev = h; \
(h)->next = x
#define dt_queue_insert_after dt_queue_insert_head
#define dt_queue_insert_tail(h, x) \
(x)->prev = (h)->prev; \
(x)->prev->next = x; \
(x)->next = h; \
(h)->prev = x
#define dt_queue_head(h) \
(h)->next
#define dt_queue_last(h) \
(h)->prev
#define dt_queue_sentinel(h) \
(h)
#define dt_queue_next(q) \
(q)->next
#define dt_queue_prev(q) \
(q)->prev
#if (DEBUG)
#define dt_queue_remove(x) \
(x)->next->prev = (x)->prev; \
(x)->prev->next = (x)->next; \
(x)->prev = NULL; \
(x)->next = NULL
#else
#define dt_queue_remove(x) \
(x)->next->prev = (x)->prev; \
(x)->prev->next = (x)->next
#endif
#define dt_queue_split(h, q, n) \
(n)->prev = (h)->prev; \
(n)->prev->next = n; \
(n)->next = q; \
(h)->prev = (q)->prev; \
(h)->prev->next = h; \
(q)->prev = n;
#define dt_queue_add(h, n) \
(h)->prev->next = (n)->next; \
(n)->next->prev = (h)->prev; \
(h)->prev = (n)->prev; \
(h)->prev->next = h;
#define dt_queue_data(q, type, link) \
(type *) ((unsigned char *) q - offsetof(type, link))
#define dt_container_of dt_queue_data
#define dt_queue_clear(queue, type, link, destroy) do { \
dt_queue *n; \
while (!dt_queue_empty(queue)) { \
n = dt_queue_head(queue); \
dt_queue_remove(n); \
destroy(dt_queue_data(n, type, link)); \
} \
}while(0);
#define dt_queue_clean(queue) do { \
dt_queue *n; \
while (!dt_queue_empty(queue)) { \
n = dt_queue_head(queue); \
dt_queue_remove(n); \
} \
} while (0);
/*
* well, you gonna not delete a node
* */
#define dt_queue_foreach(q, n) \
for (n = dt_queue_head(q); \
n != dt_queue_sentinel(q); \
n = dt_queue_next(n))
#define dt_queue_foreach_safe(q, cur, next) \
for (cur = dt_queue_head(q), next = dt_queue_next(cur); \
cur != dt_queue_sentinel(q); \
cur = next, next = dt_queue_next(cur))
#endif
|
C
|
#include<stdio.h>
#include<math.h>
main()
{int num,unit,csum=0,x;
printf("Enter the number to check for armstrong number:\n");
scanf("%d",&num);
x=num;
while(num!=0)
{
unit=num%10;
csum=csum+pow(unit,3);
num=num/10;
}
if(x==csum)
printf("The number is an armstrong number");
else
printf("The number is not an armstrong number");
}
|
C
|
#include "sys.h"
#include "delay.h"
/**
*ڵʵ(IOģ)
* ʣ9600 1-8-N
* TXD : PC13
* RXD : PB14
* ʹⲿж϶RXD½ؽдʹöʱ49600ʽжʱݽա
* Demo: 11ݣȻѽյݷͳȥ
*/
#define OI_TXD PCout(13)
#define OI_RXD PBin(14)
#define BuadRate_9600 100
u8 len = 0; //ռ
u8 USART_buf[11]; //ջ
enum{
COM_START_BIT,
COM_D0_BIT,
COM_D1_BIT,
COM_D2_BIT,
COM_D3_BIT,
COM_D4_BIT,
COM_D5_BIT,
COM_D6_BIT,
COM_D7_BIT,
COM_STOP_BIT,
};
u8 recvStat = COM_STOP_BIT;
u8 recvData = 0;
void IO_TXD(u8 Data)
{
u8 i = 0;
OI_TXD = 0;
delay_us(BuadRate_9600);
for(i = 0; i < 8; i++)
{
if(Data&0x01)
OI_TXD = 1;
else
OI_TXD = 0;
delay_us(BuadRate_9600);
Data = Data>>1;
}
OI_TXD = 1;
delay_us(BuadRate_9600);
}
void USART_Send(u8 *buf, u8 len)
{
u8 t;
for(t = 0; t < len; t++)
{
IO_TXD(buf[t]);
}
}
void IOConfig(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
EXTI_InitTypeDef EXTI_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO|RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC, ENABLE); //ʹPB,PC˿ʱ
//SoftWare Serial TXD
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IOٶΪ50MHz
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_SetBits(GPIOC,GPIO_Pin_13);
//SoftWare Serial RXD
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource14);
EXTI_InitStruct.EXTI_Line = EXTI_Line14;
EXTI_InitStruct.EXTI_Mode=EXTI_Mode_Interrupt;
EXTI_InitStruct.EXTI_Trigger=EXTI_Trigger_Falling; //½شж
EXTI_InitStruct.EXTI_LineCmd=ENABLE;
EXTI_Init(&EXTI_InitStruct);
NVIC_InitStructure.NVIC_IRQChannel= EXTI15_10_IRQn ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority =2;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void TIM4_Int_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //ʱʹ
//ʱTIM4ʼ
TIM_TimeBaseStructure.TIM_Period = arr; //һ¼װԶװؼĴڵֵ
TIM_TimeBaseStructure.TIM_Prescaler =psc; //ΪTIMxʱƵʳԤƵֵ
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //ʱӷָ:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIMϼģʽ
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); //ָIJʼTIMxʱλ
TIM_ClearITPendingBit(TIM4, TIM_FLAG_Update);
TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE ); //ʹָTIM3ж,ж
//жȼNVIC
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn; //TIM4ж
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; //ռȼ1
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; //ȼ1
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨʹ
NVIC_Init(&NVIC_InitStructure); //ʼNVICĴ
}
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//жȼΪ22λռȼ2λӦȼ
delay_init();
IOConfig();
TIM4_Int_Init(107, 71); //1MƵ
while(1)
{
if(len > 10)
{
len = 0;
USART_Send(USART_buf,11);
}
}
}
void EXTI15_10_IRQHandler(void)
{
if(EXTI_GetFlagStatus(EXTI_Line14) != RESET)
{
if(OI_RXD == 0)
{
if(recvStat == COM_STOP_BIT)
{
recvStat = COM_START_BIT;
TIM_Cmd(TIM4, ENABLE);
}
}
EXTI_ClearITPendingBit(EXTI_Line14);
}
}
void TIM4_IRQHandler(void)
{
if(TIM_GetFlagStatus(TIM4, TIM_FLAG_Update) != RESET)
{
TIM_ClearITPendingBit(TIM4, TIM_FLAG_Update);
recvStat++;
if(recvStat == COM_STOP_BIT)
{
TIM_Cmd(TIM4, DISABLE);
USART_buf[len++] = recvData;
return;
}
if(OI_RXD)
{
recvData |= (1 << (recvStat - 1));
}else{
recvData &= ~(1 << (recvStat - 1));
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* div_op.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apieropa <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/27 19:59:41 by apieropa #+# #+# */
/* Updated: 2017/07/27 20:02:55 by apieropa ### ########.fr */
/* */
/* ************************************************************************** */
#include "corewar.h"
static t_op g_op_tab[17] = {
{"live", 1, {T_DIR}, 1, 10, "alive", 0, 0},
{"ld", 2, {T_DIR | T_IND, T_REG}, 2, 5, "load", 1, 0},
{"st", 2, {T_REG, T_IND | T_REG}, 3, 5, "store", 1, 0},
{"add", 3, {T_REG, T_REG, T_REG}, 4, 10, "addition", 1, 0},
{"sub", 3, {T_REG, T_REG, T_REG}, 5, 10, "soustraction", 1, 0},
{"and", 3, {T_REG | T_DIR | T_IND, T_REG | T_IND | T_DIR, T_REG}, 6, 6,
"et (and r1, r2, r3 r1&r2 -> r3", 1, 0},
{"or", 3, {T_REG | T_IND | T_DIR, T_REG | T_IND | T_DIR, T_REG}, 7, 6,
"ou (or r1, r2, r3 r1 | r2 -> r3", 1, 0},
{"xor", 3, {T_REG | T_IND | T_DIR, T_REG | T_IND | T_DIR, T_REG}, 8, 6,
"ou (xor r1, r2, r3 r1^r2 -> r3", 1, 0},
{"zjmp", 1, {T_DIR}, 9, 20, "jump if zero", 0, 1},
{"ldi", 3, {T_REG | T_DIR | T_IND, T_DIR | T_REG, T_REG}, 10, 25,
"load index", 1, 1},
{"sti", 3, {T_REG, T_REG | T_DIR | T_IND, T_DIR | T_REG}, 11, 25,
"store index", 1, 1},
{"fork", 1, {T_DIR}, 12, 800, "fork", 0, 1},
{"lld", 2, {T_DIR | T_IND, T_REG}, 13, 10, "long load", 1, 0},
{"lldi", 3, {T_REG | T_DIR | T_IND, T_DIR | T_REG, T_REG}, 14, 50,
"long load index", 1, 1},
{"lfork", 1, {T_DIR}, 15, 1000, "long fork", 0, 1},
{"aff", 1, {T_REG}, 16, 2, "aff", 1, 0},
{0, 0, {0}, 0, 0, 0, 0, 0}
};
t_op *op_from_instr(char *instr)
{
uint op_line;
t_op *ops;
ops = g_op_tab;
op_line = 0;
while (ops[op_line].instr != NULL)
{
if (ft_strcmp(ops[op_line].instr, instr) == 0)
return (ops + op_line);
op_line++;
}
return (NULL);
}
t_bool line_begins_by_an_opcode(char *line)
{
static t_op *instrs;
static t_bool init = FALSE;
uint i;
uint len;
if (init == FALSE && TRUE + 0 * (init = TRUE))
instrs = g_op_tab;
i = 0;
while (instrs[i].instr != NULL)
{
len = ft_strlen(instrs[i].instr);
if (ft_strncmp(line, instrs[i].instr, len) == 0 && line[len] == ' ')
return (TRUE);
i++;
}
return (FALSE);
}
|
C
|
// implementation of the temperature conversion behavior from the reactive
// programming survey ...
// we have a behavior temp that continuously presents the current temperature
// in degrees Celcius
#include <stdlib.h>
#include "unit/test.h"
#include "reactive-c/api.h"
// to observe a value/variable...
double temp = 123;
// ...we create an observable...
observable_t observable_temp;
// ... and link it to the value/variable.
void observable_temp_init() {
observable_temp = observe(temp);
}
// when the value/variable is updated, we trigger the RP functionality
void temp_update(double update) {
temp = update;
// trigger update propagation
observe_update(observable_temp);
}
// a user defined convertion between Celcius and Farenheit
void c2f(observation_t ob) {
(*(double*)(ob->observer)) = ( (*(double*)(ob->observeds[0])) * 1.8 ) + 32;
}
// a user defined display function to display both C and F values
void display(observation_t ob) {
capture_printf( "observable was updated to %fC/%fF\n",
*(double*)(ob->observeds[0]), *(double*)(ob->observeds[1]) );
}
/*
level
observable_temp 0 <-- update
/ \
temp_f | 1
\ /
displayer 2 --> printf
*/
int main(void) {
// init temp behavior
observable_temp_init();
// create a new behviour that convers C to F
observable_t temp_f = observe(just(observable_temp), c2f, double);
// simulate changes to temp
temp_update(16);
temp_update(17);
temp_update(18);
assert_no_output();
assert_equal(
*(double*)observable_value(observable_temp),
18,
"Expected temperature to be 18C. Observed %f.\n",
*(double*)observable_value(observable_temp)
);
assert_equal(
*(double*)observable_value(temp_f),
18 * 1.8 + 32,
"Expected temperature to be %f. Observed %f.\n",
18 * 1.8 + 32,
*(double*)observable_value(temp_f)
);
// let's add an observer that displays the updates from now on using our
// display observer function
observable_t displayer = observe(both(observable_temp, temp_f), display, void*);
temp_update(19);
temp_update(20);
temp_update(21);
assert_output_was(
"observable was updated to 19.000000C/66.200000F\n"
"observable was updated to 20.000000C/68.000000F\n"
"observable was updated to 21.000000C/69.800000F\n"
);
clear_output();
dispose(displayer);
temp_update(22);
temp_update(23);
temp_update(24);
assert_no_output();
assert_equal(
*(double*)observable_value(observable_temp),
24,
"Expected temperature to be 18C. Observed %f.\n",
*(double*)observable_value(observable_temp)
);
assert_equal(
*(double*)observable_value(temp_f),
24 * 1.8 + 32,
"Expected temperature to be %f. Observed %f.\n",
24 * 1.8 + 32,
*(double*)observable_value(temp_f)
);
dispose(temp_f);
exit(EXIT_SUCCESS);
}
|
C
|
#include "conversion.h"
/* 256 array of Decimal values of the base64 characters
Organized by ASCII value */
int r64Lookup[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/* Byte mask for converting hex to base64 */
unsigned char mask[] = { 3, /* 00000011 */
15, /* 00001111 */
63 /* 00111111 */
};
/* Character set of base64 */
char base64set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/* Function definitions */
/* Converts binary unsigned char string to base64 encoded char string
n is size in bytes */
void btor64(unsigned char* src, char* dest, size_t n)
{
int count = 0;
int padding = n % 3;
while(count < n / 3)
{
btor64_conversion(src + 3*count, dest + 4*count, 0);
count++;
}
if ( padding )
{
src[n] = 0;
if (padding == 1)
{
src[n+1] = 0;
}
btor64_conversion(src + 3*count, dest + 4*count, padding);
count++;
}
*(dest+4*count) = '\0';
return;
}
/* Computation function for binary to base64 conversion */
void btor64_conversion(unsigned char *srcChunk, char* destPos, int padding)
{
*destPos = base64set[srcChunk[0] >> 2];
*(destPos+1) = base64set[((srcChunk[0] & mask[0]) << 4) + (srcChunk[1] >> 4) ];
if(padding == 1)
*(destPos+2) = '=';
else
*(destPos+2) = base64set[((srcChunk[1] & mask[1]) << 2) + (srcChunk[2] >> 6)];
if(padding)
*(destPos+3) = '=';
else
*(destPos+3) = base64set[srcChunk[2] & mask[2]];
return;
}
/* Convert base64 (radix64) to binary
Takes signed char string and writes to unsigned char string
n is size of base64 string in characters */
void r64tob(char* src, unsigned char* dest, size_t n)
{
int i = 0;
while(i < (n/4) )
{
r64tob_conversion(src+(4*i), dest+(3*i));
i++;
}
return;
}
/* Computation function for base64 to binary conversion */
void r64tob_conversion(char* srcChunk, unsigned char* destPos)
{
int r1 = r64Lookup[srcChunk[0]];
int r2 = r64Lookup[srcChunk[1]];
int r3 = r64Lookup[srcChunk[2]];
int r4 = r64Lookup[srcChunk[3]];
destPos[0] = (r1 << 2) + (r2 >>4);
destPos[1] = (r2 << 4) + (r3 >>2);
destPos[2] = (r3 << 6) + r4;
return;
}
/* Function that prints result in hex, doesn't do conversion,
because this is so easy to write to and from in binary */
void print_hex(unsigned char* bytes, size_t n)
{
for(int i = 0; i < n; i++)
{
printf("%02x", bytes[i]);
}
printf("\n");
}
/* Convert hex string to bytes in unsigned char array
Len is in length of hex string */
void htob(char* hex, unsigned char* bytes, int len)
{
for(int i = 0; i < len/2; i++)
{
sscanf(hex, "%2hhx", &bytes[i]);
hex +=2;
}
}
|
C
|
/* tpsimul1.c LIR simulator test 1 */
int g1, g2;
int ga1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int ga2[3], g3, g4;
int printf( char*, ... );
void initiate( int *param1, int *param2 )
{
ga2[0] = 11;
ga2[1] = 12;
ga2[3] = 13;
*param1 = *param2 ;
}
int main()
{
int i, j1, j2, aa[10], bb[5], j3, j4;
g1 = 10;
g2 = 20;
j1 = 30;
j2 = 31;
initiate(&j3, &j1);
g3 = j1 + j3;
initiate(&j4, &j2);
g4 = j2 + j4;
aa[0] = j1;
for (i = 1; i < 10; i++) {
aa[i] = aa[i-1] + g1 + j1 + 16;
}
for (i = 0; i < 5; i++) {
bb[i] = aa[i] + aa[i+5] + 17;
}
printf("bb %d %d %d %d %d \n", bb[0], bb[1], bb[2], bb[3], bb[4]);
return 0;
}
|
C
|
/* file litnet1.c */
#if !defined(COMPILE_ENVIRONMENT)
#include <phone/stdcenvf.h> /* std compile environment for functions */
#endif
void literalize_network(NETWORK *net, NODE *node, int *perr)
/*******************************************************************/
/* */
/* Recursively expands symbols in network *net which are on or */
/* below the out_arcs of *node and which represent several */
/* literal words. */
/* NOTE: for this to work right, the nodes in the net must first */
/* have had their flags turned off by "deflag1_node_r()". */
/* */
/*******************************************************************/
{char *proc = "literalize_network";
char sxx[LINE_LENGTH], *word = &sxx[0];
char dbsxx[LINE_LENGTH], *dbsx = &dbsxx[0];
SUBSTRING trx, *the_rest = &trx;
SUBSTRING wrx, *rest_of_words = &wrx;
SUBSTRING tox, *token = &tox;
SUBSTRING ssox, *ss_word = &ssox;
NODE *last_node, *new_node, *next_node;
ARC *new_arc, *arcx;
boolean done, words_done;
ARC_LIST_ATOM *p, *px, *next_arc;
/* code: */
db_enter_msg(proc,0); /* debug only */
/* initialize output variables */
*perr=0;
if (db_level > 0) printf("%s node='%s'\n",pdb,node->name);
if (db_level > 2)
{printf("%s out_arcs are:\n",pdb);
printf(" from_node symbol to_node\n");
for (px = node->out_arcs; px != NULL; px = px->next) dump_arc(px->arc);
}
/* have we visited this node already? */
if (node->flag1) goto RETURN;
else node->flag1 = T;
/* do any out_arcs have non-literal symbols? */
if (node->out_arcs != NULL)
{if (db_level > 2) printf("%s searching over out_arcs\n",pdb);
for (p = node->out_arcs; p != NULL; p = next_arc)
{
if (db_level > 2)
{printf("%s looking at p->arc w/symbol '%s'\n",pdb,p->arc->symbol);
printf("%s calling lit() on arc's next node '%s'\n",
pdb,p->arc->to_node->name);
}
literalize_network(net,p->arc->to_node,perr);
if (*perr > 0)
{fprintf(stderr,"%s: literalize_network err return=%d\n",pdb,*perr);
fprintf(stderr," applied to node '%s'\n",
p->arc->to_node->name);
goto RETURN;
}
/* save next arc in case we delete this one */
next_arc = p->next;
if (db_level > 2)
{printf("%s returned from lit() of next node to this node, '%s'\n",
pdb,node->name);
}
if (*(p->arc->symbol) == '{')
{/* yes - expand it */
if (db_level > 2)
{printf("%s expanding p->arc symbol '%s'\n",pdb,p->arc->symbol);
printf("%sThe node->out_arcs arc list itself is:\n",pdb);
dump_arc_list(node->out_arcs);
}
the_rest->start = p->arc->symbol+1;
the_rest->end = prtrim(p->arc->symbol)-1;
done = F;
while (!done)
{*token = sstok(the_rest,"/"); /* ignore "or" */
if (token->start > the_rest->end) done = T;
else
{
if (db_level > 2)
{dbsx = substr_to_str(token,dbsx,LINE_LENGTH);
printf("%s next token = '%s'\n",pdb,dbsx);
}
last_node = p->arc->from_node;
/* add parsed string to network, treating all tokens as units */
rest_of_words->start = token->start;
rest_of_words->end = token->end;
words_done = F;
while (!words_done)
{/* get next word, make arc, new node */
if (db_level > 2)
{dbsx = substr_to_str(rest_of_words,dbsx,LINE_LENGTH);
printf("%s at top of word loop, rest_of_words = '%s'\n",pdb,dbsx);
}
find_next_token3(rest_of_words,ss_word);
if (substr_length(ss_word) < 1) words_done = T;
else
{word = substr_to_str(ss_word,word,LINE_LENGTH);
if (db_level > 2) printf("%s adding word '%s'\n",pdb,word);
arcx = make_arc(word,last_node,(NODE*)NULL,perr);
last_node->out_arcs =
add_to_arc_list(last_node->out_arcs,arcx,perr);
new_node = make_node((char*)NULL,arcx,(ARC*)NULL,
&(net->highest_nnode_name),perr);
if (*perr > 0)
{printf("%s:*ERR: make_node() returns %d\n",proc,*perr);
goto RETURN;
}
arcx->to_node = new_node;
last_node = new_node;
rest_of_words->start = ss_word->end+1;
} }
/* make an epsilon arc to original to-node */
if (db_level > 2) printf("%smaking new @ arc\n",pdb);
new_arc = make_arc("@",last_node,p->arc->to_node,perr);
last_node->out_arcs = add_to_arc_list(last_node->out_arcs,new_arc,perr);
add_to_arc_list(new_arc->to_node->in_arcs,new_arc,perr);
if (db_level > 2)
{printf("%s at bottom of word loop, net=\n",pdb);
dump_network(net);
fflush(stdout);
}
the_rest->start = token->end+1;
} }
/* then delete the old version */
if (db_level > 2) printf("%s killing old arc\n",pdb);
if (db_level > 2)
{printf("%s before killing, node is:\n",pdb);
dump_node(node);
}
/* save pointer to arc to be deleted and next_node; fcns below may free(p) */
arcx = p->arc;
next_node = p->arc->to_node;
/* delete p->arc from in_arc list of next node */
del_from_arc_list(&(next_node->in_arcs),arcx,perr);
/* delete p->arc from out_arc list of this node */
del_from_arc_list(&(node->out_arcs),arcx,perr);
/* and free arc itself */
kill_arc(arcx);
if (db_level > 2)
{printf("%s after killing, node is:\n",pdb);
dump_node(node);
}
} } }
RETURN:
if (db_level > 2)
{printf("%s on exit, net=\n",pdb);
dump_network(net);
}
db_leave_msg(proc,0); /* debug only */
return;
} /* end of function "literalize_network" */
|
C
|
//
// main.c
// 9_1
//
// Created by MAC on 15/6/14.
// Copyright (c) 2015年 MAC. All rights reserved.
//
#include <stdio.h>
struct {
int year;
int month;
int day;
}date;
int main(int argc, const char * argv[]) {
int days=0,i;
int month[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
printf("please input year、month、day in order!\n");
scanf("%d%d%d",&date.year,&date.month,&date.day);
if(date.day>month[date.month]){
printf("error! please run again !\n");
return 0;
}
for(i=0;i<date.month;i++){
days=days+month[i];
}
days+=date.day;
if(((date.year%4==0&&date.year%100!=0)||date.year%400==0)&&date.month>2)
days=days+1;
printf("the date you input is the%5dth day in that year!\n",days);
return 0;
}
|
C
|
//
// Created by 单颖博 on 2019/2/20.
// 每个系统标准不一样,所以函数定义,差别较大所以这章叫unix标准与实现
//
#include "apue.h"
#include <errno.h>
#include <limits.h>
#ifdef PATH_MAX
static int pathmax = PATH_MAX;
#else
static int pathmax = 0;
#endif
#define SUSV3 200112L
static long posix_version = 0;
/* If PATH_MAX is indeterminate, no guarantee this is adequate */
#define PATH_MAX_GUESS 1024
char *
path_alloc1(int *sizep) /* also return allocated size, if nonull */
{
char *ptr;
int size;
if(posix_version == 0)
posix_version = sysconf(_SC_VERSION);
if(pathmax == 0) { /* first time trough */
errno = 0;
if((pathmax = pathconf("/", _PC_PATH_MAX)) < 0) {
if(errno == 0)
pathmax = PATH_MAX_GUESS; /* it's indeterminate */
else
err_sys("pathconf error for _PC_PATH_MAX");
} else {
pathmax++; /* add one since it's relative to root */
}
}
if(posix_version < SUSV3)
size = pathmax + 1;
else
size = pathmax;
if((ptr = malloc(size)) == NULL)
err_sys("malloc error for pathname");
if(sizep != NULL)
*sizep = size;
return(ptr);
}
int main(void)
{
printf("%ld\n",path_alloc1(3));
}
|
C
|
/*
* Programmer: Kanishk Yadav
* Project: 2K Pre-Test
* File Desc: The program outputs the minimum time required before a message sent
* from the capitol (city #1) throughout the empire, i.e. the time it is received
* in the last city to get the message.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
typedef enum { false, true } bool;
int **allocateMapMemory(int size);
void readFromFileAndFillAdjMatrix(FILE *fMap, int **map, int numOfCities);
int minDistance(int dist[], bool sptSet[], int numOfCities);
void findMinTimeToDeliverAllMsgs(int **map, int src, int numOfCities);
void freeMapMemory(int **map, int size);
int main(int argc, char **argv)
{
//Check number of arguments
if(argc != 2)
{
fprintf(stderr, "Function call must be of type: ./2kpretest input_map.txt\n");
return 0;
}
//Open input file
FILE *fMap;
fMap = fopen(argv[1], "r");
if(fMap == NULL)
{
fprintf(stderr, "Map file (%s) could not be opened\n", argv[1]);
return 0;
}
//read number of cities
int numOfCities = -1;
fscanf(fMap,"%d",&numOfCities);
if(numOfCities == -1)
{
fprintf(stderr, "Error. Cannot read (%s) header properly.\n", argv[1]);
fclose(fMap);
return 0;
}
int **map = allocateMapMemory(numOfCities);
if(map == NULL)
{
fclose(fMap);
return 0;
}
readFromFileAndFillAdjMatrix(fMap, map, numOfCities);
findMinTimeToDeliverAllMsgs(map, 0, numOfCities);
freeMapMemory(map, numOfCities);
fclose(fMap);
return 1;
}
/*
* @description : Allocates memory for the Adjacency Matrix of the graph
* @return : retuns a 2d array block of memory of int
* @argument : takes in size of 2d square array
*/
int **allocateMapMemory(int size)
{
int **map;
int i;
map = calloc(size, sizeof(int*));
if(map == NULL)
{
fprintf(stderr, "Memory Allocation failed\n");
return NULL;
}
for(i = 0; i < size; ++i)
{
map[i] = calloc(size, sizeof(int));
if(map[i] == NULL)
{
fprintf(stderr, "Memory Allocation failed\n");
return NULL;
}
}
return map;
}
/*
* @description : reads from input file and fills up the Adj. Matrix
* @return : void
* @argument : takes in file pointer, 2d map array and number of cities
*/
void readFromFileAndFillAdjMatrix(FILE *fMap, int **map, int numOfCities)
{
int row = 0;
int col = 0;
char *line = NULL;
size_t len = 0;
ssize_t read;
while((read = getline(&line, &len, fMap)) != -1)
{
char *tempLine = strtok(line," ");
col = 0;
while(tempLine != NULL)
{
if(*tempLine == 'x')
{
map[row][col] = 0;
}
else
{
map[row][col] = atol(tempLine);
}
col++;
tempLine = strtok(NULL," ");
}
row++;
}
for(row = 0; row < numOfCities; ++row)
{
for(col = row + 1; col < numOfCities; ++col)
{
map[row][col] = map[col][row];
}
}
return;
}
/*
* @description : find the min distance
* @return : retuns the index of min distance
* @argument : takes in dist array, aptSet array and number of cities
*/
int minDistance(int dist[], bool sptSet[], int numOfCities)
{
int min = INT_MAX;
int minIndex;
int i;
for(i = 0; i < numOfCities; ++i)
{
if (sptSet[i] == false && dist[i] <= min)
{
min = dist[i];
minIndex = i;
}
}
return minIndex;
}
/*
* @description : finds minimum time to deliver all messages using Dijkstra
* algorithm
* @return : void
* @argument : takes in the Adj. matrix, src city (Capitol city) and num of cities
*/
void findMinTimeToDeliverAllMsgs(int **map, int src, int numOfCities)
{
int dist[numOfCities];
bool sptSet[numOfCities];
int maxDist = INT_MIN;
int i;
for(i = 0; i < numOfCities; ++i)
{
dist[i] = INT_MAX;
sptSet[i] = false;
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
for(i = 0; i < (numOfCities - 1); ++i)
{
int tempMinDistance = minDistance(dist, sptSet, numOfCities);
sptSet[tempMinDistance] = true;
int j;
for(j = 0; j < numOfCities; ++j)
{
if (!sptSet[j] && map[tempMinDistance][j] && dist[tempMinDistance] != INT_MAX
&& dist[tempMinDistance] + map[tempMinDistance][j] < dist[j])
{
dist[j] = dist[tempMinDistance] + map[tempMinDistance][j];
}
}
}
for(i = 0; i < numOfCities; ++i)
{
if(dist[i] > maxDist)
{
maxDist = dist[i];
}
}
printf("The minimum time required before message is sent out from the capitol throughtout the empire is : %d\n", maxDist);
return;
}
/*
* @description : frees the memory for the 2d Adj. matrix
* @return : void
* @argument : takes in size of 2d square array and pointer to 2d array
*/
void freeMapMemory(int **map, int size)
{
int i;
for(i = 0; i < size; ++i)
{
free(map[i]);
}
free(map);
return;
}
|
C
|
#include"camera.h"
void init_camera(Camera *cam,SDL_Rect posperso,int width,int height)
{
cam->camera.x=posperso.x-(width*.5);
cam->camera.y=posperso.y-(height*.5);
cam->camera.w=width;
cam->camera.h=height;
}
void poscamera(Camera *cam,SDL_Rect posperso,int width,int height)
{
(cam->camera.x)=(posperso.x-posperso.w*.5)-(width*.5);
(cam->camera.y)=(posperso.y-posperso.h*.5)-(height*.5);
if((cam->camera.x)>=4000-width)
{
(cam->camera.x)=4000-width;
}
if(cam->camera.y>=4000-height)
{
(cam->camera.y)=4000-height;
}
if((cam->camera.x)<=0)
{
(cam->camera.x)=0;
}
if((cam->camera.y)<=0)
{
(cam->camera.y)=0;
}
}
|
C
|
/* gcc -Wall -o tree blatt3-rahmen.c --std=c99 */
#include <malloc.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct node {
struct node *left;
struct node *right;
int val;
};
struct node *new_node(int val)
{
struct node * new = (struct node*) malloc(sizeof(struct node));
new -> left = NULL;
new -> right = NULL;
new -> val = val;
}
struct node *insert_rec(struct node *node,
int val)
{
if(node == NULL)
return new_node(val);
if(val < node -> val)
if(node -> left == NULL) {
node -> left = new_node(val);
return node -> left;
}
else
return insert_rec(node -> left, val);
else
if(node -> right == NULL) {
node -> right = new_node(val);
return node -> right;
}
else
return insert_rec(node -> right, val);
}
struct node *make_random_tree(int num_nodes)
{
srand(time(0));
struct node * root = new_node(rand() % 100);
printf("Adding value %d.\n", root -> val);
num_nodes--;
while(num_nodes > 0) {
int val = rand() % 100;
insert_rec(root, val);
printf("Adding value %d.\n", val);
num_nodes--;
}
return root;
}
void iterate_in_order(struct node *node,
void (*f)(struct node *n))
{
if(node == NULL)
return;
iterate_in_order(node -> left, f);
f(node);
iterate_in_order(node -> right, f);
}
void iterate_pre_order(struct node *node,
void (*f)(struct node *n))
{
if(node == NULL)
return;
f(node);
iterate_pre_order(node -> left, f);
iterate_pre_order(node -> right, f);
}
void iterate_post_order(struct node *node,
void (*f)(struct node *n))
{
if(node == NULL)
return;
iterate_post_order(node -> left, f);
iterate_post_order(node -> right, f);
f(node);
}
/* Print the node's value */
void print_val(struct node *node)
{
printf("Value of node %p: %d\n", node, node -> val);
}
/* Add one to the node's value */
void plusone(struct node *node)
{
node -> val = node -> val + 1;
}
/* N.B.: -x invertiert die BST-Invariante
* * (rechter Teilbaum jetzt groesser als linker) */
void negate(struct node *node)
{
node -> val = -(node -> val);
}
/* N.B.: Nicht-monotone Funktionen zerstoeren
* die Struktur des Suchbaumes */
void magic(struct node *node)
{
int x = node -> val;
node -> val = (100-x)*x - 900;
}
/* Free only one node */
void free_node(struct node *node)
{
free(node);
}
void delete_tree(struct node *node) {
/* Jeder Teilbaum muss geloescht werden bevor der Wurzel
geloescht werden kann. Ansonsten wird die Adresse
dieses Teilbaum verloren und die Knoten darin koennen
nie geloescht werden.
*/
iterate_post_order(node, free_node);
}
int main(int argc, char *argv[])
{
struct node *root = NULL;
root = make_random_tree(5);
printf("Printing in order:\n");
iterate_in_order(root, print_val);
printf("\n");
printf("Printing in pre-order:\n");
iterate_pre_order(root, print_val);
printf("\n");
printf("Printing in post-order:\n");
iterate_post_order(root, print_val);
printf("\n");
/* Apply the manipulation functions */
printf("Original:\n");
iterate_pre_order(root, print_val);
printf("plusone:\n");
iterate_in_order(root, plusone);
iterate_pre_order(root, print_val);
printf("negate:\n");
iterate_in_order(root, negate);
iterate_pre_order(root, print_val);
printf("magic:\n");
iterate_in_order(root, magic);
iterate_pre_order(root, print_val);
printf("Printing in order (squared):\n");
iterate_in_order(root, print_val);
printf("\n");
/* Free each node*/
delete_tree(root);
//iterate_post_order(root, free_node);
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int n,b,a,count=0,c,sum=0,num,d;
printf("Enter a Number ");
scanf("%d",&n);
a=n;
d=n;
while(a!=0)
{
b=a%10;
count++;
a=a/10;
}
printf("The number %d has %d digits\n",n,count);
while(d!=0)
{
c=d%10;
num=pow(c,count);
sum+=num;
d=d/10;
}
if(n==sum)
printf("%d is Narcissistic Number",n);
else
printf("%d is Not a Narcissistic Number",n);
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
#include<malloc.h>
int factorial(int num, double fact)
{
if(num == 0)
{
printf("0");
return 0;
}
if(num == 1) return fact;
fact = fact * num;
factorial(--num, fact);
}
int main(int argc, char *argv[])
{
int num, i;
num = atoi(argv[1]);
double fact = 1;
fact = factorial(num, fact);
printf("%f\n",fact) ;
}
|
C
|
#include <stdio.h>
int linear_search(int arr[], int n, int i, int key)
{
if (i == n)
{
return -1;
}
if (arr[i] == key)
{
return i;
}
return linear_search(arr, n, i + 1, key);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", linear_search(arr, n, 0, 6));
printf("%d\n", linear_search(arr, n, 0, 100));
return 0;
}
|
C
|
#include "distance.h"
/* Find the minimum of 3 int
*
* Params:
* int a: first int
* int b: second int
* int c: third int
*
* Returns: the minimum.
*/
static int minimum (int a,int b, int c){
int minimum = a;
if (a > b){
minimum = b;
}
if (minimum > c){
minimum = c;
}
return minimum;
}
/*
* Find the distance of levenshtein for 2 words A,B.
*
* Params:
* char* : word a.
* char* : word b.
*
* Returns:
* int : returns the levenshtein distance with A and B.
*/
static void toLower(char *str) {
int i = 0;
while (str[i] != 0)
{
if (str[i] >= 'A' && str[i] <= 'Z') {
*(str + i) += 32;
}
i++;
}
}
int distance(char* a,char* b){
toLower(a);
toLower(b);
int lenA = strlen(a);
int lenB = strlen(b);
int matrice[lenA][lenB];
int check;
for (int i = 0; i < lenA; i++)
{
matrice[i][0] = i;
}
for (int j = 1; j < lenB; j++)
{
matrice[0][j] = j;
}
for (int i = 1; i < lenA; i++)
{
for (int j = 1; j < lenB; j++)
{
if (a[i] == b[j]){
check = 0;
}
else
{
check = 1;
}
matrice[i][j] = minimum(1 + matrice[i][j - 1], 1 + matrice[i-1][j], check + matrice[i-1][j-1]);
}
}
return matrice[lenA-1][lenB-1];
}
static int min(int a, int b) {
return a < b ? a : b;
}
|
C
|
#include<stdio.h>
int main()
{float tempFH, tempCS;
printf("Enter temperature in farheinheat") ;
scanf("%f",&tempFH);
tempCS = (tempFH-32)*5/9;
printf ("Temperature in centigrades is %f ",tempCS);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
unsigned power (unsigned x, unsigned y);
//void run_check (unsigned x, unsigned y, unsigned expected_ans);
void test (unsigned x, unsigned y, unsigned expected_ans) {
unsigned temp = power(x, y);
if (temp != expected_ans) {
exit (EXIT_FAILURE);
}
}
int main (void) {
char x = 2;
char y = 4;
test (1, 2, 1);
test (1, 1, 1);
test (2, 2, 4);
test (1, 0, 1);
test (0, 1, 0);
test (10000, 0, 1);
test (12345, 1, 12345);
test (x, y, 16);
// test (1, -1, 1);
// test (2, -1, 0.5);
// test (4, -2, 0.0625);
test (-2, 2, 4);
test (-2, 3, -8);
test (0, 0, 1);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main() {
struct sockaddr_in serv_addr;
int listen_fd = 0;
if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
exit(1);
}
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(8080);
if (bind(listen_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == -1) {
exit(1);
}
// 设置 backlog 为 1
if (listen(listen_fd, 1) == -1) {
exit(1);
}
sleep(100000000);
return 0;
}
|
C
|
#ifndef JHD_TLS_CAMELLIA_H
#define JHD_TLS_CAMELLIA_H
#include <tls/jhd_tls_config.h>
#include <stddef.h>
#include <stdint.h>
#include <tls/jhd_tls_cipher.h>
#define JHD_TLS_ERR_CAMELLIA_INVALID_KEY_LENGTH -0x0024 /**< Invalid key length. */
#define JHD_TLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH -0x0026 /**< Invalid data input length. */
#define JHD_TLS_ERR_CAMELLIA_HW_ACCEL_FAILED -0x0027 /**< Camellia hardware accelerator failed. */
// Regular implementation
//
/**
* \brief CAMELLIA context structure
*/
typedef struct {
int nr; /*!< number of rounds */
uint32_t rk[68]; /*!< CAMELLIA round keys */
} jhd_tls_camellia_context;
/**
* \brief CAMELLIA key schedule (encryption)
*
* \param ctx CAMELLIA context to be initialized
* \param key encryption key
* \param keybits must be 128, 192 or 256
*
* \return 0 if successful, or JHD_TLS_ERR_CAMELLIA_INVALID_KEY_LENGTH
*/
void jhd_tls_camellia_setkey_enc(jhd_tls_camellia_context *ctx, const unsigned char *key, unsigned int keybits);
/**
* \brief CAMELLIA key schedule (decryption)
*
* \param ctx CAMELLIA context to be initialized
* \param key decryption key
* \param keybits must be 128, 192 or 256
*
* \return 0 if successful, or JHD_TLS_ERR_CAMELLIA_INVALID_KEY_LENGTH
*/
void jhd_tls_camellia_setkey_dec(jhd_tls_camellia_context *ctx, const unsigned char *key, unsigned int keybits);
/**
* \brief CAMELLIA-ECB block encryption/decryption
*
* \param ctx CAMELLIA context
* \param mode JHD_TLS_CAMELLIA_ENCRYPT or JHD_TLS_CAMELLIA_DECRYPT
* \param input 16-byte input block
* \param output 16-byte output block
*
* \return 0 if successful
*/
void jhd_tls_camellia_crypt_ecb(jhd_tls_camellia_context *ctx, jhd_tls_operation_t mode, const unsigned char input[16], unsigned char output[16]);
void jhd_tls_camellia_ecb_func(jhd_tls_camellia_context *ctx, const unsigned char input[16], unsigned char output[16]);
#define jhd_tls_camellia_ecb_encrypt jhd_tls_camellia_ecb_func
#define jhd_tls_camellia_ecb_decrypt jhd_tls_camellia_ecb_func
/**
* \brief CAMELLIA-CBC buffer encryption/decryption
* Length should be a multiple of the block
* size (16 bytes)
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If on the other hand you need to retain the contents of the
* IV, you should either save it manually or use the cipher
* module instead.
*
* \param ctx CAMELLIA context
* \param mode JHD_TLS_CAMELLIA_ENCRYPT or JHD_TLS_CAMELLIA_DECRYPT
* \param length length of the input data
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
*
* \return 0 if successful, or
* JHD_TLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH
*/
void jhd_tls_camellia_crypt_cbc(jhd_tls_camellia_context *ctx, jhd_tls_operation_t mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output);
void jhd_tls_camellia_cbc_encrypt(jhd_tls_camellia_context *ctx, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output);
void jhd_tls_camellia_cbc_decrypt(jhd_tls_camellia_context *ctx, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output);
/**
* \brief CAMELLIA-CFB128 buffer encryption/decryption
*
* Note: Due to the nature of CFB you should use the same key schedule for
* both encryption and decryption. So a context initialized with
* jhd_tls_camellia_setkey_enc() for both JHD_TLS_CAMELLIA_ENCRYPT and CAMELLIE_DECRYPT.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If on the other hand you need to retain the contents of the
* IV, you should either save it manually or use the cipher
* module instead.
*
* \param ctx CAMELLIA context
* \param mode JHD_TLS_CAMELLIA_ENCRYPT or JHD_TLS_CAMELLIA_DECRYPT
* \param length length of the input data
* \param iv_off offset in IV (updated after use)
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
*
* \return 0 if successful, or
* JHD_TLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH
*/
void jhd_tls_camellia_crypt_cfb128(jhd_tls_camellia_context *ctx, jhd_tls_operation_t mode, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input,
unsigned char *output);
/**
* \brief CAMELLIA-CTR buffer encryption/decryption
*
* Note: Due to the nature of CTR you should use the same key schedule for
* both encryption and decryption. So a context initialized with
* jhd_tls_camellia_setkey_enc() for both JHD_TLS_CAMELLIA_ENCRYPT and JHD_TLS_CAMELLIA_DECRYPT.
*
* \warning You must never reuse a nonce value with the same key. Doing so
* would void the encryption for the two messages encrypted with
* the same nonce and key.
*
* There are two common strategies for managing nonces with CTR:
*
* 1. You can handle everything as a single message processed over
* successive calls to this function. In that case, you want to
* set \p nonce_counter and \p nc_off to 0 for the first call, and
* then preserve the values of \p nonce_counter, \p nc_off and \p
* stream_block across calls to this function as they will be
* updated by this function.
*
* With this strategy, you must not encrypt more than 2**128
* blocks of data with the same key.
*
* 2. You can encrypt separate messages by dividing the \p
* nonce_counter buffer in two areas: the first one used for a
* per-message nonce, handled by yourself, and the second one
* updated by this function internally.
*
* For example, you might reserve the first 12 bytes for the
* per-message nonce, and the last 4 bytes for internal use. In that
* case, before calling this function on a new message you need to
* set the first 12 bytes of \p nonce_counter to your chosen nonce
* value, the last 4 to 0, and \p nc_off to 0 (which will cause \p
* stream_block to be ignored). That way, you can encrypt at most
* 2**96 messages of up to 2**32 blocks each with the same key.
*
* The per-message nonce (or information sufficient to reconstruct
* it) needs to be communicated with the ciphertext and must be unique.
* The recommended way to ensure uniqueness is to use a message
* counter. An alternative is to generate random nonces, but this
* limits the number of messages that can be securely encrypted:
* for example, with 96-bit random nonces, you should not encrypt
* more than 2**32 messages with the same key.
*
* Note that for both stategies, sizes are measured in blocks and
* that a CAMELLIA block is 16 bytes.
*
* \warning Upon return, \p stream_block contains sensitive data. Its
* content must not be written to insecure storage and should be
* securely discarded as soon as it's no longer needed.
*
* \param ctx CAMELLIA context
* \param length The length of the data
* \param nc_off The offset in the current stream_block (for resuming
* within current cipher stream). The offset pointer to
* should be 0 at the start of a stream.
* \param nonce_counter The 128-bit nonce and counter.
* \param stream_block The saved stream-block for resuming. Is overwritten
* by the function.
* \param input The input data stream
* \param output The output data stream
*
* \return 0 if successful
*/
void jhd_tls_camellia_crypt_ctr(jhd_tls_camellia_context *ctx, size_t length, size_t *nc_off, unsigned char nonce_counter[16], unsigned char stream_block[16],
const unsigned char *input, unsigned char *output);
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*/
int jhd_tls_camellia_self_test(int verbose);
#endif /* camellia.h */
|
C
|
#include<stdio.h>
#include<stdbool.h>
bool Vowels(char str[])
{
if(str==NULL)
{
return 0;
}
while(*str != '\0')
{
if((*str=='a') || (*str=='A') || (*str=='e') || (*str=='E') || (*str=='i') || (*str=='I') || (*str=='o') || (*str=='O') || (*str=='u') || (*str=='U') )
{
break;
}
str++;
}
if(*str=='\0')
{
return false;
}
else
{
return true;
}
}
int main()
{
char Arr[40];
bool bRet;
printf("Enter String:\n");
scanf("%[^'\n']s",Arr);
bRet=Vowels(Arr);
if(bRet == true)
{
printf("Vowels are Present\n");
}
else
{
printf("Vowels are Not Present\n");
}
return 0;
}
|
C
|
#include "p11-12.h"
int main(void) /* 服務程式 */
{
struct exchange *shm;
int producer_ok,consumer_ok,i;
int shmid;
char readbuf[BUFSIZ];
/* 建立訊號量consumer和producer */
consumer_ok = open_semaphore_set(key1, 1);
producer_ok= open_semaphore_set(key2, 1);
init_a_semaphore(consumer_ok, 0, 1); /* 禁止消費 */
init_a_semaphore(producer_ok, 0, 0); /* 容許生產 */
/* 獲得並連線名為"shared"的共享儲存段 */
shm = (struct exchange *)shminit(ftok("shared",0),&shmid);
/* 從標准輸入讀資料並寫至共享儲存段 */
for ( i=0; ; i++ ) {
/* 讀入資料 */
semaphore_P(consumer_ok); /* 等待客戶執行緒釋放共享儲存段 */
printf("Enter some text:");
fgets(readbuf,BUFSIZ,stdin);
/* 填充共享儲存緩沖 */
shm->seq = i;
sprintf(shm->buf, "%s",readbuf);
semaphore_V(producer_ok); /* 容許客戶執行緒取資料 */
if (strncmp(readbuf, "end", 3) == 0 )
break;
}
semaphore_P(consumer_ok); /* 等待客戶執行緒消費完畢 */
/* 移除訊號量 */
rm_semaphore(producer_ok);
rm_semaphore(consumer_ok);
/* 分離並移除共享儲存段 */
shmdt(shm);
shmctl(shmid, IPC_RMID, (struct shmid_ds *)NULL);
exit(0);
}
|
C
|
#include <stdio.h>
#include <pthread.h>
pthread_t h1, h2;
void *hilo1 ();
void *hilo2 ();
int main() {
pthread_create (&h1, NULL, hilo1, NULL);
pthread_create (&h2, NULL, hilo2, NULL);
pthread_join (h1, NULL);
pthread_join (h2, NULL);
return 0;
}
void *hilo1(){
printf ("HILO1: Mi TID es %d\n", (int)pthread_self ());
sleep (10);
/* Esperamos 10 segundos */
pthread_exit(NULL);
}
void *hilo2(){
printf ("HILO2: Mi TID es %d\n", (int)pthread_self ());
sleep (10);
/* Esperamos 10 segundos */
pthread_exit(NULL);
}
|
C
|
#define _POSIX_C_SOURCE 200809L
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "libtep.h"
static FILE *OpenFile(char*, const char*, unsigned short);
static int AddLine(FILE*, size_t, book*, size_t);
static int RemoveLine(FILE*, size_t, book*, size_t);
static unsigned int CountLine(FILE*, size_t, unsigned int);
static char *ConcatString(char*, char*);
static char *itoa(int);
static book CslToStruct(char*, size_t, size_t);
static char *StructToCsl(book*, size_t, size_t);
static unsigned int FindLine(FILE*, char*, size_t);
static void SetupFilePath();
static void FindAndPrint(char*, char*, size_t);
static char *filename = NULL;
static char *pathname = NULL;
static FILE *OpenFile(char *inp_filename, const char *mode, unsigned short recurr)
{
if (memcmp(inp_filename, filename, strlen(filename)) == 0 || inp_filename == NULL) {
inp_filename = filename;
}
FILE *fp = fopen(inp_filename, mode);
if ( fp == NULL ) {
if ( recurr == 1 )
{
fprintf(stderr, "Error [%d]: Opening %s file\n", __LINE__, inp_filename);
exit(EXIT_FAILURE);
} else {
printf("Creating %s file...\n", inp_filename);
fp = OpenFile(inp_filename, "ab+", 1);
fp = fopen(inp_filename, mode);
}
}
return fp;
}
static int AddLine(FILE *fp, size_t max_l_len, book *to_add, size_t struct_size)
{
if ( max_l_len <= 0 ) { perror("Invalid input length given to AddLine\n"); exit(EXIT_FAILURE); }
char *line = (char *) malloc(max_l_len);
char *concd_line;
unsigned int line_n;
unsigned int line_p = 0;
unsigned int i;
char **args_arr = malloc(sizeof(char *) * struct_size);
fp = freopen(filename, "a", fp);
args_arr[0] = to_add->title;
args_arr[1] = to_add->author;
args_arr[2] = itoa(to_add->pages);
args_arr[3] = itoa(to_add->uid);
/* Traverse struct and concatenate each element into a string */
for (i=0; i<(struct_size-1); i++) {
if ( i != (struct_size-2)) {
concd_line = ConcatString(args_arr[i], ", ");
line_n = strlen(concd_line);
memcpy(line+line_p, concd_line, line_n);
} else {
line_n = strlen(args_arr[i]);
memcpy(line+line_p, args_arr[i], line_n);
free(concd_line);
}
line_p += line_n;
}
line[line_p] = '\0';
fprintf(fp, "%s\n", line);
return 1;
}
static int RemoveLine(FILE *fp, size_t max_l_len, book *to_rem, size_t struct_size)
{
/* Removes a line from the lib.txt file using the book->line variable */
char *n_fn = ConcatString(pathname, "/lib_temp.txt");
FILE *n_fp = OpenFile(n_fn, "w", 0);
char *lp = NULL;
size_t uid_len = 5;
char *uid = malloc(sizeof(char) * uid_len);
unsigned int converted_uid;
unsigned int current_line = 0;
unsigned int target_line = to_rem->line;
if ( fp != NULL ) {
fp = freopen(filename, "r", fp);
} else {
fp = OpenFile(filename, "r", 0);
}
/* Parse out the uid (last value in the string) and compare against to_rem->uid */
while(getline(&lp, &max_l_len, fp) != -1) {
if ( current_line != to_rem->line ) {
fprintf(n_fp, "%s", lp);
} else {
memcpy(uid, lp+(strlen(lp)-uid_len), uid_len);
uid[uid_len-1] = '\0';
converted_uid = atoi(uid);
if ( converted_uid != getuid()) {
printf("Cannot remove line %d: you are not the owner of this record\n");
fprintf(n_fp, "%s", lp);
}
}
current_line++;
}
if ( remove(filename) == 0 ) {
if ( rename(n_fn, filename) == 0 ) {
fclose(n_fp);
return 1;
}
}
return -1;
}
static unsigned int CountLine(FILE *fp, size_t max_l_len, unsigned int print_bool)
{
fp = freopen(filename, "r", fp);
char *lp = NULL;
unsigned int line = 0;
if ( print_bool == 1 ) {
printf("Format:\nTitle, Author, Pages, User\n\n");
}
while(getline(&lp, &max_l_len, fp) != -1) {
if ( print_bool == 1 ) {
printf("%s", lp);
}
line++;
}
return (line-1);
}
static unsigned int FindLine(FILE *fp, char *title_str, size_t max_l_len)
{
fp = freopen(filename, "r", fp);
char *lp = NULL;
unsigned int line_n = 0;
unsigned int title_len = strlen(title_str);
char *comp_str = (char *) malloc(sizeof(char) * title_len+1);
while(getline(&lp, &max_l_len, fp) != EOF) {
memcpy(comp_str, lp, title_len+1);
comp_str[title_len] = '\0';
if ( memcmp(title_str, comp_str, title_len) == 0 ) {
free(comp_str);
return line_n;
}
line_n++;
}
free(comp_str);
fprintf(stderr, "Could not find a document in %s with the title: %s\n", filename, title_str);
exit(1);
}
static char *ConcatString(char *o_str, char *a_str)
{
const size_t len_o_str = strlen(o_str);
const size_t len_a_str = strlen(a_str);
char *rtn_str = malloc(len_o_str + len_a_str + 1);
memcpy(rtn_str, o_str, len_o_str);
memcpy(rtn_str + len_o_str, a_str, len_a_str+1);
return rtn_str;
}
static char *itoa(int n)
{
char *str = (char *) calloc(1, sizeof(char) * sizeof(int)+1);
sprintf(str, "%d", n);
return str;
}
static book CslToStruct(char *inp_str, size_t max_l_len, size_t struct_size)
{
book rtn_struct;
book defaults = {"No Title", "No Author", 0, 0};
unsigned int i = 0;
unsigned int n = 0;
unsigned int c = 0;
unsigned int p = 0;
char **str_arr = calloc(struct_size, (sizeof(char) * max_l_len));
unsigned int ps_len;
inp_str = ConcatString(inp_str, ",");
ps_len = strlen(inp_str);
if ( ps_len > max_l_len ) {
fprintf(stderr, "Error [%d]: Input string is too long!\n", __LINE__);
exit(EXIT_FAILURE);
}
for(; n < ps_len ; n++) {
if ( (int)inp_str[n] == 44 ) { /* ASCII 44 is a comma */
p = n-c; /* Position is current index minus the last 'current' position. */
str_arr[i] = realloc(str_arr[i], p+1);
memcpy(str_arr[i], inp_str + c, p+1);
str_arr[i][p] = '\0';
i++;
if ( (int)inp_str[n+1] == 32 ) { /* ASCII 32 is whitespace */
c = n + 2;
} else {
c = n + 1;
}
}
}
free(inp_str);
rtn_struct.title = (str_arr[0] != NULL) ? str_arr[0] : defaults.title ;
rtn_struct.author = (str_arr[1] != NULL) ? str_arr[1] : defaults.author;
rtn_struct.pages = (str_arr[2] != NULL) ? atoi(str_arr[2]) : defaults.pages;
rtn_struct.uid = getuid();
return rtn_struct;
}
static char *StructToCsl(book *to_convert, size_t max_l_len, size_t struct_size)
{
book defaults = {"No Title", "No Author", 0, 0};
char **str_arr = malloc(sizeof(char *) * struct_size - 1);
char *part_str = NULL;
char *rtn_str = (char *) malloc(sizeof(char) * max_l_len);
unsigned int i = 0;
unsigned int p = 0;
size_t str_len;
str_arr[0] = to_convert->title; str_arr[1] = to_convert->author;
str_arr[2] = itoa(to_convert->pages); str_arr[3] = itoa(to_convert->uid);
for ( ; i < struct_size-1; i++ ) {
part_str = (i == struct_size-2) ? str_arr[i] : ConcatString(str_arr[i], ", ");
str_len = strlen(part_str);
memcpy(rtn_str+p, part_str, str_len);
p += str_len;
}
rtn_str[p] = '\0';
return rtn_str;
}
void SetupFilePath()
{
char *home_path = getenv("HOME");
char *file_path = NULL;
int rtn_code;
if ( home_path != NULL ) {
file_path = ConcatString(home_path, "/libtep");
rtn_code = mkdir(file_path, 0777);
if ( rtn_code != -1 ) {
printf("Directory created: %s\n", file_path);
}
if ( errno != EEXIST ) {
fprintf(stderr, "Error [%d]: mkdir error (%s)\n", __LINE__, strerror(errno));
exit(EXIT_FAILURE);
}
pathname = file_path;
filename = ConcatString(file_path, "/lib.txt");
}
}
void FindAndPrint(char* path, char* match, size_t max_l_len)
{
/* Finds a title in a readme.md file and prints the contents of that section (up to the next title) */
FILE *fp = OpenFile(path, "r", 0);
char *lp = NULL;
size_t lc_size = strlen(match);
char *lc = (char *) malloc(sizeof(char) * lc_size+1);
unsigned int n = 0;
unsigned int max_pound = 6; /* Reasonable value for the maximum number of pound symbols in a single README line, swap for arg or define if needed */
int m_flag = -1;
int p_flag = -1;
if ( fp == NULL ) {
fprintf(stderr, "No help file [%s] to display.\n", path);
exit(EXIT_FAILURE);
}
while(getline(&lp, &max_l_len, fp) != EOF) {
n=0;
if ( lp[n] == '#' ) {
for ( ; n <= max_pound; n++ ) {
if ( lp[n] != '#' && lp[n] != ' ' ) {
memcpy(lc, lp+n, lc_size+1);
lc[lc_size] = '\0';
m_flag = strncmp(match, lc, lc_size);
break;
}
}
}
if ( m_flag == 0 && p_flag == 0) {
printf("%s\n", lp);
} else if ( m_flag == 0 ) {
p_flag++;
}
}
fclose(fp);
free(lc);
}
|
C
|
/*
Student Name:Sunita Gosai
Subject:Programming Fundamental
Lab Sheet No:20
Program:WAP to find cube of any number using function with no argument
Date:18,Jan2017
*/
#include<stdio.h>
void cube();
int main(){
cube();
return(0);
}
void cube(){
int n,result;
printf("Enter any number:\n");
scanf("%d",&n);
result=n*n*n;
printf("%d is cube number\n",result);
}
|
C
|
#include <msp430.h>
#include <stdint.h>
#include "libs/i2c.h"
#include "libs/timer.h"
#include "libs/lcd.h"
uint8_t lcdAddr = 0x3F;
#define BT BIT3
#define EN BIT2
#define RW BIT1
void lcdWriteNibble(uint8_t nibble, uint8_t rs)
{ // BT EN RW RS
i2cSendByte(lcdAddr, nibble << 4 | BT | 0 | 0 | rs);
// Tambem pode inserir um wait aqui para diminuir a velocidade
i2cSendByte(lcdAddr, nibble << 4 | BT | EN | 0 | rs);
i2cSendByte(lcdAddr, nibble << 4 | BT | 0 | 0 | rs);
}
void lcdWriteByte(uint8_t byte, uint8_t rs)
{
// 2 repeticoes
// Pega a parte mais significativa do byte
lcdWriteNibble(byte >> 4, rs); // Desloca os bits para a direita
lcdWriteNibble(byte & 0x0F, rs); // Filtra os 4 bits menos significativos
}
void print(char * str)
{
while(*str)
lcdWriteByte(* str++, 1);
}
void lcdInit()
{
if(i2cSendByte(lcdAddr, 0)) // Descobrindo o endereco
lcdAddr = 0x27;
// Entra em modo 8 bits
lcdWriteNibble(0x3, 0);
lcdWriteNibble(0x3, 0);
lcdWriteNibble(0x3, 0);
// Entra em modo 4 bits
lcdWriteNibble(0x2, 0);
// Liga o cursor e o display sem fazer o cursor piscar
lcdWriteByte(0x0C, 0);
// Liga o cursor e o display e faz o cursor piscar
//lcdWriteByte(0x0F, 0);
// Comandos: return home and clear display
lcdWriteByte(0x02, 0);
lcdWriteByte(0x01, 0);
}
|
C
|
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/ioport.h>
// Used To Access KERNEL Macros And Functions
static int Major, result;
struct file_operations fops;
unsigned long start = 0xd260, length = 0x4;
// Parameter to assign value of any variable during loading of module
int memIO_init (void) {
// Registration of device and dynamic allocation of Major number
Major = register_chrdev (0, "memIO_device", &fops);
if (Major < 0)
{
printk (" Major number allocation is failed \n");
return (Major);
}
printk (" The Major number of the device is %d \n", Major);
result = check_region (start, length);
/* Probes the given address. If the address is already in use, the function will return an
* error, otherwise it will allocate the address range for the device. */
if (result < 0)
{
printk ("Allocation for I/O memory range is failed: Try other range\n");
return (result);
}
request_region (start, length, "memIO_device");
return 0;
}
void memIO_cleanup (void) {
// Deallocation of I/O memory region before unregistration of the device name
// and major number
release_region (start, length);
printk (" The I/O memory region is released successfully \n");
unregister_chrdev (Major, "memIO_device");
printk (" The Major number is released successfully \n");
}
module_init (memIO_init);
module_exit (memIO_cleanup);
MODULE_LICENSE("GPL");
|
C
|
#include "menger.h"
/**
* menger - draws a 2D Menger Sponge
* @level: is the level of the Menger Sponge to draw
*/
void menger(int level)
{
int i, j, size;
if (level == 0)
{
printf("#\n");
return;
}
size = pow(3, level);
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
if (sponge(i, j) == 1)
putchar(' ');
else
putchar('#');
}
putchar('\n');
}
}
/**
* sponge - posicionates the sponges
* @row: row size
* @col: column size
* Return: 1 if is posible to put a sponge 0 otherwise
*/
int sponge(int row, int col)
{
int res = 0;
if (row || col)
{
if (row % 3 == 1 && col % 3 == 1)
{
return (1);
}
else
{
res = sponge(row / 3, col / 3);
}
if (res == 1)
return (1);
}
return (0);
}
|
C
|
#include <gba_console.h>
#include <gba_video.h>
#include <gba_interrupt.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/dir.h>
#include "gbfs_stdio.h"
#define TEST(expr) if (!(expr)) printf("TEST failed! (%s:%d)\n", __FILE__, __LINE__)
void test_fopen()
{
FILE *fp;
fp = fopen("test.txt", "r");
TEST(NULL == fp);
fp = fopen("gbfs:/test.txt", "r");
TEST(NULL != fp);
fclose(fp);
chdir("gbfs:/");
fp = fopen("test.txt", "r");
TEST(NULL != fp);
fclose(fp);
}
void test_fread()
{
FILE *fp;
char buffer[256];
int bytes_read;
fp = fopen("gbfs:/test.txt", "r");
TEST(NULL != fp);
if (NULL == fp)
{
printf("failed to open file!\n");
exit(1);
}
fseek(fp, 0, SEEK_END);
TEST(87 == ftell(fp));
rewind(fp);
TEST(0 == ftell(fp));
/* test simple read */
bytes_read = fread(buffer, 1, 4, fp);
TEST(4 == bytes_read);
TEST(buffer[0] == '1');
TEST(buffer[1] == '2');
TEST(buffer[2] == '3');
TEST(buffer[3] == '4');
/* test reading end-bytes */
fseek(fp, -4, SEEK_END);
bytes_read = fread(buffer, 1, 4, fp);
TEST(4 == bytes_read);
TEST(buffer[0] == '4');
TEST(buffer[1] == '3');
TEST(buffer[2] == '2');
TEST(buffer[3] == '1');
/* test cropping output */
fseek(fp, -3, SEEK_END);
buffer[3] = 0x7f;
bytes_read = fread(buffer, 1, 4, fp);
TEST(3 == bytes_read);
TEST(buffer[0] == '3');
TEST(buffer[1] == '2');
TEST(buffer[2] == '1');
TEST(buffer[3] == 0x7f);
fclose(fp);
fp = NULL;
}
int main()
{
irqInit();
irqEnable(IRQ_VBLANK);
consoleInit(0, 4, 0, NULL, 0, 15);
BG_COLORS[0] = RGB5(0, 0, 0);
BG_COLORS[241] = RGB5(31, 31, 31);
REG_DISPCNT = MODE_0 | BG0_ON;
gbfs_init(0);
test_fopen();
test_fread();
printf("done.\n");
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int width;
int breadth;
scanf("%d %d", &width, &breadth);
if (width == 1 && breadth == 1)
printf ("#\n");
else
{
for(int i = 0; i<breadth; i++)
{
for(int j = 0; j<width;j++)
if( j == 0 || j == width - 1 || i == 0 || i == breadth - 1 )
printf("#");
else
printf(".");
printf("\n");
}
}
return 0;
}
|
C
|
#include "functions.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char* humidity() {
int leido,i,fd;
char* token;
char* chunk = (char*) malloc (128*sizeof(char));
char* buffer = (char*) malloc (512*sizeof(char));
fd = open ("request.txt", O_RDONLY);
assert(fd >= 0);
if (fd < 0){
perror("error en open()");
}
while((leido = read(fd,buffer,sizeof(buffer)*2048)) > 0) {
token = strtok(buffer, "< ");
while (token != NULL) {
if (strstr(token,"class=\"value\">")) {
strcpy(chunk,token);
chunk = strtok(token, ">");
while (chunk != NULL) {
if (strlen (chunk) <= 4) {
return chunk;
}
chunk = strtok(NULL, ">");
}
}
token=strtok(NULL, "< ");
}
}
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "map.h"
// https://en.wikipedia.org/wiki/Hash_table
void map_init(map* map, int capacity, int growth_trigger, float growth_rate) {
int size = sizeof(map_entry[capacity]);
map_entry* list = malloc(size);
memset(list, 0, size);
map->list = list;
map->capacity = capacity;
map->count = 0;
map->growth_trigger = growth_trigger;
map->growth_rate = growth_rate;
}
int map_grow(map* map) {
int new_capacity = (int)(map->capacity * map->growth_rate);
map_entry* new_list = malloc(sizeof(map_entry[new_capacity]));
memset(new_list, 0, new_capacity);
// reinserting items
int it;
for (it = 0; it < map->capacity; it++) {
if (map->list[it].key != 0) {
int new_index = triple32inc(map->list[it].key) % new_capacity;
// if key is zero, position is free, just add item there
// if key is not zero, go to first position
// while next is >= 0, go to next position
// iterate to find a value with key equal to zero
// add item there and set pointer from previous item
if (new_list[new_index].key != 0) {
int* ptr = &(new_list[new_index].first);
if (*ptr >= 0) {
while (1) {
new_index = *ptr;
ptr = &(new_list[new_index].next);
if (*ptr < 0) break;
}
}
while (1) {
new_index = (new_index + 1) % new_capacity;
if (new_list[new_index].key == 0) break;
}
*ptr = new_index;
new_list[new_index].key = map->list[it].key;
new_list[new_index].value = map->list[it].value;
new_list[new_index].first = -1;
new_list[new_index].next = -1;
}
else {
new_list[new_index].key = map->list[it].key;
new_list[new_index].value = map->list[it].value;
new_list[new_index].first = new_index;
new_list[new_index].next = -1;
}
}
}
free(map->list);
map->list = new_list;
map->growth_trigger = (int)(map->growth_trigger * map->growth_rate);
map->capacity = new_capacity;
}
int map_insert(map* map, int key, int value) {
if (key <= 0) return ERR_INVALID_KEY;
// checking whether to grow the map or not
if (map->count >= map->growth_trigger)
map_grow(map);
int new_index = triple32inc(key) % map->capacity;
// if key is zero, position is free, just add item there
// if key is not zero, go to first position
// while next is >= 0, go to next position
// iterate to find a value with key equal to zero
// add item there and set pointer from previous item
if (map->list[new_index].key != 0) {
int* ptr = &(map->list[new_index].first);
if (*ptr >= 0) {
while (1) {
new_index = *ptr;
if (map->list[new_index].key == key)
return ERR_DUPLICATE_KEY;
ptr = &(map->list[new_index].next);
if (*ptr < 0) break;
}
}
while (1) {
new_index = (new_index + 1) % map->capacity;
if (map->list[new_index].key == 0) break;
}
*ptr = new_index;
map->list[new_index].key = key;
map->list[new_index].value = value;
map->list[new_index].first = -1;
map->list[new_index].next = -1;
}
else {
map->list[new_index].key = key;
map->list[new_index].value = value;
map->list[new_index].first = new_index;
map->list[new_index].next = -1;
}
return OK;
}
int map_get(map* map, int key, int* out) {
if (key <= 0) return ERR_INVALID_KEY;
int index = triple32inc(key) % map->capacity;
// if key is zero, position is empty -> not found
// if key is not zero, go to first position and check
// while next is >= 0, go to next position and check
if (map->list[index].key != 0) {
int* ptr = &(map->list[index].first);
if (*ptr >= 0) {
while (1) {
index = *ptr;
if (map->list[index].key == key) {
*out = map->list[index].value;
return OK;
}
ptr = &(map->list[index].next);
if (*ptr < 0) break;
}
}
}
return ERR_KEY_NOT_FOUND;
}
int map_delete(map* map, int key) {
if (key <= 0) return ERR_INVALID_KEY;
int index = triple32inc(key) % map->capacity;
// if key is zero, position is empty -> not found
// if key is not zero, go to first position and check
// while next is >= 0, go to next position and check
// if found, set previous item pointer to next of deleted
// clear item
if (map->list[index].key != 0) {
int* ptr = &(map->list[index].first);
if (*ptr >= 0) {
while (1) {
index = *ptr;
if (map->list[index].key == key) {
*ptr = map->list[index].next;
map->list[index].key = 0;
map->list[index].value = 0;
map->list[index].first = 0;
map->list[index].next = 0;
return OK;
}
ptr = &(map->list[index].next);
if (*ptr < 0) break;
}
}
}
return ERR_KEY_NOT_FOUND;
}
|
C
|
int runLength(int N, int*arr, void*val_s, void*len_s){
int i;
int rN;
int *val = (int*) val_s;
int *len = (int*) len_s;
if(N==0)
return 0;
rN = 1;
val[0] = arr[0];
len[0] = 1;
for(i=(1);i<(N);i++){
if(val[rN-1] == arr[i]){
len[rN-1]++;
}
else{
val[rN] = arr[i];
len[rN] = 1;
rN++;
}
}
return rN;
}
int chmax(int*a, int b){
if(*a<b)
*a=b;
return a;
}
int N;
int A[100000];
int sz;
int val[100000];
int len[100000];
int longestSubarray(int*nums, int numsSz){
int i;
int res = 0;
N = numsSz;
for(i=0; i<N; i++)
A[i] = nums[i];
sz = runLength(N, A, val, len);
for(i=0; i<sz; i++)
if(val[i]==1)
chmax(&res, len[i] - 1);
for(i=0; i<sz; i++)
if(sz > 1 && val[i]==1)
chmax(&res, len[i]);
for(i=1; i<sz-1; i++)
if(val[i]==0 && len[i]==1)
chmax(&res, len[i-1] + len[i+1]);
return res;
}
|
C
|
/*
* Lisp Parsing Module
*/
#ifndef PARSE_H_
#define PARSE_H_
#include "tree.h"
#include "hashtable.h"
/*
* Constants
*/
#define MAX_LINE_LENGTH 1024
/*
* Functions
*/
/**
* Parse a Lisp expression of the form: (str<Child_1><Child2>...<Child_n>)
* where <Child_x> are sub-expressions,
* and return a parse tree.
* The created tree has to be destroyed by destroyTree.
*
* @param
* const char* string - string to parse.
*
* @preconditions
* string != NULL
*
* @return
* Parse tree.
*/
Tree* parseLispExpression(const char* string);
/**
* Print the given tree as a lisp expression of the same form as in parseLispExpression.
* Used for testing and debugging.
* Note: the printed expression is followed by a new-line.
*
* @param
* Tree* tree - Tree to print.
*
* @preconditions
* tree != NULL
*/
void printLisp(Tree* tree);
/**
* Check if the given expression tree represents an assignment expression.
*
* @param
* Tree* tree - Expression tree to examine.
*
* @preconditions
* tree != NULL
*
* @return
* true iff the Expression tree represents an assignment expression.
*/
bool isAssignmentExpression(Tree* tree);
/**
* Check if the given expression tree represents the quit command.
*
* @param
* Tree* tree - Expression tree to examine.
*
* @preconditions
* tree != NULL
*
* @return
* true iff the Expression tree represents a quit command.
*/
bool isEndCommand(Tree* tree);
/**
* Convert and expression tree to an equivalent expression string (infix notation, not lisp).
*
* @param
* Tree* tree - Expression tree to convert.
* char* buffer - buffer which the resulting string is saved into.
* unsigned int buffer_size - size of the buffer.
*
* @preconditions
* - tree != NULL, buffer != NULL
* - The buffer has to be large enough for the resulting string.
* preferably buffer_size should be >= MAX_LINE_LENGTH + 1.
*/
void expressionToString(Tree* tree, char* buffer, unsigned int buffer_size);
/**
* Parse variable initialization file.
*
* @param
* FILE* input_file - File to parse.
* HashTable table - Table into which parsed variables are inserted.
*
* @preconditions
* input_file != NULL, table != NULL
*/
void parseVariableInputFile(FILE* input_file, HashTable table);
/* Note: this function is in the interface for testing purposes. */
/**
* Parse a single variable assignment line (as read from a variable initialization file).
*
* @param
* char* line - line to parse.
* HashTable table - Table into which parsed variables are inserted.
*
* @preconditions
* input_file != NULL, table != NULL
*/
void parseVariableAssignmentLine(char* line, HashTable table);
#endif /* PARSE_H_ */
|
C
|
#include <stdio.h>
int a[5];
int top=-1;
void push(int x)
{
if(top==4)
{
printf("Overflow codition");
}
else
{
a[++top]=x;
}
}
void pop()
{ if(top==-1)
printf("Pop can't be done due to underflow condition");
else
top--;
}
void printstack()
{
int i;
for(i=0;i<5;i++)
printf("%d\n",a[i]);
}
int main()
{
push(3);
push(5);
push(7);
pop();
push(2);
push(8);
push(3);printstack();
}
|
C
|
#include "../test.h"
void type_c()
{
if (MANDATORY == 1)
{
title("Type c Mandatory: ");
/*1*/
{
PRINT("This %c string is %c been %c tested %c with %c", 0, 'a', 'b', 'c', 'd', 'e');
}
/*2*/
{
PRINT("This %c", 0, 0);
}
/*3*/
{
PRINT("This %c string is %c been %c tested %c with %c", 0, 'a', 'b', 0, 'd', 'e');
}
/*4*/
{
PRINT("This %c string is %c been %c tested %c with %c", 0, 'a', -1, '-', 'd', 'e' -256);
}
/*5*/
{
PRINT("This %c string is %c been %c tested %c with %c", 0, '-', 'b', '0' - 256, 'd', 0);
}
putstr_fd("\n", 2);
}
if (BONUS)
{
title("Type c Bonus: ");
/*1 - invalid flags*/
{
PRINT("% ++++##.10c", 0,'F');
}
/*2*/
{
PRINT("This %---------10c", 0, 'A');
}
/*3*/
{
PRINT("%20c", 0, 'e');
}
/*4*/
{
PRINT("%------------10c", 0, 0);
}
/*5*/
{
PRINT("%20c", 0, 0);
}
putstr_fd("\n", 2);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define S 25
void insertionSort (int * arr , int size)
{
/*
* Função de ordenação Insertion Sort
* @param endereço do array
* @param tamanho do array
*/
int temp;
int iCount, jCount;
for (iCount = 1 ; iCount < size ; iCount++)
{
temp = arr[iCount];
jCount = iCount - 1;
while (jCount >= 0 && arr[jCount] > temp)
{
arr[jCount + 1] = arr[jCount];
jCount--;
}
arr[jCount + 1] = temp;
}
return ;
}
void bucketSort(int * arr, int size, int qnt_baldes){
int i,j,k;
int min = arr[0], max = arr[0];
int *balde[qnt_baldes], qntNumeroBalde[qnt_baldes], alocadosBalde[qnt_baldes];
int tamanhoBalde = 0;
for (int i = 0; i < qnt_baldes; ++i){
alocadosBalde[i] = 1;
qntNumeroBalde[i] = 0;
balde[i] = malloc(sizeof(int) * alocadosBalde[i]);
}
for (int i = 0; i < size; ++i){
min = min < arr[i] ? min : arr[i];
max = max > arr[i] ? max : arr[i];
}
tamanhoBalde = ((max - min) / (float)qnt_baldes) + 0.5f;
for(int i = 0; i < size; ++i){
for (int j = 0; j < qnt_baldes; ++j){
if(min + (tamanhoBalde * (j + 1)) - 1 < arr[i] && j + 1 < qnt_baldes) continue;
if(alocadosBalde[j] <= qntNumeroBalde[j]){
alocadosBalde[j] *= 2;
balde[j] = realloc(balde[j], sizeof(int) * alocadosBalde[j]);
}
balde[j][qntNumeroBalde[j]++] = arr[i];
break;
}
}
k = 0; // Posição no Array final
for (int i = 0; i < qnt_baldes; ++i){
insertionSort(balde[i], qntNumeroBalde[i]);
for (int j = 0; j < qntNumeroBalde[i]; ++j){
arr[k++] = balde[i][j];
}
}
}
int main(){
int vetor[S], size;
int i;
clock_t c2, c1;
double tempo;
srand((unsigned)time(NULL));
printf ("Metodo: Bucket Sort\n");
printf("Vetor: \n");
for(i=0;i<S;i++){
vetor[i] = rand()%1000;
printf("%d ", vetor[i]);
}printf("\n");
c1=clock();
bucketSort(vetor, S, 250);
c2=clock();
tempo = (c2-c1)*1000.0/CLOCKS_PER_SEC;
printf("\nVetor Ordenado: \n");
for(i=0;i<S;i++) printf("%d ", vetor[i]);
printf("\n");
printf("\nTempo: %fms\n", tempo);
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int i=1,num,exponent;
long power=1;
printf("\nenter the number :");
scanf("%d",&num);
printf("\nexponent of num:");
scanf("%d",&exponent);
while(i<=exponent){
power=power*num;
i++;
}
printf("The %d power of %d is: %ld",num,exponent,power);
return 0;
}
|
C
|
//Derek D Kim
//Jan. 21, 2016
//CS 241
//HW0
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
//Chapter 4
//Memory allocation using malloc, heap and time
//if you want to use data after the lifetime of the function it was created in
//then you could use a static data out side of the function or create memory using malloc
//For every malloc there is a "free"
//Heap allocation Gotchas
//malloc would fail if we used up all the memory
//time would return a time_t and ctime would return a char* where most people can understand
//free(ptr); free(ptr); is wrong because it is freeing the memory twice
//free(ptr);
//printf("%s\n", ptr);
//above code is incorrect because it is trying to access part of the memory that have been freed
//above 2 mistakes could be avoided by only releasing the memory once your done with the memory
//also you could set the ptr to NULL once it has been freed as Dangling Pointer
//struct, typedefs and a linked list
struct data{
char* name;
int age;
struct data* friends;
};
typedef struct data Person;
Person* create_person(char*, int);
void destroy_person(Person*);
int main(){
Person* person1 = (Person*) malloc(sizeof(Person));
Person* person2 = (Person*) malloc(sizeof(Person));
person1->name = "Agent Smith";
person2->name = "Sonny Moore";
person1->age = 128;
person2->age = 256;
person1->friends = person2;
person2->friends = person1;
printf("%s %s %d %d %s %s \n", person1->name, person2->name, person1->age, person2->age, person1->friends->name, person2->friends->name);
free(person1);
free(person2);
//Duplicating strings, memory allocation and deallocation of structures
Person* person3 = create_person("Agent Smith", 128);
Person* person4 = create_person("Sonny Moore", 256);
printf("%s %s %d %d \n", person3->name, person4->name, person3->age, person4->age);
destroy_person(person3);
destroy_person(person4);
return 0;
}
Person* create_person(char* p_name, int p_age){
Person* result = (Person*) malloc(sizeof(Person));
result->name = strdup(p_name);
result->age = p_age;
result->friends = NULL;
return result;
}
void destroy_person(Person* p){
free(p->name);
p->name = NULL;
free(p);
p = NULL;
}
|
C
|
/*
David Morosini de Assumpção
*/
#include "linkedlist.h"
/*Funções para inicialização das estruturas de dados*/
lst_node * new_node_(cell * data, lst_node * prox_node){
lst_node * n = (lst_node *)malloc(sizeof(lst_node));
assert(n != NULL);
if(n != NULL){
n -> data = data;
n -> prox = prox_node;
}
return n;
}
lst_node * new_node(cell * data){
lst_node * n = (lst_node *)malloc(sizeof(lst_node));
assert(n != NULL);
if(n != NULL){
n -> data = data;
n -> prox = NULL;
}
return n;
}
lst * new_lst(lst_node * start){
lst * l = (lst *)malloc(sizeof(lst));
assert(l != NULL);
if(l != NULL){
l -> start = start;
l -> end = start;
}
return l;
}
lst * add_init(lst * l, lst_node * n){
if(l == NULL || l -> start == NULL){
l = new_lst(n);
}else{
n -> prox = l -> start;
l -> start = n;
}
return l;
}
lst * add_end(lst * l, lst_node * n){
if(l == NULL || l -> start == NULL){
l = new_lst(n);
}else{
l -> end -> prox = n;
l -> end = n;
}
return l;
}
cell * get_data_node(lst_node * l){
cell * data;
if(l != NULL){
data = l -> data;
}
return data;
}
lst_node * get_prox_node(lst_node * l){
lst_node * lp = NULL;
assert(l != NULL);
if(l != NULL){
lp = l -> prox;
}
return lp;
}
lst_node * get_start_node(lst * l){
lst_node * ls = NULL;
if(l != NULL){
ls = l -> start;
}
return ls;
}
lst_node * get_end_node(lst * l){
lst_node * le = NULL;
if(l != NULL){
le = l -> end;
}
return le;
}
int get_size_lst(lst * l){
int size = 0;
assert(l != NULL);
if(l != NULL && l -> start != NULL){
size = 1;
//se o comeco for igual ao fim, significa que só tem um
if(l -> start != l-> end){
lst_node * aux = l -> start -> prox;
while(aux != NULL){
size++;
aux = aux -> prox;
}
}
}
return size;
}
|
C
|
/* Authors:
* Trevor Perrin
*
* See the LICENSE file for legal information regarding use of this file.
*/
#ifndef __TACK_STORE_FUNCS_H__
#define __TACK_STORE_FUNCS_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include "TackRetval.h"
#include "TackFingerprints.h"
/* Structure used to communicate with the store functions */
typedef struct {
uint32_t initialTime;
uint32_t endTime;
char fingerprint[TACK_KEY_FINGERPRINT_TEXT_LENGTH+1];
} TackPin;
typedef struct {
uint8_t numPins;
TackPin pins[2];
} TackPinPair;
TACK_RETVAL appendPin(TackPinPair* pair, uint32_t initialTime, uint32_t endTime,
char* fingerprint);
/* Store functions used to communicate with the store: */
/* Returns TACK_OK_NOT_FOUND if no key record */
typedef TACK_RETVAL (*TackGetMinGenerationFunc)(const void* arg,
const char* keyFingerprint,
uint8_t* minGeneration);
/* Overwrites existing minGeneration if new value is larger, or writes a new value
if there's no existing key record. If new value is smaller, returns TACK_OK
but does nothing. */
typedef TACK_RETVAL (*TackSetMinGenerationFunc)(const void* arg,
const char* keyFingerprint,
uint8_t minGeneration);
/* Returns TACK_OK_NOT_FOUND if no pins */
typedef TACK_RETVAL (*TackGetPinPairFunc)(const void* arg,
const void* name,
TackPinPair* pair);
/* Returns TACK_OK_NOT_FOUND if no pins */
typedef TACK_RETVAL (*TackSetPinPairFunc)(const void* arg,
const void* name,
const TackPinPair* pair);
/* The store functions, plus a state "arg", are packaged into this struct
for convenient parameter passing */
typedef struct {
TackGetMinGenerationFunc getMinGeneration;
TackSetMinGenerationFunc setMinGeneration; /* Generations and pin activation */
TackGetPinPairFunc getPinPair;
TackSetPinPairFunc setPinPair;
} TackStoreFuncs;
#ifdef __cplusplus
}
#endif
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_convert.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ccastill <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/10 04:30:51 by carlos #+# #+# */
/* Updated: 2020/07/19 01:00:50 by ccastill ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
size_t ft_strlen_str(const char *s, int l)
{
size_t count;
count = 0;
while (s[l] >= '0' && s[l] <= '9')
{
count++;
l++;
}
return (count);
}
int ft_asterisk_1(t_list_printf *next)
{
int width;
width = 0;
width = va_arg(next->args, int);
if (width < 0)
{
width *= -1;
next->neg = 1;
}
next->len++;
return (width);
}
int ft_convert(const char *s, t_list_printf *next)
{
char *new;
int n;
if (s[next->len] >= '0' && s[next->len] <= '9')
{
new = ft_substr(s, next->len, (ft_strlen_str(s, next->len)));
next->len += ft_strlen_str(s, next->len);
n = ft_atoi(new);
free(new);
new = NULL;
return (n);
}
else if (s[next->len] == '*')
return(ft_asterisk_1(next));
}
else if (s[next->len] == '*' && next->flags == '0')
{
return(ft_asterisk_1(next));
}
else if (s[next->len] == '*' && next->flags == '-')
{
next->flags = '0';
}
else if (!((s[next->len] >= '0' && s[next->len] <= '9')))
return (0);
else
return(next->width);
}
|
C
|
/**
* 3460:677 Final Project: Paralelizing OCR using PCA
* Christopher Stoll, 2014
*/
#ifndef OCRLIB_C
#define OCRLIB_C
#include <stdlib.h>
#include <math.h>
#include "ocrKit.c"
#include "imageDocument.c"
#include "resizeImage.c"
#define STANDARD_IMAGE_SIDE 16
#define DEBUG_SAVE_STANDARDIZED_CHARACTERS 0
#define DEBUG_PRINT_STANDARDIZED_CHARACTERS 0
static int standardizeImageMatrix(int *imageVector, int imageWidth, struct imageDocumentChar *imageDocChar, int **charImage)
{
int width = imageDocChar->x2 - imageDocChar->x1;
int height = imageDocChar->y2 - imageDocChar->y1;
// ignore things, spaces, which do not need sizing
if ((width == 0) || height == 0) {
return 0;
}
int padding = 0;
int paddingQ = 0;
int paddingR = 0;
int newWidth = width;
int newHeight = height;
int padLeft = 0;
int padRight = newWidth;
int padTop = 0;
int padBottom = newHeight;
// only if the area is rectangular
// determine how to fix the shorter dimension
if (height != width) {
if (height > width) {
padding = height - width;
paddingQ = (int)(padding / 2);
paddingR = padding - (paddingQ * 2);
newWidth = paddingQ + width + paddingQ + paddingR;
padLeft = paddingQ;
padRight = padLeft + width - 1;
} else {
padding = width - height;
paddingQ = (int)(padding / 2);
paddingR = padding - (paddingQ * 2);
newHeight = paddingQ + paddingR + height + paddingQ;
padTop = paddingQ + paddingR;
padBottom = padTop + height - 1;
}
}
// create a working image
int *tempImage = (int*)malloc((unsigned long)newWidth * (unsigned long)newHeight * sizeof(int));
memset(tempImage, 0, ((unsigned long)newWidth * (unsigned long)newHeight * sizeof(int)));
int k = 0;
int l = 0;
int imagePixel = 0;
int currentPixel = 0;
for (int i = 0; i < newHeight; ++i) {
if ((i >= padTop) && i <= padBottom) {
k = 0;
for (int j = 0; j < newWidth; ++j) {
if ((j >= padLeft) && (j <= padRight)) {
imagePixel = ((imageDocChar->y1 + l) * imageWidth) + (imageDocChar->x1 + k);
currentPixel = (i * newWidth) + j;
++k;
tempImage[currentPixel] = imageVector[imagePixel];
}
}
++l;
}
}
int targetImageWidth = STANDARD_IMAGE_SIDE;
int *resizedImage = (int*)malloc((unsigned long)targetImageWidth * (unsigned long)targetImageWidth * sizeof(int));
memset(resizedImage, 0, ((unsigned long)targetImageWidth * (unsigned long)targetImageWidth * sizeof(int)));
sizeSquareImage(tempImage, resizedImage, newWidth, targetImageWidth);
if (DEBUG_SAVE_STANDARDIZED_CHARACTERS) {
char fName[100] = "./tst/tst-1-";
char buffer[32];
snprintf(buffer, sizeof(buffer), "%d-%d.png", imageDocChar->y1, imageDocChar->x1);
strcat(fName, buffer);
write_png_file(resizedImage, targetImageWidth, targetImageWidth, fName);
// write_png_file(tempImage, newWidth, newHeight, fName);
}
*charImage = resizedImage;
if (DEBUG_PRINT_STANDARDIZED_CHARACTERS) {
for (int i = 0; i < (STANDARD_IMAGE_SIDE*STANDARD_IMAGE_SIDE); ++i) {
printf("%3d ", resizedImage[i]);
if (!(i % STANDARD_IMAGE_SIDE)) {
printf("\n");
}
if (!(i % (STANDARD_IMAGE_SIDE*STANDARD_IMAGE_SIDE))) {
printf("\n");
}
}
}
return 1;
}
static double *projectCandidate(int *charImageVector, struct OCRkit *ocrKit)
{
int klimit = (int)(ocrKit->klimit / 4);
double *tempWeights = (double*)malloc((unsigned long)klimit * sizeof(double));
memset(tempWeights, 0, ((unsigned long)klimit * sizeof(double)));
double *eigenImageSpace = ocrKit->eigenImageSpace;
int dimensionality = ocrKit->dimensionality;
int currentEigen = 0;
double weight = 0;
for (int i = 0; i < klimit; ++i) {
weight = 0;
for (int j = 0; j < (STANDARD_IMAGE_SIDE * STANDARD_IMAGE_SIDE); ++j) {
currentEigen = (i * dimensionality) + j;
weight += (charImageVector[j] * eigenImageSpace[currentEigen]);
}
tempWeights[i] = weight;
}
return tempWeights;
}
static void ocrCharacter(struct OCRkit *ocrKit, struct imageDocumentChar *imageDocChar)
{
if (imageDocChar) {
//printf("%c", imageDocChar->value);
int *charImage;
int standardizeOk = standardizeImageMatrix(ocrKit->imageVector, ocrKit->imageWidth, imageDocChar, &charImage);
if (standardizeOk) {
double *weights = projectCandidate(charImage, ocrKit);
free(charImage);
char answer = nearestNeighbor(ocrKit, weights);
imageDocChar->value = answer;
// printf("%c", answer);
} else {
imageDocChar->value = imageDocChar->value;
// printf("%c", imageDocChar->value);
}
}
}
static void ocrCharLoop(struct OCRkit *ocrKit, struct imageDocumentLine *imageDocLine)
{
if (imageDocLine) {
if (imageDocLine->characters) {
struct imageDocumentChar *currentChar = imageDocLine->characters;
struct imageDocumentChar *nextChar = NULL;
ocrCharacter(ocrKit, currentChar);
while (currentChar->nextChar) {
nextChar = currentChar->nextChar;
currentChar = nextChar;
ocrCharacter(ocrKit, currentChar);
}
freeImageDocumentChar(nextChar);
}
}
}
static void ocrLineLoop(struct OCRkit *ocrKit)
{
struct imageDocument *imageDoc = ocrKit->imageDoc;
if (imageDoc) {
if (imageDoc->lines) {
struct imageDocumentLine *currentLine = imageDoc->lines;
struct imageDocumentLine *nextLine = NULL;
ocrCharLoop(ocrKit, currentLine);
while (currentLine->nextLine) {
nextLine = currentLine->nextLine;
currentLine = nextLine;
ocrCharLoop(ocrKit, currentLine);
}
freeImageDocumentLine(nextLine);
}
}
}
static void startOcr(struct OCRkit *ocrKit)
{
ocrLineLoop(ocrKit);
}
#endif
|
C
|
#include<stdio.h>
#include"Create.c"
#define ARRAYLWN 12
/*
ðĻ˼ǣ
ͷɨ¼УɨĹ˳ȽԪصĴС
ִlength-1ɣÿ˶n-iΡͻύݣύ
һûзô˵鱾Ѿõ
Ծֹ
*/
void BubbleSort(int a[],int n){
int i ,j ,change = 1;
int x= 0;
for(i = 1;(i<=n-1) && (change==1);i++){
change = 0;
for(j = 1;j<=n-i;j++)
if(a[j]>a[j+1]){
x = a[j];
a[j] = a[j+1];
a[j+1] = x;
change = 1;
}
}
printf(":");
for(i = 0;i<ARRAYLWN;i++)
printf("%d ",a[i]);
printf("\n");
}
int main(void){
int i ;
int a[ARRAYLWN];
for(i = 0;i<ARRAYLWN;i++)
a[i] = 0;
if(!Create(a,ARRAYLWN,1,100)){
printf("ʧܣ");
getch();
return 1;
}
printf("ԭ:");
for(i = 0;i<ARRAYLWN;i++){
printf("%d ",a[i]);
}
printf("\n");
BubbleSort(a,ARRAYLWN);
getch();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <3ds.h>
#include "fs.h"
#include "file.h"
FS_Archive fsArchive, ctrArchive;
//extern FS_Archive fsArchive;
u32 crc32(u8 *buf, u32 len)
{
uint32_t crc=0;
static uint32_t table[256];
uint32_t rem;
uint8_t octet;
int i, j;
u8 *p, *q;
/* This check is not thread safe; there is no mutex. */
/* Calculate CRC table. */
for (i = 0; i < 256; i++) {
rem = i; /* remainder from polynomial division */
for (j = 0; j < 8; j++) {
if (rem & 1) {
rem >>= 1;
rem ^= 0xedb88320;
} else
rem >>= 1;
}
table[i] = rem;
}
crc = ~crc;
q = buf + len;
for (p = buf; p < q; p++) {
octet = *p; /* Cast to unsigned octet. */
crc = (crc >> 8) ^ table[(crc & 0xff) ^ octet];
}
return ~crc;
}
void openArchive(FS_ArchiveID id)
{
FSUSER_OpenArchive(&fsArchive, id, fsMakePath(PATH_EMPTY, ""));
}
void closeArchive(FS_ArchiveID id)
{
FSUSER_CloseArchive(fsArchive);
}
Result makeDir(FS_Archive archive, const char * path)
{
if ((!archive) || (!path))
return -1;
return FSUSER_CreateDirectory(archive, fsMakePath(PATH_ASCII, path), 0);
}
bool fileExists(const char * path)
{
if (!path)
return false;
Handle handle;
openArchive(ARCHIVE_SDMC);
Result ret = FSUSER_OpenFile(&handle, fsArchive, fsMakePath(PATH_ASCII, path), FS_OPEN_READ, 0);
closeArchive(fsArchive);
if (R_FAILED(ret))
return false;
ret = FSFILE_Close(handle);
if (R_FAILED(ret))
return false;
return true;
}
bool fileExistsNand(const char * path)
{
if (!path)
return false;
Handle handle;
openArchive(ARCHIVE_NAND_CTR_FS);
Result ret = FSUSER_OpenFileDirectly(&handle, ARCHIVE_NAND_CTR_FS, fsMakePath(PATH_EMPTY, ""), fsMakePath(PATH_ASCII, path), FS_OPEN_READ, 0);
if (R_FAILED(ret))
{
closeArchive(ARCHIVE_NAND_CTR_FS);
return false;
}
ret = FSFILE_Close(handle);
if (R_FAILED(ret))
{
closeArchive(ARCHIVE_NAND_CTR_FS);
return false;
}
closeArchive(ARCHIVE_NAND_CTR_FS);
return true;
}
bool dirExists(FS_Archive archive, const char * path)
{
if ((!path) || (!archive))
return false;
Handle handle;
Result ret = FSUSER_OpenDirectory(&handle, archive, fsMakePath(PATH_ASCII, path));
if (R_FAILED(ret))
return false;
ret = FSDIR_Close(handle);
if (R_FAILED(ret))
return false;
return true;
}
u64 getFileSize(const char * path)
{
u64 st_size;
Handle handle;
openArchive(ARCHIVE_SDMC);
FSUSER_OpenFile(&handle, fsArchive, fsMakePath(PATH_ASCII, path), FS_OPEN_READ, 0);
FSFILE_GetSize(handle, &st_size);
closeArchive(fsArchive);
FSFILE_Close(handle);
return st_size;
}
Result readFile(const char * path, void * buf, u32 size)
{
Handle handle;
u32 read=0;
Result res;
//if (fileExists(path))
//FSUSER_DeleteFile(fsArchive, fsMakePath(PATH_ASCII, path));
Result ret = FSUSER_OpenFileDirectly(&handle, ARCHIVE_SDMC, fsMakePath(PATH_EMPTY, ""), fsMakePath(PATH_ASCII, path), FS_OPEN_READ, 0);
if(ret) return ret;
res = FSFILE_Read(handle, &read, 0, buf, size);
ret = FSFILE_Close(handle);
return R_SUCCEEDED(res)? 0 : -1;
}
Result writeFile(const char * path, void * buf, u32 size)
{
Handle handle;
u32 written=0;
Result res;
if (fileExists(path))
FSUSER_DeleteFile(fsArchive, fsMakePath(PATH_ASCII, path));
Result ret = FSUSER_OpenFileDirectly(&handle, ARCHIVE_SDMC, fsMakePath(PATH_EMPTY, ""), fsMakePath(PATH_ASCII, path), (FS_OPEN_WRITE | FS_OPEN_CREATE), 0);
if(ret) return ret;
ret = FSFILE_SetSize(handle, size);
res = FSFILE_Write(handle, &written, 0, buf, size, FS_WRITE_FLUSH);
ret = FSFILE_Close(handle);
if(size != written) return 1;
return R_SUCCEEDED(res)? 0 : -1;
}
Result copy_file(char * old_path, char * new_path)
{
int chunksize = (512 * 1024);
char * buffer = (char *)malloc(chunksize);
u32 bytesWritten = 0, bytesRead = 0;
u64 offset = 0;
Result ret = 0;
Handle inputHandle, outputHandle;
Result in = FSUSER_OpenFileDirectly(&inputHandle, ARCHIVE_SDMC, fsMakePath(PATH_EMPTY, ""), fsMakePath(PATH_ASCII, old_path), FS_OPEN_READ, 0);
u64 size = getFileSize(old_path);
openArchive(ARCHIVE_SDMC);
if (R_SUCCEEDED(in))
{
// Delete output file (if existing)
FSUSER_DeleteFile(fsArchive, fsMakePath(PATH_ASCII, new_path));
Result out = FSUSER_OpenFileDirectly(&outputHandle, ARCHIVE_SDMC, fsMakePath(PATH_EMPTY, ""), fsMakePath(PATH_ASCII, new_path), (FS_OPEN_CREATE | FS_OPEN_WRITE), 0);
if (R_SUCCEEDED(out))
{
// Copy loop (512KB at a time)
do
{
ret = FSFILE_Read(inputHandle, &bytesRead, offset, buffer, chunksize);
bytesWritten += FSFILE_Write(outputHandle, &bytesWritten, offset, buffer, size, FS_WRITE_FLUSH);
if (bytesWritten == bytesRead)
break;
}
while(bytesRead);
ret = FSFILE_Close(outputHandle);
if (bytesRead != bytesWritten)
return ret;
}
else
return out;
FSFILE_Close(inputHandle);
closeArchive(ARCHIVE_SDMC);
}
else
return in;
free(buffer);
return ret;
}
Result delete_file(const char * path){
Result ret;
ret = FSUSER_DeleteFile(fsArchive, fsMakePath(PATH_ASCII, path));
return ret;
}
Result cia_install(const char* path) {
u8 media=MEDIATYPE_SD; //sd
u32 bufSize = 1024 * 1024; // 1MB
void* buf = malloc(bufSize);
u64 pos = 0;
u32 bytesRead;
Result res;
AM_InitializeExternalTitleDatabase(false); //dont overwrite if db already exists
FILE *f=fopen(path,"rb");
if(!f) {
res = 1;
goto exit;
}
u64 size;
size = getFileSize(path);
Handle ciaHandle;
res=AM_StartCiaInstall(media, &ciaHandle);
if(res) goto exit;
FSFILE_SetSize(ciaHandle, size);
for(pos=0; pos<size; pos+=bufSize){
//FSFILE_Read(fileHandle, &bytesRead, pos, buf, bufSize);
bytesRead = fread(buf, 1, bufSize, f);
FSFILE_Write(ciaHandle, NULL, pos, buf, bytesRead, FS_WRITE_FLUSH);
printf("\rProgress %d/%d MB ",(int)(pos/bufSize+1),(int)(size/bufSize+1));
}
printf("\n");
res=AM_FinishCiaInstall(ciaHandle);
exit:
free(buf);
fclose(f);
return res;
}
|
C
|
/* open.c */
#include <fcntl.h> /* defines options flags */
#include <sys/types.h> /* defines types used by sys/stat.h */
#include <sys/stat.h> /* defines S_IREAD & S_IWRITE */
static char message[] = "Hello, world";
int main()
{
int fd;
char buffer[80];
/* open datafile.dat for read/write access (O_RDWR)
create datafile.dat if it does not exist (O_CREAT)
return error if datafile already exists (O_EXCL)
permit read/write access to file (S_IWRITE | S_IREAD)
*/
fd = open("datafile.dat",O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE);
if (fd != -1)
{
printf("datafile.dat opened for read/write access\n");
write(fd, message, sizeof(message));
lseek(fd, 0L, 0); /* go back to the beginning of the file */
if (read(fd, buffer, sizeof(message)) == sizeof(message))
printf("\"%s\" was written to datafile.dat\n", buffer);
else
printf("*** error reading datafile.dat ***\n");
close (fd);
}
else
printf("*** datafile.dat already exists ***\n");
exit (0);
}
|
C
|
#include "pbdata.h"
/* ----------------------------------------------------------------------*/
__IO uint32_t AsynchPrediv = 0, SynchPrediv = 0;
#define RTC_CLOCK_SOURCE_LSI //ʹLSIʱ
#define RTC_FLAG_BKP 0xA55A //־
/************************************************
RTC_Configuration
RTC
ֵ
MCD Application Team
*************************************************/
void RTC_Configuration(void)
{
/* 1ʹLSIʱ */
#if defined (RTC_CLOCK_SOURCE_LSI)
RCC_LSICmd(ENABLE); //ʹLSIʱ
while(RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET)
{ //ȴLSI
}
RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI); //ѡLSIʱ
SynchPrediv = 0x18F;
AsynchPrediv = 0x63;
/* 2ʹLSEʱ */
#elif defined (RTC_CLOCK_SOURCE_LSE)
RCC_LSEConfig(RCC_LSE_ON); //ʹLSIʱ
while(RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
{ //ȴLSI
}
RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); //ѡLSIʱ
SynchPrediv = 0xFF;
AsynchPrediv = 0x7F;
#else
#error Please select the RTC Clock source inside the main.c file
#endif
RCC_RTCCLKCmd(ENABLE); //ʹRTC
RTC_WaitForSynchro(); //ȴͬ
}
/************************************************
RTC_Initializes
RTCʼ
ֵ
Huang Fugui
*************************************************/
void RTC_Initializes(void)
{
RTC_InitTypeDef RTC_InitStructure;
RTC_DateTimeTypeDef RTC_DateTimeStructure;
PWR_BackupAccessCmd(ENABLE); //RTC
if(RTC_ReadBackupRegister(RTC_BKP_DR0) != RTC_FLAG_BKP)
{
RTC_Configuration(); //RTC
RTC_InitStructure.RTC_AsynchPrediv = AsynchPrediv;
RTC_InitStructure.RTC_SynchPrediv = SynchPrediv;
RTC_InitStructure.RTC_HourFormat = RTC_HourFormat_24;
if(RTC_Init(&RTC_InitStructure) == ERROR)
{
while(1); //ʼʧ
}
RTC_DateTimeStructure.Hour = 23;
RTC_DateTimeStructure.Minute = 59;
RTC_DateTimeStructure.Second = 59;
RTC_SetDateTime(RTC_DateTimeStructure);
RTC_WriteBackupRegister(RTC_BKP_DR0, RTC_FLAG_BKP);
}
else
{
#ifdef RTC_CLOCK_SOURCE_LSI
RCC_LSICmd(ENABLE);
#endif
RTC_WaitForSynchro(); //ȴRTCRTC_APBʱͬ
}
}
/************************************************
RTC_DateRegulate
RTCڽ
RTC_DateTimeStructure -- RTCṹ
ֵ RTC_OK ----------------- ɹ
RTC_ERR ----------------
Huang Fugui
*************************************************/
RTC_RESULT RTC_DateRegulate(RTC_DateTimeTypeDef RTC_DateTimeStructure)
{
RTC_DateTypeDef RTC_DateStructure;
if(RTC_SetDate(RTC_Format_BIN, &RTC_DateStructure) == SUCCESS)
{
return RTC_OK;
}
else
{
return RTC_ERR;
}
}
/************************************************
RTC_TimeRegulate
RTCʱ
RTC_DateTimeStructure -- RTCṹ
ֵ RTC_OK ----------------- ɹ
RTC_ERR ----------------
Huang Fugui
*************************************************/
RTC_RESULT RTC_TimeRegulate(RTC_DateTimeTypeDef RTC_DateTimeStructure)
{
RTC_TimeTypeDef RTC_TimeStructure;
RTC_TimeStructure.RTC_H12 = RTC_H12_AM;
RTC_TimeStructure.RTC_Hours = RTC_DateTimeStructure.Hour;
RTC_TimeStructure.RTC_Minutes = RTC_DateTimeStructure.Minute;
RTC_TimeStructure.RTC_Seconds = RTC_DateTimeStructure.Second;
if(RTC_SetTime(RTC_Format_BIN, &RTC_TimeStructure) == SUCCESS)
{
return RTC_OK;
}
else
{
return RTC_ERR;
}
}
/************************************************
RTC_SetDateTime
RTCʱ
RTC_DateTimeStructure -- RTCṹ
ֵ RTC_OK ----------------- ɹ
RTC_ERR ----------------
Huang Fugui
*************************************************/
RTC_RESULT RTC_SetDateTime(RTC_DateTimeTypeDef RTC_DateTimeStructure)
{
if(RTC_ERR == RTC_DateRegulate(RTC_DateTimeStructure))
{
return RTC_ERR;
}
if(RTC_ERR == RTC_TimeRegulate(RTC_DateTimeStructure))
{
return RTC_ERR;
}
return RTC_OK;
}
/************************************************
RTC_GetDateTime
ȡRTCʱ䣨ڣ
RTC_DateTimeStructure -- RTCṹ
ֵ
Huang Fugui
*************************************************/
void RTC_GetDateTime(RTC_DateTimeTypeDef *RTC_DateTimeStructure)
{
RTC_TimeTypeDef RTC_TimeStructure;
RTC_DateTypeDef RTC_DateTypeDef_N0W;
RTC_GetTime(RTC_Format_BIN, &RTC_TimeStructure);
RTC_DateTimeStructure->Hour = RTC_TimeStructure.RTC_Hours;
RTC_DateTimeStructure->Minute = RTC_TimeStructure.RTC_Minutes;
RTC_DateTimeStructure->Second = RTC_TimeStructure.RTC_Seconds;
RTC_GetDate(RTC_Format_BIN, &RTC_DateTypeDef_N0W);
RTC_DateTimeStructure->Year = RTC_DateTypeDef_N0W.RTC_Year;
RTC_DateTimeStructure->Month = RTC_DateTypeDef_N0W.RTC_Month;
RTC_DateTimeStructure->Date = RTC_DateTypeDef_N0W.RTC_Date;
}
//void RTC_Demo(void)
//{
// RTC_DateTimeTypeDef RTC_DateTimeStructure;
// RTC_GetDateTime(&RTC_DateTimeStructure); //ȡǰʱ
//// printf("ʱ䣺%0.2d:%0.2d:%0.2d\r\n",
//// RTC_DateTimeStructure.Hour,
//// RTC_DateTimeStructure.Minute,
//// RTC_DateTimeStructure.Second);
//// delay_ms(1000);
//}
/**** Copyright (C)2016 strongerHuang. All Rights Reserved **** END OF FILE ****/
|
C
|
/**
* @file libpower.c
*
* @author Lorenz Gerber
* @date 31.10.2016
* @brief dynamic library for calculating power from resistance or current.
*
*/
#include "libpower.h"
/**
*
* @brief function to calculate power from voltage and resistance
*
* The function calculates power in watt according to the formula volt^2/resistance
*
* @param volt float, Voltage in volt
* @param resistance float, Resistance in ohm
* @return power float, Power in watt
*
*/
float calc_power_r(float volt, float resistance)
{
if(volt == 0 || resistance == 0){
fprintf(stderr, "Please enter non-negative values for volt and resistance");
exit(EXIT_FAILURE);
}
float power;
power = (volt * volt) / resistance;
return power;
}
/**
*
* @brief function to calculate power from voltage and current
*
* The function calculates power in watt according to the formula volt* current
*
* @param volt float, Voltage in volt
* @param current float, current in ampere
* @return power float, Power in watt
*
*/
float calc_power_i(float volt, float current)
{
if(volt == 0 | current == 0){
fprintf(stderr, "Please enter non-negative values for volt and current");
exit(EXIT_FAILURE);
}
float power;
power = volt * current;
return power;
}
|
C
|
#include "types.h"
#include "debug.h"
#include "pmm.h"
#include "vmm.h"
#include "boot.h"
// 内核初始化函数
void kmain();
// 开启分页机制之后的 Multiboot 数据指针
multiboot_t *glb_mboot_ptr;
// 开启分页机制之后的内核栈
char kern_stack[STACK_SIZE];
// 内核使用的临时页表和页目录
// 该地址必须是页对齐的地址,内存 0-640KB 肯定是空闲的
__attribute__((section(".init.data"))) pgd_t *pgd_tmp = (pgd_t *)0x1000;
__attribute__((section(".init.data"))) pgd_t *pte_low = (pgd_t *)0x2000;
__attribute__((section(".init.data"))) pgd_t *pte_hign = (pgd_t *)0x3000;
// 内核入口函数
__attribute__((section(".init.text"))) void kern_entry()
{
pgd_tmp[0] = (uint32_t)pte_low | PAGE_PRESENT | PAGE_WRITE;
pgd_tmp[PGD_INDEX(PAGE_OFFSET)] = (uint32_t)pte_hign | PAGE_PRESENT | PAGE_WRITE;
// 映射内核虚拟地址 4MB 到物理地址的前 4MB
int32_t i;
for (i = 0; i < 1024; i++) {
pte_low[i] = (i << 12) | PAGE_PRESENT | PAGE_WRITE;
}
// 映射 0x00000000-0x00400000 的物理地址到虚拟地址 0xC0000000-0xC0400000
for (i = 0; i < 1024; i++) {
pte_hign[i] = (i << 12) | PAGE_PRESENT | PAGE_WRITE;
}
// 设置临时页表
asm volatile ("mov %0, %%cr3" : : "r" (pgd_tmp));
uint32_t cr0;
// 启用分页,将 cr0 寄存器的分页位置为 1 就好
asm volatile ("mov %%cr0, %0" : "=r" (cr0));
cr0 |= 0x80000000;
asm volatile ("mov %0, %%cr0" : : "r" (cr0));
// 切换内核栈
uint32_t kern_stack_top = ((uint32_t)kern_stack + STACK_SIZE) & 0xFFFFFFF0;
asm volatile ("mov %0, %%esp\n\t"
"xor %%ebp, %%ebp" : : "r" (kern_stack_top));
// 更新全局 multiboot_t 指针
glb_mboot_ptr = mboot_ptr_tmp + PAGE_OFFSET;
// 调用内核初始化函数
kmain();
}
void kmain() {
setup_gdt();
setup_idt();
init_timer(1000);
init_kbd();
console_clear();
printk("kernel in memory start: 0x%08X\n", kern_start);
printk("kernel in memory end: 0x%08X\n", kern_end);
printk("kernel in memory used: %d KB\n\n", (kern_end - kern_start) / 1024);
show_memory_map();
init_pmm();
printk_color(rc_black, rc_red, "\nThe Count of Physical Memory Page is: %u\n\n", phy_page_count);
printk_color(rc_light_grey, rc_white, "===============================================================================\n\n");
printk_color(rc_black, rc_green, "Hello, OS kernel!\n");
asm volatile ("sti");
while(1){
asm volatile ("hlt");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <dirent.h>
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while(0)
int main(int argc, char *argv[]) {
int p[2];
pid_t child;
/* p[0] --> read end of the pipe
* p[1] --> write end of the pipe
*/
if(pipe(p) == -1) {
handle_error("pipe creation");
}
/* Spawn Child to execlp the input command */
if( (child=fork()) == -1) {
handle_error("fork");
}
if(child) {
/* Parent process */
/* Connect p[0] to stdin and close p[1] */
if(dup2(p[0],0) == -1) {
handle_error("dup2");
}
/* Close p[1] as its not relevant to parent process */
if(close(p[1]) == -1) {
handle_error("close");
}
/* run sort -n on whatever comes into stdin */
execlp("sort", "sort", "-r", NULL);
} else {
/* Connect p[1] to stout and close p[0] */
if(dup2(p[1],1) == -1) {
handle_error("dup2");
}
/* Close p[0] as its not relevant to child process */
if(close(p[0]) == -1) {
handle_error("close");
}
/* run sort -n on whatever comes into stdin */
execlp("ls", "ls", NULL);
}
return EXIT_SUCCESS;
}
|
C
|
#include "holberton.h"
/**
* print_last_digit - prints the last digit of a number.
* @i: input integer
*
* Return: the value of the last digit;
*/
int print_last_digit(int i)
{
if (i < 0)
{
i = i % 10;
i = -i;
}
else
i = i % 10;
_putchar(i + '0');
return (i);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: [email protected] <ddecourt> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/29 15:51:47 by ddecourt #+# #+# */
/* Updated: 2021/10/20 15:29:41 by ddecourt@st ### ########.fr */
/* */
/* ************************************************************************** */
#include "../so_long.h"
int check_file_extension(char *map)
{
int size;
size = ft_strlen(map);
if (map[size - 4] != '.' || map[size - 3] != 'b' || \
map[size - 2] != 'e' || map[size - 1] != 'r')
return (0);
return (1);
}
int get_nb_of_line(char *map)
{
int fd;
char *line;
int j;
line = NULL;
j = 0;
fd = open(map, O_RDONLY);
if (fd < 0)
return (0);
while (get_next_line(fd, &line) > 0)
{
j++;
free(line);
}
free(line);
close(fd);
if (j == 1)
map_error(3);
return (j);
}
int check_map(char *map, int i, int j)
{
int fd;
char *line;
line = NULL;
fd = open(map, O_RDONLY);
if (fd < 0)
map_error(2);
get_next_line(fd, &line);
while (line[++i] != '\0')
{
if (line[i] != '1')
map_error(3);
}
free(line);
while (get_next_line(fd, &line) > 0)
{
j += check_walls_side(line, ft_strlen(line), i);
free(line);
}
close(fd);
free(line);
if ((j > 0) || (i <= 1))
map_error(3);
return (i);
}
char **store_map(char **map, int width, int height, char *file)
{
int fd;
int i;
i = 0;
map = malloc((sizeof(char *) * (height + 1)) + (sizeof(char) * \
(height + 1) * (width + 1)));
if (!(map))
return (NULL);
fd = open(file, O_RDONLY);
map[i] = NULL;
while (get_next_line(fd, &map[i]) > 0)
{
i++;
map[i] = NULL;
}
map[i + 1] = NULL;
close(fd);
return (map);
}
int check_last_line(char **map, int height)
{
int i;
i = -1;
if (height <= 1)
{
ft_clear_tab(&map);
map_error(3);
}
height -= 1;
while (map[height][++i])
{
if (map[height][i] != '1')
return (0);
}
return (1);
}
|
C
|
#include<stdio.h>
void display(int arr[], int size){
int i;
for(i = 0; i <= size; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
int main(){
int array[] = {5,3,1,9,8,2,4,7};
int size = sizeof(array)/sizeof(array[0]);
display(array,size);
int i, j, temp;
for(i=0; i<size-1;i++) //This loop for passess.
{
for(j=0;j<size-i-1;j++) //This loop is for iteration.
{
if(array[j]>array[j+1])
{
temp = array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
display(array,size);
return 0;
}
|
C
|
#ifndef __MENU_H__
#define __MENU_H__
#include "screen.h"
typedef enum menu_states_e {
STATE_INTRO,
STATE_READY,
STATE_OUTRO,
} menu_states_e;
typedef struct menu_t {
screen_t screen;
} menu_t;
menu_t menu_init();
void menu_update();
void menu_fini();
#endif
#ifdef __MENU_H_IMPLEMENTATION__
#undef __MENU_H_IMPLEMENTATION__
menu_t menu_init(){
menu_t return_value = {0};
return return_value;
}
void menu_update(void){
while(!(IsKeyPressed(KEY_ENTER) || WindowShouldClose())){
BeginDrawing();
{
ClearBackground(WHITE);
DrawText("Press Enter to Start, ESC to close", 100, 100, 14, BLACK);
}EndDrawing();
}
}
void menu_fini();
#endif
|
C
|
#include<stdio.h>
void main(){
int x;
printf("输出男女\n");
scanf("%d",&x);
if(x==0){
printf("女\n");
}
else if(x==1){
printf("男\n");
}
else {
printf("输入有误,请重新输出\n");
}
}
|
C
|
#include "hash_table.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
static int hash_func(char *string, int max) {
int len = strlen(string);
unsigned long long hash = 0;
for (int i = 0; i < len; i++) {
hash = (((hash << 5) + hash) + string[i]) % max;
}
return hash % max;
}
/**
* 새로운 해쉬 테이블을 만들고 주소를 반환한다.
* 실패시 NULL반환
*/
hash_table *hash_table_alloc(void) {
hash_table *this = malloc(sizeof(hash_table));
this->body = malloc(sizeof(element) * 12345);
this->capacity = 12345;
for (int i = 0; i < this->capacity; i++) {
this->body[i].key = NULL;
this->body[i].val = NULL;
}
return this;
}
/**
* 해쉬 테이블 동적메모리 해제
*/
void hash_table_free(hash_table *this) {
for (int i = 0; i < this->capacity; i++) {
if (this->body[i].key != NULL) {
free(this->body[i].key);
free(this->body[i].val);
}
}
free(this->body);
free(this);
}
/**
* 해쉬 테이블에 key: value 삽입
*/
bool hash_table_insert(hash_table *this, char *key, char *val) {
int hash = hash_func(key, this->capacity);
for (int i = hash; ; i = (i + 1) % this->capacity) {
if (this->body[i].key != NULL)
continue;
this->body[i].key = strdup(key);
this->body[i].val = strdup(val);
return true;
}
return false;
}
/**
* 해쉬 테이블에서 키를 검색해서 value의 주소를 리턴한다.
* 찾지 못했을 경우는 NULL 리턴
*/
char *hash_table_get(hash_table *this, char *key) {
int hash = hash_func(key, this->capacity);
for (int i = hash; ; i = (i + 1) % this->capacity) {
if (this->body[i].key == NULL)
return NULL;
if (strcmp(this->body[i].key, key) == 0)
return this->body[i].val;
}
return NULL;
}
/**
* 해쉬 테이블에서 키를 검색해서 해당 원소 삭제.
* 실패시 (찾지 못할경우) false리턴
*/
bool hash_table_remove(hash_table *this, char *key) {
int hash = hash_func(key, this->capacity);
for (int i = hash; ; i = (i + 1) % this->capacity) {
if (this->body[i].key == NULL)
return false;
if (strcmp(this->body[i].key, key) == 0) {
free(this->body[i].key);
free(this->body[i].val);
this->body[i].key = NULL;
this->body[i].val = NULL;
return true;
}
}
return false;
}
|
C
|
#include <stdio.h>
int main()
{
float M, MM;
printf("Digite um valor em metros para ser convertido para milimetros: \n");
scanf("%f", &M);
MM = M * 1000;
printf("%.2f milimetros \n", MM);
return 0;
}
|
C
|
/*
* ListOfPrimes.c
*/
#include <stdio.h>
#include "mathutils.h"
#define MAXSIZE 2000
#define SEARCHLIMIT 17389
int ArrayOfPrimes[MAXSIZE];
int main(int argc, char **argv)
{
int index = 0;
for (int i = 2; i <= SEARCHLIMIT; i++)
{
if (primechecker(i) == 1)
{
ArrayOfPrimes[index] = i;
index++ ;
}
}
printf("The hundredth prime is = %d\n",ArrayOfPrimes[1999]);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_check_content_and_create_s_array.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nkuchyna <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/30 20:46:58 by nkuchyna #+# #+# */
/* Updated: 2018/05/14 20:57:02 by nkuchyna ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
static int ft_check_nbr(char *str)
{
long int nbr;
int i;
int len;
i = 0;
len = 0;
if (str[i] == '-')
i++;
while (str[i] != ',' && str[i] != '\0')
{
if (!(str[i] >= '0' && str[i] <= '9'))
return (1);
len++;
i++;
}
if (len > 10 || (str[i - len] == '0' && len != 1))
return (1);
nbr = ft_atoi(str);
if (!(nbr >= -2147483648 && nbr <= 2147483647))
return (1);
return (0);
}
static int ft_check_color(char *str, int i)
{
int len;
if ((len = ft_strlen(str) - i) != 8 && len != 5 && len != 6 && len != 4)
return (1);
if (!(str[i] == '0' && str[i + 1] == 'x'))
return (1);
i += 2;
while (str[i] != '\0')
{
if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'f')
|| (str[i] >= 'A' && str[i] <= 'F'))
i++;
else
return (1);
}
return (0);
}
static int ft_check_numbers_and_color(char *str, t_points *s_array, int k)
{
int i;
i = 0;
if (ft_check_nbr(str) == 1)
return (1);
while (str[i] != ',' && str[i] != '\0')
i++;
if (str[i] == ',')
{
if (ft_check_color(str, i + 1) != 1)
s_array[k].valid_color = i + 1;
else
s_array[k].valid_color = -1;
}
if (str[i] == '\0')
s_array[k].valid_color = 0;
return (0);
}
static char **ft_check_content(char *str, t_points *s_ar, int k)
{
int i;
char **numbers;
i = 0;
if (!(numbers = ft_strsplit_new(str)))
return (NULL);
while (numbers[i])
{
if (ft_check_numbers_and_color(numbers[i], s_ar, k) == 1)
{
s_ar[k].invalid_nbr = 1;
s_ar[k].valid_color = -1;
}
else
s_ar[k].invalid_nbr = 0;
i++;
k++;
}
return (numbers);
}
t_points *ft_check_content_and_create_s_array(int size, char *argv)
{
int fd;
t_points *s_ar;
char *line;
int k;
int line_nbr;
line = NULL;
k = 0;
line_nbr = 0;
fd = open(argv, O_RDWR);
if (!(s_ar = (t_points*)malloc(sizeof(t_points) * size)))
return (NULL);
while (get_next_line(fd, &line) == 1)
{
if (ft_fill_s_array(s_ar, ft_check_content(line, s_ar, k),
&line_nbr, &k) == 1)
return (NULL);
free(line);
line = NULL;
}
if (get_next_line(fd, &line) == -1)
return (NULL);
close(fd);
return (s_ar);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int prime(int num){
for (int i = 2; i < num; i++){
if (num%i == 0){
printf("");
break;
}
else{
printf("");
}
}
return 0;
}
int main(){
int Num;
printf("һ:");
scanf("%d\n", &Num);
prime( Num);
system("pause");
return 0;
}
|
C
|
#define CHAR_SIZE sizeof(char)
#define INT_SIZE sizeof(int)
#define null '\0'
#include <stdlib.h>
#include "expr_assert.h"
#include "arrayUtil.h"
#include <string.h>
#include <stdio.h>
#include <stddef.h>
typedef char* String;
ArrayUtil util, resultUtil, expectedUtil;
int sample[] = {1,2,3,4,5};
//-----------------------------------------------Helper Functions --------------------------------
int isEven(void *hint, void *item){
int *numberPtr = (int*)item;
return *numberPtr % 2 ? 0 : 1;
}
int isDivisible(void *hint, void *item){
int *numberPtr = (int*)item;
int *hintPtr = (int*)hint;
return *numberPtr % *hintPtr ? 0 : 1;
}
void increment(void* hint, void* sourceItem, void* destinationItem){
int *hintPtr = (int*)hint;
int *numberPtr = (int*)sourceItem;
int *resultPtr = (int*)destinationItem;
*resultPtr = *numberPtr + *hintPtr;
}
void toChar(void* hint, void* sourceItem, void* destinationItem){
int *numberPtr = (int*)sourceItem;
int *charPtr = (int*)destinationItem;
*charPtr = *numberPtr;
}
void test_create_should_set_the_length_and_typeSize_fields_of_array_to_the_values_passed_to_create_function(){
ArrayUtil a = create(1,3);
assert(a.length == 3);
assert(a.typeSize == 1);
dispose(a);
}
void test_map_should_map_source_to_destination_using_the_provided_convert_function(){
int hint = 1, result[] = {2,3,4,5,6};
util = (ArrayUtil){sample, sizeof(int), 5};
resultUtil = create(util.typeSize, util.length);
expectedUtil = (ArrayUtil){result, sizeof(int), 5};
map(util, resultUtil, increment, &hint);
assert(areEqual(expectedUtil, resultUtil));
dispose(resultUtil);
}
void test_resize_should_grow_length_of_array_and_set_them_to_zero_when_new_size_is_more(){
ArrayUtil a = create(4,2);
int i;
a = resize(a,5);
assert(a.length == 5);
for (i = 0; i < 20; ++i)
{
assert(((char*)a.base)[i] == 0);
}
dispose(a);
}
void test_resize_should_not_change_length_of_array_when_new_size_is_same_as_old_size(){
ArrayUtil a = create(1,5);
int i;
a = resize(a,5);
assert(a.length == 5);
dispose(a);
}
|
C
|
#include<stdio.h>
#include<conio.h>
void greatest(double,double,double);
void greatest(double a,double b,double c)
{
if(a>b&&a>c)
{
printf("\n A=%lf is greatest",a);
}
else if(b>c&&b>a)
{
printf("\n B=%lf is greatest",b);
}
else if(c>a&&c>b)
{
printf("\n C=%lf is greatest",c);
}
else if(a=b=c)
{
printf("\n A=%lf,B=%lf and C=%lf all are equal",a,b,c);
}
}
void main()
{
double i,j,k;
clrscr();
printf("\n Enter three numbers to find the greates of three:");
scanf("%lf %lf %lf",&i,&j,&k);
greatest(i,j,k);
getch();
}
|
C
|
void ingresar_cola(ptrNodo *ptrS, ptrNodo *ptrF )
{
ptrNodo ptrActual;
ptrNodo ptrNuevo;
ptrNodo ptrFinal;
int dato;
ptrNuevo = (ptrNodo)malloc(sizeof(NODO));//se crea espacio para el nodo
ptrActual = *ptrS;
ptrFinal = *ptrF;
if(ptrNuevo != NULL)//si se pudo crear el espacio entra
{
/*ACA VA LA FUNCION QUE LEE EL ARCHIVO Y GUARDA LOS DATOS EN EL NODO*/
ptrNuevo->ptrSig = NULL;
if(ptrActual != NULL)
{
ptrFinal->ptrSig = ptrNuevo;
*ptrF = ptrNuevo;
}
else
{
*ptrS = ptrNuevo;
*ptrF = ptrNuevo;
}
}
else//por si no hay espacio en el sistema
{
printf("\n error, no hay espacio \n");
}
}
|
C
|
#include <stdio.h>
/*
int main(){
int rest[10] = {0, };
int cnt = 0;
int num;
for(int i = 0; i<10; i++){
scanf("%d",&num);
rest[i] = num % 42;
}
for(int i = 0; i<42; i++){
for(int j = 0; j<10; j++){
if(rest[j] == i){
cnt++;
break;
}
}
}
printf("%d\n", cnt);
}
*/
/*
int main(){
int rest[42] = {0,};
int cnt = 0;
int num;
for(int i=0; i<10; i++) {
scanf("%d",&num);
for (int j = 0;j < 42; j++){
if(num % 42 == j)
rest[j]++;
}
}
for(int i=0; i<42; i++){
if(rest[i] != 0)
cnt++;
}
printf("%d\n", cnt);
}
*/
/*
#include <stdio.h>
#include <stdbool.h>
int main(){
int n;
int rest[42] = {0, };
int cnt = 0;
for(int i = 0; i<10; i++){
scanf("%d", &n);
if(rest[n%42] == 1){
continue;
} else {
rest[n%42] += 1;
cnt++;
}
}
printf("%d", cnt);
}
*/
|
C
|
/**
* @file test2.cpp
* @Author Kolesnikov Alexandr([email protected])
* @date October, 2017
* @brief test file for Test_PixelPlex project
**/
/* Required header files of standard libraries. ---------------------*/
#include <iostream>
#include <string>
/**
* @brief some function
* @param var
* @retval none
*/
void func1(int var)
{
std::cout << ++var << "\n"; //print var
}
/**
* @brief some function
* @param var
* @retval none
*/
void func2(int var)
{
/* print var*/std::cout << var++ << "\n";
}
//main function
int main() /*sume func*/
{
/*some parameter*/ int var = 5; //equal to 5
if(true)
{
func1(var); //call func1
}
else
{
func2(var); /*call func2*/
}
std::cout << "END"<< "\n";
}
|
C
|
/*
// Author: Chris Hyman, [email protected]
// Date: 3 Oct 2020
// A solution to Programming Exercises and Projects from
// Chapter 5 of C Programming: A Modern Approach by K. N. King
//
// 9. Write a program that prompts the user to enter two dates and then
// indicates which date comes earlier on the calendar:
// Enter first date (mm/dd/yy): `3/6/08`
// Enter second date (mm/dd/yy): `5/17/07`
// 5/17/07 is earlier than 3/6/08
*/
#include <stdbool.h>
#include <stdio.h>
int main(void)
{
int fst_mm, fst_dd, fst_yy, snd_mm, snd_dd, snd_yy;
bool first_is_earlier;
printf("Enter first date (mm/dd/yy): ");
scanf("%d/%d/%d", &fst_mm, &fst_dd, &fst_yy);
printf("Enter second date (mm/dd/yy): ");
scanf("%d/%d/%d", &snd_mm, &snd_dd, &snd_yy);
if (fst_yy == snd_yy) {
if (fst_mm == snd_mm) {
if (fst_dd == snd_dd) {
printf("Both dates are the same!\n");
return 0; // exit program
}
else if (fst_dd < snd_dd)
first_is_earlier = true;
else
first_is_earlier = false;
}
else if (fst_mm < snd_mm)
first_is_earlier = true;
else
first_is_earlier = false;
}
else if (fst_yy < snd_yy)
first_is_earlier = true;
else
first_is_earlier = false;
if (first_is_earlier)
printf("%d/%d/%.2d is earlier than %d/%d/%.2d\n",
fst_mm, fst_dd, fst_yy, snd_mm, snd_dd, snd_yy);
else
printf("%d/%d/%.2d is earlier than %d/%d/%.2d\n",
snd_mm, snd_dd, snd_yy, fst_mm, fst_dd, fst_yy);
return 0;
}
|
C
|
#ifndef CORC_CORE_STR_H
#define CORC_CORE_STR_H
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct CorcString_ CorcString;
struct CorcString_
{
char *string;
char *end;
size_t len;
size_t size;
};
extern size_t corcstr_concat_raw(char *dst, const char *src, size_t siz);
extern size_t corcstr_copy_raw(char *dst, const char *src, size_t siz);
extern CorcString *corcstr_create(void);
extern size_t corcstr_append(CorcString *cs, const char *src, size_t len);
extern size_t corcstr_remove(CorcString *cs, size_t len);
extern CorcString *corcstr_join(char **words, char sep, size_t count);
static inline CorcString *corcstr(const char *in)
{
CorcString *s;
s = corcstr_create();
if (in != NULL)
corcstr_append(s, in, sizeof(in));
return s;
}
static inline size_t corcstr_resize(CorcString *cs, size_t siz)
{
cs->string = realloc(cs->string, siz);
if (cs->string == NULL)
exit(1);
cs->size = siz;
return siz;
}
static inline size_t corcstr_append_char(CorcString *cs, char c)
{
if ((cs->len + 1) >= cs->size)
corcstr_resize(cs, cs->size + 1);
if (c == '\0')
{
*(cs->end + 1) = c;
return cs->len;
}
cs->string[cs->len] = c;
cs->string[cs->len+1] = '\0';
return ++cs->len;
}
static inline void corcstr_clear(CorcString *cs)
{
unsigned int i;
for (i = 0; i < cs->size; ++i)
cs->string[i] = '\0';
cs->len = 0;
cs->end = cs->string;
}
#endif /* CORC_CORE_STR_H */
|
C
|
#include <stdio.h>
#define PRINCIPAL 100
#define SINGLE_INSTEREST 0.1
#define COMPOUND_INSTEREST 0.05
double Daphne_investment(int year)
{
return (1 + SINGLE_INSTEREST * year) * PRINCIPAL;
}
double my_pow(double x, int y)
{
double a = 1;
for(int i = 0; i < y; i++)
a *= x;
return a;
}
double Deirgre_investment(int year)
{
return my_pow(1 + COMPOUND_INSTEREST, year) * PRINCIPAL;
}
int main(void)
{
int i = 0;
while(Deirgre_investment(i) <= Daphne_investment(i))
i++;
printf("Daphne's investment%8.2lf\n",Daphne_investment(i));
printf("Deirgre's investment%8.2lf\n",Deirgre_investment(i));
printf("year%8d\n",i);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//o codigo pede por 2 horarios diferentes e calcula a diferenca entre eles (caso o horario final seja menor que o inicial, subentende-se que se trata do dia seguinte)
struct cronometro {
int hora;
int min;
int seg;
};
typedef struct cronometro relogio;
void printIntervalo(relogio r1, relogio r2);
int main(){
relogio r1;
relogio r2;
r1.seg = -1;
r2.seg = -1;
//verificacao do formato de hora
printf("Digite o horario inicial e final no formato 00:00:00 (horas, minutos e segundos)\n");
while(r1.seg == -1){
scanf("%d", &r1.hora);
scanf("%d", &r1.min);
scanf("%d", &r1.seg);
if(r1.seg>=60 || r1.seg <0 || r1.min >=60 || r1.min <0 || r1.hora >=24 || r1.hora <0){
printf("Formato de hora invalido");
return 0;
}
printf("Hora inicial: %d:%d:%d\n", r1.hora,r1.min,r1.seg);
}
//idem
while(r2.seg == -1){
scanf("%d", &r2.hora);
scanf("%d", &r2.min);
scanf("%d", &r2.seg);
printf("Hora final: %d:%d:%d\n", r2.hora,r2.min,r2.seg);
if(r2.seg>=60 || r2.seg <0 || r2.min >=60 || r2.min <0 || r2.hora >=24 || r2.hora <0){
printf("Formato de hora invalido");
return 0;
}
printIntervalo(r1,r2);
}
}
void printIntervalo(relogio r1, relogio r2){
relogio rf;
//caso 0
if((r1.hora>=24 || r2.hora>=24) || (r1.min>=60 || r2.min>=60) || (r1.seg>=60 || r2.seg>=60)){
printf("Formato de hora invalido!");
return;
}
//caso 1
if(r1.hora > r2.hora){
rf.hora = (r2.hora+24)-r1.hora;
//caso 1.1
if(r1.min > r2.min){
rf.min = (r2.min+60)-r1.min;
if(r1.seg > r2.seg) rf.seg = r2.seg+60-r1.seg;
else rf.seg = r2.seg - r1.seg;
}
//caso 1.2
else {
rf.min = r2.min - r1.min;
if(r1.seg > r2.seg) rf.seg = r2.seg+60-r1.seg;
else rf.seg = r2.seg - r1.seg;
}
//caso 2
} else{
rf.hora = r2.hora-r1.hora;
//caso 2.1
if(r1.min > r2.min){
rf.min = (r2.min+60)-r1.min;
if(r1.seg > r2.seg) rf.seg = r2.seg+60-r1.seg;
else rf.seg = r2.seg - r1.seg;
}
//caso 2.2
else {
rf.min = r2.min - r1.min;
if(r1.seg > r2.seg) rf.seg = r2.seg+60-r1.seg;
else rf.seg = r2.seg - r1.seg;
}
}
printf("Intervalo: %dh %dmin %ds\n",rf.hora,rf.min,rf.seg);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "stack.h"
#include "integer.h"
void
Fatal(char *fmt, ...)
{
va_list ap;
fprintf(stderr,"An error occured: ");
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
exit(-1);
}
static void showStack(stack *s)
{
printf("The stack is ");
displayStack(stdout,s);
printf(".\n");
}
int main(void) {
stack *items = newStack(displayInteger);
showStack(items);
printf("The stack size is: %d\n", sizeStack(items));
push(items,newInteger(3));
showStack(items);
printf("The stack size is: %d\n", sizeStack(items));
push(items,newInteger(2));
showStack(items);
printf("The stack size is: %d\n", sizeStack(items));
printf("The value ");
displayInteger(stdout,pop(items));
printf(" was popped.\n");
showStack(items);
printf("The stack size is: %d\n", sizeStack(items));
printf("The value ");
displayInteger(stdout, pop(items));
printf(" was popped.\n");
showStack(items);
printf("The stack size is: %d\n", sizeStack(items));
push(items, newInteger(22));
showStack(items);
printf("The stack size is: %d\n", sizeStack(items));
pop(items);
showStack(items);
printf("The stack size is: %d\n", sizeStack(items));
push(items, newInteger(25));
showStack(items);
printf("The stack size is: %d\n", sizeStack(items));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rmander <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/12 21:45:42 by rmander #+# #+# */
/* Updated: 2021/04/11 18:07:21 by rmander ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft.h"
static int is_oneof(char c, char const *set)
{
unsigned int flag;
flag = FALSE;
while (*set)
if (c == *set++)
flag = TRUE;
return (flag);
}
char *ft_strtrim(char const *s1, char const *set)
{
char *start;
char *end;
char *out;
char *outp;
start = (char *)s1;
while (*start && is_oneof(*start, set))
++start;
if (!*start)
return (ft_strdup(""));
end = (char *)s1 + ft_strlen(s1) - 1;
while (is_oneof(*end, set))
--end;
++end;
out = malloc(sizeof(char) * ((end - start) + 1));
if (!out)
return (NULL);
outp = out;
while (start != end)
*outp++ = *start++;
*outp = '\0';
return (out);
}
|
C
|
int main(void){
char m[5][7] = {"abcdef", "ghijkl", "mnopqr", "stuvwx", "yz"};
char (*p)[7] = m;
printf("%c ", **m);
printf("%c ", *(*m+2));
printf("%c ", *(*(m+1)+1));
printf("%c ", *(m[1] + 2));
printf("%c ", (*(m+2))[3]);
printf("%c ", (*(p+3))[2]);
p++;
printf("%d ", (int)p - (int)m);
}
|
C
|
#include <stdio.h>
int grow_up(int n) {
int prev_n = 10, flag = 1;
while(n > 0) {
if (prev_n > (n % 10)) {
prev_n = n % 10;
} else {
flag = 0;
break;
};
n /= 10;
}
return flag;
}
int main() {
int val = 0;
scanf("%i", &val);
if (grow_up(val)) {
printf("YES");
} else {
printf("NO");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include "listFunctions.h"
#include "searchFunctions.h"
bool binarySearch(LIST *data, int key, int *location)
// Ask for number to search using binary search algorithm
{
bool res=0;
nodePtr mid, low, high;
// initialize node pointers
low = data->head;
high = data->tail;
// start binary search
while (low->num<=high->num && key!=mid->num)
{
// find middle node
mid = findMid(data, low->index, high->index);
if (mid==high && mid==low && mid->num!=key)
{
return res;
}
if (mid->num == key)
{
res=1;
*location = mid->index;
}
else if (mid->num > key)
{
high = mid->prev;
}
else if (mid->num < key)
{
low = mid->next;
}
}
return res;
}
nodePtr findMid(LIST *L, int l, int h)
{
int x, i;
nodePtr thisNode;
thisNode = L->head;
x = (l+h)/2;
while (thisNode->index != x)
{
thisNode = thisNode->next;
}
return thisNode;
}
bool linearSearch(LIST *data, int key, int *location)
{
bool res=0;
nodePtr thisNode;
thisNode = data->head;
while (thisNode!=NULL && res!=1)
{
if (thisNode->num == key)
{
res=1;
*location = thisNode->index;
}
thisNode = thisNode->next;
}
return res;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
printf("************************************\n");
printf("*********** 1. Ϸ ************\n");
printf("*********** 0. ˳Ϸ ************\n");
printf("************************************\n");
}
void game()
{
int guess = 0;
//1.
//srand((unsigned int)time(NULL));
int ret = rand() % 100 + 1;
//printf("%d\n", ret);
//2.
printf("еһ֣ܲµ:>\n");
while (1)
{
scanf("%d", &guess);
if (guess < ret)
{
printf("µʵʵС\n");
}
else if (guess > ret)
{
printf("µʵʵĴ\n");
}
else
{
printf("ϲ¶\n");
break;
}
}
}
void test()
{
//Ϸ
int input = 0;
srand((unsigned int)time(NULL));
do
{
//ӡ˵
menu();
printf("ѡ:>\n");
scanf("%d", &input);
switch (input)
{
case 1:
printf("Ϸ\n");
game();
break;
case 0:
printf("˳Ϸ\n");
break;
default:
printf("룡\n");
break;
}
} while (input);
}
int main()
{
test();
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
void main(int argc,char *argv[])
{
int tomalloc; // for ben
int malloced = 0;
void *p;
tomalloc = atoi(argv[1]);
printf("mallocing at least %d MB\n",tomalloc);
tomalloc *= 1000000;
while (malloced < tomalloc)
{
p = malloc(1000000);
malloced += 1000000;
}
printf("DONE mallocing\n");
}
|
C
|
#include<stdio.h>
int main(){
int n,tmp;
int list[1000]={0,};
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&list[i]);
}
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(list[i]>list[j]){
tmp=list[i];
list[i]=list[j];
list[j]=tmp;
}
}
}
for(int i=0;i<n;i++)
printf("%d\n",list[i]);
}
|
C
|
#include "gtools.h"
/* This is a pruning function for use with geng. It causes
geng output to be restricted to chordal graphs. To use it
you need to compile it together with geng.c like this (assuming
your compiler is gcc). The file nautyW1.a is made by the nauty
distribution. It needs access to the *.h files of nauty, so if
you aren't in that directory you need to include -I directory
before geng.c, where "directory" is where the *.h files are.
gcc -o chordal -O3 -DMAXN=WORDSIZE -DWORDSIZE=32 -DPRUNE=chordless \
geng.c chordal.c nautyW1.a
All of the options of geng are available when you run it.
*/
static boolean
hasinducedpath(graph *g, int start, setword body, setword last)
/* return TRUE if there is an induced path in g starting at start,
extravertices within body and ending in last.
* {start}, body and last should be disjoint. */
{
setword gs,w;
int i;
gs = g[start];
if ((gs & last)) return TRUE;
w = gs & body;
while (w)
{
TAKEBIT(i,w);
if (hasinducedpath(g,i,body&~gs,last&~bit[i]&~gs))
return TRUE;
}
return FALSE;
}
boolean
chordless(graph *g, int n, int maxn)
/* g is a graph of order n. Return TRUE if there is a
chordless cycle of length at least 4 that includes
the last vertex. */
{
setword all,gn,w,gs;
int v,s;
all = ALLMASK(n);
gn = g[n-1];
while (gn)
{
TAKEBIT(v,gn);
gs = g[v] & ~(bit[n-1]|g[n-1]);
while (gs)
{
TAKEBIT(s,gs);
if (hasinducedpath(g,s,all&~(g[n-1]|g[v]),gn&~g[v]))
return TRUE;
}
}
return FALSE;
}
|
C
|
/*
* ===================================================================================== *
* Filename: cgragh.c
*
* Description:
*
* Version: 1.0
* Created: 2017年11月24日 13时40分08秒
* Revision: none
* Compiler: gcc
*
* Author: Cz (mn), [email protected]
* Company: None
*
* =====================================================================================
*/
#include"cgraph.h"
int ctraverse(struct mgraph *g, int col, int *s1, int *s2, int *ptr1, int *ptr2);
int rtraverse(struct mgraph *g, int col, int *s1, int *s2, int *ptr1, int *ptr2);
struct mgraph init(size_t size){
struct mgraph grp;
grp.size=size;
grp.ptr=malloc(sizeof(char)*size*size);
memset(grp.ptr, 0x00, size*size*sizeof(char));
return grp;
}
void clean(struct mgraph* g){
free(g->ptr);
return ;
}
int set(int a, int b, struct mgraph *g){
if(a>=g->size || b>=g->size){
return -1;
}
*(g->ptr+a*g->size+b)=1;
return 0;
}
char get(int a, int b, struct mgraph *g){
if(a>=g->size || b>=g->size){
return -1;
}
return *(g->ptr+a*g->size+b);
}
int clear(int a, int b, struct mgraph *g){
if(a>=g->size || b>=g->size){
return -1;
}
*(g->ptr+a*g->size+b)=0;
return 0;
}
void printg(struct mgraph *g){
int i,j;
for(i=0;i<g->size;i++){
for(j=0;j<g->size;++j){
printf("%d ", get(i,j,g));
}
printf("\n");
}
}
int isbipart(struct mgraph *g){
int *v1,*v2,flag,i;
int *ptr1,*ptr2, s1, s2;
int bl1,bl2;
bl1=bl2=0;
s1=s2=0;
flag = 0;
v1=malloc(sizeof(int)*g->size);
v2=malloc(sizeof(int)*g->size);
memset(v1,-1,g->size);
memset(v2,-1,g->size);
ptr1=v1,ptr2=v2;
*v1=0;
++bl1;
for(;;){
if(!flag){
if(s1 == bl1){
for(i=0;i<s1;++i){
printf("%d ",*(v1+i));
}
printf("\n");
for(i=0;i<s2;++i){
printf("%d ",*(v2+i));
}
return 0;
}
for(s1;s1<bl1;++s1){
if(rtraverse(g, *(v1+s1), &bl1, &bl2, ptr1, ptr2) == -1){
return -1;
}
}
s1 = bl1;
flag = 1;
continue;
}
if(flag){
if(s2 == bl2){
for(i=0;i<s1;++i){
printf("%d ",*(v1+i));
}
printf("\n");
for(i=0;i<s2;++i){
printf("%d ",*(v2+i));
}
return 0;
}
for(s2;s2<bl2;++s2){
if(ctraverse(g, *(v2+s2), &bl2, &bl1, ptr2, ptr1) == -1){
return -1;
}
}
s2=bl2;
flag = 0;
continue;
}
}
}
int rtraverse(struct mgraph *g, int row, int *s1, int *s2, int *ptr1, int *ptr2){
int i,j;
for(i=row+1;i<g->size;++i){
if(get(row,i,g) == 1){
clear(row,i,g);
for(j=0;j<*s1;++j){
if(*(ptr1+j) == i){
return -1;
}
}
*(ptr2+*s2)=i;
++*s2;
}
}
return 0;
}
int ctraverse(struct mgraph *g, int col, int *s1, int *s2, int *ptr1, int *ptr2){
int i,j;
for(i=0;i<col;++i){
if(get(i,col,g) == 1){
clear(i,col,g);
for(j=0;j<*s1;++j){
if(*(ptr1+j) == i){
return -1;
}
}
*(ptr2+*s2)=i;
++*s2;
}
}
return 0;
}
|
C
|
#include "alloc_btree_internal_header.h"
void alloc_btree_swap_data(
struct s_node *node_a,
struct s_node *node_b)
{
void *content;
void *size;
uint8_t node_type;
content = node_a->ptr_a;
node_a->ptr_a = node_b->ptr_a;
node_b->ptr_a = content;
size = node_a->m.ptr_b;
node_a->m.ptr_b = node_b->m.ptr_b;
node_b->m.ptr_b = size;
node_type = node_a->mask.s.node_type;
node_a->mask.s.node_type = node_b->mask.s.node_type;
node_b->mask.s.node_type = node_type;
node_type = node_a->mask.s.range;
node_a->mask.s.range = node_b->mask.s.range;
node_b->mask.s.range = node_type;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void hanoi (int n, char dest_c, char origem_c, char aux_c);
int main (void){
return 0;}
void hanoi (int n, char dest_c, char origem_c, char aux_c){
if(n>0){
hanoi(n, origem_c, aux_c, dest_c);
printf("%c (origem) -> %c (destino)\n", origem_c, dest_c);
hanoi(n, aux_c, dest_c, origem_c);}}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int ostatnia_cyfra(int n)
{
n;
if(n==39)
{
return 9;
}
}
int main()
{
int n = 39;
printf("Ostatnia cyfra argumentu to: ");
printf("%d", ostatnia_cyfra(n));
return 0;
}
|
C
|
/*
鲢ǽڹ鲢ϵһЧ㷨㷨Dz÷ηһdz͵Ӧ
кϲõȫУʹÿ
ʹжμϲһΪ·鲢
*/
/*
鲢ϲУ
ֽ:ݰλãķֳУһֻһ
ϲڵнкϲ
ҪO(n)ĸռ
*/
//кϲbegin end end+1 end2
//begin mid end
void merge(int* arr, int begin, int mid, int end, int* tmp)
{
//
//䣺[begin,mid][mid+1,end]
int begin1 = begin;
int end1 = mid;
int begin2 = mid + 1;
int end2 = end;
//ռʼλ
int idx = begin;
//ϲ
while (begin1 <= end1&&begin2 <= end2)
{
if (arr[begin1] < arr[begin2])
tmp[idx++] = arr[begin1++];
else
tmp[idx++] = arr[begin2++];
}
//жǷδϲԪ
if (begin1 <= end1)
memcpy(tmp + idx, arr + begin1, sizeof(int)*(end1 - begin1 + 1));
if (begin2 <= end2)
memcpy(tmp + idx, arr + begin2, sizeof(int)*(end2 - begin2 + 1));
//ϲ֮пԭʼĶӦ
memcpy(arr + begin, tmp + begin, sizeof(int)*(end - begin + 1));
}
void _mergeSort(int* arr, int begin, int end, int* tmp)
{
if (begin >= end)
return;
int mid = begin + (end - begin) / 2;
//Ⱥϲ
_mergeSort(arr, begin, mid, tmp);
_mergeSort(arr, mid + 1, end, tmp);
//ϲСbeginmidmid+1end
merge(arr, begin, mid, end, tmp);
}
void mergeSort(int* arr, int n)
{
int* tmp = (int *)malloc(sizeof(int)*n);
_mergeSort(arr, 0, n - 1, tmp);
free(tmp);
}
//ǵݹ㷨
void mergeSortNor(int* arr, int n)
{
int* tmp = (int*)malloc(sizeof(int)*n);
//еIJ
int step = 1;
while (step < n)
{
int idx;
for (idx = 0; idx < 0; idx += 2 * step)
{//ҵϲ
//[beginmid][mid+1end]
int begin = idx;
int mid = idx + step - 1;
//жǷڵڶ
if (mid >= n - 1)
continue;
int end = idx + 2 * step - 1;
//жǷԽ
if (end>n - 1)
end = n - 1;
merge(arr, begin, mid, end, tmp);
}
}
{
}
}
|
C
|
#include "fillit.h"
void print_result(t_res *res)
{
int i;
i = 0;
while (i < res->size)
{
write(1, res->tab + (i * res->size), res->size);
ft_putchar('\n');
i++;
}
}
void delete_tetris(t_res *res, t_tetro tetris)
{
int i;
i = 0;
while (i < (res->size * res->size))
{
if (res->tab[i] == tetris.shape[tetris.place])
res->tab[i] = '.';
i++;
}
}
void put_piece(t_res *res, t_tetro piece)
{
int i;
i = piece.place;
while (i < 16)
{
if (piece.shape[i] != '.')
res->tab[coordinate_transformation(i, res, piece)] = piece.shape[i];
i++;
}
}
|
C
|
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int A[n];
int i;
for(i=0;i<n;i++)
scanf("%d",&A[i]);
int maxSum = -1;
for(i=0;i<n;i++)
{
if(A[i]<=0)
continue;
int bestSum = -1;
for(int j=i;j<n;j++)
{
int currSum = 0;
for(int k=i;k<=j;k++)
currSum += A[k];
if(currSum>bestSum)
bestSum = currSum;
}
if(maxSum<bestSum)
maxSum = bestSum;
}
printf("%d\n",maxSum);
}
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* ft_resol.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: ythollet <[email protected]> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2017/11/23 17:17:05 by ythollet #+# ## ## #+# */
/* Updated: 2017/11/27 17:53:47 by evella ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "fillit.h"
void ft_reset_tetri(t_cord **tetri, int nbr_tetri)
{
int i;
i = 0;
while (i < nbr_tetri)
ft_leftup_tetri(tetri[i++]);
}
int ft_resol(char *str)
{
char **array;
t_cord **tetri;
int nbr_tetri;
int size_array;
int count;
nbr_tetri = ft_nbrchar(str, '#') / 4;
tetri = ft_get_info_tetri(str, nbr_tetri);
size_array = ft_calc_size(nbr_tetri, tetri);
array = ft_dimarray(size_array);
count = 0;
tetri[0][0].i = 0;
while (ft_btking(array, tetri, nbr_tetri, count) == 0)
{
tetri[0][0].i = 0;
free(array);
ft_reset_tetri(tetri, nbr_tetri);
array = ft_dimarray(++size_array);
}
ft_readarray(array);
return (1);
}
|
C
|
/*
* Userspace program that communicates with the led_vga device driver
* primarily through ioctls
*
* Ayush Jain : aj2672
* Shivam Choudhary : sc3973
* Columbia University
*/
#include <stdio.h>
#include "vga_led.h"
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int vga_led_fd;
/* Read and print the segment values */
void print_segment_info() {
vga_led_arg_t vla;
int i;
for (i = 0 ; i < 4 ; i++) {
vla.digit = i;
if (ioctl(vga_led_fd, VGA_LED_READ_DIGIT, &vla)) {
perror("ioctl(VGA_LED_READ_DIGIT) failed");
return;
}
printf("%02x ", vla.segments);
}
printf("\n");
}
/* Write the contents of the array to the display */
void write_segments(const unsigned char segs[4])
{
vga_led_arg_t vla;
int i;
for (i = 0 ; i < 4 ; i++) {
vla.digit = i;
vla.segments = segs[i];
if (ioctl(vga_led_fd, VGA_LED_WRITE_DIGIT, &vla)) {
perror("ioctl(VGA_LED_WRITE_DIGIT) failed");
return;
}
}
}
int main()
{
vga_led_arg_t vla;
int i;
static const char filename[] = "/dev/vga_led";
static unsigned char message[4] = { 0x3f, 0x00, 0x3f, 0x00 };
printf("VGA LED Userspace program started\n");
if ( (vga_led_fd = open(filename, O_RDWR)) == -1) {
fprintf(stderr, "could not open %s\n", filename);
return -1;
}
printf("initial state: ");
print_segment_info();
write_segments(message);
printf("current state: ");
print_segment_info();
int slope = -1, x = 0x3f, y = 0x3f;
char direction = 'd';
for(;;) {
switch(direction){
case('d'):{
x -= slope;
y += 1;
if( x<=0x3f || x>= (640-0x3f))
slope *= -1;
if( y >= (480-0x3f) ){
direction = 'u';
slope *= -1;
}
break;
}
case('u'):{
x += slope;
y -= 1;
if( x <= 0x3f || x >= (640-0x3f))
slope *= -1;
if( y <= (0x3f) ){
direction = 'd';
slope *= -1;
}
break;
}
}
message[0] = x%256;
message[1] = x/256;
message[2] = y%256;
message[3] = y/256;
write_segments(message);
usleep(4000);
}
printf("VGA LED Userspace program terminating\n");
return 0;
}
|
C
|
#include <unistd.h>
#include <sys/types.h>
#define MAP_ANONYMOUS 0x20
#define MAP_PRIVATE 0x02
#define MAP_SHARED 0x01
#define PROT_READ 0x1
#define PROT_WRITE 0x2
#define PROT_EXEC 0x4
#define PROT_NONE 0x0
typedef struct {
void *addr;
int blockSize;
struct meta_block * next;
} meta_block;
meta_block *ROOT = NULL;
meta_block * getNewBlock(int len) {
//Aloocate the info block
meta_block* new_meta_block =
mmap(NULL, sizeof(meta_block)+len, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
if (new_meta_block == NULL) {
//Failed to allocate
return NULL;
}
new_meta_block->blockSize = len;
new_meta_block->addr = new_meta_block + sizeof(meta_block);
new_meta_block->next = NULL;
return new_meta_block;
}
void allocateMemoryWhenListIsEmpty(meta_block ** root, size_t size) {
*root = getNewBlock(size);
}
meta_block * getMemoryBlockFromOs(size_t size) {
meta_block * new_metaBlock = getNewBlock(size);
new_metaBlock->next = ROOT->next;
ROOT = new_metaBlock;
return ROOT;
}
void *malloc(int size) {
if (size <= 0) { // Invalid Arguments
return NULL;
}
if (ROOT == NULL) { // List is empty
allocateMemoryWhenListIsEmpty(&ROOT, size);
return (ROOT->addr);
}
meta_block * last_block = getMemoryBlockFromOs(size);
return (last_block);
}
void free (void * ptr) {
if (ptr == NULL) {
// do nothing
return;
}
meta_block* trav = ROOT;
meta_block* prev = NULL;
while (trav != NULL) {
if(trav->addr == ptr){
if(prev != NULL){
prev->next = trav->next;
}
munmap(trav, trav->blockSize+ sizeof(meta_block));
return;
}
prev = trav;
trav = (meta_block *)trav->next;
}
return;
}
|
C
|
/***********************************************
Author: Vibishan Wigneswaran
Date: 7/15/2020
Answer to question:
If a large number is used it will still dsiplay. In the recursive example there wasnt enough memory to store each number because all 500000 numbers needed to be stored in a n instant.
Using a loop, this is not the case because the data stored in the memory is overwritten consecutivly resulting in no stack overflow.(in other words all 500000 numbers arent saved at an instance, rather a few memory blocks are overwritten over time)
***********************************************/
#include <stdio.h>
void loop_down_to_zero(int value);
void loop_up_to_int(int value);
int main(int argc, char * argv[]) {
int n;
printf("Please enter a positive integer: ");
scanf("%d",&n);
loop_down_to_zero(n);
printf("****\n");
loop_up_to_int(n);
return 0;
}
void loop_down_to_zero(int value)
{
while (value>=0){
printf("%d\n",value);
value--;
}
}
void loop_up_to_int(int value)
{
int i = 0;
while (i<=value){
printf("%d\n",i);
i++;
}
}
|
C
|
#include<stdio.h>
#include<string.h>
main(){
char palabra[100];
int n,aux,largo;
scanf("%d",&n);
while(n--){
scanf("%s",palabra);
largo=strlen(palabra);
for(int i=0;i<largo;i++){
aux=palabra[i];
if(aux<91){
aux+=32;
printf("%c",aux);
}
else{
aux-=32;
printf("%c",aux);
}
}
printf("\n");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Max Min functions
#define MIN(a, b) a<b?a:b
#define MAX(a, b) a>b?a:b
//fixed size and dimensions
#define trainsize 6670
#define testsize 3333
#define dimensions 193
//classifier function
void Bayes(int trainingset[][dimensions], int testingset[][dimensions], double Probability[][192][5])
{
double classCounter[10];
int error = 0;
int i, j, k;
//initializing Class counter
for(i = 0; i <= 9; i++)
{
classCounter[i] = 0.000000;
}
//initializing Probability counter
for(i = 0; i <= 9; i++)
{
for(j = 0; j <= 191; j++)
{
for(k = 0; k <= 4; k++)
{
Probability[i][j][k] = 0.000000;
}
}
}
//finding out count of value of each feature with respect to class
for(i = 0; i < trainsize; i++)
{
classCounter[trainingset[i][192]] = classCounter[trainingset[i][192]]+1.000000;
for(j = 0; j < dimensions-1; j++)
{
Probability[trainingset[i][192]][j][trainingset[i][j]] = Probability[trainingset[i][192]][j][trainingset[i][j]] + 1.000000;
}
}
//dividing for probability and applying log on it
for(i = 0; i <= 9; i++)
{
for(j = 0; j <= 191; j++)
{
for(k = 0; k <= 4; k++)
{
Probability[i][j][k] = (double)Probability[i][j][k]/(double)classCounter[i];
Probability[i][j][k] = log(Probability[i][j][k]);
}
}
}
//testing
for(i = 0; i < testsize; i++)
{
double solution[10];
//initializing probability that it belongs to each class
for(j = 0; j < 10; j++)
{
solution[j] = 0.000000;
}
//finding out probability for each class based on it's features
printf("\nSOLUTION SET FOR TEST NO.%d:\n", i+1);
for(k = 0; k < 10; k++)
{
for(j = 0; j < dimensions-1; j++)
{
solution[k] = solution[k] + Probability[k][j][testingset[i][j]];
}
printf("%d:%lf\n", k, solution[k]);
}
//finding out class having max probability
int maxindex = 0;
double maxcount = solution[0];
for(k = 0; k < 10; k++)
{
if(maxcount <= solution[k])
{
maxcount = solution[k];
maxindex = k;
}
}
//adding to error if class doesn't match
if(maxindex != testingset[i][192])
{
error++;
}
printf("GAINED CLASS:%d ACTUAL CLASS:%d\n", maxindex, testingset[i][192]);
}
printf("WRONGLY CLASSIFIED: %d CORRECTLY CLASSIFIED: %d\nACCURACY:%lf%%\n", error, testsize-error, (1 - (float)error/testsize)*100);
}
int main()
{
double Probability[10][192][5];
int trainingset[trainsize][dimensions];
FILE *train = fopen("pp_tra.dat", "r");
int testingset[testsize][dimensions];
FILE *test = fopen("pp_tes.dat", "r");
int temp[dimensions],i = 0, j = 0;
//train file scanning
while(i < trainsize)
{
j = 0;
while(j < dimensions)
{
fscanf(train, "%d", &trainingset[i][j]);
j++;
}
i++;
}
fclose(train);
i = 0;
//test file scanning
while(i < testsize)
{
j = 0;
while(j < dimensions)
{
fscanf(test, "%d", &testingset[i][j]);
j++;
}
i++;
}
fclose(test);
//Calling classifier function
Bayes(trainingset, testingset, Probability);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_5__ TYPE_1__ ;
/* Type definitions */
struct TYPE_5__ {scalar_t__ val; } ;
typedef TYPE_1__ score ;
/* Variables and functions */
int /*<<< orphan*/ dl_swap (TYPE_1__,TYPE_1__) ;
void partial_score_val_sort (score *sc, int limit, int size) {
score *begin_stack[32];
score *end_stack[32];
begin_stack[0] = sc;
end_stack[0] = sc + size - 1;
int depth;
for (depth = 0; depth >= 0; --depth) {
score *begin = begin_stack[depth];
score *end = end_stack[depth];
while (begin < end) {
int offset = (end - begin) >> 1;
dl_swap (*begin, begin[offset]);
score *i = begin + 1, *j = end;
while (1) {
for ( ; i < j && begin->val < i->val; i++) {
}
for ( ; j >= i && j->val < begin->val; j--) {
}
if (i >= j) {
break;
}
dl_swap (*i, *j);
++i;
--j;
}
dl_swap (*begin, *j);
if (j - begin <= end - j) {
if (j + 1 < end && j + 1 < sc + limit) {
begin_stack[depth] = j + 1;
end_stack[depth++] = end;
}
end = j - 1;
} else {
if (j - 1 > begin) {
begin_stack[depth] = begin;
end_stack[depth++] = j - 1;
}
begin = j + 1;
}
}
}
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#define MAX_LEN 512
void myPrint(char *msg)
{
write(STDOUT_FILENO, msg, strlen(msg));
}
void errorPrint(){
/*
If a command does not exist or a command is over the length limit
*/
char error_message[30] = "An error has occured\n";
write(STDOUT_FILENO, error_message, strlen(error_message));
}
void remove_leading_space(char* str){
/*
removes leading spaces
*/
int index, i;
index = 0;
//find last index
while(str[index] == ' ' || str[index] == '\t' || str[index] == '\n')
{
index++;
}
if(index != 0)
{
//shift
i = 0;
while(str[i + index] != '\0')
{
str[i] = str[i + index];
i++;
}
// null terminated
str[i] = '\0';
}
}
int my_cd(char *args){
/*
changes directory
args[0] is "cd". args[1] is the directory.
always returns 1, to continue executing.
*/
char* cd_path = strchr(args, ' ');
//if no path or $HOME
if(cd_path == NULL){
chdir(getenv("HOME"));
} else {
// go to path
remove_leading_space(cd_path);
if(strcmp(cd_path, "$HOME") == 0){
chdir(getenv("HOME"));
}
if (chdir(cd_path) != 0) {
errorPrint();
}
}
return 1;
}
char** split_line(char* pinput, int* num_args) {
/*
splits line into tokens
returns null terminated array of tokes
*/
int buffsize = MAX_LEN;
int position = 0;
char delim[5] = {'\t', '\r', '\n', ';'};
char **tokens = malloc(buffsize * sizeof(char *));
char *token;
if (!tokens) {
errorPrint();
exit(0);
}
//first tokenize
token = strtok(pinput, delim);
//iterate through getting every token
while (token != NULL) {
remove_leading_space(token);
tokens[position] = token;
position++;
//tokenize again
token = strtok(NULL, delim);
}
tokens[position] = NULL;
*num_args = position;
return tokens;
}
char** split_space(char* pinput) {
/*
splits line into tokens
returns null terminated array of tokes
*/
int buffsize = MAX_LEN;
int position = 0;
char delim[5] = {' '};
char **tokens = malloc(buffsize * sizeof(char *));
char *token;
if (!tokens) {
exit(0);
}
//first tokenize
token = strtok(pinput, delim);
//iterate through getting every token
while (token != NULL) {
remove_leading_space(token);
tokens[position] = token;
position++;
//tokenize again
token = strtok(NULL, delim);
}
tokens[position] = NULL;
return tokens;
}
int execute(char **args)
{
/*
executes
takes null terminated list of arguments (including program)
always returns 1, to continue execution.
*/
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
errorPrint();
}
exit(0);
} else if (pid < 0) {
// Error forking
errorPrint();
} else {
// Parent process
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
int to_redirect_or_not(char* arg){
/*
returns 1 if normal redirect
returns 2 if advanced
returns 0 if none
*/
int i = 0;
while(cmd[i] != '\0'){
//normal
if(cmd[i] == '>'){
//advanced
if(cmd[i + 1] == '+' ){
return 2;
}
return 1;
}
}
return 0;
}
int invalid_redirect(char* arg, int num_pipe, int num_files, int no_cmd, int built_in){
/*
checks:
no more than one <
no more than one file
no command
built in commands
*/
int pos_redir = 0;
int redirect_type = 0;
num_pipe = 0;
num_files = 0;
no_cmd = 0;
built_in = 0;
redirect_type = to_redirect_or_not(arg);
for(int i = 0; arg[i] != '\0'; i++){
// checking num pipes
if(arg[i] == '>'){
num_pipe++;
// setting position of redirect for both cases
pos_redir = i;
if(redirect_type == 2){
pos_redir = i + 1;
}
i++;
}
}
}
if(num_pipe == 1 && num_files == 1 && no_cmd == 0 && built_in == 0){
return 1;
}
else{
return 0;
}
}
int main(int argc, char *argv[])
{
char cmd_buff[MAX_LEN];
char *pinput;
char **args;
FILE* batch_file;
int batch_flag = 0;
int num_args = 0;
if(argc == 2){
batch_file = fopen(argv[1], "r");
if(batch_file == NULL){
errorPrint();
exit(0);
}
batch_flag = 1;
}
while (1) {
//BATCH MODE
if(batch_flag){
pinput = fgets(cmd_buff, MAX_LEN, batch_file);
//exit if no input
if(!pinput){
errorPrint();
exit(0);
}
myPrint(pinput);
remove_leading_space(pinput);
}else{
//INTERACTIVE MODE
myPrint("myshell> ");
pinput = fgets(cmd_buff, MAX_LEN, stdin);
//exit if no input
if (!pinput) {
errorPrint();
exit(0);
}
}
//PARSE
char* ptr = pinput;
args = split_line(ptr, &num_args);
for(int i =0; i < num_args; i++){
//REDIRECTION
int redirect_flag;
redirect_flag = to_redirect_or_not(args[i]);
if(redirect_flag == 1){
//normal redirection
}
else if(redirect_flag == 2){
//advanced
}
else{
//everything else
}
//CHECKING FOR BUILT INS
if(strcmp(args[i], "exit") == 0){
exit(0);
}
else if(strcmp(args[i], "pwd") == 0){
char wd[MAX_LEN];
myPrint(getcwd(wd, MAX_LEN));
myPrint("\n");
}
else if(strstr(args[i], "cd") != NULL){
my_cd(args[i]);
}
else {
//EXECUTION
char **exec_args;
//exec_args= malloc (4 * sizeof (char *));
exec_args = split_space(args[i]);
//exec_args[0] = malloc (514 * sizeof (char));
//strcpy(exec_args[0], args[i]);
//exec_args[1] = NULL;
execute(exec_args);
free(exec_args);
}
}
}
if(batch_flag){
fclose(batch_file);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.