language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdlib.h>
#include <stdio.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* swapPairs(struct ListNode* head) {
struct ListNode *p, *pre, dummy;
pre = &dummy;
pre->next = p = head;
while(p) {
struct ListNode *p1, *p2;
p1 = p->next;
if(p1 == NULL) {
break;
}
p2 = p1->next;
pre->next = p1;
p1->next = p;
p->next = p2;
pre = p;
p = p->next;
}
return dummy.next;
}
int main(int argc,char *argv[])
{
return 0;
}
|
C
|
#include "vendor/unity.h"
#include "../src/stack.h"
#include <stdlib.h>
#include <string.h>
#define STACK_CAPACITY 1024
void setUp(void) {}
void tearDown(void) {}
static void test_push_stack(void) {
Stack *stack = new_stack(STACK_CAPACITY, sizeof(int));
TEST_ASSERT_NOT_NULL(stack);
for (int i = 0; i < STACK_CAPACITY; i++) {
int result = push(stack, &i);
TEST_ASSERT_EQUAL(0, result);
}
TEST_ASSERT_EQUAL(1, is_stack_full(stack));
delete_stack(stack);
}
static void test_pop_stack(void) {
Stack *stack = new_stack(STACK_CAPACITY, sizeof(int));
TEST_ASSERT_NOT_NULL(stack);
for (int i = 0; i < STACK_CAPACITY; i++) {
int result = push(stack, &i);
TEST_ASSERT_EQUAL(0, result);
}
int value;
for (int i = 0; i < STACK_CAPACITY; i++) {
pop(stack, &value);
TEST_ASSERT_EQUAL(i + 1, STACK_CAPACITY - value);
}
TEST_ASSERT_EQUAL(1, is_stack_empty(stack));
delete_stack(stack);
}
int main() {
UnityBegin("test/test_stack.c");
RUN_TEST(test_push_stack);
RUN_TEST(test_pop_stack);
return UnityEnd();
}
|
C
|
#include<stdio.h>
int main()
{
int n,f,f1=0,f2=1,i;
printf("\n enter the n value");
scanf("%d",&n);
printf("%d%d",f1,f2);
for(i=2;i<n;i++)
{
f=f1+f2;
f1=f2;
f2=f;
printf("%d",f);
}
}
|
C
|
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stm8s.h>
#include <uart.h>
#include <delay.h>
// brief:
// Mode: 8-N-1, flow-control: none.
// uart 115200 baud on following pins:
// * PD5 -> TX
// * PD6 -> RX
// use console:
// $ picocom -b 115200 --imap lfcrlf /dev/ttyUSB0
// to exit: CTRL + A + X
// Redirect stdout to UART
int putchar(int c) {
uart_write(c);
return 0;
}
// Redirect stdin to UART
int getchar() {
return uart_read();
}
void main() {
uint8_t counter = 0;
enable_interrupts(); // for delays to work
uart_init();
while (1) {
printf("Test, %d\n", counter++);
delay_ms(500);
}
}
|
C
|
#include "linkedlist.h"
typedef struct NodeTag {
nodeData data;
Node* next;
}Node;
Node* MakeNode(nodeData data)
{
Node* new_node=(Node*)malloc(sizeof(Node));
if(new_node != NULL)
{
new_node->data=data;
new_node->next=NULL;
}
return new_node;
}
void push_back(Node** head,Node** tail,Node* element)
{
if(*head == NULL ) //and *tail==NULL
{
*head=*tail=element;
(*head)->next=NULL;
(*tail)->next=NULL;
}
else
{
(*tail)->next=element;
*tail=element;
(*tail)->next=NULL;//safety
}
return;
}
nodeData pop_front(Node** head,Node** tail)
{
nodeData data=NULL;
if(*head != NULL){
data=(*head)->data;
Node* del=*head;
*head=(*head)->next;
if(*head == NULL)
*tail=NULL;
free(del);
del=NULL;
}
return data;
}
|
C
|
/*******************************************************************************************
*
* raylib - sample game: snake
*
* Sample game developed by Ian Eito, Albert Martos and Ramon Santamaria
*
* This game has been created using raylib v1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
* Extension by Ismail Zegour - 31/10/2020
*
********************************************************************************************/
#include "raylib.h"
#include <stdio.h>
#include <stdlib.h>
#if defined(PLATFORM_WEB)
#include <emscripten/emscripten.h>
#endif
//----------------------------------------------------------------------------------
// Some Defines
//----------------------------------------------------------------------------------
#define SNAKE_LENGTH 256
#define SQUARE_SIZE 31
//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
typedef struct Snake {
Vector2 position;
Vector2 size;
Vector2 speed;
Color color;
} Snake;
typedef struct Food {
Vector2 position;
Vector2 size;
bool active;
Color color;
} Food;
typedef struct Obstacle {
Vector2 position;
Vector2 size;
bool active;
Color color;
} Obstacle;
//------------------------------------------------------------------------------------
// Module Functions Declaration (local)
//------------------------------------------------------------------------------------
static void InitGame(void); // Initialize game
static void UpdateGame(void); // Update game (one frame)
static void DrawGame(void); // Draw game (one frame)
static void UnloadGame(void); // Unload game
static void UpdateDrawFrame(void); // Update and Draw (one frame)
//------------------------------------------------------------------------------------
// Global Variables Declaration
//------------------------------------------------------------------------------------
static const int gameScreenWidth = 800;
static const int screenHeight = 450;
static const int screenWidth = 1000;
static int framesCounter = 0;
static bool gameOver = true;
static bool pause = false;
static bool start = true;
static bool personnalise = false;
static bool automatique = false;
static bool avecTraverser = false;
static bool avecObstacle = false;
static Food fruit = { 0 };
static Obstacle obstacle = { 0 };
static Snake snake[SNAKE_LENGTH] = { 0 };
static Vector2 snakePosition[SNAKE_LENGTH] = { 0 };
static bool allowMove = false;
static Vector2 offset = { 0 };
static int counterTail = 0;
static int score = 0;
static int bestScore = 0;
static int fps = 30;
//------------------------------------------------------------------------------------
// Nouvelles fonction implémentées
//------------------------------------------------------------------------------------
void convert(int Nb, char* NombreaEcrire)// Converti un int en char* pour l'affichage
{
int Puissance, chiffre, i;
bool HasWriteNumber;
Puissance = 100000;
i = 0;
HasWriteNumber = false;
while (Puissance != 0)
{
chiffre = Nb / Puissance;
Nb = Nb - Puissance * chiffre;
if ((chiffre != 0) || (HasWriteNumber == true))
{
NombreaEcrire[i] = chiffre + 48;
i++;
HasWriteNumber = true;
}
Puissance = Puissance / 10;
}
if ((i == 0) && (HasWriteNumber == false))
{
NombreaEcrire[i] = 48;
i++;
}
NombreaEcrire[i] = '\0';
}
void traverserMur()
{
if (((snake[0].position.x) > (gameScreenWidth - offset.x)))
snake[0].position.x = offset.x / 2;
else if (((snake[0].position.x) < offset.x / 2))
snake[0].position.x = (gameScreenWidth - offset.x / 2 - SQUARE_SIZE);
else if (((snake[0].position.y) > (screenHeight - offset.y)))
snake[0].position.y = offset.y / 2;
else if (((snake[0].position.y) < offset.y / 2))
snake[0].position.y = (screenHeight - offset.y / 2 - SQUARE_SIZE);
}
void creerObstacle()
{
obstacle.active = true;
obstacle.position = (Vector2){ GetRandomValue(0, (gameScreenWidth / SQUARE_SIZE) - 1) * SQUARE_SIZE + offset.x / 2,
GetRandomValue(0, (screenHeight / SQUARE_SIZE) - 1) * SQUARE_SIZE + offset.y / 2 }; // On genere une position aléatoire pour l'obstacle
for (int i = 0; i < counterTail; i++)
{
while (((obstacle.position.x == snake[i].position.x) && (obstacle.position.y == snake[i].position.y)) ||
((obstacle.position.x == fruit.position.x) && (obstacle.position.y == fruit.position.y))) // On vérifie qu'il ne tombe pas sur un fruit ou sur le serpent
{
obstacle.position = (Vector2){ GetRandomValue(0, (gameScreenWidth / SQUARE_SIZE) - 1) * SQUARE_SIZE + offset.x / 2,
GetRandomValue(0, (screenHeight / SQUARE_SIZE) - 1) * SQUARE_SIZE + offset.y / 2 };
i = 0;
}
}
}
void collisionFruit()
{
snake[counterTail].position = snakePosition[counterTail - 1];
counterTail += 1;
fruit.active = false;
obstacle.active = false;
score += 1;
if (score >= bestScore) bestScore = score;
}
void personnaliser() {
ClearBackground(WHITE);
DrawText("PERSONNALISER", screenWidth / 2 - MeasureText("PERSONNALISER", 30) / 2 - 50, 50, 30, BLACK);
//Affichage obstacle
DrawText("Obstacles : ", screenWidth / 4 - MeasureText("SNAKE", 40) / 2 - 50, 150, 30, BLACK);
DrawText("[O]", screenWidth / 2 + 150, 150, 30, BLACK);
if (avecObstacle) DrawText("Oui ", screenWidth / 2, 150, 30, GREEN);
else DrawText("Non", screenWidth / 2, 150, 30, RED);
//Affichage traverser les murs
DrawText("Traverser les murs : ", screenWidth / 4 - MeasureText("SNAKE", 40) / 2 - 50, 200, 30, BLACK);
DrawText("[T]", screenWidth / 2 + 150, 200, 30, BLACK);
if (avecTraverser) DrawText("Oui ", screenWidth / 2, 200, 30, GREEN);
else DrawText("Non", screenWidth / 2, 200, 30, RED);
//Affichage vitesse
DrawText("Vitesse : ", screenWidth / 4 - MeasureText("SNAKE", 40) / 2 - 50, 250, 30, BLACK);
DrawText("[<]", screenWidth / 2 - 50, 250, 30, BLACK);
DrawText("[>]", screenWidth / 2 + 50, 250, 30, BLACK);
const char* fpss = malloc(sizeof(int));
convert(fps, fpss);
if (fps < 30) DrawText(fpss, screenWidth / 2, 250, 30, BLUE);
else if (fps >= 30 && fps <= 60) DrawText(fpss, screenWidth / 2, 250, 30, GREEN);
else if (fps > 60) DrawText(fpss, screenWidth / 2, 250, 30, RED);
free(fpss);
//Affichage touches
DrawText("[M] pour le Menu", screenWidth / 8, screenHeight - 50, 20, GRAY);
DrawText("[ENTREE] pour lancer", screenWidth - MeasureText("[ENTREE] pour lancer", 20) - 125, screenHeight - 50, 20, GRAY);
if (IsKeyPressed('O')) avecObstacle = !avecObstacle;
else if (IsKeyPressed('T')) avecTraverser = !avecTraverser;
else if (IsKeyPressed(KEY_LEFT) && fps > 0) fps -= 5;
else if (IsKeyPressed(KEY_LEFT) && fps == 0) fps = 0;
else if (IsKeyPressed(KEY_RIGHT) && fps < 120) fps += 5;
else if (IsKeyPressed(KEY_SEMICOLON)) // Equivalent de la touche [M] en AZERTY
{
start = true;
personnalise = false;
gameOver = true;
}
else if (IsKeyPressed(KEY_ENTER) && fps > 0)
{
InitGame();
SetTargetFPS(fps);
start = false;
personnalise = false;
}
else if (fps == 0)
DrawText("Veuillez entrer une vitesse superieure a 0", screenWidth / 4, screenHeight - 100, 20, RED);
}
void lireFichierScore()
{
char* nomFichier = "score.txt";
FILE* fichier;
fichier = fopen(nomFichier, "r");
if (fichier == NULL)
{
printf("Error opening file score.txt ");
exit(1);
}
fscanf(fichier, "%u\n", &bestScore);
fclose(fichier);
}
void modifierFichierScore() {
char* nomFichier = "score.txt";
FILE* fichier;
fichier = fopen(nomFichier, "r+");
fscanf(fichier, "%u\n", &bestScore);
if (score > bestScore)
{
const char* scoreChar = (const char*)malloc(sizeof(int));
convert(score, scoreChar);
fseek(fichier, SEEK_SET, 0);
fputs(scoreChar, fichier);
free(scoreChar);
}
fclose(fichier);
score = 0;
}
void menuPrincipal()
{
ClearBackground(SKYBLUE);
DrawText("ISMAIL ZEGOUR", 50, 10, 20, GRAY);
DrawText("RAYLIB", screenWidth - 150, 10, 20, GRAY);
DrawText("SNAKE 2.0", screenWidth / 2 - MeasureText("SNAKE 2.0", 40) / 2, 100, 40, BLACK);
DrawText("FACILE : [F]", screenWidth / 2 - MeasureText("FACILE : [F]", 25) / 2, screenHeight / 2 - 20, 25, BLACK);
DrawText("INTERMEDIAIRE : [I]", screenWidth / 2 - MeasureText("INTERMEDIAIRE : [I]", 25) / 2, screenHeight / 2 + 20, 25, BLACK);
DrawText("DIFFICILE : [D]", screenWidth / 2 - MeasureText("DIFFICILE :[D]", 25) / 2, screenHeight / 2 + 60, 25, BLACK);
DrawText("PERSONNALISER : [P]", screenWidth / 2 - MeasureText("PERSONNALISE: [P]", 25) / 2, screenHeight / 2 + 100, 25, BLACK);
DrawText("MODE AUTOMATIQUE :[A]", screenWidth / 2 - MeasureText("MODE AUTOMATIQUE :[A]", 30) / 2, screenHeight / 2 + 140, 30, BLACK);
DrawText("BEST SCORE", screenWidth - 140 - MeasureText("BEST SCORE", 25) / 2, 200, 25, RED);
DrawText("Can you beat that ?", screenWidth - 140 - MeasureText("Can you beat that ?", 20) / 2, 280, 20, BLACK);
lireFichierScore();
const char* bestScoreAffiche = (const char*)malloc(sizeof(int));
convert(bestScore, bestScoreAffiche);
DrawText(bestScoreAffiche, screenWidth - 140 - MeasureText(bestScoreAffiche, 25) / 2, 225, 25, RED);
free(bestScoreAffiche);
if (IsKeyPressed(KEY_F)) {
InitGame();
fps = 45;
SetTargetFPS(fps);
avecObstacle = false;
avecTraverser = true;
start = false;
}
if (IsKeyPressed(KEY_I)) {
InitGame();
fps = 45;
SetTargetFPS(fps);
avecObstacle = true;
avecTraverser = true;
start = false;
}
if (IsKeyPressed(KEY_D)) {
InitGame();
fps = 60;
SetTargetFPS(fps);
avecObstacle = true;
avecTraverser = false;
start = false;
}
if (IsKeyPressed(KEY_P)) {
personnalise = true;
start = false;
}
if (IsKeyPressed(KEY_Q)) {
InitGame();
fps = 60;
SetTargetFPS(fps);
automatique = true;
avecObstacle = true;
avecTraverser = false;
start = false;
}
}
void moveRight()
{
if (allowMove) {
snake[0].speed = (Vector2){ SQUARE_SIZE, 0 };
allowMove = false;
}
}
void moveLeft()
{
if (allowMove) {
snake[0].speed = (Vector2){ -SQUARE_SIZE, 0 };
allowMove = false;
}
}
void moveUp()
{
if (allowMove) {
snake[0].speed = (Vector2){ 0, -SQUARE_SIZE };
allowMove = false;
}
}
void moveDown()
{
if (allowMove) {
snake[0].speed = (Vector2){ 0, SQUARE_SIZE };
allowMove = false;
}
}
bool murHaut()
{
return ((snake[0].position.y - SQUARE_SIZE) < offset.y / 2)
|| (avecObstacle && snake[0].position.x == obstacle.position.x && snake[0].position.y - SQUARE_SIZE == obstacle.position.y);
}
bool murBas()
{
return (snake[0].position.y + SQUARE_SIZE) > (screenHeight - offset.y)
|| (avecObstacle && snake[0].position.x == obstacle.position.x && snake[0].position.y + SQUARE_SIZE == obstacle.position.y);
}
bool murDroit()
{
return (snake[0].position.x + SQUARE_SIZE) > (gameScreenWidth - offset.x)
|| (avecObstacle && snake[0].position.x + SQUARE_SIZE == obstacle.position.x && snake[0].position.y == obstacle.position.y);
}
bool murGauche()
{
return ((snake[0].position.x - SQUARE_SIZE) < offset.x / 2)
|| (avecObstacle && snake[0].position.x - SQUARE_SIZE == obstacle.position.x && snake[0].position.y == obstacle.position.y);
}
void mouvementAuto()
{
float depx = fruit.position.x - snake[0].position.x;
float depy = fruit.position.y - snake[0].position.y;
// Mouvement à droite
if (depx > 0 && allowMove)
{
bool queueDroite = false;
bool queueGauche = false;
bool queueBas = false;
bool queueHaut = false;
for (int i = 1; i < counterTail; i++)// On verifie s'il y a sa queue aux alentours
{
if (((snake[0].position.x + SQUARE_SIZE == snake[i].position.x) && (snake[0].position.y == snake[i].position.y))) // Si queue a droite
queueDroite = true;
if (((snake[0].position.x - SQUARE_SIZE == snake[i].position.x) && (snake[0].position.y == snake[i].position.y))) // Si queue a gauche
queueGauche = true;
if (((snake[0].position.x == snake[i].position.x) && (snake[0].position.y + SQUARE_SIZE == snake[i].position.y))) // Si queue en bas
queueBas = true;
if (((snake[0].position.x == snake[i].position.x) && (snake[0].position.y - SQUARE_SIZE == snake[i].position.y))) // Si queue a droite
queueHaut = true;
}
if (queueDroite || murDroit()) //Si queue ou obstacle à droite
{
if (snake[0].speed.y < 0)// si on montait
{
if (queueHaut || murHaut())
moveLeft();
else
allowMove = false;
}
if (snake[0].speed.y > 0)// si on descendait
{
if (queueBas || murBas())
moveLeft();
else
allowMove = false;
}
//Prévision pour éviter les culs de sac
if (snake[0].speed.x > 0 && depy == 0 && snake[0].position.y - snake[counterTail / 2].position.y > 0) // Si on allait a droite en venant du haut a n-4
{
if (queueBas || murBas())
moveUp();
else
moveDown(); // Alors on va essayer de s'eloigner de nos précedentes positions en allant vers le bas en priorité
}
if (snake[0].speed.x > 0 && depy == 0) // Si on allait a droite en venant du bas ou de la gauche
{
if (queueHaut || murHaut())
moveDown();
else
moveUp();
}
if (depy == 0 && snake[0].speed.x < 0)// Si on est sur la meme ligne et qu'on va à gauche
{
if (queueHaut || murHaut())
{
if (queueBas || murBas())
moveLeft();
else
moveDown();
}
else
moveUp();
}
}
else
moveRight();
}
// Mouvement à gauche
if (depx < 0 && allowMove)
{
bool queueDroite = false;
bool queueGauche = false;
bool queueBas = false;
bool queueHaut = false;
for (int i = 1; i < counterTail; i++)// On verifie s'il y a sa queue aux alentours
{
if (((snake[0].position.x + SQUARE_SIZE == snake[i].position.x) && (snake[0].position.y == snake[i].position.y))) // Si queue a droite
queueDroite = true;
if (((snake[0].position.x - SQUARE_SIZE == snake[i].position.x) && (snake[0].position.y == snake[i].position.y))) // Si queue a gauche
queueGauche = true;
if (((snake[0].position.x == snake[i].position.x) && (snake[0].position.y + SQUARE_SIZE == snake[i].position.y))) // Si queue en bas
queueBas = true;
if (((snake[0].position.x == snake[i].position.x) && (snake[0].position.y - SQUARE_SIZE == snake[i].position.y))) // Si queue a droite
queueHaut = true;
}
if (queueGauche || murGauche()) //Si queue ou obstacle à gauche
{
if (snake[0].speed.y < 0)// si on montait
{
if (queueHaut || murHaut())
moveRight();
else
moveUp();
}
if (snake[0].speed.y > 0)// si on descendait
{
if (queueBas || murBas())
moveRight();
else
moveDown();
}
if (snake[0].speed.x < 0 && depy == 0 && snake[0].position.y - snake[counterTail / 2].position.y > 0) // Si on allait a gauche en venant du haut
{
if (queueBas || murBas())
moveUp();
else
moveDown(); // Alors on va essayer de s'eloigner de nos précedentes positions en allant vers le bas en priorité
}
if (snake[0].speed.x < 0 && depy == 0)// Si on allait a gauche en venant du bas ou de la droite a n-4
{
if (queueHaut || murHaut())
moveDown();
else
moveUp();
}
if (depy == 0 && snake[0].speed.x > 0)// Si on est sur la meme ligne et qu'on va à droite
{
if (queueHaut || murHaut())
{
if (queueBas || murBas())
moveRight();
else
moveDown();
}
else
moveUp();
}
}
else
moveLeft();
}
// Mouvement en bas
if (depy > 0 && allowMove)
{
bool queueDroite = false;
bool queueGauche = false;
bool queueBas = false;
bool queueHaut = false;
for (int i = 1; i < counterTail; i++)// On verifie s'il y a sa queue aux alentours
{
if (((snake[0].position.x + SQUARE_SIZE == snake[i].position.x) && (snake[0].position.y == snake[i].position.y))) // Si queue a droite
queueDroite = true;
if (((snake[0].position.x - SQUARE_SIZE == snake[i].position.x) && (snake[0].position.y == snake[i].position.y))) // Si queue a gauche
queueGauche = true;
if (((snake[0].position.x == snake[i].position.x) && (snake[0].position.y + SQUARE_SIZE == snake[i].position.y))) // Si queue en bas
queueBas = true;
if (((snake[0].position.x == snake[i].position.x) && (snake[0].position.y - SQUARE_SIZE == snake[i].position.y))) // Si queue a droite
queueHaut = true;
}
if (queueBas || murBas()) //Si queue ou obstacle en bas
{
if (snake[0].speed.x < 0)// si on allait a gauche
{
if (queueGauche || murGauche())
moveUp();
else
allowMove = false;
}
if (snake[0].speed.x > 0)// si on allait a droite
{
if (queueDroite || murDroit())
moveUp();
else
allowMove = false;
}
// Prevision ( pour éviter les culs de sac)
if (snake[0].speed.y > 0 && depx == 0 && snake[0].position.x - snake[counterTail / 2].position.x < 0)// Si on allait en bas et que l'on vient de la droite (verification etat n-10 arbitrairement)
{
if (queueGauche || murGauche())
moveRight();
else
moveLeft();// Alors on va essayer de s'eloigner de nos précedentes positions en allant vers la gauche en priorité
}
if (snake[0].speed.y > 0 && depx == 0)// Sinon on vient de la gauche ou d'en haut
{
if (queueDroite || murDroit())
moveLeft();
else
moveRight();
}
if (depx == 0 && snake[0].speed.y < 0)// Si on est sur la meme colonne et qu'on va dans le sens contraire
{
if (queueDroite || murDroit())
{
if (queueGauche || murGauche())
moveDown();
else
moveLeft();
}
else
moveRight();
}
}
else
moveDown();
}
// Mouvement en haut
if (depy < 0 && allowMove)
{
bool queueDroite = false;
bool queueGauche = false;
bool queueBas = false;
bool queueHaut = false;
for (int i = 1; i < counterTail; i++)// On verifie s'il y a sa queue aux alentours
{
if (((snake[0].position.x + SQUARE_SIZE == snake[i].position.x) && (snake[0].position.y == snake[i].position.y))) // Si queue a droite
queueDroite = true;
if (((snake[0].position.x - SQUARE_SIZE == snake[i].position.x) && (snake[0].position.y == snake[i].position.y))) // Si queue a gauche
queueGauche = true;
if (((snake[0].position.x == snake[i].position.x) && (snake[0].position.y + SQUARE_SIZE == snake[i].position.y))) // Si queue en bas
queueBas = true;
if (((snake[0].position.x == snake[i].position.x) && (snake[0].position.y - SQUARE_SIZE == snake[i].position.y))) // Si queue a droite
queueHaut = true;
}
if (queueHaut || murHaut()) //Si queue ou obstacle en haut
{
if (snake[0].speed.x < 0)// si on allait a gauche
{
if (queueGauche || murGauche())
moveDown();
else
allowMove = false;
}
if (snake[0].speed.x > 0)// si on allait a droite
{
if (queueDroite || murDroit())
moveDown();
else
allowMove = false;;
}
// Prevision ( pour éviter les culs de sac)
if (snake[0].speed.y < 0 && depx == 0 && snake[0].position.x - snake[counterTail / 2].position.x < 0)// Si on allait en haut et que l'on vient de la droite (verification a la moitié arbitrairement)
{
if (queueGauche || murGauche())
moveRight();
else
moveLeft();// Alors on va essayer de s'eloigner de nos précedentes positions en allant vers la gauche en priorité
}
if (snake[0].speed.y < 0 && depx == 0)// Si on allait en haut
{
if (queueDroite || murDroit())
moveLeft();
else
moveRight();
}
if (depx == 0 && snake[0].speed.y > 0)// Si on est sur la meme colonne et qu'on va dans le sens contraire
{
if (queueDroite || murDroit())
{
if (queueGauche || murGauche())
moveDown();
else
moveLeft();
}
else
moveRight();
}
}
else
moveUp();
}
}
void mouvementManuel()
{
if (IsKeyPressed(KEY_RIGHT) && (snake[0].speed.x == 0))
moveRight();
if (IsKeyPressed(KEY_LEFT) && (snake[0].speed.x == 0))
moveLeft();
if (IsKeyPressed(KEY_UP) && (snake[0].speed.y == 0))
moveUp();
if (IsKeyPressed(KEY_DOWN) && (snake[0].speed.y == 0))
moveDown();
}
//------------------------------------------------------------------------------------
// Program main entry point
//------------------------------------------------------------------------------------
int main(void)
{
// Initialization (Note windowTitle is unused on Android)
//---------------------------------------------------------
InitWindow(screenWidth, screenHeight, "Snake");
start = true;
#if defined(PLATFORM_WEB)
emscripten_set_main_loop(UpdateDrawFrame, 60, 1);
#else
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update and Draw
//----------------------------------------------------------------------------------
UpdateDrawFrame();
//----------------------------------------------------------------------------------
}
#endif
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadGame(); // Unload loaded data (textures, sounds, models...)
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
//------------------------------------------------------------------------------------
// Module Functions Definitions (local)
//------------------------------------------------------------------------------------
// Initialize game variables
void InitGame(void)
{
framesCounter = 0;
gameOver = false;
pause = false;
counterTail = 1;
allowMove = false;
offset.x = gameScreenWidth % SQUARE_SIZE;
offset.y = screenHeight % SQUARE_SIZE;
for (int i = 0; i < SNAKE_LENGTH; i++)
{
snake[i].position = (Vector2){ offset.x / 2, offset.y / 2 };
snake[i].size = (Vector2){ SQUARE_SIZE, SQUARE_SIZE };
snake[i].speed = (Vector2){ SQUARE_SIZE, 0 };
if (i == 0) snake[i].color = DARKBLUE;
else snake[i].color = BLUE;
}
for (int i = 0; i < SNAKE_LENGTH; i++)
{
snakePosition[i] = (Vector2){ 0.0f, 0.0f };
}
fruit.size = (Vector2){ SQUARE_SIZE, SQUARE_SIZE };
fruit.color = SKYBLUE;
fruit.active = false;
obstacle.size = (Vector2){ SQUARE_SIZE, SQUARE_SIZE };
obstacle.color = RED;
obstacle.active = false;
lireFichierScore();
}
// Update game (one frame)
void UpdateGame(void)
{
if (!gameOver && !start && !personnalise) // en cours de partie
{
if (IsKeyPressed('P')) pause = !pause;
if (!pause)
{
// Player control
mouvementManuel();
if (automatique) mouvementAuto();
// Snake movement
for (int i = 0; i < counterTail; i++) snakePosition[i] = snake[i].position;
if ((framesCounter % 5) == 0)
{
for (int i = 0; i < counterTail; i++)
{
if (i == 0)
{
snake[0].position.x += snake[0].speed.x;
snake[0].position.y += snake[0].speed.y;
allowMove = true;
}
else snake[i].position = snakePosition[i - 1];
}
}
// Collision contre mur sans traverserMur
if (!avecTraverser && (((snake[0].position.x) > (gameScreenWidth - offset.x)) ||
((snake[0].position.y) > (screenHeight - offset.y)) ||
(snake[0].position.x < 0) || (snake[0].position.y < 0)))
{
gameOver = true;
modifierFichierScore;
}
// Collision contre mur avec traverserMur
if (((snake[0].position.x) > (gameScreenWidth - offset.x)) ||
((snake[0].position.y) > (screenHeight - offset.y)) ||
(snake[0].position.x < 0) || (snake[0].position.y < 0) && avecTraverser)
{
traverserMur();
}
// Collision with yourself
for (int i = 1; i < counterTail; i++)
{
if ((snake[0].position.x == snake[i].position.x) && (snake[0].position.y == snake[i].position.y)) gameOver = true;
}
// Fruit position calculation
if (!fruit.active)
{
fruit.active = true;
fruit.position = (Vector2){ GetRandomValue(0, (gameScreenWidth / SQUARE_SIZE) - 1) * SQUARE_SIZE + offset.x / 2, GetRandomValue(0, (screenHeight / SQUARE_SIZE) - 1) * SQUARE_SIZE + offset.y / 2 };
for (int i = 0; i < counterTail; i++)
{
while ((fruit.position.x == snake[i].position.x) && (fruit.position.y == snake[i].position.y))
{
fruit.position = (Vector2){ GetRandomValue(0, (gameScreenWidth / SQUARE_SIZE) - 1) * SQUARE_SIZE + offset.x / 2, GetRandomValue(0, (screenHeight / SQUARE_SIZE) - 1) * SQUARE_SIZE + offset.y / 2 };
i = 0;
}
}
}
// Collision avec fruit
if ((snake[0].position.x < (fruit.position.x + fruit.size.x) && (snake[0].position.x + snake[0].size.x) > fruit.position.x) &&
(snake[0].position.y < (fruit.position.y + fruit.size.y) && (snake[0].position.y + snake[0].size.y) > fruit.position.y))
{
collisionFruit();
}
// Calcul de la position de l'obstacle
if (avecObstacle && !obstacle.active)
{
creerObstacle();
}
//Collision avec obstacle
if (avecObstacle && (snake[0].position.x < (obstacle.position.x + obstacle.size.x) && (snake[0].position.x + snake[0].size.x) > obstacle.position.x) &&
(snake[0].position.y < (obstacle.position.y + obstacle.size.y) && (snake[0].position.y + snake[0].size.y) > obstacle.position.y))
{
gameOver = true;
modifierFichierScore();
}
if (IsKeyPressed(KEY_SEMICOLON))// Equivalent de la touche [M] en AZERTY
{
gameOver = true;
modifierFichierScore();
start = true;
automatique=false;
}
if (IsKeyPressed(KEY_W))
{
fps += 5;
SetTargetFPS(fps);
}
if (IsKeyPressed(KEY_Q))
{
if (fps > 5)fps -= 5;
SetTargetFPS(fps);
}
framesCounter++;
}
}
else if (gameOver && !start && !personnalise) { // en fin de partie
if (IsKeyPressed(KEY_R))
{
modifierFichierScore();
InitGame();
gameOver = false;
start = false;
personnalise = false;
automatique=false;
}
if (IsKeyPressed(KEY_SEMICOLON)) // Equivalent de la touche [M] en AZERTY
{
modifierFichierScore();
start = true;
personnalise = false;
automatique=false;
}
}
}
// Draw game (one frame)
void DrawGame(void)
{
BeginDrawing();
ClearBackground(RAYWHITE);
if (!gameOver && !start) // Pendant la partie
{
// Draw grid lines
for (int i = 0; i < gameScreenWidth / SQUARE_SIZE + 1; i++)
{
DrawLineV((Vector2) { SQUARE_SIZE* i + offset.x / 2, offset.y / 2 }, (Vector2) { SQUARE_SIZE* i + offset.x / 2, screenHeight - offset.y / 2 }, LIGHTGRAY);
}
for (int i = 0; i < screenHeight / SQUARE_SIZE + 1; i++)
{
DrawLineV((Vector2) { offset.x / 2, SQUARE_SIZE* i + offset.y / 2 }, (Vector2) { gameScreenWidth - offset.x / 2, SQUARE_SIZE* i + offset.y / 2 }, LIGHTGRAY);
}
// Draw snake
for (int i = 0; i < counterTail; i++) DrawRectangleV(snake[i].position, snake[i].size, snake[i].color);
// Draw fruit to pick
DrawRectangleV(fruit.position, fruit.size, fruit.color);
// Draw side score
DrawText("SCORE", screenWidth - 100 - MeasureText("SCORE", 25) / 2, 25, 25, BLUE);
const char* scoreAffiche = (const char*)malloc(sizeof(int));
convert(score, scoreAffiche);
DrawText(scoreAffiche, screenWidth - 100 - MeasureText(scoreAffiche, 25) / 2, 50, 25, BLUE);
free(scoreAffiche);
//Draw best score
DrawText("BEST SCORE", screenWidth - 100 - MeasureText("BEST SCORE", 25) / 2, 100, 25, RED);
const char* bestScoreAffiche = (const char*)malloc(sizeof(int));
convert(bestScore, bestScoreAffiche);
DrawText(bestScoreAffiche, screenWidth - 100 - MeasureText(bestScoreAffiche, 25) / 2, 125, 25, RED);
free(bestScoreAffiche);
//Draw commands
DrawText("[P] for pause", screenWidth - 100 - MeasureText("[P] for pause", 20) / 2, screenHeight - 75, 20, GRAY);
DrawText("[M] for the menu", screenWidth - 100 - MeasureText("[M] for the menu", 20) / 2, screenHeight - 50, 20, GRAY);
//Draw FPS
DrawText("[A]- VITESSE +[Z]", screenWidth - 100 - MeasureText("[A]- VITESSE +[Z]", 20) / 2, 200, 20, BLACK);
const char* fpss = malloc(sizeof(int));
convert(fps, fpss);
DrawText(fpss, screenWidth - 100 - MeasureText(fpss, 20) / 2, 220, 20, BLACK);
free(fpss);
// Draw traverser
DrawText("Traverser les murs :", screenWidth - 100 - MeasureText("Traverser les murs :", 20) / 2, 300, 20, BLACK);
if (avecTraverser) DrawText("Oui", screenWidth - 100 - MeasureText("Oui", 20) / 2, 330, 20, GREEN);
if (!avecTraverser)DrawText("Non", screenWidth - 100 - MeasureText("Non", 20) / 2, 330, 20, RED);
// Draw Obstacle
if (avecObstacle) DrawRectangleV(obstacle.position, obstacle.size, obstacle.color);
if (pause) DrawText("GAME PAUSED", gameScreenWidth / 2 - MeasureText("GAME PAUSED", 40) / 2, screenHeight / 2 - 40, 40, GRAY);
}
else if (start && gameOver && !personnalise) menuPrincipal(); // Menu principal
else if (personnalise && gameOver && !start) personnaliser(); // Menu parametres
else {
DrawText("Rejouer : [R]", GetScreenWidth() / 2 - MeasureText("Rejouer : [R]", 20) / 2, GetScreenHeight() / 2 - 50, 20, GRAY);
DrawText("Menu Principal : [M]", GetScreenWidth() / 2 - MeasureText("Menu Principal : [M]", 20) / 2, GetScreenHeight() / 2 + 50, 20, GRAY);
}
EndDrawing();
}
// Update and Draw (one frame)
void UpdateDrawFrame(void)
{
UpdateGame();
DrawGame();
}
|
C
|
#include<stdio.h>
int main()
{
int n,m;
long int sum1,sum2,t,temp;
long long int sum;
while(scanf("%d %d",&n,&m)==2)
{
if (n>m)
{
temp=n;
n=m;
m=temp;
}
t=n-1;
sum1=(m*(m+1))/2;
sum2=(t*(t+1))/2;
sum=sum1-sum2;
printf("Sum of %d to %d is -> %ld;\n",n,m,sum);
}
}
|
C
|
#ifndef _MY_SPI_H
#define _MY_SPI_H
#include "main.h"
/*
SPIݸʽ
0 Head̶ 0x86
1 DevId
2 CmdType
3 CmdLen
4~֮CmdData
4DataTypeЧ/ack/ǷҪǰ֡
5Ƶ
6~֮跢͵2.4G
*/
#define SPI_LINK_OFFSET_HEAD (0)
#define SPI_LINK_OFFSET_DEV_ID (1)
#define SPI_LINK_OFFSET_CMD_TYPE (2)
#define SPI_LINK_OFFSET_CMD_LEN (3)
#define SPI_LINK_OFFSET_CMD_DATA (4)
// SPIٻijȺ
#define SPI_MAX_BUFFER_SIZE (255)
#define SPI_MAX_CACHE_SIZE (10)
#define TX_BUF_SIZE (255) /**< SPI TX buffer size. */
#define RX_BUF_SIZE TX_BUF_SIZE /**< SPI RX buffer size. */
#define SPIS_IRQ_PIN 0
#define SPIS_CE_PIN 1
#define SPIS_MOSI_PIN 2 // SPI MOSI signal.
#define SPIS_MISO_PIN 3 // SPI MISO signal.
#define SPIS_SCK_PIN 4 // SPI SCK signal.
#define SPIS_CSN_PIN 5 // SPI CSN signal.
typedef enum
{
SPI_CMD_NONE = 0x00,
SPI_CMD_SET_CHANNAL = 0x20,
SPI_CMD_GET_STATE = 0x21,
SPI_CMD_GET_24G_DATA = 0x22,
SPI_CMD_SEND_24G_DATA = 0x23
}SPI_CMD_TYPE;
typedef struct
{
uint8_t Head;
uint8_t DevId;
uint8_t CmdType;
uint8_t CmdLen;
uint8_t CmdData[255];
uint8_t Xor;
uint8_t End;
}SPI_CMD_FORMAT_T;
typedef enum
{
SPI_DATA_NULL, // ʼ״̬
SPI_DATA_NEW, // µSPI
SPI_DATA_24G, // Ҫ2.4G㴦
SPI_DATA_INVALID // ɵݣɴµ
}SPI_DATA_HANDLER_STATE;
typedef struct
{
uint8_t Data[SPI_MAX_BUFFER_SIZE]; // SPIԭʼ
uint8_t DataLen;
SPI_DATA_HANDLER_STATE State; // ݴ״̬
// 0δ
// 1SPI㴦ɣ2.4GͲ㴦
// 3
}SPI_DATA_T;
typedef struct
{
uint32_t SpiEnterPos; // SPI㴦λ
uint32_t SpiExitPos;
uint32_t _24gEnterPos; // 2.4G㴦λ
uint32_t _24gExitPos;
SPI_DATA_T DATA[SPI_MAX_CACHE_SIZE];
SPI_CMD_FORMAT_T RX;
bool SpiTriggerIrqFlg;
}SPI_PARAMETERS_T;
extern uint8_t tx_data_len;
extern uint8_t m_tx_buf[TX_BUF_SIZE]; /**< SPI TX buffer. */
extern uint8_t m_rx_buf[RX_BUF_SIZE]; /**< SPI RX buffer. */
extern SPI_PARAMETERS_T SPI;
void my_spi_slave_init(void);
void spi_gpio_init(void);
void spi_trigger_irq(void);
void SPI_DataHandler(void);
#endif
|
C
|
int main()
{
int n, i, j, k, l;
scanf("%d", &n);
if(n==1)
{
printf("End");
return 0;
}
do
{
if(n%2!=0)
{
k=n*3+1;
printf("%d*3+1=%d\n", n, k);
n=k;
}
if(n%2==0)
{
j=n/2;
printf("%d/2=%d\n", n, j);
n=j;
}
}while(n>1);
printf("End");
return 0;
}
|
C
|
#include "cidade.h"
//https://programacaodescomplicada.wordpress.com/2012/11/09/aula-64-alocacao-dinamica-pt-6-alocacao-de-matrizes/
//Adaptado
int** alocarMatriz(int Linhas, int Colunas) { //Recebe a quantidade de Linhas e Colunas como Parâmetro
int i, j; //Variáveis Auxiliares
int **m = (char**) malloc(Linhas * sizeof (char*)); //Aloca um Vetor de Ponteiros
for (i = 0; i < Linhas; i++) { //Percorre as linhas do Vetor de Ponteiros
m[i] = (int*) malloc(Colunas * sizeof (int)); //Aloca um Vetor de Inteiros para cada posição do Vetor de Ponteiros.
for (j = 0; j < Colunas; j++) { //Percorre o Vetor de Inteiros atual.
m[i][j] = 0; //Inicializa com 0.
}
}
return m; //Retorna o Ponteiro para a Matriz Alocada
}
//transforma vetor de caracteres em inteiro
int stringToInt(char *num) {
int i, n = 0;
for (i = 0; i < strlen(num); i++) {
n = (n * 10) + num[i] - 48;
}
return n;
}
void insereObra(int linha, int coluna, Mapa* mapa, char lado) {
linha--;
coluna--;
if (lado == 'L') {
if (mapa->mapa[linha][coluna] == NORTE) { //caso ja houver norte inserido
mapa->mapa[linha][coluna] = NORTE_LESTE;
return;
}
mapa->mapa[linha][coluna] = LESTE;
}
if (lado == 'N') {
if (mapa->mapa[linha][coluna] == LESTE) { //caso ja houver leste inserido
mapa->mapa[linha][coluna] = NORTE_LESTE;
return;
}
mapa->mapa[linha][coluna] = NORTE;
}
}
int carregaArquivo(char *nomeArq, Mapa *retorno) {
FILE *arq;
arq = fopen(nomeArq, "r");
char ch;
char numLinhas[5] = {}, numColunas[5] = {};
int i = 0, cont = 0;
int atual = 0;
char xInicial[5], yInicial[5], xFinal[5], yFinal[5];
char x[5], y[5], lado;
if (arq == NULL) { //erro ao carregar arquivo
printf("ERRO AO LER ARQUIVO");
return 0;
} else {
while (1) { //enquanto o arquivo não termina
ch = fgetc(arq);
//printf("\n olhando: %c",ch);
switch (i) {
case 0: //tamanhos de linha e coluna
if (ch == '\n') {//termina de olhar qtd de linhas e colunas
i = 1;
numColunas[cont] = '\0';
retorno->qtdLinhas = stringToInt(numLinhas);
retorno->qtdColunas = stringToInt(numColunas);
retorno->mapa = alocarMatriz(retorno->qtdLinhas, retorno->qtdColunas);
atual = 0;
cont = 0;
} else {
if (ch != ' ') {
if (atual == 0) {
numLinhas[cont] = ch;
cont++;
} else {
numColunas[cont] = ch;
cont++;
}
} else {
atual = 1;
numLinhas[cont] = '\0';
cont = 0;
}
}
break;
case 1: //ponto inicial
if (ch == '\n') {//termina de olhar ponto inicial
i = 2;
yInicial[cont] = '\0';
retorno->inicio.linha = stringToInt(xInicial) - 1;
retorno->inicio.coluna = stringToInt(yInicial) - 1;
retorno->mapa[retorno->inicio.linha][retorno->inicio.coluna] = 6;
atual = 0;
cont = 0;
} else {
if (ch != ' ') {
if (atual == 0) {
xInicial[cont] = ch;
cont++;
} else {
yInicial[cont] = ch;
cont++;
}
} else {
atual = 1;
xInicial[cont] = '\0';
cont = 0;
}
}
break;
case 2: //pronto final
if (ch == '\n') {//termina de olhar ponto final
i = 3;
yFinal[cont] = '\0';
retorno->fim.linha = stringToInt(xFinal) - 1;
retorno->fim.coluna = stringToInt(yFinal) - 1;
retorno->mapa[retorno->fim.linha][retorno->fim.coluna] = 9;
atual = 0;
cont = 0;
} else {
if (ch != ' ') {
if (atual == 0) {
xFinal[cont] = ch;
cont++;
} else {
yFinal[cont] = ch;
cont++;
}
} else {
atual = 1;
xFinal[cont] = '\0';
cont = 0;
}
}
break;
default: //locais das obras
if (ch == '\n' || ch == EOF) {//termina de olhar local
y[cont] = '\0';
insereObra(stringToInt(x), stringToInt(y), retorno, lado);
atual = 0;
cont = 0;
} else {
if (ch != ' ') {
if (atual == 0) {
x[cont] = ch;
cont++;
} else if (atual == 1) {
y[cont] = ch;
cont++;
} else if (atual == 2) {
lado = ch;
}
} else {
if (atual == 0) {
atual = 1;
x[cont] = '\0';
cont = 0;
} else if (atual == 1) {
atual = 2;
y[cont] = '\0';
}
}
}
}
if (ch == EOF) { //fim do arquivo
break;
}
}
}
fclose(arq);
return 1;
}
//imprime o mapa na tela
void mostraMapa(Mapa *mapa) {
int i, j;
char cI, cF;
printf("Mapa:\n");
for (i = 0; i <= mapa->qtdLinhas; i++) {//faz borda superior
printf("_ _ _ _ ");
}
printf("\n");
for (j = mapa->qtdColunas - 1; j >= 0; j--) {
if (j != mapa->qtdColunas - 1) { //insere as ruas
for (i = 0; i < mapa->qtdLinhas - 1; i++) {
printf(" ");
}
printf(" |\n");
for (i = 0; i < mapa->qtdLinhas - 1; i++) {
printf("| |MM");
}
printf("| |\n");
for (i = 0; i < mapa->qtdLinhas - 1; i++) {
if (mapa->mapa[i][j] == NORTE || mapa->mapa[i][j] == NORTE_LESTE) { //olha se tem obra no norte
printf("| XX |WW");
} else {
printf("| |WW");
}
}
if (mapa->mapa[i][j] == NORTE || mapa->mapa[i][j] == NORTE_LESTE) { //olha se tem obra no norte na ultima coluna
printf("| XX |\n|");
} else {
printf("| |\n|");
}
for (i = 0; i < mapa->qtdLinhas - 1; i++) {
printf(" ");
}
printf(" |\n");
}
for (i = 0; i < mapa->qtdLinhas; i++) {
if (i == 0) {
printf("|");
}
//para posições inicial e final mostrarem de forma diferente
if (i == mapa->inicio.linha && j == mapa->inicio.coluna) {
cI = '(';
cF = ')';
} else if (i == mapa->fim.linha && j == mapa->fim.coluna) {
cI = '[';
cF = ']';
} else {
cI = ' ';
cF = ' ';
}
printf(" %c%d,%d%c", cI, i + 1, j + 1, cF);
if (i == mapa->qtdLinhas - 1) {
printf("|");
} else {
if (mapa->mapa[i][j] == LESTE || mapa->mapa[i][j] == NORTE_LESTE) { //olha se tem obra no leste
printf(" XX ");
} else {
printf(" ");
}
}
}
printf("\n|");
}
printf(" ");
for (i = 0; i <= mapa->qtdLinhas; i++) { //faz borda inferior
printf("_ _ _ _ ");
}
printf("\n");
}
//retorna 1 se tem obra ou não existe a posição ou 0 se não tem
int temObra(int linha, int coluna, int direcao, Mapa * mapa) {
//se não consigo ir para NORTE, na vdd não consigo ir para DIREITA (i,j+1)
//se não consigo ir para LESTE, na vdd não consigo ir para BAIXO (i+1,j)
if (direcao == NORTE) {
if (linha >= mapa->qtdLinhas || linha < 0 || (coluna - 1) >= mapa->qtdColunas || (coluna - 1) < 0) { //se estrapolar o mapa
return 1;
}
if (mapa->mapa[linha][coluna - 1] == NORTE || mapa->mapa[linha][coluna - 1] == NORTE_LESTE) {
return 1;
}
}
if (direcao == LESTE) {
if ((linha - 1) >= mapa->qtdLinhas || (linha - 1) < 0 || coluna >= mapa->qtdColunas || coluna < 0) {//se estrapolar o mapa
return 1;
}
if (mapa->mapa[linha - 1][coluna] == LESTE || mapa->mapa[linha - 1][coluna] == NORTE_LESTE) {
return 1;
}
}
return 0;
}
void calcular(Mapa *m) {
int i, j;
int **count = alocarMatriz(m->qtdLinhas + 1, m->qtdColunas + 1);
int **caminho = alocarMatriz(m->qtdLinhas + 1, m->qtdColunas + 1);
count[m->fim.linha][m->fim.coluna] = 1;
//adaptação feita a partir dos slides
for (i = m->qtdLinhas - 1; i >= 0; i--) {
for (j = m->qtdColunas - 1; j >= 0; j--) {
if (j > 0 && !temObra(i, j, NORTE, m)) {
count[i][j - 1] += count[i][j];
caminho[i][j] = -1;
}
if (i > 0 && !temObra(i, j, LESTE, m)) {
count[i - 1][j] += count[i][j];
caminho[i][j] = 1;
}
}
}
printf("Count:");
printf("\n");
for (j = m->qtdColunas - 1; j >= 0; j--) {
for (i = 0; i < m->qtdLinhas; i++) {
printf("%d ", count[i][j]);
}
printf("\n");
}
mostraCaminho(count, m);
}
void mostraCaminho(int **count, Mapa *m) {
int i, j, cont = 0;
int tamMax = m->qtdColunas * m->qtdLinhas;
Posicao caminho[tamMax];
int x = m->inicio.linha, y = m->inicio.coluna;
while (x < (m->fim.linha) || y < (m->fim.coluna)) { //percorre o caminho
if (count[x][y] == 0) {
if (x == m->fim.linha - 1 && y == m->fim.coluna - 1) { //chegada
caminho[cont].linha = x + 1;
caminho[cont].coluna = y + 1;
cont++;
}
break;
}
//insere posição no caminho
caminho[cont].linha = x + 1;
caminho[cont].coluna = y + 1;
cont++;
if (count[x + 1][y] > 0 && m->mapa[x][y] != LESTE && m->mapa[x][y] != NORTE_LESTE) { //anda pra leste
x++;
} else if (count[x][y + 1] > 0 && m->mapa[x][y] != NORTE && m->mapa[x][y] != NORTE_LESTE) { //anda pra norte
y++;
} else { //nao ha caminhos
cont = 0;
break;
}
}
printf("\nCaminho possivel: ");
for (i = 0; i < cont; i++) {
printf("(%d,%d)-> ", caminho[i].linha, caminho[i].coluna);
}
if (cont > 0) {
printf("(%d,%d)", m->fim.linha + 1, m->fim.coluna + 1);
} else {
printf(" Nao ha caminho!");
}
}
|
C
|
#include <getopt.h>
#include <stdio.h>
#include <libapp.h>
#include <errno.h>
#include <string.h>
extern int archFlag;
elf_info g_elf;
static int get_machine_type(int machine){
dbgprintf("Machine architecture is:");
switch ( machine ) {
case 0x02:
strcpy(g_elf.cmachine, "SPARC");
break;
case 0x03:
strcpy(g_elf.cmachine ,"X86");
break;
case 0x08:
strcpy(g_elf.cmachine , "MIPS");
break;
case 0x14:
strcpy(g_elf.cmachine , "PowerPC");
break;
case 0x16:
strcpy(g_elf.cmachine , "S390");
break;
case 0x28:
strcpy(g_elf.cmachine , "ARM");
break;
case 0x2A:
strcpy(g_elf.cmachine , "SuperH");
break;
case 0x32:
strcpy(g_elf.cmachine , "IA-64");
break;
case 0x3E:
strcpy(g_elf.cmachine , "x86-64");
break;
case 0xB7:
strcpy(g_elf.cmachine , "AArch64");
break;
case 0xF3:
strcpy(g_elf.cmachine , "RISC-V");
break;
default:
strcpy(g_elf.cmachine , "UNKWN??");
break;
}
dbgprintf("%s\n",g_elf.cmachine);
return 0;
}
/*
* Retreive data from litle endian library
* getData = number of bytes we want to retreive from data buffer
*/
long long get_little_endian(unsigned char *data,int getData){
switch(getData){
case 2:// machine arch is 2 bytes
return ( (unsigned int)data[0] | (unsigned int) (data[1] << 8) );
default:
dbgprintf("unsupported data size!!\n");
}
}
/*
* Retreive data from big endian library
* getData = number of bytes we want to retreive from data buffer
*/
long long get_big_endian(unsigned char *data,int getData){
switch(getData){
case 2:// machine arch is of 2 bytes
return ( (unsigned int)data[1] | (unsigned int) (data[0] << 8) );
default:
dbgprintf("unsupported data size!!\n");
}
}
/*
* Parse file here, read headers, return machine value
*/
int check_header(char *header){
if ( (header[0] == ELF_MAG0) &&
(header[1] == ELF_MAG1) &&
(header[2] == ELF_MAG2) &&
(header[3] == ELF_MAG3)){
return 0;
}
return -1;
}
int check_elf_header(char *filename){
FILE *file = NULL;
memset(&g_elf, 0, sizeof(struct _elf_info));
dbgprintf("trying to open file:%s\n", filename);
file = fopen(filename, "rb");
if ( file == NULL ) {
printf("Error!!! Unable to read File:%s\n", filename);
return -1;
}
elf_header_t local_elf_header;
if ( !fread(&local_elf_header, 24, 1 ,file)) {
printf("unable to read header\n, try again");
fclose(file);
return -1;
}
dbgprintf("header elf?0x%x %c %c %c\n",local_elf_header.e_ident[0],
local_elf_header.e_ident[1],
local_elf_header.e_ident[2],
local_elf_header.e_ident[3]);
/*Check endianness to understand how to read data from header!!*/
if ( check_header(local_elf_header.e_ident) ) {
dbgprintf("%s is not an library\n", filename);
return -1;
}
dbgprintf("found lib file:%s\n", filename);
dbgprintf("endianness:%d\n", local_elf_header.endian);
switch ( local_elf_header.endian ) {
case ELFDATA2LSB:
get_byte_data = get_little_endian;
break;
case ELFDATA2MSB:
get_byte_data = get_big_endian;
break;
default:
printf("Unable to read endianness:%d\n", local_elf_header.endian);
}
/*
*Extract machine Architecture
*/
dbgprintf("machine?0x%x0x%x\n", local_elf_header.e_machine[0],
local_elf_header.e_machine[1]);
unsigned short machine = get_byte_data(local_elf_header.e_machine, 2);
if ( archFlag ) {
get_machine_type(machine);
}
dbgprintf("g_elf.machine:%s\n", g_elf.cmachine);
return 0;
}
|
C
|
#include <stdio.h> ///basic input-output functions
#include <time.h> ///time & date related functions
#include <string.h> ///string related functions
#include <conio.h> ///for using getch() functions
#include <windows.h> ///windows console related functions
///a function that returns current date
const char * date ()
{
time_t now = time(NULL); ///time() with NULL parameter returns current date-time
struct tm *date = localtime(&now); ///it contains date-time in a struct
static char data[15]; ///it contains date
strftime(data, sizeof(data), "%d%m%Y", date); ///formatting the date in a string
return data;
}
struct date
{
char name[100], date[4], month[4], year[6];
} add;
///a function to add a task
void addTask ()
{
system("cls");
printf("******************************\n");
printf("*** Add Task ***\n");
printf("******************************\n");
printf("\n\n");
printf("\nWhat task do you want to add?\n");
gets(add.name); //read task name
printf("\nWhen do you want to %s? [dd mm year]\n", add.name);
scanf("%s", &add.date);
scanf("%s", &add.month);
scanf("%s", &add.year); //read task date
//create file path
char path[30]; //contains file path
strcpy(path, "./tasks/"); //add directory name in file path
strcat(path, add.date); //add date in file path
strcat(path, add.month); //add month in file path
strcat(path, add.year); //add year in file path
strcat(path, ".txt"); //add file extension in file path
//add task in file
FILE *addtask = fopen(path, "a");
fprintf(addtask, "%s\n", add.name);
fclose(addtask);
printf("\nThe task has been added successfully\n");
system("pause");
return;
}
void updateTask ()
{
system("cls");
printf("******************************\n");
printf("**** Update Task ***\n");
printf("******************************\n");
printf("\n\n");
char taskd[4], taskm[4], tasky[6];
printf("\nDate of the Task? [dd mm year]\n"); //contains task date
scanf("%s %s %s", &taskd, &taskm, &tasky); //read task date
//create file path
char path[30];
strcpy(path, "./tasks/");
strcat(path, taskd);
strcat(path, taskm);
strcat(path, tasky);
strcat(path, ".txt");
char output[100];
FILE *file = fopen(path, "r");
if (file == NULL)
{
printf("No task found in %s/%s/%s", taskd, taskm, tasky);
}
else
{
printf("\nIn %s/%s/2019, List of Your Task(s)\n", taskd, taskm, tasky);
printf("************************************************************\n\n");
int i = 0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
printf("%d. %s", i, output);
}
fclose(file);
int line;
printf("\n\nWhich task Do You Want to Update?\n");
scanf("%d", &line);
getchar();
char newtask[100]; // contains task name
printf("\nWhat task do you want to add?\n");
gets(newtask); //read task name
FILE *uptask = fopen("./tasks/tmp.txt", "a");
FILE *file = fopen(path, "r");
i=0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
if (i == line)
fprintf(uptask, "%s\n", newtask);
else
fprintf(uptask, "%s", output);
}
fclose(uptask);
fclose(file);
remove(path);
int p = rename("./tasks/tmp.txt", path);
if(p == 0)
printf("\n%d no task has been updated successfully\n\n", line);
else
printf("\nError: Unable to update the task\n\n");
system("pause");
}
}
void cmpltTask ()
{
system("cls");
printf("\t\t\t******************************\n");
printf("\t\t\t**** Complete Task ***\n");
printf("\t\t\t******************************\n");
printf("\n\n");
char taskd[4], taskm[4], tasky[6];
printf("\nDate of the Task? [dd mm year]\n"); //contains task date
scanf("%s %s %s", &taskd, &taskm, &tasky); //read task date
//create file path
char path[30];
strcpy(path, "./tasks/");
strcat(path, taskd);
strcat(path, taskm);
strcat(path, tasky);
strcat(path, ".txt");
char output[100];
FILE *file = fopen(path, "r");
if (file == NULL)
{
printf("No task found in %s/%s/%s", taskd, taskm, tasky);
}
else
{
printf("\nIn %s/%s/2019, List of Your Task(s)\n", taskd, taskm, tasky);
printf("************************************************************\n\n");
int i = 0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
printf("%d. %s", i, output);
}
fclose(file);
int line;
printf("\n\nWhich task Do You Want to flag as completed?\n");
scanf("%d", &line);
getchar();
FILE *uptask = fopen("./tasks/tmp.txt", "a");
FILE *file = fopen(path, "r");
FILE *cmplt = fopen("./tasks/completed.txt", "a");
i=0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
if (i == line)
fprintf(cmplt, "%s", output);
else
fprintf(uptask, "%s", output);
}
fclose(uptask);
fclose(file);
fclose(cmplt);
remove(path);
int p = rename("./tasks/tmp.txt", path);
if(p == 0)
printf("\n%d no task has been flagged successfully\n\n", line);
else
printf("\nError: Unable to update the task\n\n");
system("pause");
}
}
void cancelTask ()
{
system("cls");
printf("\t\t\t******************************\n");
printf("\t\t\t**** Cancel Task ***\n");
printf("\t\t\t******************************\n");
printf("\n\n");
char taskd[4], taskm[4], tasky[6];
printf("\nDate of the Task? [dd mm year]\n"); //contains task date
scanf("%s %s %s", &taskd, &taskm, &tasky); //read task date
//create file path
char path[30];
strcpy(path, "./tasks/");
strcat(path, taskd);
strcat(path, taskm);
strcat(path, tasky);
strcat(path, ".txt");
char output[100];
FILE *file = fopen(path, "r");
if (file == NULL)
{
printf("No task found in %s/%s/%s", taskd, taskm, tasky);
}
else
{
printf("\nIn %s/%s/2019, List of Your Task(s)\n", taskd, taskm, tasky);
printf("************************************************************\n\n");
int i = 0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
printf("%d. %s", i, output);
}
fclose(file);
int line;
printf("\n\nWhich task Do You Want to cancel?\n");
scanf("%d", &line);
getchar();
FILE *uptask = fopen("./tasks/tmp.txt", "a");
FILE *file = fopen(path, "r");
i=0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
if (i != line)
fprintf(uptask, "%s", output);
}
fclose(uptask);
fclose(file);
remove(path);
int p = rename("./tasks/tmp.txt", path);
if(p == 0)
printf("\n%d no task has been canceled successfully\n\n", line);
else
printf("\nError: Unable to update the task\n\n");
system("pause");
}
}
void nextTask ()
{
system("cls");
printf("\t\t\t******************************\n");
printf("\t\t\t**** Check Upcoming Task ***\n");
printf("\t\t\t******************************\n");
printf("\n\n");
char path[30];
strcpy(path, "./tasks/");
strcat(path, date());
strcat(path, ".txt");
char output[1000];
FILE *file = fopen(path, "r");
if (file == NULL)
{
printf("\n\nNo Upcoming Task Found\n\n");
}
else
{
printf("\n\nList of Your Upcoming Task(s):\n");
printf("************************************************************\n\n");
int i = 0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
printf("%d. %s", i, output);
}
}
fclose(file);
system("pause");
}
void checkTask ()
{
system("cls");
printf("******************************\n");
printf("* Tasks of Specific Date *\n");
printf("******************************\n");
printf("\n\n");
char taskd[4], taskm[4], tasky[6];
printf("\nDate of the Task? [dd mm year]\n"); //contains task date
scanf("%s %s %s", &taskd, &taskm, &tasky); //read task date
//create file path
char path[30];
strcpy(path, "./tasks/");
strcat(path, taskd);
strcat(path, taskm);
strcat(path, tasky);
strcat(path, ".txt");
char output[1000];
FILE *file = fopen(path, "r");
if (file == NULL)
{
printf("\nNo task found in %s/%s/%s\n\n", taskd, taskm, tasky);
}
else
{
printf("\nIn %s/%s/%s, List of Your Task(s):\n", taskd, taskm, tasky);
printf("************************************************************\n\n");
int i = 0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
printf("%d. %s", i, output);
}
printf("\n\n");
}
fclose(file);
system("pause");
return;
}
void checkDone ()
{
system("cls");
printf("******************************\n");
printf("**** Completed Task ***\n");
printf("******************************\n");
printf("\n\n");
char path[30];
strcpy(path, "./tasks/");
strcat(path, "completed");
strcat(path, ".txt");
char output[1000];
FILE *file = fopen(path, "r");
if (file == NULL)
{
printf("\n\nNo Completed Task Found\n\n");
}
else
{
printf("\nList of Your Completed Task(s):\n");
printf("************************************************************\n\n");
int i = 0;
while (fgets(output, sizeof(output), file) != NULL)
{
i++;
printf("%d. %s", i, output);
}
printf("\n\n");
}
fclose(file);
system("pause");
}
void bye ()
{
char ans[5];
printf("\nDo you really want to exit?\n");
scanf ("%[^\n]%*c", ans);
if(strcmp(ans, "Yes") == 0 || strcmp(ans, "yes") == 0 || strcmp(ans, "sure") == 0)
{
system("cls");
exit (1);
}
}
void home ()
{
printf("**************************************************\n");
printf("****** ******\n");
printf("**** Personal Assistant ***\n");
printf("****** ******\n");
printf("**************************************************\n");
printf("\n\n\n");
printf("1. Add task\n");
printf("2. Update task\n");
printf("3. Complete task\n");
printf("4. Cancel task\n");
printf("5. Upcoming task\n");
printf("6. Check tasks of specific date\n");
printf("7. Check completed task\n");
printf("8. Exit\n");
printf("\n");
printf("Enter your choice: ");
int ans; //contains the choice from user
scanf("%d", &ans); //read the choice from user
getchar();
switch (ans)
{
case 1:
addTask();
break;
case 2:
updateTask ();
break;
case 3:
cmpltTask ();
break;
case 4:
cancelTask();
break;
case 5:
nextTask();
break;
case 6:
checkTask();
break;
case 7:
checkDone();
break;
case 8:
bye();
break;
}
system("cls");
home();
return;
}
int main ()
{
home ();
return 0;
}
|
C
|
/** @file UART.c
* @see UART.h for description.
* @author Adrien RICCIARDI
*/
#include "UART.h"
#ifdef WIN32 // Windows
#include <windows.h>
// This variable is global in this module in order to avoid passing it as a parameter.
static HANDLE COM_Handle;
int UARTOpen(char *Device_File_Name)
{
DCB COM_Parameters;
COMMTIMEOUTS Timing_Parameters;
// Open the serial port and set all access rights
COM_Handle = CreateFile(Device_File_Name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (COM_Handle == INVALID_HANDLE_VALUE) return 0; // Error : can't access to serial port
// Configure port
COM_Parameters.DCBlength = sizeof(DCB);
COM_Parameters.fBinary = 1; // Must be set to 1 or Windows becomes angry
COM_Parameters.fParity = 0; // No parity
// Ignore modem signals
COM_Parameters.fOutxCtsFlow = 0;
COM_Parameters.fOutxDsrFlow = 0;
COM_Parameters.fDtrControl = DTR_CONTROL_DISABLE;
COM_Parameters.fDsrSensitivity = 0;
COM_Parameters.fTXContinueOnXoff = 0;
COM_Parameters.fOutX = 0;
COM_Parameters.fInX = 0;
COM_Parameters.fErrorChar = 0;
COM_Parameters.fNull = 0;
COM_Parameters.fRtsControl = RTS_CONTROL_DISABLE;
COM_Parameters.fAbortOnError = 0;
COM_Parameters.fDummy2 = 0;
COM_Parameters.wReserved = 0;
COM_Parameters.XonLim = 0;
COM_Parameters.XoffLim = 0;
COM_Parameters.ByteSize = 8; // 8 bits of data
COM_Parameters.Parity = NOPARITY; // Parity check disabled
COM_Parameters.StopBits = ONESTOPBIT;
COM_Parameters.XonChar = 0;
COM_Parameters.XoffChar = 0;
COM_Parameters.ErrorChar = 0;
COM_Parameters.EofChar = 0;
COM_Parameters.EvtChar = 0;
COM_Parameters.wReserved1 = 0;
// Set transmit and receive speed
COM_Parameters.BaudRate = CBR_230400;
// Set new parameters
SetCommState(COM_Handle, &COM_Parameters);
// Make reads non blocking
Timing_Parameters.ReadIntervalTimeout = MAXDWORD; // According to MSDN, make the ReadFile() function returns immediately
Timing_Parameters.ReadTotalTimeoutMultiplier = 0;
Timing_Parameters.ReadTotalTimeoutConstant = 0;
Timing_Parameters.WriteTotalTimeoutMultiplier = 0;
Timing_Parameters.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(COM_Handle, &Timing_Parameters);
// No error
return 1;
}
unsigned char UARTReadByte(void)
{
unsigned char Byte;
DWORD Number_Bytes_Read;
do
{
ReadFile(COM_Handle, &Byte, 1, &Number_Bytes_Read, NULL);
} while (Number_Bytes_Read == 0);
return Byte;
}
void UARTWriteByte(unsigned char Byte)
{
DWORD Number_Bytes_Written;
WriteFile(COM_Handle, &Byte, 1, &Number_Bytes_Written, NULL);
}
int UARTIsByteAvailable(unsigned char *Available_Byte)
{
DWORD Number_Bytes_Read;
ReadFile(COM_Handle, Available_Byte, 1, &Number_Bytes_Read, NULL);
if (Number_Bytes_Read == 0) return 0;
return 1;
}
void UARTClose(void)
{
CloseHandle(COM_Handle);
}
#else // Linux / UNIX
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// File representing the UART
static int File_Descriptor_UART;
// Old UART parameters
static struct termios Parameters_Old;
int UARTOpen(char *Device_File_Name)
{
struct termios Parameters_New;
// Open device file
File_Descriptor_UART = open(Device_File_Name, O_RDWR | O_NONBLOCK);
if (File_Descriptor_UART == -1) return 0;
// Backup old UART parameters
if (tcgetattr(File_Descriptor_UART, &Parameters_Old) == -1) return 0;
// Configure new parameters
Parameters_New.c_iflag = IGNBRK | IGNPAR; // Ignore break, no parity
Parameters_New.c_oflag = 0;
Parameters_New.c_cflag = CS8 | CREAD | CLOCAL; // 8 data bits, receiver enabled, ignore modem control lines
Parameters_New.c_lflag = 0; // Use raw mode
// Set speeds
if (cfsetispeed(&Parameters_New, B230400) == -1) return 0;
if (cfsetospeed(&Parameters_New, B230400) == -1) return 0;
// Set parameters
if (tcsetattr(File_Descriptor_UART, TCSANOW, &Parameters_New) == -1) return 0;
return 1;
}
unsigned char UARTReadByte(void)
{
unsigned char Byte;
while (read(File_Descriptor_UART, &Byte, 1) <= 0);
return Byte;
}
void UARTWriteByte(unsigned char Byte)
{
write(File_Descriptor_UART, &Byte, 1);
}
int UARTIsByteAvailable(unsigned char *Available_Byte)
{
if (read(File_Descriptor_UART, Available_Byte, 1) == 1) return 1;
return 0;
}
void UARTClose(void)
{
tcsetattr(File_Descriptor_UART, TCSANOW, &Parameters_Old);
close(File_Descriptor_UART);
}
#endif
|
C
|
#include<graphics.h>
void fillrectangle(int,int,int,int,int);
void pattern(int,int,int,int,int,int);
void fillrectangle(int x1,int y1,int x2,int y2,int color)
{
int let;
for(let=x1;let<x2;let++)
{
setcolor(color);
rectangle(let,y1,let,y2);
}
}
void pattern(int x1,int y1,int x2,int y2,int pat,int color)
{
setfillstyle(pat,color);
bar(x1,y1,x2,y2);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
unsigned long long max(unsigned long long a, unsigned long long b) {
if (a > b)
return a;
return b;
}
int main() {
unsigned long long N, a[1000000], i, j, count[1000000], length = 0;
scanf("%llu", &N);
if(N==0) {
printf("%llu", length);
return 0;
}
for(i=0; i<N; i++) {
scanf("%llu", &a[i]);
count[i] = 0;
}
count[0] = 1;
length = 1;
for(i=1; i<N; i++) {
count[i] = 1;
for(j=0; j<i; j++) {
if(a[i] > a[j]) {
count[i] = max(count[i], count[j] + 1);
}
}
length = max(count[i], length);
}
printf("%llu", length);
return 0;
}
|
C
|
/*
* Led.c
*
* Created on: Mar 7, 2021
* Author:
*/
#include "Led.h"
#include "derivative.h"
static void timerHandler();
void Led_init(){
SIM_SCGC5=SIM_SCGC5|((1<<10)+(1<<11)); //ͨ1ʹPORTCʱ
PORTB_PCR16=0x0100;
PORTB_PCR17=0x0100;
PORTB_PCR18=0x0100;
PORTB_PCR19=0x0100;
PORTC_PCR0=0x0100;
PORTC_PCR2=0x0100;//PTC0ΪGPIO
PORTC_PCR3=0x0100;
PORTC_PCR4=0x0100;
PORTC_PCR5=0x0100;//PTC4ΪGPIO
GPIOB_PDDR|=0x0f0000;
GPIOC_PDDR =0x003d;//PTC0PTC4Ϊ
}
void delay(){
unsigned int i,j;
for(i=0;i<5000;i++){
for(j=0;j<100;j++)
asm("nop");
}
}
void Led_play(){
unsigned int i;
for(i=0;i<3;++i)
{
GPIOB_PDOR=0x090000;
GPIOC_PDOR=0x0008; //PTC0PTC4Ϊ1СƵ
delay();
GPIOB_PDOR=0x020000;
GPIOC_PDOR=0x0011; //PTC0PTC4Ϊ1СƵ
delay();
GPIOB_PDOR=0x040000;
GPIOC_PDOR=0x0024; //PTC0PTC4Ϊ1СƵ
delay();
//GPIOC_PDOR = ~ GPIOC_PDOR;
//GPIOB_PDOR = ~ GPIOB_PDOR;
// ~ΪȡҲGPIOC_PTORĴת˿
}
Led_stop();
}
void Led_stop(){
GPIOC_PDOR &= ~ GPIOC_PDOR;
GPIOB_PDOR &= ~ GPIOB_PDOR;
OLED_Init();
OLEDFB_init();
}
|
C
|
/* Mandy La, mla1
* CS152, Spring 2019
* Project 1
*/
#include <stdlib.h>
#include <stdio.h>
#include "board.h"
board* board_new(unsigned int side, enum type type){
if (side==0 || (side%2 != 0)) {
fprintf(stderr, "error board_new: odd or 0 side length\n");
exit(1);
}
unsigned int n=0, m;
board* new;
if (type == BITS) {
new = (board*)malloc(sizeof(board));
if (side*side*2%32 == 0) {
m = side*side*2/32;
} else {
m = 1 + side*side*2/32;
}
unsigned int* res = (unsigned int*)
malloc(sizeof(unsigned int)*m);
while (n < m){
res[n] = 0;
n++;
}
new->u.bits = res;
} else {
new = (board*)malloc(sizeof(board));
square **res = (square**)malloc(sizeof(square*)*side);
for (m=0; m<side; m++) {
square *rows = (square*)malloc(sizeof(square)*side);
for (n=0; n < side; n++) {
rows[n] = EMPTY;
}
res[m] = rows;
}
new->u.cells = res;
}
new->side = side;
new->type = type;
return new;
}
void board_free(board *b){
unsigned int n = 0;
switch (b->type){
case BITS:
free(b->u.bits);
free(b);
break;
case CELLS:
while (n < b->side){
free((b->u.cells)[n]);
n++;
}
free(b->u.cells);
free(b);
break;
}
}
/* Helper function for board_show: prints one row */
void row_show(board* b, unsigned int r){
if (r <= 9) {
printf("%d ",r);
} else if ((9 < r) && (r < 36)) {
printf("%c ", 'A'+(r-10));
} else if ((35 < r) && (r < 62)) {
printf("%c ", 'a'+(r-36));
} else {
printf("? ");
}
unsigned int n=0;
for (n = 0; n < b->side; n++) {
if (n == (b->side)/2) {
printf(" ");
}
switch (board_get(b, make_pos(r,n))) {
case EMPTY:
printf(".");
break;
case BLACK:
printf("*");
break;
case WHITE:
printf("o");
break;
default:
fprintf(stderr, "row_show error: invalid square\n");
exit(1);
}
}
}
void board_show(board* b){
unsigned int n = 0;
printf(" ");
while (n < b->side) {
if (n == (b->side)/2) {
printf(" ");
}
if (n <= 9) {
printf("%d",n);
} else if ((9 < n)&&(n < 36)) {
printf("%c", 'A'+(n-10));
} else if ((35 < n)&&(n < 62)) {
printf("%c", 'a'+(n-36));
} else {
printf("?");
}
n++;
}
printf("\n");
printf("\n");
for(n=0; n < b->side; n++) {
if (n == (b->side)/2) {
printf("\n");
}
row_show(b, n);
printf("\n");
}
}
square bit_to_square(unsigned int n) {
switch (n) {
case 0:
return EMPTY;
break;
case 1:
return BLACK;
break;
case 2:
return WHITE;
break;
default:
fprintf(stderr, "row_show error: bit == 11");
exit(1);
}
}
square board_get(board* b, pos p) {
unsigned int n = (p.r*2*(b->side)+p.c*2);
unsigned int m = n%32;
switch (b->type){
case BITS:
return bit_to_square((b->u.bits)[n/32] >> m & 3);
break;
case CELLS:
return (b->u.cells)[(p.r)][(p.c)];
break;
default:
fprintf(stderr, "invalid type\n");
exit(1);
}
}
void board_set(board* b, pos p, square s) {
unsigned int n = (p.r*2*(b->side)+p.c*2);
unsigned int m = n%32;
unsigned int e = (b->u.bits)[n/32];
unsigned int x = ~(3 << m);
switch (b->type){
case BITS:
if (s == WHITE) {
e = (e & x) | (2 << m);
} else if (s == BLACK) {
e = (e & x) | (1 << m);
} else {
e = e & x;
}
(b->u.bits)[n/32] = e;
break;
case CELLS:
((b->u.cells)[(p.r)])[(p.c)] = s;
}
}
|
C
|
#include<stdio.h>
int main (void){
int n, a, b, c;
int i = 1;
scanf("%d", &n);
a = n / 100;
b = (n - 100 * a) / 10;
c = n % 10;
while(a > 0){
printf("B");
a--;
}
while(b > 0){
printf("S");
b--;
}
while(i <= c){
printf("%d", i);
i++;
}
return 0;
}
|
C
|
/* atexit( void (*)( void ) )
This file is part of the Public Domain C Library (PDCLib).
Permission is granted to use, modify, and / or redistribute at will.
*/
#include <stdlib.h>
#ifndef REGTEST
#include "_PDCLIB_io.h"
/* TODO: 32 is guaranteed. This should be dynamic but ATM gives problems
with my malloc XXX Check this!
*/
#define NUMBER_OF_SLOTS 40
struct atexit_func
{
enum at_type {
AF_STD,
AF_CXX,
AF_Ignore,
} at_type;
union {
void (*std_func)(void);
void (*cxx_func)(void*);
} at_func;
void* at_arg;
void* at_dso;
};
static struct atexit_func _PDCLIB_exitfunc[ NUMBER_OF_SLOTS ] = { { .at_type = AF_STD, .at_func.std_func = &_PDCLIB_closeall } };
static size_t _PDCLIB_exitptr = NUMBER_OF_SLOTS;
int atexit( void (*func)( void ) )
{
if ( _PDCLIB_exitptr == 0 )
return -1;
struct atexit_func* at = &_PDCLIB_exitfunc[ --_PDCLIB_exitptr ];
at->at_type = AF_STD;
at->at_func.std_func = func;
at->at_arg = NULL;
at->at_dso = NULL;
return 0;
}
int __cxa_atexit(void (*func)(void*), void* arg, void* dso)
{
if ( _PDCLIB_exitptr == 0 )
return -1;
struct atexit_func* at = &_PDCLIB_exitfunc[ --_PDCLIB_exitptr ];
at->at_type = AF_CXX;
at->at_func.cxx_func = func;
at->at_arg = arg;
at->at_dso = dso;
return 0;
}
void __cxa_finalize(void* dso)
{
for (int n = _PDCLIB_exitptr; n < NUMBER_OF_SLOTS; n++ )
{
struct atexit_func* at = &_PDCLIB_exitfunc[n];
if (dso != NULL && (at->at_type != AF_CXX || dso != at->at_dso))
continue;
switch(at->at_type)
{
case AF_STD:
at->at_func.std_func();
break;
case AF_CXX:
at->at_func.cxx_func(at->at_arg);
break;
default:
break;
}
at->at_type = AF_Ignore; /* do not call again */
}
}
#endif
#ifdef TEST
#include "_PDCLIB_test.h"
#include <assert.h>
static int flags[ 32 ];
static void counthandler( void )
{
static int count = 0;
flags[ count ] = count;
++count;
}
static void checkhandler( void )
{
for ( int i = 0; i < 31; ++i )
{
assert( flags[ i ] == i );
}
}
int main( void )
{
TESTCASE( atexit( &checkhandler ) == 0 );
for ( int i = 0; i < 31; ++i )
{
TESTCASE( atexit( &counthandler ) == 0 );
}
return TEST_RESULTS;
}
#endif
|
C
|
//
// Yating Zhou(aka syscl)'s lib
//
#ifndef __SYSCL_LIB_H__
#define __SYSCL_LIB_H__
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
//
// define kDEBUG, 1 = turn on
// , 0 = turn off(default) *
//
#define kDEBUG true
//
// common constant place here
//
#define kTRUE true
#define kFALSE false
#define kRETSUCCESS 0
#define kRETFAILURE 1
#if kDEBUG
#define DBG_PREFIX "Debug: "
#define DBG(args...) do { printf(DBG_PREFIX args); } while(kFALSE)
//
// getFunctionName: retrieve function's name
//
#define getFunctionName(args...) do { printf(DBG_PREFIX "%s()", __func__); } while(kFALSE)
//
// list init information for specific function
//
#define InitDBG(args...) do { printf(DBG_PREFIX "%s() ===>\n", __func__); } while(kFALSE)
//
// list return information for specific function
//
// usage: e.g. ReturnDBG("%s\n", string); ReturnDBG("%d\n", ret);
//
#define ReturnDBG(args...) do { printf(DBG_PREFIX "%s() <==", __func__); printf("=" args); } while(kFALSE)
#else
#define DBG(args...)
#define getFunctionName(args...)
#define InitDBG(args...)
#define ReturnDBG(args...)
#endif
#endif
|
C
|
#include "sim.h"
// C library headers
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
// Linux headers
#include <fcntl.h> // Contains file controls like O_RDWR
#include <errno.h> // Error integer and strerror() function
#include <termios.h> // Contains POSIX terminal control definitions
#include <unistd.h> // write(), read(), close()
static int serial_g = 0;
static bool Debug = true;
#ifdef GPIO_ENABLE
void sim_power_on()
{
if (Debug) printf("Power on starting...\n");
wiringPiSetup();
pinMode(POWER_PIN, OUTPUT);
digitalWrite(POWER_PIN, HIGH);
sleep(2);
digitalWrite(POWER_PIN, LOW);
sleep(20);
if (Debug) printf("Power on done...\n");
}
void sim_power_off()
{
if (Debug) printf("Power off starting...\n");
digitalWrite(POWER_PIN, HIGH);
sleep(3);
digitalWrite(POWER_PIN, LOW);
sleep(18);
if (Debug) printf("Power off done...\n");
}
#endif
bool at_init(char* port, bool enableDebug)
{
Debug = enableDebug;
serial_g = open(port, O_RDWR | O_NOCTTY | O_SYNC);
// Create new termios struc, we call it 'tty' for convention
struct termios tty;
// Read in existing settings, and handle any error
if(tcgetattr(serial_g, &tty) != 0) {
printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
return false;
}
tty.c_cflag &= ~PARENB; // Clear parity bit, disabling parity (most common)
tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication (most common)
tty.c_cflag &= ~CSIZE; // Clear all bits that set the data size
tty.c_cflag |= CS8; // 8 bits per byte (most common)
tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common)
tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1)
tty.c_lflag &= ~ICANON;
tty.c_lflag &= ~ECHO; // Disable echo
tty.c_lflag &= ~ECHOE; // Disable erasure
tty.c_lflag &= ~ECHONL; // Disable new-line echo
tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes
tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed
// tty.c_oflag &= ~OXTABS; // Prevent conversion of tabs to spaces (NOT PRESENT ON LINUX)
// tty.c_oflag &= ~ONOEOT; // Prevent removal of C-d chars (0x004) in output (NOT PRESENT ON LINUX)
tty.c_cc[VTIME] = 1; // Wait for up to 0.1s (10 deciseconds), returning as soon as any data is received.
tty.c_cc[VMIN] = 0;
// Set in/out baud rate to be baud
cfsetispeed(&tty, BAUD);
cfsetospeed(&tty, BAUD);
// Save tty settings, also checking for error
if (tcsetattr(serial_g, TCSANOW, &tty) != 0) {
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
return false;
}
if (Debug) printf("init AT success\n");
return true;
}
void at_close()
{
close(serial_g);
}
bool _at_send(const char* ATcommand, const char* expected_answer, char* response, unsigned int timeout, unsigned int step_check)
{
char _response[256];
char buff[256];
tcflush(serial_g,TCIOFLUSH);
memset(_response, '\0', 256); // Initialize the string
memset(buff, '\0', 256);
// Send AT command
if (ATcommand != NULL)
{
write(serial_g, ATcommand, strlen(ATcommand));
write(serial_g, "\r\n", strlen("\r\n"));
if (Debug) printf("%s\r\n", ATcommand);
}
// Read response
int num_bytes1, num_bytes2;
for (unsigned int i = 0; i < (timeout / step_check); i++)
{
// printf("sleep");
usleep(step_check*1000);
// printf("sleep done");
num_bytes1 = read(serial_g, buff, sizeof(buff));
if (num_bytes1 > 0)
{
if (num_bytes1 > 255 )
{
// byte 256 = '\0'
strncpy(_response, buff, 255);
break;
}
// else
strncpy(_response, buff, num_bytes1);
memset(buff, '\0', 256);
usleep(step_check*1000);
num_bytes2 = read(serial_g, buff, sizeof(buff));
if (num_bytes2 > 0)
{
// byte 256 = '\0'
strncpy(_response + num_bytes1, buff, 255 - num_bytes1);
}
break;
}
}
if (Debug) printf("%s", _response);
if (response != NULL)
{
strcpy(response, _response);
}
if (strstr(_response, expected_answer) != NULL)
{
return true;
}
return false;
}
bool sim_check_network()
{
// Check AT service
if (_at_send("AT", "OK", NULL, 1000, 10) != true) return false;
// SIM Card Status
if (_at_send("AT+CPIN?", "READY", NULL, 1000, 10) != true) return false;
// Check signal quality
if (_at_send("AT+CSQ", "OK", NULL, 1000, 10) != true) return false;
// GPRS network status
if (_at_send("AT+CREG?", "+CREG: 0,1", NULL, 1000, 10) != true) return false;
if (_at_send("AT+CGREG?", "+CGREG: 0,1", NULL, 1000, 10) != true) return false;
// end the previous http session if any
_at_send("AT+HTTPTERM", "OK", NULL, 120000, 10);
return true;
}
bool _http_config_param(const char* url, const char* contentType, const char* connTimeout, const char* recvTimeout)
{
char str[256];
// config param: url
sprintf(str, "AT+HTTPPARA=\"URL\",\"%s\"", url);
if (_at_send(str, "OK", NULL, 1000, 10) != true) return false;
// config param: content type
sprintf(str, "AT+HTTPPARA=\"CONTENT\",\"%s\"", contentType);
if (_at_send(str, "OK", NULL, 1000, 10) != true) return false;
// config param: connect timeout
sprintf(str, "AT+HTTPPARA=\"CONNECTTO\",%s", connTimeout);
if (_at_send(str, "OK", NULL, 1000, 10) != true) return false;
// config param: recive timeout
sprintf(str, "AT+HTTPPARA=\"RECVTO\",%s", connTimeout);
if (_at_send(str, "OK", NULL, 1000, 10) != true) return false;
return true;
}
bool sim_http_post(const char* url, const char* contentType, const char* data, \
const char* connTimeout, const char* recvTimeout)
{
bool ok = true;
char str[256];
// Start HTTP session
_at_send("AT+HTTPINIT", "OK", NULL, 120000, 10);
// Config HTTP session
if (_http_config_param(url, contentType, connTimeout, recvTimeout) != true)
{
// End HTTP session
_at_send("AT+HTTPTERM", "OK", NULL, 120000, 10);
return false;
}
// POST data
sprintf(str, "AT+HTTPDATA=%d,10000", strlen(data));
ok = _at_send(str, "DOWNLOAD", NULL ,1000, 10);
if (ok)
{
ok = _at_send(data, "OK", NULL, 1000, 10);
if (ok)
{
ok = _at_send("AT+HTTPACTION=1", "OK", NULL, 1000, 10);
if (ok)
{
// "1,200" <-> Action = 1 = POST; Status = 200 = success
ok = _at_send(NULL, "1,200", NULL, 120000, 10);
}
}
}
// End HTTP session
_at_send("AT+HTTPTERM", "OK", NULL, 120000, 10);
return ok;
}
void sim_gps_start()
{
_at_send("AT+CGPS=1", "OK", NULL, 1000, 10);
sleep(2);
}
bool sim_gps_get_position(char result[])
{
bool ok = true;
ok = _at_send("AT+CGPSINFO", "OK", result, 1000, 10);
if (ok != true) return false;
if (strstr(result, ",,,,") != NULL) return false;
return true;
}
void sim_gps_stop()
{
_at_send("AT+CGPS=0", "OK", NULL, 1000, 10);
// _at_send("", "+CGPS: 0", NULL, 5000, 10);
}
void sim_time(char result[])
{
_at_send("AT+CCLK?", "OK", result, 1000, 10);
}
|
C
|
/*********************************************************************************************************
*
* File : hexstring.c
* Version : V1.0
* By : alireza roozitalab
* email : alireza.roozitalab@gmail.com
* git user : ARoozitalab
*
* All Rights Reserved
*
*********************************************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include "hexString.h"
/*******************************************************************************
* Function Name : hexStringToBytes
* Description : convert string to value
* Input : inhex
* Output : None
* Return : value1
*******************************************************************************/
uint8_t hexStringToBytes(char *inhex)
{
uint8_t value1=0,value2=0;
value1=inhex[0]-48;
if (value1>10)
value1=value1-7;
value2=inhex[1]-48;
if (value2>10)
value2=value2-7;
value1=(value1<<4)|value2;
return value1;
}
/*******************************************************************************
* Function Name : bytesToHexString
* Description : convert value to string
* Input : hex,bytesin
* Output : None
* Return : None
*******************************************************************************/
void bytesToHexString(char *bytesin,uint8_t hex)
{
uint8_t value1=0,value2=0;
value1=hex>>4;
value2=hex&0x0f;
if(value1<10)
bytesin[0]=value1+48;
else
bytesin[0]=value1+55;
if(value2<10)
bytesin[1]=value2+48;
else
bytesin[1]=value2+55;
bytesin[2]=0x20;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include "common.h"
char *add_user(json_value *param, int *success) {
char *username = NULL;
if (param->type != json_object)
return "Invalid parameters";
if (!strcmp(param->u.object.values[0].name, "user")) {
printf("Creating new user %s\n", param->u.object.values[0].value->u.string.ptr);
username = param->u.object.values[0].value->u.string.ptr;
}
if (!username) {
return "Not all parameters are given";
}
if (getpwnam(username)) {
return "User already exists";
}
int rtn = 0;
rtn += invoke_exec("useradd -s /bin/bash %s ", username);
rtn += invoke_exec("mkdir -p /home/%s/bin", username);
rtn += invoke_exec("mkdir -p /home/%s/etc", username);
rtn += invoke_exec("mkdir -p /home/%s/www", username);
rtn += invoke_exec("mkdir -p /home/%s/logs", username);
rtn += invoke_exec("chown -R %s:%s /home/%s/*", username, username, username);
rtn += invoke_exec("chmod +x /home/%s/", username);
if (rtn > 0) {
return "User setup failed";
}
*success = 1;
return "User setup";
}
char *delete_user(json_value *param, int *success) {
char *username = NULL;
if (param->type != json_object)
return "Invalid parameters";
if (!strcmp(param->u.object.values[0].name, "user")) {
printf("Deleting user %s\n", param->u.object.values[0].value->u.string.ptr);
username = param->u.object.values[0].value->u.string.ptr;
}
if (!username) {
return "Not all parameters are given";
}
if (!getpwnam(username)) {
return "User does not exist";
}
int rtn = 0;
rtn += invoke_exec("userdel -r %s ", username);
if (rtn > 0) {
return "User deletion failed";
}
*success = 1;
return "User deleted";
}
|
C
|
#include <GL/glut.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include "messages.h"
// populates image packet
ImagePacket* set_image_packet(PacketHeader header, int id, Image* image) {
ImagePacket* new_packet = (ImagePacket*) malloc(sizeof(ImagePacket));
new_packet->header = header;
new_packet->id = id;
new_packet->image = image;
return new_packet;
}
// inizializza id packet
IdPacket* id_packet_init(Type header_type, int id){
PacketHeader id_header;
id_header.type = header_type;
IdPacket* id_packet = (IdPacket*)malloc(sizeof(IdPacket));
id_packet->header = id_header;
id_packet->id = id;
return id_packet;
}
/*-------------------------- funzioni create per inviare pacchetti da SERVER a CLIENT --------------------------------------------*/
// pacchetto usato per assegnare surface texture
ImagePacket* CreateSurfaceTexturePacket(Image* selected_image) {
PacketHeader packet_header;
packet_header.type = PostTexture;
ImagePacket* new_packet = set_image_packet(packet_header, 0, selected_image);
return new_packet;
}
// pacchetto usato per assegnare surface elevation
ImagePacket* CreateElevationMapPacket(Image* selected_image) {
PacketHeader packet_header;
packet_header.type = PostElevation;
ImagePacket* new_packet = set_image_packet(packet_header, 0, selected_image);
return new_packet;
}
// pacchetto usato per assegnare vehicle texture
ImagePacket* CreateVehicleTexturePacket(Image* selected_image, int client_id) {
PacketHeader packet_header;
packet_header.type = PostTexture;
ImagePacket* new_packet = set_image_packet(packet_header, client_id, selected_image);
return new_packet;
}
// pacchetto usato per assegnare vehicle texture nel caso in cui il client non scelga la texture e quindi venga assegnata dal server (default)
ImagePacket* CreateDefaultTexturePacket(int client_id) {
PacketHeader packet_header;
packet_header.type = PostTexture;
ImagePacket* new_packet = set_image_packet(packet_header, client_id, NULL);
return new_packet;
}
/*-------------------------- funzioni create per inviare pacchetti da CLIENT a SERVER --------------------------------------------*/
// pacchetto usato per richiedere surface texture
ImagePacket* CreateSurfaceTextureRequestPacket(void) {
PacketHeader packet_header;
packet_header.type = GetTexture;
ImagePacket* new_packet = set_image_packet(packet_header, 0, NULL);
return new_packet;
}
// pacchetto usato per richiedere surface elevation
ImagePacket* CreateElevationMapRequestPacket(void) {
PacketHeader packet_header;
packet_header.type = GetElevation;
ImagePacket* new_packet = set_image_packet(packet_header, 0, NULL);
return new_packet;
}
// pacchetto usato per richiedere vehicle texture
ImagePacket* CreateVehicleTextureRequestPacket(int client_id) {
PacketHeader packet_header;
packet_header.type = GetTexture;
ImagePacket* new_packet = set_image_packet(packet_header, client_id, NULL);
return new_packet;
}
|
C
|
/*Q8. Passing 1D, 2D arrays to a function
– sum, min, max of array elements
– Matrix operations
*/
#include<stdio.h>
#define r 2
#define c 3
void sum(int (*)[r][c]);
void min(int (*)[r][c]);
void max(int (*)[r][c]);
int main(){
int arr[r][c]={{8,7,6},{5,4,1}};
sum(&arr);
min(&arr);
max(&arr);
}
void sum(int (*p)[r][c]){
int sum=0;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
// printf("\n===%d",((*p)[i])[j]);// *(*((*p)+i)+J);
// printf("\t%d", *(*((*p)+i)+j));
sum=sum+ *(*((*p)+i)+j);
}
}
printf("\nsum=%d",sum);
}
void min(int (*p)[r][c]){
int min= *(*((*p)+0)+0);
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if (*(*((*p)+i)+j)<min){
min= *(*((*p)+i)+j);
}
}
}
printf("\nmin=%d",min);
}
void max(int (*p)[r][c]){
int max= *(*((*p)+0)+0);
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if (*(*((*p)+i)+j)>max){
max= *(*((*p)+i)+j);
}
}
}
printf("\nmax=%d",max);
}
|
C
|
#include <stdio.h>
#include "Stack.h"
status createStack(stack_t ** stack , stackSize_t size){
status currentStatus = E_OK;
if(stack==NULL){
currentStatus = E_NOT_OK;
}else{
/*create stack from the type stack_t to carry the pointers of the stack*/
stack_t* newStack = (stack_t*)malloc(sizeof(stack_t));
if(newStack==NULL){
currentStatus = E_NOT_OK;
}else{
/*create stack with size given as parameter*/
newStack -> bottom = (StackDataType_t*)malloc(sizeof(StackDataType_t)*size);
newStack -> stackPointer = NULL;
newStack -> top = newStack->bottom + (size-1);
*stack = newStack;
}
}
return currentStatus;
}
status pushToStack(stack_t * stack , StackDataType_t data){
status currentStatus = E_OK;
if(stack==NULL){
currentStatus = E_NOT_OK;
}else{
/*check for the overflow*/
if(stack ->stackPointer == stack ->top){
currentStatus = STACK_OVERFLOW;
}else{
/*check if the stack is empty*/
if(stack->stackPointer==NULL){
stack->stackPointer=stack->bottom;
/*if stack was not empty the inceament the stack pointer and add the element*/
}else{
(stack->stackPointer)++;
}
*(stack->stackPointer)=data;
}
}
return currentStatus;
}
status popFromStack(stack_t * stack , StackDataType_t *data){
status currentStatus = E_OK;
if(stack==NULL){
currentStatus = E_NOT_OK;
}else{
/*stack is empty*/
if(stack -> stackPointer == NULL){
currentStatus=STACK_UNDERFLOW;
}else{
*data=*(stack->stackPointer);
if(stack->stackPointer==stack->bottom){
stack->stackPointer=NULL;
}
else{
stack->stackPointer--;
}
}
}
return currentStatus;
}
|
C
|
#include "open.h"
#include "scan.h"
int main(int argc, char* argv[])
{
char * openData = argv[1];
char * openTemplate = argv[2];
char * outputFile = argv[3];
// FILE * openData;
// FILE * openTemplate;
// FILE * outputFile;
// char line[255];
char value[255];
char key[255];
// char word[25];
// int wordLength = 0;
// int length = 0;
// int argNum = 0;
// int argLength = 0;
// int sucNum = 0;
// int updateCounter = 0;
//makes sure 4 arguements are included, opens all the necessary files based on what the user enters
if (argc != 4)
{
printf(" incorrect number of arguments given\n");
return 1;
}
dataOpen(openData, key, value);
templateOpen(openTemplate, outputFile, key, value);
// // prints out stats about program execution, and closes all files to prevent memory leaks
// printf("%d Variables Successfully Replaced\nProcess Executed Successfully\n", updateCounter);
// closeFiles(openTemplate, openData, outputFile);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* string.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rmalkevy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/17 17:45:46 by rmalkevy #+# #+# */
/* Updated: 2017/02/03 16:04:59 by rmalkevy ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
char *ft_precision_string(char *format, char *string)
{
int end;
int precision;
end = (int)ft_strlen(format);
while (end > -1)
{
if (format[end] == '.')
{
precision = ft_atoi(format + end + 1);
return (ft_strsub(string, 0, (size_t)precision));
}
end--;
}
return (string);
}
int ft_zero_string(char *format)
{
int i;
int zero;
i = 0;
zero = 0;
while (format[i])
{
if (format[i] == '0' && !(format[i - 1] >= '1' && format[i - 1] <= '9'))
zero = 1;
i++;
}
return (zero);
}
void ft_print_string(char *format, char *string)
{
int width;
width = 0;
string = ft_precision_string(format, string);
if (ft_width(format) > (int)ft_strlen(string))
width = ft_width(format) - (int)ft_strlen(string);
if (ft_minus(format))
ft_putstr(string);
if (width > 0)
while (width)
{
if (ft_zero_string(format) && !ft_minus(format))
ft_putchar('0');
else
ft_putchar(' ');
width--;
}
if (!ft_minus(format))
ft_putstr(string);
}
void ft_string(char *format, va_list ap)
{
char *string;
string = va_arg(ap, char*);
if (!string)
string = "(null)";
ft_print_string(format, string);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
float sqrt_min(float x) {
// Approximate the square root of x
float guess = 1.0;
int iter = 10;
while (iter) {
float quot = x / guess;
guess = 0.5 * (guess + quot);
iter = iter - 1;
}
printf("%f\n", guess);
printf("%f\n", guess * guess);
return guess;
}
int gcd(int m, int n) {
if (m == 0 && n == 0) return 0;
else {
if (m == 0) return n;
else {
if (m < 0) m = -m;
if (n < 0) n = -n;
int divisor = 1;
int a = 1;
while (a <= m) {
int m_mod_a_rem = m;
int n_mod_a_rem = n;
while (m_mod_a_rem >= a) m_mod_a_rem = m_mod_a_rem - a;
while (n_mod_a_rem >= a) n_mod_a_rem = n_mod_a_rem - a;
if (m_mod_a_rem == 0 && n_mod_a_rem == 0) divisor = a;
a = a + 1;
}
return divisor;
}
}
}
int main() {
sqrt_min(2500);
printf("%d\n", gcd(100, 170));
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
int main()
{
int a=15,b=37;
printf("%dȥ%dĽ%d\n",a,b,a-b);
return 0;
}
|
C
|
#include "logger.h"
#include <SDL_plus.h>
#include <stdarg.h>
void LogVerbosely(void) {
SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE);
}
static void logv(SDL_LogPriority priority, const char * fmt, va_list ap) {
SDL_LogMessageV(SDL_LOG_CATEGORY_CUSTOM, priority, fmt, ap);
}
void Log(const char * fmt, ...) {
va_list ap;
va_start(ap, fmt);
logv(SDL_LOG_PRIORITY_INFO, fmt, ap);
va_end(ap);
}
void Warn(const char * fmt, ...) {
va_list ap;
va_start(ap, fmt);
logv(SDL_LOG_PRIORITY_WARN, fmt, ap);
va_end(ap);
}
static int error_count = 0;
void Err(const char * fmt, ...) {
error_count += 1;
va_list ap;
va_start(ap, fmt);
logv(SDL_LOG_PRIORITY_CRITICAL, fmt, ap);
va_end(ap);
}
int ErrorCount(void) {
return error_count;
}
|
C
|
#include<stdio.h>
int main()
{
int n,i;
printf("How many todos would you like to add?\n");
scanf("%d", &n);
char todo[n][20];
for(i = 1; i<=n; i++)
{
printf("Enter a todo: ");
scanf("%s",&todo[i]);
}
for ( i = 1; i <=n; i++)
{
printf("%s\n", todo[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "opcode.h"
struct opcode_desc *lookup_1byte_opcode_map(uint8_t index)
{
return &one_byte_opcode_map[index];
}
struct opcode_desc *lookup_2byte_opcode_map1(uint8_t index)
{
}
struct opcode_desc *lookup_2byte_opcode_map2(uint8_t index)
{
}
struct opcode_desc *lookup_3byte_opcode_map1(uint8_t index)
{
}
struct opcode_desc *lookup_3byte_opcode_map2(uint8_t index)
{
}
int select_operand_size(int op_flag, struct rex_prefix *rex)
{
int op_size = -1;
/* 64bit size. */
if (rex->w == 1) {
op_size = 8;
}
else {
/* 16bit size. */
if (op_flag == 1) {
op_size = 2;
}
/* 32bit size. */
else {
op_size = 4;
}
}
return op_size;
}
int select_operand_type(int op_size, char *op_desc)
{
int n = op_size;
if (!op_desc)
return n;
switch (op_desc[1]) {
case 'b':
/* force 1 byte. */
n = 1;
break;
case 'w':
/* force 2 byte. */
n = 2;
break;
case 'd':
/* force 4 byte. */
n = 4;
break;
case 'q':
/* force 8 byte. */
n = 8;
break;
case 'v':
/*
if (op_desc[0] == 'I')
n = 4;
else
*/
n = op_size;
break;
case 'a':
break;
case 'c':
break;
}
return n;
}
int convert_size(int size)
{
int n = size;
if (size == 8)
n = 4;
if (size == 4)
n = 3;
return n;
}
char mnemonic_size[5] = {'b', 'w', 'l', 'q'};
int select_mnemonic_size(int op_flag, struct rex_prefix *rex)
{
int n;
n = select_operand_size(op_flag, rex);
switch (n) {
case 1:
return mnemonic_size[0];
case 2:
return mnemonic_size[1];
case 4:
return mnemonic_size[2];
case 8:
return mnemonic_size[3];
default:
return -1;
}
}
int get_operand_size(int op_flag, char *op_desc, struct rex_prefix *rex)
{
int op_size, n;
op_size = select_operand_size(op_flag, rex);
if (op_size == -1)
return -1;
n = select_operand_type(op_size, op_desc);
if (n == -1)
return -1;
return convert_size(n);
}
char *__select_effective_reg(int index, char op_flag,
char *op_desc,
struct rex_prefix *rex,
int rex_flag)
{
char *reg;
int n;
n = get_operand_size(op_flag, op_desc, rex);
if (n == -1)
return NULL;
if (rex_flag == 1) {
reg = mod_reg_ex[(n - 1) * 8 + index];
}
else {
reg = mod_reg_general[n * 8 + index];
}
return reg;
}
char *select_effective_reg(int index, char op_flag,
char *op_desc, struct rex_prefix *rex)
{
return __select_effective_reg(index, op_flag, op_desc, rex, rex->b);
}
char *select_general_reg(int index, char op_flag,
char *op_desc, struct rex_prefix *rex)
{
return __select_effective_reg(index, op_flag, op_desc, rex, rex->r);
}
void parse_sib(uint8_t value, struct sib *sib)
{
sib->scale = value >> 6;
sib->index = (value >> 3) & 0x7;
sib->base = value & 0x7;
}
void parse_mod_reg(uint8_t value, struct mod_reg *reg)
{
reg->mod = value >> 6;
reg->reg = (value >> 3) & 0x7;
reg->rm = value & 0x7;
}
void decode_rex(uint8_t value, struct rex_prefix *rex)
{
rex->w = (value & 0x8) >> 3;
rex->r = (value & 0x4) >> 2;
rex->x = (value & 0x2) >> 1;
rex->b = value & 0x1;
}
void print_rex(struct rex_prefix *rex)
{
printf("decode: rex.w=%d rex.r=%d rex.x=%d rex.b=%d\n",
rex->w, rex->r, rex->x, rex->b);
}
void print_mod_reg(struct mod_reg *reg)
{
printf("modr/m: mod=%d reg=%d rm=%d\n",
reg->mod, reg->reg, reg->rm);
}
void print_sib(struct sib *sib)
{
printf("sib: scale=%d, index=%d, base=%d\n",
sib->scale, sib->index, sib->base);
}
int is_rex_enable(struct rex_prefix *rex)
{
if (rex->w == 1 || rex->r == 1 || rex->x == 1 || rex->b == 1)
return 1;
return 0;
}
int is_regex_enable(struct rex_prefix *rex)
{
if (rex->r == 1 || rex->x == 1 || rex->b == 1)
return 1;
return 0;
}
int select_reg_index(char *reg, struct rex_prefix *rex)
{
int i = 0;
if (is_regex_enable(rex)) {
for (i = 0; i < 8; i++) {
if (!strcmp(mod_reg_ex[24 + i], reg))
return i % 8;
}
return -1;
}
for (i = 0; i < 8; i++) {
if (!strcmp(mod_reg_general[16 + i], reg))
return i % 8;
}
return -1;
}
int get_effective_reg(char *op_desc, char *reg_buf,
struct x86_opcode *op_code)
{
struct rex_prefix *rex = &op_code->op_rex;
char arg0[16], arg1[16];
char *reg, *p;
int op_size, index = -1;
strcpy(arg0, op_desc);
p = strchr(arg0, '/');
if (p) {
strcpy(arg1, p + 1);
*p = 0;
}
if (op_desc[0] != 'r' && op_desc[0] != 'e') {
if (is_regex_enable(rex))
strcpy(reg_buf, arg1);
else
strcpy(reg_buf, arg0);
return 0;
}
if (op_desc[0] == 'e' && op_desc[1] == 's') {
strcpy(reg_buf, arg0);
return 0;
}
if (is_regex_enable(rex) && arg1[0] != '\0')
p = arg1;
else
/* escape the 'r' or 'e' prefix. */
p = arg0 + 1;
index = select_reg_index(p, rex);
if (index == -1)
return -1;
reg = select_effective_reg(index,
op_code->op_size, NULL, rex);
if (!reg)
return -1;
strcpy(reg_buf, reg);
return 0;
}
char *select_sib_reg(int index, char op_flag,
struct rex_prefix *rex, int rex_flag)
{
char *reg;
int op_size, n;
op_size = select_operand_size(op_flag, rex);
if (op_size == -1)
return NULL;
n = convert_size(op_size);
if (rex_flag == 1) {
reg = mod_reg_ex[(n - 1) * 8 + index];
}
else {
reg = mod_reg_general[n * 8 + index];
}
return reg;
}
int select_sib_ss_index(char *op_buf, int op_buf_size,
struct x86_opcode *op_code)
{
struct rex_prefix *rex = &op_code->op_rex;
struct sib *sib = &op_code->op_sib;
char *reg;
if (sib->index == 0x4 && rex->x == 0)
return 0;
reg = select_sib_reg(sib->index, op_code->op_size, rex, rex->x);
if (!reg)
return -1;
switch (sib->scale) {
case 0x0:
snprintf(op_buf, op_buf_size - 1, "%s", reg);
break;
case 0x1:
snprintf(op_buf, op_buf_size - 1, "%s*2", reg);
break;
case 0x2:
snprintf(op_buf, op_buf_size - 1, "%s*4", reg);
break;
case 0x3:
snprintf(op_buf, op_buf_size - 1, "%s*8", reg);
break;
default:
return -1;
}
printf("si: %s\n", op_buf);
return 0;
}
int select_sib_base(char *op_string, char *op_buf,
int op_buf_size, struct x86_opcode *op_code)
{
struct rex_prefix *rex = &op_code->op_rex;
struct mod_reg *reg = &op_code->op_reg;
struct sib *sib = &op_code->op_sib;
char *reg_name, *s = op_string;
int n = 0, disp;
reg_name = select_sib_reg(sib->base,
op_code->op_size, rex, rex->b);
if (!reg_name)
return -1;
if (sib->base != 0x5) {
snprintf(op_buf, op_buf_size, "%s", reg_name);
printf("b: %s\n", op_buf);
return 0;
}
switch (reg->mod) {
case 0x0:
disp = *(uint32_t *)s;
n = 4;
snprintf(op_buf, op_buf_size, "0x%x", disp);
break;
case 0x1:
disp = *(uint8_t *)s;
n = 1;
snprintf(op_buf, op_buf_size, "%s+0x%x", reg_name, disp);
break;
case 0x2:
disp = *(uint32_t *)s;
n = 4;
snprintf(op_buf, op_buf_size, "%s+0x%x", reg_name, disp);
break;
default:
return -1;
}
printf("b: %s\n", op_buf);
return n;
}
int decode_sib(char *op_string, char *op_buf,
int op_buf_size, struct x86_opcode *op_code)
{
char ss_index[16] = {0}, base[16] = {0};
int n = 0;
if (select_sib_ss_index(ss_index, 16, op_code) == -1)
return -1;
n = select_sib_base(op_string, base, 16, op_code);
if (n == -1)
return -1;
if (ss_index[0] != '\0')
snprintf(op_buf, op_buf_size, "%s+%s", base, ss_index);
else
snprintf(op_buf, op_buf_size, "%s", base);
printf("sib: %s\n", op_buf);
return n;
}
int decode_effective_sib(uint8_t *op_string, char *op_buf,
int op_buf_size, struct x86_opcode *op_code)
{
struct ins_prefix *ins = &op_code->op_ins;
struct rex_prefix *rex = &op_code->op_rex;
struct mod_reg *reg = &op_code->op_reg;
struct sib *sib = &op_code->op_sib;
uint8_t *s = op_string;
char sib_buf[32];
int m = 0, i = 0;
parse_sib(*s, sib);
print_sib(sib);
m = decode_sib(s + 1, sib_buf, sizeof(sib_buf) - 1, op_code);
if (m == -1)
return -1;
if (ins->op_seg_buf[0] != '\0')
i = snprintf(op_buf, op_buf_size - 1, "%s", ins->op_seg_buf);
if (m == 0) {
switch (reg->mod) {
case 0x1:
op_code->disp_value = *(uint8_t *)(s + 1);
m += 1;
break;
case 0x2:
op_code->disp_value = *(uint32_t *)(s + 1);
m += 4;
break;
}
printf("sib disp: 0x%x\n", op_code->disp_value);
snprintf(op_buf + i, op_buf_size - i - 1,
"[%s+0x%x]", sib_buf, op_code->disp_value);
}
else {
snprintf(op_buf + i, op_buf_size - i - 1, "[%s]", sib_buf);
}
printf("%s\n", op_buf);
return m + 1;
}
int decode_effective_rip(char *op_buf, int op_buf_size,
struct x86_opcode *op_code, int value)
{
struct ins_prefix *ins = &op_code->op_ins;
struct rex_prefix *rex = &op_code->op_rex;
int i = 0;
if (ins->op_seg_buf[0] != '\0')
i = snprintf(op_buf, op_buf_size - 1, "%s", ins->op_seg_buf);
if (rex->w == 1)
snprintf(op_buf + i, op_buf_size - i - 1, "[rip+0x%x]", value);
else
snprintf(op_buf + i, op_buf_size - i - 1, "[eip+0x%x]", value);
return 0;
}
int decode_effective_reg(uint8_t *op_string, char *op_buf,
int op_buf_size, char *op_desc,
int flag, struct x86_opcode *op_code)
{
struct ins_prefix *ins = &op_code->op_ins;
struct rex_prefix *rex = &op_code->op_rex;
struct mod_reg *reg = &op_code->op_reg;
uint8_t *s = op_string;
char *tmp;
int i = 0, n = 0;
tmp = select_effective_reg(reg->rm, op_code->op_size, op_desc, rex);
if (!tmp)
return -1;
if (ins->op_seg_buf[0] != '\0')
i = snprintf(op_buf, op_buf_size - 1, "%s", ins->op_seg_buf);
switch (reg->mod) {
case 0x0:
snprintf(op_buf + i, op_buf_size - i - 1, "[%s]", tmp);
break;
case 0x1:
if (flag == 1)
op_code->disp_value = *(uint8_t *)(s + 1);
else
op_code->disp_value = *(uint8_t *)s;
snprintf(op_buf + i, op_buf_size - i - 1, "[%s+0x%x]",
tmp, op_code->disp_value);
n += 1;
break;
case 0x2:
if (flag == 1)
op_code->disp_value = *(uint32_t *)(s + 1);
else
op_code->disp_value = *(uint32_t *)s;
snprintf(op_buf + i, op_buf_size - i - 1, "[%s+0x%x]",
tmp, op_code->disp_value);
n += 4;
break;
case 0x3:
snprintf(op_buf + i, op_buf_size - i - 1, "%s", tmp);
break;
}
printf("%s\n", op_buf);
return n;
}
int decode_effective_imm(uint8_t *op_string, char *op_buf,
int op_buf_size, char *op_desc,
struct x86_opcode *op_code)
{
struct rex_prefix *rex = &op_code->op_rex;
unsigned int size;
int n = 0;
size = get_operand_size(op_code->op_size, op_desc, rex);
if (size <= 0)
return -1;
switch (size) {
case 1:
op_code->imm_value = *(uint8_t *)op_string;
n += 1;
break;
case 2:
op_code->imm_value = *(uint16_t *)op_string;
n += 2;
break;
case 3:
case 4:
/* in 64bit mode, must immediate data is 4byte. */
op_code->imm_value = *(uint32_t *)op_string;
n += 4;
break;
default:
return -1;
}
snprintf(op_buf, op_buf_size - 1, "0x%x", op_code->imm_value);
return n;
}
int decode_operand(uint8_t *op_string, char *op_buf, int buf_size,
char *op_desc, struct x86_opcode *op_code)
{
struct ins_prefix *ins = &op_code->op_ins;
struct rex_prefix *rex = &op_code->op_rex;
struct mod_reg *reg = &op_code->op_reg;
uint8_t *s = op_string;
char *tmp;
int m = 0, n = 0, i = 0;
if (op_desc[0] >= 'a' && op_desc[0] <= 'z') {
if (get_effective_reg(op_desc, op_buf, op_code) == -1)
return -1;
printf("%s\n", op_buf);
}
/* decode effective address. */
if (op_desc[0] == 'E') {
/* the modreg r/m failed has not been decoded. */
if (reg->mod == -1) {
n += 1;
parse_mod_reg(*s, reg);
}
print_mod_reg(reg);
/* sib mode. */
if (reg->mod != 0x3 && reg->rm == 0x4) {
m = decode_effective_sib(s + n, op_buf, buf_size, op_code);
if (m == -1)
return -1;
n += m;
return n;
}
/* 64bit rip reltaive mode. */
if (reg->mod == 0x0 && reg->rm == 0x5) {
if (n == 1)
op_code->disp_value = *(int *)(s + 1);
else
op_code->disp_value = *(int *)s;
n += 4;
decode_effective_rip(op_buf, buf_size, op_code, op_code->disp_value);
return n;
}
/* decode effective general register. */
m = decode_effective_reg(s, op_buf, buf_size, op_desc, n, op_code);
if (m == -1)
return -1;
printf("%s\n", op_buf);
return n + m;
}
/* modrm refer to general register. */
if (op_desc[0] == 'G') {
if (reg->mod == -1) {
n += 1;
parse_mod_reg(*s, reg);
}
print_mod_reg(reg);
tmp = select_general_reg(reg->reg, op_code->op_size, op_desc, rex);
if (!tmp)
return -1;
snprintf(op_buf, buf_size, "%s", tmp);
printf("%s\n", op_buf);
return n;
}
/* modrm only refer to memory. */
if (op_desc[0] == 'M') {
/* sib mode. */
if (reg->mod != 0x3 && reg->rm == 0x4) {
m = decode_effective_sib(s + n, op_buf, buf_size, op_code);
if (m == -1)
return -1;
n += m;
return n;
}
/* 64bit rip reltaive mode. */
if (reg->mod == 0x0 && reg->rm == 0x5) {
op_code->imm_value = *(int *)s;
decode_effective_rip(op_buf, buf_size,
op_code, op_code->imm_value);
n += 4;
return n;
}
/* decode effective general register. */
m = decode_effective_reg(s, op_buf, buf_size, op_desc, n, op_code);
if (m == -1)
return -1;
printf("%s\n", op_buf);
return n + m;
}
/* handle immediate data. */
if (op_desc[0] == 'I') {
m = decode_effective_imm(s, op_buf, buf_size, op_desc, op_code);
if (m == -1)
return -1;
printf("%s\n", op_buf);
n += m;
}
if (op_desc[0] == 'Y') {
snprintf(op_buf, buf_size, "%s", "es:%rdi");
}
if (op_desc[0] == 'X') {
snprintf(op_buf, buf_size, "%s", "ds:%rsi");
}
return n;
}
int select_reg_by_arg(struct x86_opcode *op_code,
struct opcode_desc *op_desc)
{
struct rex_prefix *rex = &op_code->op_rex;
char arg[8] = {0}, arg1[8] = {0};
char tmp[32], op_buf[32];
char *s;
int op_size, r_flag = 0;
if (!op_desc->arg) {
printf("#%s\n", op_desc->mnemonic);
return 0;
}
if (op_desc->arg[0] != 'r' && op_desc->arg[0] != 'e') {
printf("#%s %s\n", op_desc->mnemonic, op_desc->arg);
return 0;
}
if (op_desc->arg[0] == 'e' && op_desc->arg[1] == 's') {
printf("#%s %s\n", op_desc->mnemonic, op_desc->arg);
return 0;
}
strcpy(tmp, op_desc->arg);
s = strchr(tmp, '/');
if (s) {
strcpy(arg1, s + 1);
*s = 0;
if (rex->b == 1 || rex->r == 1)
r_flag = 1;
}
op_size = select_operand_size(op_code->op_size, rex);
if (op_size == -1)
return -1;
if (op_desc->opcode >= 0x50 &&
op_desc->opcode <= 0x5f &&
op_code->op_size == 0)
op_size = 8;
switch (op_size) {
case 1:
/* 64bit mode does not support 8bit operand size. */
break;
case 2:
if (r_flag == 1) {
snprintf(op_buf, sizeof(op_buf) - 1,
"%s %%%sw", op_desc->mnemonic, arg1);
}
else {
snprintf(op_buf, sizeof(op_buf) - 1,
"%s %%%s", op_desc->mnemonic, &tmp[1]);
}
break;
case 4:
if (r_flag == 1) {
snprintf(op_buf, sizeof(op_buf) - 1,
"%s %%%sd", op_desc->mnemonic, arg1);
}
else {
snprintf(op_buf, sizeof(op_buf) - 1,
"%s %%e%s", op_desc->mnemonic, &tmp[1]);
}
break;
case 8:
if (r_flag == 1) {
snprintf(op_buf, sizeof(op_buf) - 1,
"%s %%%s", op_desc->mnemonic, arg1);
}
else {
snprintf(op_buf, sizeof(op_buf) - 1,
"%s %%r%s", op_desc->mnemonic, &tmp[1]);
}
break;
}
printf("#%s\n", op_buf);
return 0;
}
int is_rex_encode(uint8_t **op_buf, struct rex_prefix *rex)
{
uint8_t *s = *op_buf;
if (*s >= 0x40 && *s <= 0x4f) {
decode_rex(*s, rex);
print_rex(rex);
*op_buf++;
return 0;
}
return -1;
}
struct opcode_desc *lookup_code_map(uint8_t index,
struct x86_opcode *op_code)
{
struct opcode_desc *op_desc;
struct ins_prefix *ins = &op_code->op_ins;
if (ins->op_0x66 || ins->op_rep1 || ins->op_rep2) {
if (!ins->op_0x0f) {
/* 0x66 is operand size prefix. */
if (ins->op_0x66)
op_code->op_size = 1;
/* 0xf2 is repeat prefix. */
if (ins->op_rep1)
strcpy(ins->op_rep_buf, "repne");
/* 0xf3 is repeat prefix. */
if (ins->op_rep2)
strcpy(ins->op_rep_buf, "repe");
return lookup_1byte_opcode_map(index);
}
/* lookup three byte code map1. */
if (ins->op_0x38)
op_desc = lookup_3byte_opcode_map1(index);
/* lookup three byte code map2. */
else if (ins->op_0x3a)
op_desc = lookup_3byte_opcode_map2(index);
/* lookup two byte code map2. */
else
op_desc = lookup_2byte_opcode_map2(index);
}
else if (ins->op_0x0f) {
/* lookup three byte code map1. */
if (ins->op_0x38)
op_desc = lookup_3byte_opcode_map1(index);
/* lookup three byte code map2. */
else if (ins->op_0x3a)
op_desc = lookup_3byte_opcode_map2(index);
/* lookup two byte code map1. */
else
op_desc = lookup_2byte_opcode_map1(index);
}
else {
/* lookup one byte code map. */
op_desc = lookup_1byte_opcode_map(index);
}
return op_desc;
}
void print_opcode(struct opcode_desc *op_desc)
{
printf("opcode: 0x%02x name: %s arg: %s op1: %s op2: %s op3: %s\n",
op_desc->opcode, op_desc->mnemonic, op_desc->arg,
op_desc->op1, op_desc->op2, op_desc->op3);
}
void print_ins(struct x86_opcode *op_code, struct opcode_desc *op_desc,
char *op1_buf, char *op2_buf, char *op3_buf)
{
struct ins_prefix *ins = &op_code->op_ins;
char op_desc_buf[64];
char mnemonic[16], s, *p;
int n = 0;
strcpy(mnemonic, op_desc->mnemonic);
p = strchr(mnemonic, '*');
if (p) {
s = select_mnemonic_size(op_code->op_size, &op_code->op_rex);
if (s == -1)
return ;
*p = s;
}
if (ins->op_lock_buf[0] != '\0')
n = snprintf(op_desc_buf, sizeof(op_desc_buf) - 1,
"%s ", ins->op_lock_buf);
if (ins->op_rep_buf[0] != '\0')
n += snprintf(op_desc_buf + n, sizeof(op_desc_buf) - n - 1,
"%s ", ins->op_rep_buf);
n += snprintf(op_desc_buf + n, sizeof(op_desc_buf) - n - 1,
"%s ", mnemonic);
if (op1_buf[0] != '\0')
n += snprintf(op_desc_buf + n, sizeof(op_desc_buf) - n - 1,
"%s", op1_buf);
if (op2_buf[0] != '\0')
n += snprintf(op_desc_buf + n, sizeof(op_desc_buf) - n - 1,
", %s", op2_buf);
if (op3_buf[0] != '\0')
n += snprintf(op_desc_buf + n, sizeof(op_desc_buf) - n - 1,
", %s", op3_buf);
printf("#%s\n", op_desc_buf);
}
int decode_prefix(uint8_t *op, struct x86_opcode *op_code)
{
struct ins_prefix *ins = &op_code->op_ins;
struct rex_prefix *rex = &op_code->op_rex;
uint8_t *s = op;
switch (*s) {
case 0x40 ... 0x4f:
decode_rex(*s, rex);
print_rex(rex);
break;
case 0x66:
ins->op_0x66 = 1;
break;
case 0x67:
ins->op_0x67 = 1;
break;
case 0xf2:
ins->op_rep1 = 1;
break;
case 0xf3:
ins->op_rep2 = 1;
break;
case 0x38:
ins->op_0x38 = 1;
break;
case 0x3a:
ins->op_0x3a = 1;
break;
case 0x2e:
ins->op_seg_cs = 1;
strcpy(ins->op_seg_buf, "cs:");
break;
case 0x36:
ins->op_seg_ss = 1;
strcpy(ins->op_seg_buf, "ss:");
break;
case 0x3e:
ins->op_seg_ds = 1;
strcpy(ins->op_seg_buf, "ds:");
break;
case 0x26:
ins->op_seg_es = 1;
strcpy(ins->op_seg_buf, "es:");
break;
case 0x64:
ins->op_seg_fs = 1;
strcpy(ins->op_seg_buf, "fs:");
break;
case 0x65:
ins->op_seg_gs = 1;
strcpy(ins->op_seg_buf, "gs:");
break;
case 0x0f:
ins->op_0x0f = 1;
break;
case 0xf0:
ins->op_0xf0 = 1;
strcpy(ins->op_lock_buf, "lock ");
break;
default:
return -1;
}
return 0;
}
int decode_operand_arg(uint8_t *op_string, struct opcode_desc *op_desc,
struct x86_opcode *op_code)
{
char op1_buf[32], op2_buf[32], op3_buf[32];
uint8_t *s = op_string;
int n = 0, n1 = 0, n2 = 0;
n = decode_operand(s, op1_buf, 31, op_desc->op1, op_code);
if (n == -1)
return -1;
s += n;
if (op_desc->op2) {
n1 = decode_operand(s, op2_buf, 31, op_desc->op2, op_code);
if (n1 == -1)
return -1;
s += n1;
}
if (op_desc->op3) {
n2 = decode_operand(s, op3_buf, 31, op_desc->op3, op_code);
if (n2 == -1)
return -1;
s += n2;
print_ins(op_code, op_desc, op1_buf, op2_buf, op3_buf);
}
else {
print_ins(op_code, op_desc, op1_buf, op2_buf, op3_buf);
}
return n + n1 + n2;
}
int decode_instruction(uint8_t *op_string, struct x86_opcode *op_code)
{
struct opcode_desc *op_desc;
uint8_t *s = op_string, *p;
int n = 0;
op_code->op_reg.mod = -1;
while (*s) {
if (!decode_prefix(s, op_code)) {
s++;
continue;
}
op_desc = lookup_code_map(*s, op_code);
if (!op_desc)
return -1;
s++;
break;
}
print_opcode(op_desc);
/* decode opcode with no arguments. */
if (!op_desc->op1 && !op_desc->op2 && !op_desc->op3) {
if (select_reg_by_arg(op_code, op_desc) == -1)
return -1;
goto out;
}
n = decode_operand_arg(s, op_desc, op_code);
if (n == -1)
return -1;
s += n;
out:
return s - op_string;
}
int disass_opcode(uint8_t *op_string, int op_len)
{
struct x86_opcode op_code;
uint8_t *s = op_string;
int i = 0, n = 0;
while (i < op_len) {
bzero(&op_code, sizeof(op_code));
n = decode_instruction(s + i, &op_code);
if (n == -1)
return -1;
i += n;
}
return 0;
}
|
C
|
#include "parser.h"
/*
Variveis utilizadas:
'e' representa o valor a ser utilizado no critrio de paragem.
'f' um apontador para a funo que calcula o valor da expresso.
'f_d' um apontador para a funo derivada de 'f'.
'i' acumula o nmero de iteraes.
*/
#include <math.h>
#define PI M_PI
double _abs(double x)
{
return ((x>=0.0) ? x : -x);
}
double bisseccao(double x1, double x2, double e, int *i, char *expr)
{
double a, b, ym, y;
*i = 0;
a = parse(expr, x1);
b = parse(expr, x2);
if(a * b > 0)
return a-1;
while(x2 - x1 > e){
ym = (x1 + x2) / 2;
y = parse(expr, ym);
if(
(y <= 0 && parse(expr, x1) < 0 && parse(expr, x2) > 0) ||
(y > 0 && parse(expr, x1) > 0 && parse(expr, x2) < 0)
)
x1 = ym;
else
x2 = ym;
(*i)++;
}
return ym;
}
double secante(double x1, double x2, double e, int *i, char *expr)
{
double a, b, x3, x4, tmp;
*i = 0;
x3 = 0;
do{
a = parse(expr, x1);
b = parse(expr, x2);
x4 = x3;
x3 = x2 - ((x1 - x2) * b / a) / (1 - b / a);
if(b < a){
tmp = x1;
x1 = x2;
x2 = tmp;
}
x1 = x2;
x2 = x3;
tmp = _abs(x3 - x4);
(*i)++;
}while(tmp > e);
return x3;
}
double newton(double x, double e, int *i, char *expr, char *expr_d)
{
double a, b, tmp;
*i = 0;
do{
tmp = x;
a = parse(expr, x);
b = parse(expr_d, x);
x = x - a / b;
tmp = _abs((x - tmp) / x);
(*i)++;
}while(tmp > e);
return x;
}
double muller(double x1, double x3, double x2, double e, int *i, char *expr)
{
double x11, x22, x33, l, d, g, c, t, r, d1, d2, x4, t1, t2, n;
*i = 0;
x4 = x3;
for(;;){
x11 = parse(expr, x1);
x33 = parse(expr, x3);
if(_abs(x33) < e)
return x4;
x22 = parse(expr, x2);
l = (x3 - x2) / (x2 - x1);
d = (x3 - x1) / (x2 - x1);
g = l * l * x11 - d * d * x22 + (l + d) * x33;
c = l * (l * x11 - d * x22 + x33);
n = (-2 * d * x33); /* numerador */
r = sqrt(g*g - 4 * d * c * x33); /* raiz */
d1 = g + r; /* denominador 1 */
d2 = g - r; /* denominador 2 */
t1 = _abs(n / d1); /* valor absoluto 1 */
t2 = _abs(n / d2); /* valor absoluto 2 */
t = ((t1 >= t2) ? n / d2 : n / d1); /* escolher o menor */
x4 = x3 + t * (x3 - x2); /* utiliz-lo para x4 */
x1 = x2;
x2 = x3;
x3 = x4;
(*i)++;
}
}
#include <ctype.h>
#include <stdio.h>
void main(void)
{
int i, a, b;
double r;
float erro;
char m, expr[100], expr_d[100], te[2];
printf("\nDeterminao de zeros de funes no lineares\n");
do{
printf("Mtodo ([B]isseco, [S]ecante, [M]uller, [N]ewton) = ");
scanf("%s", &te);
m = toupper(te[0]);
}while(m!='B' && m!='N' && m!='M' && m!='S');
fflush(stdin);
printf("f(x) = ");
gets(expr);
if(m=='N'){
printf("f'(x) = ");
gets(expr_d);
}
switch(m){
case 'B':
printf("a = ");
scanf("%d", &a);
printf("b = ");
scanf("%d", &b);
printf("erro < ");
scanf("%f", &erro);
r = bisseccao(a, b, erro, &i, expr);
break;
case 'S':
printf("a = ");
scanf("%d", &a);
printf("b = ");
scanf("%d", &b);
printf("erro < ");
scanf("%f", &erro);
r = secante(a, b, erro, &i, expr);
break;
case 'N':
printf("a = ");
scanf("%d", &a);
printf("erro < ");
scanf("%f", &erro);
r = newton(a, erro, &i, expr, expr_d);
break;
case 'M':
printf("a = ");
scanf("%d", &a);
printf("b = ");
scanf("%d", &b);
printf("erro < ");
scanf("%f", &erro);
r = muller(a, (b + a) / 2, b, erro, &i, expr);
}
if(parse(expr, r) == 0)
printf("\nf(%f) = 0, em %d iteraes", r, i);
else
printf("\nAo fim de %d iteraes, o zero no foi encontrado...", i);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
Ej-iterativas: 2. Escriu un programa que demana a l'usuari un valor i quantes vegades ho vol sumar i mostri el resultat
de totes les sumes fins a arribar a les vegades demanades.
*/
int main ()
{
//Iniciar variable.
int num, sum, res, i;
//Ttulo.
printf("\n\t\t\4 \4 \4 \4 \4 Iterativas - Ex 2 \4 \4 \4 \4 \4\n\n");// Utilice /4 en modo decorativo.
//Introduccin.
printf("\n\t\4 Introduce un numero y las veces que quieras sumarlo.\n\n");
//Pedir valor a usuario.
printf("\n\t \376 Numero: ");// Utilice /376 en modo decorativo.
scanf("%i", &num);
//Pedir cantidad de veces a usuario.
printf("\n\t \376 Cuantas veces lo quieres sumar?\n\n\t \32 ");// Utilice /32 en modo decorativo para lo que ponga el usuario.
scanf("%i", &sum);
printf("\n");//salto de lnea.
//Procesar datos con FOR.
//Condicin: i comienza 0 ; i <= sum(la cantidad de veces) ; i aumenta uno a uno.
for( i = 0; i < sum; i++ )
{
//Operacin matemtica.
res=num+i;
//Respuesta de la operacin anterior.
printf("\n\t\t\20 %i + %i = %i\n\n", num, i, res);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define LIMIT 1001000
long find_smallest_nsubtract(void);
double find_largest(void);
long match_time[LIMIT];
long L, R, num_of_matches, smallest_present;
int main()
{
long i=0, Q;
double largest;
scanf("%ld",&num_of_matches);
while(num_of_matches--)
scanf("%ld",&match_time[i++]);
num_of_matches = i;
scanf("%ld",&Q);
while(Q--){
scanf("%ld %ld",&L,&R);
smallest_present = find_smallest_nsubtract();
largest = (find_largest() + (smallest_present));
printf("%.1f\n",largest);
}
return 0;
}
long find_smallest_nsubtract(void){ //find smallest time between L and R, and subtract from the interval this num and divide by 2
long i;
long smallest = match_time[L];
for(i = (L+1); i <= R; i++){
if(match_time[i] < smallest)
smallest = match_time[i];
}
/*for(i = L; i <= R; i++)
temp[i] = (temp[i] - smallest) / 2;*/
return smallest;
}
double find_largest(void){
long i, largest1 = 0, temp_l2=0;
double largest2;
for(i = 0; i < num_of_matches; i++){
if(i == L){
while(i <= R){
if(match_time[i] > temp_l2)
temp_l2 = match_time[i];
i++;
}
i--;
}
else{
if(match_time[i] > largest1)
largest1 = match_time[i];
}
}
largest2 = temp_l2;
largest2 = ((largest2 - (smallest_present)) * 0.5);
if(largest2 > (largest1))
return largest2;
else
return largest1;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct employee_s{
char name[20];
float basicSalary;
int hra;
struct employee_s *pNext;
}employee_t;
employee_t* addEmpdata(void);
vioid printEmpList(void);
employee_t *pHead = NULL;
main()
{
employee_t *emp1, *emp2,*emp3;
emp1 = addEmpdata();
emp2 = addEmpdata();
emp3 = addEmpdata();
// Link the employees as List
pHead = emp1;
emp1->pNext = emp2;
emp2->pNext = emp3;
emp3->pNext = NULL;
// Print Employee Data
printEmpList();
}
employee_t* addEmpdata(void)
{
employee_t* emp;
emp = (employee_t*)malloc(sizeof(employee_t));
printf("Enter the name of Employee\n");
scanf("%s", emp->name);
printf("Enter Salary of Employee\n");
scanf("%f", &emp->basicSalary);
printf("Enter HRA of Employee\n");
scanf("%d", &emp->hra);
emp->pNext = NULL;
return emp;
}
void printEmpList(void)
{
employee_t *pTemp = NULL;
pTemp = pHead;
while(pTemp != NULL)
{
printf("name of Employee is: %s\n", pTemp->name);
printf("Salary of Employee is :%f\n", pTemp->basicSalary);
printf("HRA of Employee is : %d\n", pTemp->hra);
pTemp = pTemp->pNext;
}
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
printf("\t\t\t\t\t*****************************************************\n");
printf("\t\t\t\t\t****\t\tWELCOME TO MY PROGRAM\t\t ****\n");
printf("\t\t\t\t\t*****************************************************\n");
int choice;
printf("\n->Enter 1 for Non-Premption\n->Enter 2 for Premption");
printf("\nEnter your choice : ");
scanf("%d",&choice);
if(choice==2)
{
int a[10],b[10],x[10];
int w[10],t[10],c[10];
int i,j,littile,count=0,time,n;
double avg=0,tt=0,end;
printf("\nEnter the number of Processes: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter arrival time of process %d : ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
printf("\nEnter burst time of process %d : ",i+1);
scanf("%d",&b[i]);
}
for(i=0;i<n;i++)
x[i]=b[i];
b[9]=9999;
//printf("time => process number");
for(time=0;count!=n;time++)
{
littile=9;
for(i=0;i<n;i++)
{
if(a[i]<=time && b[i]<b[littile] && b[i]>0 )
littile=i;
}
b[littile]--;
//printf("\n%d => p%d",time+1,littile);
if(b[littile]==0)
{
count++;
end=time+1;
c[littile] = end;
w[littile] = end - a[littile] - x[littile];
t[littile] = end - a[littile];
// printf("\n %d %d %d",littile,wt[littile],ttp[littile]);
}
}
printf("\nProcess_Id\t Burst_Time \t Arival_Time \tWaiting_Time \tTurnaround_Time \tCompletion_Time");
for(i=0;i<n;i++)
{
printf("\n %d \t \t %d \t\t %d \t\t%d \t\t%d\t\t\t%d",i+1,x[i],a[i],w[i],t[i],c[i]);
avg = avg + w[i];
tt = tt + t[i];
}
//printf("\n %lf %lf",avg,tt);
printf("\n\nAverage waiting time = %lf\n",avg/n);
printf("\nAverage Turnaround time = %lf\n",tt/n);
}
else if(choice==1)
{
int flag, i, j, lt, total = 0, pt;
float aw_t, at_t;
int b_t[20], p[20], w_t[20], t_t[20];
printf("\nEnter Total Number of Processes:\t");
scanf("%d", <);
for(i = 0; i < lt; i++)
{
printf("Enter Burst Time For Process[%d]:\t", i + 1);
scanf("%d", &b_t[i]);
p[i] = i + 1;
}
for(i = 0; i < lt; i++)
{
pt = i;
for(j = i + 1; j < lt; j++)
{
if(b_t[j] < b_t[pt])
{
pt = j;
}
}
flag = b_t[i];
b_t[i] = b_t[pt];
b_t[pt] = flag;
flag = p[i];
p[i] = p[pt];
p[pt] = flag;
}
w_t[0] = 0;
for(i = 1; i < lt; i++)
{
w_t[i] = 0;
for(j = 0; j < i; j++)
{
w_t[i] = w_t[i] + b_t[j];
}
total = total + w_t[i];
}
aw_t = (float)total / lt;
total = 0;
printf("\nProcess ID\t\tBurst Time\t Waiting Time\t Turnaround Time\n");
for(i = 0; i < lt; i++)
{
t_t[i] = b_t[i] + w_t[i];
total = total + t_t[i];
printf("\nProcess[%d]\t\t%d\t\t %d\t\t %d\n", p[i], b_t[i], w_t[i], t_t[i]);
}
at_t = (float)total / lt;
printf("\nAverage Waiting Time:\t%f\n", aw_t);
printf("\nAverage Turnaround Time:\t%f\n", at_t);
}
}
|
C
|
#include <stdio.h>
int main()
{
int h1, m1, h2, m2;
int min0, minf,mint;
while(scanf("%d %d %d %d", &h1, &m1, &h2, &m2) && (h1 || m1 || h2 || m2))
{
min0 = h1*60 + m1;
minf = h2*60 + m2;
mint = (min0>=minf) ? ((1440 - min0) + minf) : (minf -min0);
printf("%d\n",mint);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "fileops.h"
int GetFileLen(const char* szFilename);
int LoadFile(const char* szFilename, char** ppBuffer)
{
int iBytesRead = 0;
int iFileLen = GetFileLen(szFilename);
if ( 0 < iFileLen )
{
*ppBuffer = (char*) malloc(iFileLen);
if ( NULL != *ppBuffer )
{
FILE* fp = fopen (szFilename, "rb");
if ( NULL != fp )
{
iBytesRead = fread(*ppBuffer, 1, iFileLen, fp);
fflush(fp);
fclose(fp);
}
}
} else {
printf("LoadFile: unable to load %s", szFilename);
}
return iBytesRead;
}
int GetFileLen(const char* szFilename)
{
FILE* fp;
int iFileLen = 0;
fp = fopen(szFilename, "rb");
if ( NULL != fp )
{
fseek(fp, 0, SEEK_END);
iFileLen = ftell(fp);
fclose(fp);
}
return iFileLen;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char s[],int i,int j)
{
char tmp=s[i];
s[i]=s[i];
s[j]=tmp;
}
int foo(char*s,int n)
{
int i,j,len=strlen(s);
n=n%len;
for (i = 0,j = len-n; i<j; i++)
swap(s,i,--j);
for (i = len-n, j = len; i<j; i++)
swap(s, i, --j);
for (i = 0; i < j; i++)
swap(s, i, --j);
return 0;
}
int main(int argc, const char *argv[])
{
char s[]="abcdefg";
int n = atoi(argv[1]);
printf("%s\n",s);
foo(s,n);
printf("%s\n",s);
return 0;
}
|
C
|
/*
File : hw2_p2.c
Description : APES Homework 2, Problem 2.
This is program demonstrates the use of basic file operations.
Author : Jeff Schornick (jesc5667@colorado.edu)
Version : Version and history information is available at the GitHub repository:
https://github.com/jschornick/ecen5013_apes/hw2
*/
#include <stdio.h> // printf, file functions
#include <stdlib.h> // malloc
#include <sys/stat.h> // chmod
#define FILENAME "testfile_hw2_p2.txt"
#define MAX_CHARS 100
#define _STRINGIFY(x) #x
#define STRINGIFY(x) _STRINGIFY(x)
#define ERR_USAGE (-1)
#define ERR_FILE (-2)
#define ERR_MEM (-3)
int main( int argc, char **argv )
{
FILE *p_file = NULL;
// If not compiled to read form standad input, require command-line argument
#ifndef READ_STDIN
if( argc < 2 )
{
printf( "Usage: %s <string-to-print>\n", argv[0]);
return ERR_USAGE;
}
#endif
// Part 0 : Print a string
// *************************
printf("This is an interesting string. Marvel at its fascinating characters.\n");
// Part 1 : Create a file and change its mode
// *********************************************
p_file = fopen( FILENAME, "w+" );
if( !p_file )
{
printf( "Failed to open/create file: %s\n", FILENAME );
return ERR_FILE;
}
fclose( p_file );
// Change permissions to be read/write for user
chmod( FILENAME, S_IRUSR | S_IWUSR );
// Part 2 : Write character to file
// **********************************
p_file = fopen( FILENAME, "w+" ); // open for writing, overwrite
if( !p_file )
{
printf( "Failed to open file for writing: %s\n", FILENAME );
return ERR_FILE;
}
fputc( 'Z', p_file );
fclose( p_file );
// Part 3 : Read an input string, append, and flush
// **************************************************
p_file = fopen( FILENAME, "a" ); // open for append
if( !p_file )
{
printf( "Failed to open file for writing: %s\n", FILENAME );
return ERR_FILE;
}
char *p_buf = NULL;
p_buf = malloc( sizeof(*p_buf) * (MAX_CHARS+1) ); // characters + null
if( !p_buf )
{
printf( "Failed dynamically allocate array size %u!\n", (MAX_CHARS+1) );
return ERR_MEM;
}
// Read either from stdin or command-line based on how compiled
#ifdef READ_STDIN
scanf( "%" STRINGIFY(MAX_CHARS) "s", p_buf); // scanf reads X character + null
fprintf( p_file, "%s", p_buf );
#else
fprintf( p_file, "%s", argv[1] );
#endif
fflush( p_file );
fclose( p_file );
// Part 4 : Read from file
// *************************
p_file = fopen( FILENAME, "r" ); // open for reading
if( !p_file )
{
printf( "Failed to open file for reading: %s\n", FILENAME );
return ERR_FILE;
}
char my_char;
my_char = fgetc( p_file );
printf( "Read character: %c\n", my_char );
fgets( p_buf, (MAX_CHARS+1), p_file ); // fgets reads X-1 chars + null
if( p_buf )
{
printf( "Read string: %s\n", p_buf );
} else {
printf( "Failed to read string!\n" );
}
fclose( p_file );
free( p_buf );
printf( "\n" );
return 0;
}
|
C
|
/**
* Task:
Assignment name : ft_split
Expected files : ft_split.c
Allowed functions: malloc
--------------------------------------------------------------------------------
Write a function that takes a string, splits it into words, and returns them as
a NULL-terminated array of strings.
A "word" is defined as a part of a string delimited either by spaces/tabs/new
lines, or by the start/end of the string.
Your function must be declared as follows:
char **ft_split(char *str);
*/
int ft_word_len(char *str)
{
int len;
int i;
len = 0;
i = 0;
while (str[i] == ' ' || str[i] == '\t')
i++;
while (str[i])
{
if (str[i] != ' ' && str[i] != '\t')
{
while (str[i] != ' ' && str[i] != '\t')
i++;
len++;
}
i++;
}
return (len);
}
#include <stdlib.h>
char **ft_split(char *str)
{
char **arr;
int words_num;
words_num = ft_word_len();
if (!(arr = (char **)malloc(sizeof(char *) * words_num + 1)))
return (NULL);
return (arr);
}
#include <stdio.h> //
int main() //
{
char *split_str;
char **arr;
int i;
split_str = " One Two Three Four Five ";
arr = ft_split(split_str);
i = 0;
while (arr[i])
{
printf("%s\n", arr[i]);
i++;
}
return (0);
}
|
C
|
#include "../includes/pushswap.h"
void ft_strat_zero(t_a *a)
{
int i;
i = -1;
if (a->use_rr)
{
if (a->strat_tab[a->strat] > 2)
{
i++;
ft_rr(a);
}
else
ft_ra(a);
a->use_rr = 0;
}
while (++i < a->strat_tab[a->strat] - 2)
ft_rb(a);
ft_pa(a);
a->use_rr = 1;
}
void ft_strat_one(t_a *a)
{
int i;
i = -1;
if (a->use_rr)
{
ft_ra(a);
a->use_rr = 0;
}
while (++i < a->strat_tab[a->strat] - 2)
ft_rrb(a);
ft_pa(a);
a->use_rr = 1;
}
void ft_strat_two(t_a *a)
{
int i;
i = -1;
if (a->use_rr)
{
if (a->strat_tab[a->strat] > 2)
{
i++;
ft_rr(a);
}
else
ft_ra(a);
a->use_rr = 0;
}
while (++i < a->strat_tab[a->strat] - 1)
ft_rb(a);
ft_pa(a);
a->ramember++;
}
void ft_strat_three(t_a *a)
{
int i;
i = -1;
if (a->use_rr)
{
ft_ra(a);
a->use_rr = 0;
}
while (++i < a->strat_tab[a->strat] - 1)
ft_rrb(a);
ft_pa(a);
a->ramember++;
}
int *ft_brutal_sort(int *tab, int init, int end)
{
int i;
int k;
int tmp;
i = 0;
while (i < end - init)
{
k = 0;
while (k < i)
{
if (tab[k] < tab[i])
{
tmp = tab[k];
tab[k] = tab[i];
tab[i] = tmp;
}
k++;
}
i++;
}
return (tab);
}
|
C
|
//
// Created by Salman S on 2018-11-26.
//
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "datatype.h"
//duplicate the string
char *string_dup(char *str){
char *string=strdup(str);
return string;
}
//generate a new key type
Key key_gen(char *skey, char *skey2){
Key newKey =(Key*)malloc(sizeof(Key_struct));
newKey->skey1=string_dup(skey);
newKey->skey2=string_dup(skey2);
return newKey;
}
//compare the keys
int key_comp(Key key1, Key key2){
int compVal=strcmp(key1->skey1,key2->skey1);
if(compVal==0){
compVal=strcmp(key1->skey2,key2->skey2);
}
return compVal;
}
//print the key
void key_print(Key key){
printf("%s\t\t%s",key->skey1,key->skey2);
}
//free the memoery for key
void key_free(Key key){
free(key->skey1);
free(key->skey2);
free(key);
}
//generate the data type
Data data_gen(int data){
Data newData =malloc(sizeof(Data));
*newData=data;
return newData;
}
//set the data to data
void data_set(Data data, int idata){
*data=idata;
}
//print the data
void data_print(Data data){
printf("\t\t%d\n",*data);
}
//free memeory for data
void data_free(Data data){
free(data);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include "dmalloc.h"
#define DMALLOC_DEVICE "/dev/dmalloc"
#define DMALLOC_FREE 1
#define DMALLOC_GETPHYS 2
#define DBG if (0)
#define ERR if (1)
#ifndef SIM
static int dmalloc_fd = -1;
static int dmalloc_fd_cached = -1;
int DMALLOC_init(void)
{
if (dmalloc_fd < 0)
dmalloc_fd = open(DMALLOC_DEVICE, O_RDWR|O_SYNC);
if (dmalloc_fd < 0) {
ERR fprintf(stderr, "DMALLOC_init - failed: %s\n", strerror(errno));
return -1;
}
fcntl(dmalloc_fd, F_SETFD, FD_CLOEXEC);
if (dmalloc_fd_cached < 0)
dmalloc_fd_cached = open(DMALLOC_DEVICE, O_RDWR);
if (dmalloc_fd_cached < 0) {
ERR fprintf(stderr, "DMALLOC_init - failed: %s\n", strerror(errno));
return -1;
}
fcntl(dmalloc_fd_cached, F_SETFD, FD_CLOEXEC);
return 0;
}
void* DMALLOC_alloc(size_t size)
{
void* addr;
if (dmalloc_fd <0) {
ERR fprintf(stderr, "DMALLOC_alloc - not initialized\n");
return 0;
}
addr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, dmalloc_fd, 0);
if (addr == MAP_FAILED) {
ERR fprintf(stderr, "DMALLOC_alloc - cannot allocate %d byte: %s\n", size, strerror(errno));
return NULL;
}
DBG fprintf(stderr, "DMALLOC_alloc - allocated %d byte at %p\n", size, addr);
return addr;
}
int DMALLOC_free(void* addr)
{
if (dmalloc_fd < 0) {
DBG fprintf(stderr, "DMALLOC_free - not initialized\n");
return -1;
}
if (ioctl(dmalloc_fd, DMALLOC_FREE, (unsigned long)addr) < 0) {
ERR fprintf(stderr, "DMALLOC_free - cannot free memory at %p: %s\n", addr, strerror(errno));
return -1;
}
DBG fprintf(stderr, "DMALLOC_free - freed memory at %p\n", addr);
return 0;
}
int DMALLOC_exit(void)
{
close(dmalloc_fd);
dmalloc_fd = -1;
return 0;
}
/* CMEM compatibility functions */
int CMEM_init(void)
{
return DMALLOC_init();
}
int CMEM_exit(void)
{
return DMALLOC_exit();
}
void* CMEM_alloc(size_t size)
{
return DMALLOC_alloc(size);
}
int CMEM_free(void* buf)
{
return DMALLOC_free(buf);
}
unsigned long CMEM_getPhys(void *ptr)
{
unsigned long addr = (unsigned long)ptr;
if (dmalloc_fd < 0) {
DBG fprintf(stderr, "CMEM_getPhys - not initialized\n");
return 0;
}
if (ioctl(dmalloc_fd, DMALLOC_GETPHYS, &addr) < 0) {
ERR fprintf(stderr, "CMEM_getPhys - translation of %p failed\n", ptr);
return 0;
}
DBG fprintf(stderr, "CMEM_getPhys - %p -> 0x%08X\n", ptr, addr);
return addr;
}
//////////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////////
void* DMALLOC_alloc_cached(size_t size)
{
void* addr;
if (dmalloc_fd_cached <0) {
ERR fprintf(stderr, "DMALLOC_alloc - not initialized\n");
return 0;
}
addr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, dmalloc_fd_cached, 0);
if (addr == MAP_FAILED) {
ERR fprintf(stderr, "DMALLOC_alloc - cannot allocate %d byte: %s\n", size, strerror(errno));
return NULL;
}
DBG fprintf(stderr, "DMALLOC_alloc - allocated %d byte at %p\n", size, addr);
return addr;
}
int DMALLOC_free_cached(void* addr)
{
if (dmalloc_fd_cached < 0) {
DBG fprintf(stderr, "DMALLOC_free - not initialized\n");
return -1;
}
if (ioctl(dmalloc_fd_cached, DMALLOC_FREE, (unsigned long)addr) < 0) {
ERR fprintf(stderr, "DMALLOC_free - cannot free memory at %p: %s\n", addr, strerror(errno));
return -1;
}
DBG fprintf(stderr, "DMALLOC_free - freed memory at %p\n", addr);
return 0;
}
#else
int DMALLOC_init(void)
{
return 0;
}
int DMALLOC_exit(void)
{
return 0;
}
void* DMALLOC_alloc(size_t size)
{
unsigned char *start = (unsigned char*)malloc(size + sizeof(unsigned int) + 32);
if (!start)
return NULL;
unsigned char *ptr = (unsigned char *)(((unsigned long)start + 31) & ~0x1f);
if (ptr == start)
ptr += 32;
DBG fprintf(stderr, "DMALLOC_alloc - allocated %d byte at real %p, %p\n", size, start, ptr);
*((unsigned int*)(ptr-sizeof(unsigned int*))) = (unsigned int)start;
return ptr;
}
int DMALLOC_free(void* addr)
{
unsigned int start = *((unsigned int*)(((unsigned char*)addr)-sizeof(unsigned int)));
DBG fprintf(stderr, "DMALLOC_free - freed memory at real %p, %p\n", start, addr);
free(start);
return 0;
}
void* DMALLOC_alloc_cached(size_t size)
{
return malloc(size);
}
int DMALLOC_free_cached(void* addr)
{
free(addr);
return 0;
}
#endif
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, string argv[])
{
if (argc==2)
{
string z;
int k=atoi(argv[1]);
z=get_string("plaintext: ");
printf("cyphertext: ");
for(int i=0;i<strlen(z);i++)
if(isalpha(z[i]))
{
if(isupper(z[i]))
{
printf("%c",(((z[i]- 65)+ k)%26)+ 65);
}
if(islower(z[i]))
{
printf("%c",(((z[i]- 97)+ k)%26)+ 97);
}
}
else
{
printf("%c",z[i]);
}
}
}
|
C
|
#include <stdio.h>
void swap(int a, int b);
void swap_add(int * a, int * b);
void changeArray(int* ptr);
int main_pointer2(void)
{
//迭 Ϳ ִ.
int arr[3] = { 5,10,15 };
int* ptr = arr; // ptr ͺ
for (int i = 0; i < 3; i++)
{
printf("迭 arr[%d] : %d\n", i, arr[i]);
}
for (int i = 0; i < 3; i++)
{
printf(" ptr[%d] : %d\n", i, ptr[i]);
}
ptr[0] = 100;
ptr[1] = 200;
ptr[2] = 300; // ͺ̹Ƿ ü ٲ
for (int i = 0; i < 3; i++)
{
printf("迭 arr[%d] : %d\n", i, arr[i]);
printf("迭 arr[%d] : %d\n", i, *(arr + i));
}
/* arrü ּҰ (arr == &arr[0])
arr 迭 ù° ּҿ */
printf("arr ü (arr): %d\n", arr);
printf("arr[0] ּ(&arr[0]): %d\n", &arr[0]);
/* "arr + i" arrκ iŭ ּ
"*(arr + i)" ̶
arr[i] *(arr + i) ϴ.
*/
for (int i = 0; i < 3; i++)
{
printf(" ptr[%d] : %d\n", i, ptr[i]);
printf(" ptr[%d] : %d\n", i, *(ptr + i));
}
printf("arr ü (ּ) : %d\n", *arr);
printf("arr[0] : %d\n", *&arr[0]);
// arr = arr[0] ּ̹Ƿ (arr == &arr[0])
// شǴ *arr Ͽ
// *arr = *(arr[0] ּ) = *&arr[0]
// *(arr + 0)
// Swap
int a = 10;
int b = 20;
printf("a = %d, b = %d\n\n", a, b);
printf("a ּ = %d\nb ּ = %d\n\n", &a, &b);
swap(a, b);
printf("[Լ ] a = %d, b = %d\n\n", a, b);
/* ½ a, b Լ Ȱ ٲ .
(Call by Value) -> Ѵٴ ǹ
swap(10, 20); 10,20̶
a b ü ƴ.
=> ִ ּҰ ü ѱ?(̼Ǹ)
*/
printf("\n\na ּ = %d\nb ּ = %d\n\n", &a, &b);
swap_add(&a, &b);
printf("[Լ ] a = %d, b = %d\n\n", a, b);
int arr2[3] = { 10,20,30 };
changeArray(arr2);
/* 迭϶ arr2 ü ּ
changeArray(&arr[0]);
Ű & ʿ arr2
ּҸ .
*/
for (int i = 0; i < 3; i++)
{
printf("%d\n", arr2[i]);
}
// scanf_s ڴ & : ּҸ ؾϹǷ
return 0;
}
void swap(int a, int b)
{
printf("[Լ ]a = %d, b = %d\n\n", a, b);
printf("[Լ ]\na ּ = %d\nb ּ = %d\n\n", &a, &b);
int temp = a;
a = b;
b = temp;
printf("[Լ ] a = %d, b = %d\n\n", a, b);
}
void swap_add(int * a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
printf("[Լ ] a = %d, b = %d\n\n", *a, *b);
}
void changeArray(int * ptr)
{
ptr[2] = 50;
}
|
C
|
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#define boolean unsigned char
#define Nil NULL
#define true 1
#define false 0
///elemen Queue
typedef int infotype;
typedef struct ElmtQueue *address;
typedef struct ElmtQueue{
infotype INFO;
address NEXT;
}ElmtQueue;
///QUEUE
typedef struct {
address HEAD ;
address TAIL;
}Queue;
///macro QUEUE
#define Head(Q) (Q).HEAD
#define Tail(Q) (Q).TAIL
#define InfoHead(Q) (Q).HEAD->INFO
#define InfoTail(Q) (Q).TAIL->INFO
///macro elemen
#define Info(P) (P)->INFO
#define Next(P) (P)->NEXT
void CreateEmpty (Queue *Q);
void dealokasi (address *P);
boolean isempty (Queue Q);
int NBElmt (Queue Q);
address Alokasi (infotype X);
void AddElmt(Queue *Q,infotype X);
void Del (Queue *Q);
void cetak (Queue Q);
#endif // HEADER_H_INCLUDED
|
C
|
// pe12-2a.c
#include "pe12-2a.h"
static int smode;
static double distance;
static double fuel;
void set_mode (int mode)
{
if (mode == 0)
smode = 0;
else if (mode == 1)
smode = 1;
else
{
smode = mode % 2;
printf ("Invalid mode specified. Mode %d (%s) used.\n",
smode, smode == 0 ? "metric" : "US");
}
}
void get_info (void)
{
printf ("Enter distance traveled in %s: ", smode == 0 ? "kilometers" : "miles");
scanf ("%lf", &distance);
printf ("Enter fuel consumed in %s: ", smode == 0 ? "liters" : "gallons");
scanf ("%lf", &fuel);
}
void show_info (void)
{
if (smode == 0)
printf ("Fuel consumption is %.2lf liters per 100 km.\n", 100 * fuel / distance);
else
printf ("Fuel consumption is %.1lf miles per gallon.\n", distance / fuel);
}
|
C
|
#include<stdio.h>
int a[100]={10, 30, 70, 16, 95, 22};
void Insert()
{
int x,m,n=6,i;
printf("Enter the value of x & m: ");
scanf("%d %d",&x,&m);
if( 0<=m && m<= n-1){
for(i=n-1 ;m<=i;i--){
a[i+1]=a[i];
}
a[m]=x;
n+=1;
}
else
{
printf("Sorry invalid input\n");
}
}
void Delete()
{
int m,n=6;
printf("Enter m:");
scanf("%d",&m);
int i;
if( 0<=m && m<= n-1){
for(i=m;i<n-1;i++){
a[i]= a[i+1];
}
n-=1;
}
else
{
printf("Sorry invalid input\n");
}
}
void Display()
{
int i,n=6;
printf("The array is\n");
for(i=0;i<n;i++){
printf("%d\t",a[i]);
}
printf("\n");
}
int menu()
{
int i;
while(1)
{
printf("1.Insert \n2.Delete \n3.Display \n4.Bubble Sort\n5.Exit\nEnter your option(1-5) \n");
scanf("%d",&i);
switch(i){
case 1:
Insert();
break;
case 2:
Delete();
break;
case 3:
Display();
break;
case 4:
sort();
break;
default:
break;
}
if(i ==5){
printf("Your program is finished...\n");
break;
}
}
}
void sort()
{
int a[100]={10, 30, 70, 16, 95, 22};
int i,j,k,t,n=6;
for (i = 0 ; i < (n-1) ; i+=1)
for (j = 0 ; j <= (n-2)-i ; j+=1)
if(a[j] > a[j+1]) {
t = a[j];
a[j] = a[j+1];
a[j+1]=t;
}
printf("Bubble sort is done successfully...\n");
}
int main()
{
int a[100];
int op = menu();
return 0;
}
|
C
|
#include<stdio.h>
int S, E, val, mid, i;
int maximo(int a[10010], int b, int ideal, int target) // funcao que procura o maior valor possivel para o tamanho do pao
{
S=1;
E=ideal;
while(S<E)
{
val=0;
mid = (S+E+1)/2;
for(i=0;i<b;i++){
val+=a[i]/mid;
}
if(val>=target){ //se a divisao dos paes pelo tamanho mid for maior ou igual que o numero de paes necessarios, mudar o start para mid
S=mid;
}
else if(val<target){ //se a divisao dos paes pelo tamanho mid for menor que o numero de paes necessarios, mudar o end para mid - 1
E=mid - 1;
}
}
if(S==E) return S;
return -1;
}
int main()
{
int N, K, num;
int tamanho[10010];
scanf("%d %d",&N, &K);
for(i=0;i<K;i++){
scanf("%d",&tamanho[i]);
num += tamanho[i];
}
num = num/N;//num eh o valor ideal para o tamanho do pao
printf("%d", maximo(tamanho,K,num,N));
}
|
C
|
/*
** bienvuenue.c for bienvenue in /home/qu_j/DicoWesh
**
** Made by QU Juliette
** Login <qu_j@etna-alternance.net>
**
** Started on Thu Oct 15 11:00:31 2015 QU Juliette
** Last update Sat Oct 17 15:26:50 2015 QU Juliette
*/
#include "juliette.h"
void bienvenue()
{
t_mot *dico;
char *commande;
dico = dictionnaire();
my_putstr("\n \033[1;34m Bienvenue sur le DicoWesh !\033[0m\n\n");
my_putstr("\033[1;31ma\033[0m");
my_putstr(" : afficher le dictionnaire sous la forme wesh : fr\n");
my_putstr("\033[1;31mb\033[0m");
my_putstr(" : afficher le dictionnaire sous la forme fr : wesh\n");
my_putstr("\033[1;35m1\033[0m");
my_putstr(" : ajouter une definition\n");
my_putstr("\033[1;35m2\033[0m");
my_putstr(" : traduire du wesh au francais\n");
my_putstr("\033[1;35m3\033[0m");
my_putstr(" : traduire du francais au wesh\n\n");
my_putstr("Quelle commande choisissez-vous ? (a, b, 1, 2 ou 3)\n");
commande = readLine();
my_putstr("\x1b[2J\x1b[1;1H");
while (my_strcmp("q", commande) != 0)
{
affichage_commande(commande, &dico);
aide_text();
commande = readLine();
}
free(dico);
}
|
C
|
#include <linux/init.h>
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
//指定的主设备号
#define MAJOR_NUM 250
//自己的字符设备
struct mycdev
{
int len;
unsigned char buffer[50];
struct cdev cdev;
}dev_led;
MODULE_LICENSE("GPL");
//设备号
static dev_t dev_num = {0};
//设备类
struct class *cls;
//打开设备
static int dev_led_open(struct inode *inode, struct file *file)
{
printk("dev_led_open success!\n");
return 0;
}
//读设备
static ssize_t dev_led_read(struct file *file, char __user *ubuf, size_t size, loff_t *ppos)
{
printk("dev_led_read success!\n");
return 0;
}
//写设备
static ssize_t dev_led_write(struct file *file, const char __user *ubuf, size_t size, loff_t *ppos)
{
printk("dev_led_write success!\n");
return 0;
}
//设备操作函数接口
static const struct file_operations led_operations = {
.owner = THIS_MODULE,
.open = dev_led_open,
.read = dev_led_read,
.write = dev_led_write,
};
//模块入口
int __init dev_led_init(void)
{
int i = 0;
int ret;
struct device *device;
//设备号 : 主设备号(12bit) | 次设备号(20bit)
dev_num = MKDEV(MAJOR_NUM, 0);
//动态注册设备号
ret = alloc_chrdev_region(&dev_num,0,1,"dev_led");
if(ret < 0){
printk("Fail to register_chrdev_region\n");
}
//创建设备类
cls = class_create(THIS_MODULE, "dev_led");
if(IS_ERR(cls)){
ret = PTR_ERR(cls);
}
//初始化字符设备
cdev_init(&dev_led.cdev,&led_operations);
//添加设备到操作系统
ret = cdev_add(&dev_led.cdev,dev_num,1);
//导出设备信息到用户空间(/sys/class/类名/设备名)
device = device_create(cls,NULL,dev_num ,NULL,"dev_led",0);
if(IS_ERR(device)){
ret = PTR_ERR(device);
printk("Fail to device_create\n");
}
printk("Register dev_led to system,ok!\n");
return 0;
}
void __exit dev_led_exit(void)
{
//删除sysfs文件系统中的设备
device_destroy(cls,dev_num );
//删除系统中的设备类
class_destroy(cls);
//从系统删除添加的字符设备
cdev_del(&dev_led.cdev);
//释放申请的设备号
unregister_chrdev_region(dev_num, 1);
printk("Exit dev_led ok!\n");
return;
}
module_init(dev_led_init);
module_exit(dev_led_exit);
|
C
|
#ifndef EPOCHCONVERTER_h_
#define EPOCHCONVERTER_h_
#include<stdio.h>
#include<stdint.h>
#include "stm32f4xx.h"
typedef uint32_t epochTime;
typedef struct TimeElements{
uint8_t Second;
uint8_t Minute;
uint8_t Hour;
uint8_t Wday; // day of week, sunday is day 1
uint8_t Day;
uint8_t Month;
uint16_t Year; // offset from 1970;
}tm;
void convertTime(epochTime input_time, uint8_t TimeZone); //convert epoch time to human readable time and save in TimeElements
/* Basic time elements functions */
uint32_t now(void); // the current epoch time
uint8_t second(void); // the second
uint8_t minute(void); // the minute
uint8_t hour(void); // the hour
uint8_t day(void); // the day
char weekday(void); // the weekday (Sunday is day 1)
uint8_t month(void); // the month (Jan is month 1)
uint16_t year(void); // the year
/* 12 hour format functions */
uint8_t hourFormat12(void); // the hour in 12 hour format
uint8_t isAM(void); // returns true if time is AM
uint8_t isPM(void); // returns true if time is PM
void setTime(uint32_t epochTime);
#endif /* EPOCHCONVERTER_h_ */
|
C
|
/*
** EPITECH PROJECT, 2020
** libjzon
** File description:
** JSON object parser
*/
#include "my/my.h"
#include "jzon/jzon.h"
#include "jzon/parser.h"
#include "priv.h"
static char *read_key(const char **str)
{
char *key = NULL;
OPT(jzon_parser_res) res = jzon_parse__ws(*str);
res = jzon_parse_string(res.v.rem);
if (!res.is_some)
return (NULL);
key = my_cstrdup(jzon_str(res.v.u.jz));
jzon_drop(res.v.u.jz);
res = jzon_parse__ws(res.v.rem);
*str = res.v.rem;
return (key);
}
static jzon_t read_element(const char **str)
{
OPT(jzon_parser_res) res = jzon_parse_element(*str);
if (!res.is_some)
return (NULL);
*str = res.v.rem;
return (res.v.u.jz);
}
static bool read_member(const char **str, jzon_t obj)
{
char *key = read_key(str);
jzon_t elem = NULL;
if (key == NULL || **str != ':') {
my_free(key);
return (true);
}
(*str)++;
elem = read_element(str);
if (elem == NULL || jzon_setk(obj, key, elem)) {
my_free(key);
return (true);
}
my_free(key);
return (false);
}
static bool read_member_list(const char **str, jzon_t obj)
{
if (read_member(str, obj))
return (false);
while (**str == ',') {
(*str)++;
if (read_member(str, obj))
return (true);
}
return (false);
}
OPT(jzon_parser_res) jzon_parse_object(const char *str)
{
jzon_parser_res_t res;
if (*str != '{')
return (NONE(jzon_parser_res));
res.rem = jzon_parse__ws(str + 1).v.rem;
res.u.jz = jzon_create_obj();
if (res.u.jz == NULL || read_member_list(&res.rem, res.u.jz)) {
jzon_drop(res.u.jz);
return (NONE(jzon_parser_res));
}
if (*res.rem != '}') {
jzon_drop(res.u.jz);
return (NONE(jzon_parser_res));
}
res.rem++;
return (SOME(jzon_parser_res, res));
}
|
C
|
/*
*
*
*/
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#define streq(s1, s2) (strcmp((s1),(s2)) == 0)
#define PATHSIZE 1024
#define MCDIR "/.mx"
#define MCDIR_L 9
char root_dir[PATHSIZE];
void usage() {
printf("USAGE: Not really usable yet\n");
}
void error(const char* msg, ...) {
va_list ap;
va_start(ap, msg);
fprintf(stderr, "ERROR: ");
vfprintf(stderr, msg, ap);
fprintf(stderr, "\n");
va_end(ap);
}
int find_root_dir() {
getcwd(root_dir, PATHSIZE - MCDIR_L - 3);
if(root_dir == NULL) {
error("Couldn't open current directory");
exit(3);
}
int endpos = strlen(root_dir);
do {
memcpy(&root_dir[endpos], MCDIR, MCDIR_L+1);
if(access(root_dir, X_OK) == 0) return 1;
} while( (endpos = go_up(root_dir)) );
return 0;
}
int go_up(char *dir) {
int i = 0;
int last_pos = 0;
int last_pos2 = 0;
char ch;
while((ch = dir[i])) {
if(ch == '/' || ch == '\\') {
if(dir[i+1]) {
last_pos2 = last_pos;
last_pos = i; // don't count if trailing slash
}
}
i++;
}
return last_pos2;
}
void curr() {
// 1. project name (directory or .mx/ override)
// 2. git context/state (with state flags like merging/cherry-picking/unmerged...)
// 3. environment
// 4. role
// 5. machine (host)
// 6. os
stat_project
printf("/");
stat_context(1);
printf("/");
stat_role(1);
}
int main(int argc, char *argv[], char *envp[]) {
if(argc < 2) {
usage();
return 1;
}
/* -- Commands --
* => stat + help
* (help|-h|--help|-help) => help
* (version|-v|--version|-version) => version
*
* init [directory] => init
* st[at] [-verbose] [-long] [type] => stat `mx st env` == `mx env`
*
* role [-list|new] => role_ops
* env[ironment] [-list|new] => env_ops
* os => os_ops
* host => host_ops
*
* conf[ig] [group] => conf
* refresh => refresh project based on current stat
*
* [COMMAND] => misc. command from .mx/commands/...
*
* -- Environment variables / settings --
*
* environment | settings | default
* -------------+------------+-----------
* MX_COLOR | mx-color | 1
* MX_PATH | mx-path |
*
*/
if(streq(argv[1], "help")) {
usage(); return 0;
} else if(streq(argv[1], "curr")) {
if(find_root_dir()) {
curr();
} else {
error("Not in a mx project.");
}
} else error("Unknown command %s. Try 'help'.", argv[1]);
}
|
C
|
/*
* Copyright (C) 2017 Niko Rosvall <niko@byteptr.com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <getopt.h>
#include "cmd_ui.h"
#include "entry.h"
#include "db.h"
#include "utils.h"
#include "pwd-gen.h"
#include "crypto.h"
static int show_password = 0;
static int force = 0;
static int auto_encrypt = 0;
static void version()
{
printf("Titan version 0.9\n");
}
static void usage()
{
#define HELP "\
SYNOPSIS\n\
\n\
titan [flags] [options]\n\
\n\
OPTIONS\n\
\n\
-i --init <path> Initialize new database\n\
-e --encrypt Encrypt current database\n\
-d --decrypt <path> Decrypt database\n\
-a --add Add new entry\n\
-s --show-db-path Show current database path\n\
-u --use-db Switch using another database\n\
-r --remove <id> Remove entry pointed by id\n\
-f --find <search> Search entries\n\
-c --edit <id> Edit entry pointed by id\n\
-l --list-entry <id> List entry pointed by id\n\
-A --list-all List all entries\n\
-h --help Show short help and exit. This page\n\
-g --gen-password <length> Generate password\n\
-q --quick <search> This is the same as running\n\
--auto-encrypt --show-passwords -f\n\
\n\
-V --version Show version number of program\n\
\n\
FLAGS\n\
\n\
--auto-encrypt Automatically encrypt after exit\n\
--show-passwords Show passwords in listings\n\
--force Ignore everything and force operation\n\
--force only works with --init option\n\
\n\
For more information and examples see man titan(1).\n\
\n\
AUTHORS\n\
Copyright (C) 2017 Niko Rosvall <niko@byteptr.com>\n\
"
printf(HELP);
}
int main(int argc, char *argv[])
{
int c;
if(argc == 1)
{
usage();
return 0;
}
while(true)
{
static struct option long_options[] =
{
{"init", required_argument, 0, 'i'},
{"decrypt", required_argument, 0, 'd'},
{"encrypt", no_argument, 0, 'e'},
{"add", no_argument, 0, 'a'},
{"remove", required_argument, 0, 'r'},
{"find", required_argument, 0, 'f'},
{"edit", required_argument, 0, 'c'},
{"list-entry", required_argument, 0, 'l'},
{"use-db", required_argument, 0, 'u'},
{"list-all", no_argument, 0, 'A'},
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"show-db-path", no_argument, 0, 's'},
{"gen-password", required_argument, 0, 'g'},
{"quick", required_argument, 0, 'q'},
{"auto-encrypt", no_argument, &auto_encrypt, 1},
{"show-passwords", no_argument, &show_password, 1},
{"force", no_argument, &force, 1},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long(argc, argv, "i:d:ear:f:c:l:Asu:hVg:q:", long_options, &option_index);
if(c == -1)
break;
switch(c)
{
case 0:
/* Handle flags here automatically */
break;
case 'i':
init_database(optarg, force, auto_encrypt);
break;
case 'd': //decrypt
decrypt_database(optarg);
break;
case 'e': //encrypt
encrypt_database();
break;
case 'a':
add_new_entry(auto_encrypt);
break;
case 's':
show_current_db_path();
break;
case 'h':
usage();
break;
case 'r':
remove_entry(atoi(optarg), auto_encrypt);
break;
case 'u':
set_use_db(optarg);
case 'f':
find(optarg, show_password, auto_encrypt);
break;
case 'c':
edit_entry(atoi(optarg), auto_encrypt);
break;
case 'l':
list_by_id(atoi(optarg), show_password, auto_encrypt);
break;
case 'A':
list_all(show_password, auto_encrypt);
break;
case 'V':
version();
break;
case 'g':
generate_password(atoi(optarg));
break;
case 'q':
auto_encrypt = 1;
show_password = 1;
find(optarg, show_password, auto_encrypt); //TODO: implement auto_encrypt. it's only possible to use it if database is encrypted
//first decrypt, then keep the passphrase in a stack and use it to encrypt after the operation
break;
case '?':
usage();
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#define MAX_NAME_LENGHT 256
#define BUF_SIZE 128
int main(int argc, char **argv) {
int logicalSize, fileSize, bufSizeReal = BUF_SIZE, i;
int sd, port, len, fd, ris;
const int on = 1;
struct sockaddr_in cliaddr, servaddr;
struct hostent *clienthost;
char fileName[MAX_NAME_LENGHT];
int result, count;
char buf[BUF_SIZE];
//Controllo argomenti
if (argc != 2) {
printf("Error Usage : %s port \n", argv[0]);
exit(1);
}
printf("NUMERO ARGC CONTROLLATO\n");
len = 0;
while (argv[1][len] != '\0') {
if (argv[1][len] < '0' || argv[1][len] > '9') {
printf("Argument passed is not a integer");
exit(1);
}
len++;
}
printf("PORT CONTROLLATA\n");
port = atoi(argv[1]);
if (port < 1024 || port > 65535) {
printf("Error: incorrect number port ");
exit(1);
}
printf("ARGOMENTI CONTROLLATI\n");
//inizializzo indirizzo server
memset((char*) &servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(port);
//creazione socket
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd < 0) {
perror("Error creating socket ");
exit(1);
}
printf("Server: socket created, sd = %d\n", sd);
//opzioni socket
if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
perror("set opzions socket ");
exit(1);
}
printf("Server: Socket Options setted ok\n");
// connessione socket
if (bind(sd, (struct sockaddr*) &servaddr, sizeof(servaddr)) < 0) {
perror("bind socket ");
exit(1);
}
printf("Server: bind socket ok\n");
//INZIO BODY
while (1) {
//ricevo nomeFile
len = sizeof(struct sockaddr_in);
if (recvfrom(sd, &fileName, sizeof(fileName), 0, (struct sockaddr*) &cliaddr, &len) < 0) {
perror("recvfrom");
continue;
}
printf("Operazione richiesta sul file %s \n", fileName);
clienthost = gethostbyaddr((char*) &cliaddr.sin_addr,sizeof(cliaddr.sin_addr), AF_INET);
if (clienthost == NULL)
printf("client host information not found\n");
else
printf("Operation required from: %s %i\n", clienthost->h_name,
(unsigned) ntohs(cliaddr.sin_port));
//trovare lunghezza della parola piu lunga
fd = open(fileName, O_RDONLY);
if (fd < 0) {
printf("Impossible open %s\n", fileName);
result = -1;
} else {
fileSize = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
if (fileSize < bufSizeReal) {
bufSizeReal = fileSize;
}
count=0;
result=0;
while (read(fd, &buf, bufSizeReal * sizeof(char)) > 0) {
logicalSize = sizeof(buf) / sizeof(buf[0]);
for (i = 0; i < logicalSize; i++) {
if (buf[i] == ' ' || buf[i] == '\n' || buf[i] == '\t') {
if (count > result) {
result = count;
}
count = 0;
} else {
count++;
}
}
// Flush array
memset(buf, 0, bufSizeReal * (sizeof buf[0]));
}
}
close(fd);
printf("RESULT: %d \n ", result);
result = htonl(result);
if (sendto(sd, &result, sizeof(result), 0, (struct sockaddr*) &cliaddr,
len) < 0) {
perror("ERROR sendto");
continue;
}
}
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
#define MAX 100
#define infinity 9999
#define nil -1
#define white 0
#define grey 1
#define black 2
void push(int stack[],int *top,int i);
int pop(int stack[], int *top);
void enqueue(int q[],int *front,int *rear,int i);
int dequeue(int q[],int *front,int *rear);
void bfs(int arr[][MAX], int v,int s,int state[],int path[],int pred[],int q[],int *front,int *rear);
void dfs(int arr[][MAX], int v,int s,int state[],int path[],int pred[],int stack[],int *front);
void dfs_rec(int arr[][MAX],int v,int i,int state[],int dis[],int fin[],int *time);
void short_bfs(int arr[][MAX], int v,int s,int des,int state[],int path[],int pred[],int stack[],int *front,int *rear);
void ins_edge(int arr[][MAX], int v,int i,int j);
void del_edge(int arr[][MAX], int v,int i,int j);
void display(int arr[][MAX],int v);
void create_graph(int arr[][MAX], int v);
void warshall(int arr[][MAX], int v);
int main(){
int arr[MAX][MAX]= {0}, state[MAX], pred[MAX], path[MAX],q[MAX],stack[MAX],dis[MAX],fin[MAX];
int i,j,v,front = -1,rear =-1, top = -1,time= 0;
scanf("%d",&v);
for(i = 1; i<=v; i++){
state[i] = white;
pred[i] = nil;
path[i] = infinity;
}
for(i = 1; i<=v; i++){
for(j = 1; j<=v; j++){
scanf("%d",&arr[i][j]);
}
}
//create_graph(arr,v);
display(arr,v);
//warshall(arr,v);
scanf("%d%d",&i,&j);
short_bfs(arr,v,i,j,state,path,pred,q,&front,&rear);
dfs(arr,v,j,state,path,pred,stack,&top);
for(i = 0; i<v; i++){
state[i] = white;
pred[i] = nil;
path[i] = infinity;
}
dfs_rec(arr,v,j,state,dis,fin,&time);
for(i = 1; i<=v; i++){
printf("%d id dis & %d is fin of %d\n",dis[i],fin[i],i);
}
return 0;
}
void push(int stack[],int *top,int i){
if(*top == 99){
printf("overflow\n");
return;
}
(*top)++;
stack[*top] = i;
}
int pop(int stack[], int *top){
if(*top == -1){
printf("underflow\n");
return;
}
int i = stack[(*top)--];
return i;
}
void enqueue(int q[],int *front,int *rear,int i){
if(*front == (*rear+1) % MAX ){
printf("overflow\n");
return;
}
if(*front == -1)
(*front)++;
*rear = (*rear +1) %MAX;
q[*rear] = i;
}
int dequeue(int q[],int *front,int *rear){
if(*front == -1){
printf("underflow\n");
return;
}
int i = q[*front];
if(*front == *rear)
*front = *rear = -1;
else *front = (*front +1) %MAX;
return i;
}
void bfs(int arr[][MAX], int v,int s,int state[],int path[],int pred[],int q[],int *front,int *rear){
int cur,i;
enqueue(q,front,rear,s);
state[s] = grey;
path[s] = 1;
pred[s] = nil;
while(*front != -1){
cur = dequeue(q,front,rear);
state[cur] = black;
printf("%d_",cur);
for(i =1; i<= v; i++){
if(arr[cur][i] != 0 && state[i] == white){
enqueue(q,front,rear,i);
state[i] = grey;
path[i] = path[cur] + 1;
pred[i] = cur;
}
}
}
printf("\n");
}
void dfs(int arr[][MAX], int v,int s,int state[],int path[],int pred[],int stack[],int *front){
int cur,i;
for(i = 1; i<= v; i++){
state[i] = white;
pred[i] = nil;
path[i] = infinity;
}
push(stack,front,s);
path[s] = 1;
pred[s] = nil;
while(*front != -1){
cur = pop(stack,front);
if(state[cur] == white)
printf("%d_",cur);
state[cur] = black;
for(i =v; i>0; i--){
if(arr[cur][i] != 0 && state[i] == white){
push(stack,front,i);
path[i] = path[cur] + 1;
pred[i] = cur;
}
}
}
printf("\n");
}
void dfs_rec(int arr[][MAX],int v,int s,int state[],int dis[],int fin[],int *time){
state[s] = grey;
(*time)++;
dis[s] = *time;
printf("%d + ",s);
int i;
for(i =1;i <=v; i++){
if(arr[s][i] != 0 && state[i] == white){
dfs_rec(arr,v,i,state,dis,fin,time);
}
}
state[s] = black;
fin[s] = (*time)++;
}
void short_bfs(int arr[][MAX], int v,int s,int des,int state[],int path[],int pred[],int q[],int *front,int *rear){
bfs(arr,v,s,state,path,pred,q,front,rear);
if(pred[des] == nil){
//printf("no pred\n");
return;
}
int pat[MAX] ,i = 0,j,u;
while(pred[des] != nil){
pat[i++] = pred[des];
u = pred[des];
des = u;
}
for(j = 0; j<i; j++){
printf("%d ",pat[j]);
}
}
void warshall(int arr[][MAX], int v){
int path[MAX][MAX],i,j,k;
for(k =1; k<=v; k++){
for(i = 1; i<=v; i++)
path[k][i] = arr[k][i];
}
for(k =1; k<=v; k++){
for(i = 1; i<=v; i++){
for(j =1; j<=v; j++){
if(path[i][j] == 1 || (path[i][k] && path[k][j]))
path[i][j] = 1;
else path[i][j] = 0;
}
}
}
for(i = 1; i<=v; i++){
for(j =1; j<=v; j++)
printf("%d ",path[i][j]);
printf("\n");
}
}
void dijkshtra(int arr[][MAX], int v,int s,int path[]){
}
void ins_edge(int arr[][MAX], int v,int i,int j){
if(i >v || j> v){
printf("vertices not exist\n");
return;
}
arr[i][j] = 1;
}
void del_edge(int arr[][MAX], int v,int i,int j){
if(i >v || j> v){
printf("vertices not exist\n");
return;
}
arr[i][j] = 0;
}
void display(int arr[][MAX],int v){
int i,j;
for(i =1; i<=v; i++){
for(j =1; j<=v; j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
printf("\n");
}
void create_graph(int arr[][MAX], int v){
int i,s,d;
for(i = 1; i<v *(v-1); i++){
scanf("%d%d",&s,&d);
if(s <= -1 || d <= -1)
return;
if(s > v || d > v){
i--;
continue;
}
arr[s][d] = 1;
}
}
|
C
|
#include<stdio.h>
#define sqr(x) ((x)*(x))
#define cube(x) ((x)*(x)*(x))
#define abs(x) ((x) > 0 ? (x) : (-x))
#define min_of(x,y) ((x) > (y) ? (y) : (x))
#define max_of(x,y) ((x) > (y) ? (x) : (y))
#define diff(x,y) ((x) > (y) ? ((x)-(y)) : ((y)-(x)))
#define swap(type,x,y) do{ type tmp = x; x = y; y = tmp; }while(0)
#define put_alert2(str) (putchar('\a'),puts(str))
void reverse(double v[],int n){
int i;
for(i = 0; i < n/2; i++){
swap(double,v[i],v[n-i-1]);
}
}
void print_v(double v[],int n){
int i;
for(i = 0;i < n; i++){
printf("v[%d] = %lf\n",i,v[i]);
}
}
void bsort(double *v,int n){
int i,j;
for(i = 0; i < n; i++){
for(j = n-1; j > i; j--){
if(v[j] < v[j-1])
swap(double ,v[j], v[j-1]);
}
}
}
int main(void){
int n1 = 21;
int n2 = 6;
int n3 = 0;
int x = 15;
int y = 5;
double v[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.2 };
char *str = "awefoawiejfaowiejf";
print_v(v,10);
reverse(v,10);
print_v(v,10);
bsort(v,10);
print_v(v,10);
put_alert2(str);
printf("x = %d, y = %d \n",x,y);
swap(double,x,y);
printf("x = %d, y = %d \n",x,y);
swap(double,x,y);
printf("\"ABC\"\n");
printf("\'ABC\'\n");
printf("'ABC'\n");
putchar('\"');
putchar('\n');
putchar(7 + '0');
putchar('\n');
printf("5 = %d \n",'5'- '0');
printf("diff(x++,y) = %d = 10\n",diff(x++,y));
printf("diff(++x,y) = %d = 12\n",diff(++x,y));
printf("diff(%d,%d) = %d\n",n1,n2,diff(n1,n2));
printf("diff(%d,%d) = %d\n",n2,n1,diff(n2,n1));
printf("min_of(%d,%d) = %d\n",n2,n1,min_of(n2,n1));
printf("min_of(%d,%d) = %d\n",n2,n1,min_of(n2,n1));
printf("max_of(%d,%d) = %d\n",n1,n2,max_of(n1,n2));
printf("max_of(%d,%d) = %d\n",n2,n1,max_of(n2,n1));
printf("abs(-%d) = %d \n",n1,abs(-n1));
printf("abs(%d) = %d \n",n1,abs(n1));
printf("sqr(%d) = %d \n",n1,sqr(n1));
printf("cube(%d) = %d \n",n1,cube(n1));
printf("21,6 n1 = %2d ,n2 = %2d\n",n1 ,n2);
printf("6 ,0 n2 = %2d ,n3 = %2d\n",n2 ,n3);
printf("21,6 n1++ = %2d ,n2++ = %2d\n",n1++ ,n2++);
printf("1 ,7 1 = %2d ,n2 = %2d\n",1 ,n2);
printf("22,7 n1 = %2d ,n2 = %2d\n",n1 ,n2);
printf("%2d,7 n1 = (n1,n2)\n",n1 = (n1,n2));
printf("%2d,7 n1 / (n2,++n3)\n",n1 / (n2,++n3));
printf("\a");
printf("\b");
printf("\\");
printf("\r");
printf("\'");
printf("\n");
printf("\t");
printf("\"");
printf("EOF = %d (EOF < 0 ) == %d",EOF,EOF < 0);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/input.h>
void usage ( int argc, char *argv[] )
{
printf("Usage:\n\t%s key\n\nvalid keys are:\n" , argv[0]);
printf("\tlshift\t- Left Shift key\n");
printf("\trshift\t- Right Shift key\n");
printf("\tlalt\t- Left Alt key\n");
printf("\tralt\t- Right Alt key\n");
printf("\tlctrl\t- Left Ctrl key\n");
printf("\trctrl\t- Right Ctrl key\n");
exit(EXIT_FAILURE);
}
int main ( int argc, char *argv[], char *env[] )
{
if ( argc != 2 ) usage(argc, argv);
int key;
if ( strcmp(argv[1], "lshift") == 0 ) key = KEY_LEFTSHIFT;
else if ( strcmp(argv[1], "rshift") == 0 ) key = KEY_RIGHTSHIFT;
else if ( strcmp(argv[1], "lalt") == 0 ) key = KEY_LEFTALT;
else if ( strcmp(argv[1], "ralt") == 0 ) key = KEY_RIGHTALT;
else if ( strcmp(argv[1], "lctrl") == 0 ) key = KEY_LEFTCTRL;
else if ( strcmp(argv[1], "rctrl") == 0 ) key = KEY_RIGHTCTRL;
FILE *kbd = fopen("/dev/input/by-path/platform-i8042-serio-0-event-kbd", "r");
if (!kbd) {
printf("Cannot get keyboard state");
exit(EXIT_FAILURE);
}
char key_map[KEY_MAX/8 + 1]; // Create a byte array the size of the number of keys
memset(key_map, 0, sizeof(key_map)); // Initate the array to zero's
ioctl(fileno(kbd), EVIOCGKEY(sizeof(key_map)), key_map); // Fill the keymap with the current keyboard state
int keyb = key_map[key/8]; // The key we want (and the seven others arround it)
int mask = 1 << (key % 8); // Put a one in the same column as out key state will be in;
return !(keyb & mask); // Returns true if pressed otherwise false
}
|
C
|
#include "monty.h"
#define NO_PINT ("L%d: can't pint, stack empty\n")
#define NO_POP ("L%d: can't pop, an empty stack\n")
#define NO_MALLOC ("Error: malloc failed\n")
#define NO_SWAP ("L%d: cant swap, stack too short\n")
/**
* p_all - print all values on the stack
*
* @stack: double pointer to the head of a doubly linked list (the stack)
* @line_number: unused
*
* Return: void
*/
void p_all(stack_t **stack, unsigned int line_number)
{
stack_t *node;
(void)line_number;
if (!(stack) || (!(*stack)))
return;
/*dprintf(STDERR_FILENO, NO_MALLOC);*/
node = *stack;
for (; node; node = node->next)
printf("%d\n", node->n);
}
/**
* p_int - prints the value at the top of the stack
*
* @stack: double pointer to the head of a doublky linked list (the stack)
* @line_number: unused
*
* Return: void
*/
void p_int(stack_t **stack, unsigned int line_number)
{
(void)line_number;
if (!*stack || !stack)
{
fclose((FILE *)to_free[0]);
free(to_free[1]);
dprintf(STDERR_FILENO, NO_PINT, line_number), free_stack(*stack), EXIT_F;
}
printf("%d\n", (*stack)->n);
}
/**
* pop_it - removes the top element of the stack
*
* @stack: double pointer to the head of a doubly linked list (the stack)
* @line_number: line number error
*
* Return: void
*/
void pop_it(stack_t **stack, unsigned int line_number)
{
stack_t *node;
if (!stack || (!*stack))
{
fclose((FILE *)to_free[0]);
free((char *)to_free[1]);
dprintf(STDERR_FILENO, NO_POP, line_number), free_stack(*stack), EXIT_F;
}
node = (*stack)->next;
(*stack)->next = NULL;
(*stack)->prev = NULL;
free(*stack);
*stack = node;
}
/**
* swap_it - swaps the top two elemets of the stack
*
* @stack: double pointer to the head of a doubly linked list (the stack)
* @line_number: line number error
*
* Return: void
*/
void swap_it(stack_t **stack, unsigned int line_number)
{
stack_t *node, *nother_node, *tmp;
int count = 0;
if (!stack || !*stack)
{
dprintf(STDERR_FILENO, NO_SWAP, line_number);
free_stack(*stack), EXIT_F;
fclose((FILE *)to_free[0]);
free((char *)to_free[1]);
}
node = *stack;
nother_node = (*stack)->next;
while (node)
{
node = node->next;
count++;
}
node = *stack;
if (count <= 1)
{
fclose((FILE *)to_free[0]);
free((char *)to_free[1]);
dprintf(STDERR_FILENO, NO_SWAP, line_number), free_stack(*stack), EXIT_F;
}
tmp = nother_node->next;
nother_node->next = node;
nother_node->prev = NULL;
node->prev = nother_node;
node->next = tmp;
if (tmp)
tmp->prev = node;
*stack = nother_node;
}
/**
* no_op - Does nothing
*
* @stack: unused
* @line_number: unused
*
* Return: void
*/
void no_op(__attribute__ ((unused)) stack_t **stack, unsigned int line_number)
{
(void)line_number;
}
|
C
|
#include "uart.h"
#define BAUD_RATE 115200
void init_UART() {
RCC->APB2ENR |= RCC_APB2ENR_USART1EN;
/* Set PA9 to USART1_TX */
GPIOA->CRH &=~GPIO_CRH_CNF9_0;
GPIOA->CRH |= GPIO_CRH_CNF9_1 | GPIO_CRH_CNF9_0;
GPIOA->CRH |= GPIO_CRH_MODE9_1 | GPIO_CRH_MODE9_0;
/* Assuming Baud Rate of 230400 by a clock of 64MHz Core Clock*/
USART1->GTPR |= 1;
USART1->BRR = 17 << 4;
USART1->BRR |= 6;
USART1->CR1 |= USART_CR1_TE;
USART1->CR1 |= USART_CR1_UE;
}
void send_char(char c) {
USART1->DR = c;
while(!(USART1->SR & USART_SR_TXE))
asm volatile ("nop");
}
void send_str(char *c, int size) {
for(uint8_t i = 0; i < size; i++)
send_char(c[i]);
}
|
C
|
// ĐẶng Lâm San 20170111
#include <stdio.h>
#include <conio.h>
int main() {
char s;
int n;
printf("Nhap vao ky tu ");
scanf("%c",&s);
printf("\n So tuong ung %d",s);
printf("\nNhap vao so ");
scanf("%d",&n);
printf("\n ky tu tuong ung %c",n);
printf("\nDANG LAM SAN 20170111");
return 0;
}
|
C
|
//
// Created by Stefan Andonov on 11/18/20.
//
/*
* Да се напише програма за „диплење на број во десно“. Диплење во десно е дефинирано на следниов начин:
Секоја цифра од левата половина на бројот се додава на соодветната спротивна цифра од десната половина на бројот (и се отстранува од бројот) – првата се додава на последната, втората на претпоследната, итн. Собирањето на цифрите се прави модуло 10 така што доколку при собирање на две цифри се добие број поголем од 9, се зема само цифрата на единиците. Доколку бројот има непарен број цифри, средишната цифра се додава самата на себе и не се отстранува (станува прва цифра на новодобиениот број). Да се напише програма која за даден цел број n>=10 ќе го отпечати бројот здиплен во десно. Задачата да се реши без употреба на низи.
Za doma: zdipleno od desno kon levo da se reshi.
* */
#include<stdio.h>
#include <math.h>
int main () {
int n;
scanf("%d", &n);
int brojNaCifri = 0;
//1. broj na cifri na brojot
int temp = n;
while (temp) {
temp/=10;
++brojNaCifri;
}
// printf("%d", brojNaCifri);
int desnaPolovina = n % (int) pow(10,brojNaCifri/2);
int levaPolovina;
int srednaCifra = 0;
if (brojNaCifri%2==0)
levaPolovina = n / pow(10,brojNaCifri/2);
else {
levaPolovina = n / pow(10, brojNaCifri / 2 + 1);
srednaCifra = n / (int) pow(10,brojNaCifri/2) % 10;
}
temp = levaPolovina;
int obratnaLevaPolovina = 0;
while (temp) {
obratnaLevaPolovina = 10*obratnaLevaPolovina + temp%10;
temp/=10;
}
int rezultat = 0;
int koef = 1;
while(obratnaLevaPolovina) {
rezultat += ((obratnaLevaPolovina%10 + desnaPolovina%10) % 10) * koef;
koef*=10;
obratnaLevaPolovina/=10;
desnaPolovina/=10;
}
if (brojNaCifri%2==1) {
rezultat += 2 * srednaCifra * (int) pow (10,brojNaCifri/2);
}
printf("%d", rezultat);
// if (brojNaCifri%2==0) { //paren broj na cifri
// int levaPolovina = n / pow(10,brojNaCifri/2);
// int desnaPolovina = n % (int) pow(10,brojNaCifri/2);
//
//
//
// int rezultat = 0;
// int koef = 1;
// while(obratnaLevaPolovina) {
// rezultat += ((obratnaLevaPolovina%10 + desnaPolovina%10) % 10) * koef;
// koef*=10;
// obratnaLevaPolovina/=10;
// desnaPolovina/=10;
// }
// printf("%d", rezultat);
//
// } else { //neparen broj na cifri (igranje so sredna cifra)
// int levaPolovina = n / (int) pow(10,(brojNaCifri/2) + 1);
// int srednaCifra = n / (int) pow(10,brojNaCifri/2) % 10;
// int desnaPolovina = n % (int) pow(10,brojNaCifri/2);
//
// temp = levaPolovina;
// int obratnaLevaPolovina = 0;
// while (temp) {
// obratnaLevaPolovina = 10 * obratnaLevaPolovina + temp % 10;
// temp /= 10;
// }
//
// int rezultat = 0;
// int koef = 1;
// while(obratnaLevaPolovina) {
// rezultat += ((obratnaLevaPolovina%10 + desnaPolovina%10) % 10) * koef;
// koef*=10;
// obratnaLevaPolovina/=10;
// desnaPolovina/=10;
// }
//
//
// printf("%d", rezultat);
// }
return 0;
}
|
C
|
/*
Roman calculator: performs addition and subtraction of roman values
Author: Vinay vittal Karagod
File dependents: main.c, calculator.h, calculator.c,calculator-test.check
Date: 08/21/2016
calculator.h: Header file where all the functions are refered
*/
#ifndef calculator_H
#define calculator_H
char * calculate(char roman_number1[50],char roman_number2[50], int option);
int romanValue(char c);
int roman_decimal(char number[]);
void predigits(char character1,char character2);
void postdigits(char character,int count);
char * decimal_roman(int total);
#endif
|
C
|
/*三角形判定*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int temp;
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c) != EOF)
{
if(a > b){
temp = b;
b = a;
a = temp;
}
if(b > c){
temp = b;
b = c;
c = temp;
}
if(a*a + b*b > c*c)
printf("锐角三角形\n");
else if(a*a + b*b == c*c)
printf("直角三角形\n");
else
printf("钝角三角形\n");
}
return 0;
}
|
C
|
/**
***************************************************************************************************
* @file equ_Hygrometre.c
* @author j.daheron
* @version 1.0.0
* @date 21 sept. 2014
* @brief Gestion de l'Hygrometrie.
***************************************************************************************************
*/
/* Includes ***************************************************************************************/
#include "equ_Hygrometre.h"
/* External Variables *****************************************************************************/
/** @addtogroup equ_Hygrometre
* @{
*/
/**
***************************************************************************************************
* @defgroup Private_TypesDefinitions Private TypesDefinitions
* @{
*/
/**
* @}
*/
/**
***************************************************************************************************
* @defgroup Private_Defines Private Defines
* @{
*/
#define NB_ECHANTILLONS 100
/**
* @}
*/
/**
***************************************************************************************************
* @defgroup Private_Macros Private Macros
* @{
*/
/**
* @}
*/
/**
***************************************************************************************************
* @defgroup Private_FunctionPrototypes Private FunctionPrototypes
* @{
*/
/**
* @}
*/
/**
***************************************************************************************************
* @defgroup Private_Variables Private Variables
* @{
*/
static uint32_t Acq_Values[NB_ECHANTILLONS] = {0};
/**
* @}
*/
/**
***************************************************************************************************
* @defgroup Private_Functions Private Functions
* @{
*/
/**
***************************************************************************************************
* @brief Ajout d'une valeur d'acquisition.
* @return void.
*/
void
AddAcquisitionValue(
uint32_t ADC_Value /**<[in] Valeur d'ADC.*/
)
{
static int iBuffer = 0;
Acq_Values[iBuffer] = ADC_Value;
iBuffer++;
if (iBuffer >= NB_ECHANTILLONS)
iBuffer = 0;
}
/**
* @}
*/
/**
***************************************************************************************************
* @brief Initialisation de l'acquisition d'Hygrometrie.
* @return void
*/
void
Hygrometre_Init(
void
)
{
ADC1_ChannelConf_t ADC_Channel = {0};
MappingGpio_s PinConfig = {0};
uint32_t ID_ADC_Channel;
uint32_t Index = 0;
uint32_t port;
PinConfig = GPIO_GetPinConfiguration(PORT_TRIM);
// Effacement du buffer de filtrage
for (int i=0; i<NB_ECHANTILLONS; i++)
Acq_Values[i] = 0;
// Initialisation de l'ADC
ADC_Channel.ADCx = (ADC_TypeDef *) PinConfig.PERIPH;
ADC_Channel.ADC_Channel = PinConfig.PARAM;
ADC_Channel.pStoreValue_mV = NULL;
ADC_Channel.pFct_CallbackEOC = AddAcquisitionValue;
ID_ADC_Channel = ADC1_ChannelConfigure(ADC_Channel);
ADC1_ConversionContinue_Activer(ID_ADC_Channel);
}
/**
***************************************************************************************************
* @brief Lecture de la valeur actuelle d'Hygrometrie.
* @return Hygrometrie en pr100.
*/
uint16_t
Hygrometre_GetValue(
void
)
{
uint32_t MoyenneADC = 0;
// Moyennage
for (int i=0; i<NB_ECHANTILLONS; i++)
MoyenneADC += Acq_Values[i];
MoyenneADC /= NB_ECHANTILLONS;
return (uint16_t) MoyenneADC;
}
/**
* @}
*/
/* End Of File ************************************************************************************/
|
C
|
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/PrintLib.h>
#include <stdio.h>
int vsnprintf(char *str, size_t size, const char *format, va_list ap)
{
CHAR8 localfmt[100];
UINTN i;
UINTN fmtlen = AsciiStrSize(format);
// copy fmt to our buffer
CopyMem(localfmt, format, fmtlen);
localfmt[fmtlen - 1] = 0;
// fix format
for (i = 1; localfmt[i]; i++) {
if (localfmt[i - 1] == '%' && localfmt[i] == 's')
localfmt[i] = 'a';
}
return AsciiVSPrint(str, size, localfmt, ap);
}
int snprintf(char *str, size_t size, const char *format, ...)
{
int err;
VA_LIST ap;
VA_START(ap, format);
err = vsnprintf(str, size, format, ap);
VA_END(ap);
return err;
}
int vprintf(const char *format, va_list ap)
{
CHAR8 buf[100];
vsnprintf(buf, ARRAY_SIZE(buf), format, ap);
DEBUG((DEBUG_ERROR, "%a", buf));
return 0;
}
int printf(const char *format, ...)
{
int err;
VA_LIST ap;
VA_START(ap, format);
err = vprintf(format, ap);
VA_END(ap);
return err;
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct node
{
struct node* next;
int val;
};
struct queue
{
struct node* tail;
struct node* head;
};
void push(int wartosc, struct queue* kolejka)
{
struct node* el = (struct node*)malloc(sizeof(struct node));
el->val = wartosc;
if (kolejka->tail == NULL)
{
el->next = NULL;
kolejka->tail = el;
kolejka->head = el;
}
else
{
el->next = kolejka->tail;
kolejka->tail = el;
}
}
int pop(struct queue* kolejka)
{
if (kolejka->head == NULL)
{
printf("The list is empty ");
return 0;
}
int val = kolejka->head->val;
if (kolejka->head == kolejka->tail)
{
free(kolejka->head);
kolejka->head = NULL;
kolejka->tail = NULL;
return val;
}
struct node* temp = kolejka->tail;
while (temp->next != kolejka->head)
{
temp = temp->next;
}
free(kolejka->head);
temp->next = NULL;
kolejka->head = temp;
return val;
}
void clear(struct queue* kolejka)
{
if (kolejka->tail != NULL)
{
struct node* temp = kolejka->tail;
while (temp->next != NULL)
{
temp = temp->next;
free(kolejka->tail);
kolejka->tail = temp;
}
}
}
void deleteList(struct queue* kolejka)
{
if (kolejka != NULL)
{
clear(kolejka);
free(kolejka);
}
}
struct queue* initLista(struct queue* kolejka)
{
deleteList(kolejka);
kolejka = (struct queue*)malloc(sizeof(struct queue));
kolejka->tail = NULL;
kolejka->head = NULL;
return kolejka;
}
void pushWrapper(struct list* lista)
{
printf("Enter the value: \n");
int val;
scanf("%d", &val);
push(val, lista);
}
int main()
{
struct queue* lista = NULL;
lista = initLista(lista);
int isQueueCreated = 0;
unsigned char znak;
do
{
printf("Enter the number: \n");
printf("1. Push element \n");
printf("2. Pop element \n");
znak = getch();
while (kbhit())
{
znak = getch();
}
switch(znak)
{
case '1':
pushWrapper(lista);
break;
case '2':
printf("%d\n", pop(lista));
break;
}
} while (znak != 27);
clear(lista);
deleteList(lista);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(){
long long int n_cut,s,i;
while(scanf("%lld",&n_cut)!=EOF){
if(n_cut<0)
break;
s=0;
for(i=1;i<=n_cut;i++)
s+=i;
printf("%lld\n",s+1);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void)
{
char ch;
int i, j = 0;
char str[50];
char a[20], b[20], op;
int fp = 0;
while ((ch = getchar()) != EOF) {
str[i++] = ch; //입력되는 문자를 str문자열에 저장
if (ch == '\n') { //개행 입력
//입력되는 문자가 숫자이거나 '.'이면 str문자열을 연산자 앞의 수인 a문자열에 저장
for(i = 0, j = 0; isdigit(str[i]) || str[i] == '.'; ) {
if (str[i] == '.') //수 중간에 '.'가 있으면 fp로 소수임을 표시
fp = 1;
a[j++] = str[i++];
}
a[j] = '\0';
for(; str[i] == ' '; i++); //공백 건너뛰기
op = str[i++]; //연산자를 str문자열에 저장
for(; str[i] == ' '; i++); //공백 건너뛰기
//a문자열과 같이 b문자열 저장
for(j = 0; isdigit(str[i]) || str[i] == '.'; ) {
if (str[i] == '.')
fp = 1;
b[j++] = str[i++];
}
b[j] = '\0';
switch (op) {
case '+': //연산자가 +면 : 덧셈
if(fp) //a b중 소수가 있으면 float형식으로 덧셈
printf("%f\n", atof(a) + atof(b));
else //소수가 없으면 int형식으로 덧셈
printf("%d\n", atoi(a) + atoi(b));
break;
case '-': //연산자가 -면 : 뺄셈
if(fp)
printf("%f\n", atof(a) - atof(b));
else
printf("%d\n", atoi(a) - atoi(b));
break;
case '*': //연산자가 *면 : 곱셈
if(fp)
printf("%f\n", atof(a) * atof(b));
else
printf("%d\n", atoi(a) * atoi(b));
break;
case '/': //연산자가 /면 : 나눗셈의 몫
if(fp)
printf("%f\n", atof(a) / atof(b));
else
printf("%d\n", atoi(a) / atoi(b));
break;
case '%': //연산자가 %면 : 나눗셈의 나머지
printf("%d\n", atoi(a) % atoi(b));
}
i = 0; fp = 0; //다음 연산을 위해 문자열 인덱스와 소수 표시 초기화
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int binarySearch(int key, int array[], int n);
void selectionSort(int array[], int n);
#define ARRAYSIZE 256
int main(int argc, char *argv[]) {
int space,i;
int j=0;
int *arrayOne;
int *arrayTwo;
int *arrayThree;
int a,b,c;
if(argc!=2) {
fprintf(stderr, "Usage: %s filename\n", argv[0]);
return 0;
}
FILE *fp = fopen(argv[1], "r");
if(!fp) {
fprintf(stderr, "Could not open %s\n", argv[1]);
return 0;
}
space=ARRAYSIZE;
arrayOne=malloc(space * sizeof(int));
arrayTwo=malloc(space * sizeof(int));
arrayThree=malloc(space * sizeof(int));
while(3==fscanf(fp, "%d %d %d", &a, &b, &c)) { //storing column contents in the 2 arrays
if(j>=space) {
space*=2;
arrayOne=realloc(arrayOne, space * sizeof(int));
arrayTwo=realloc(arrayTwo, space * sizeof(int));
arrayThree=realloc(arrayThree, space * sizeof(int));
}
arrayOne[j]=a;
arrayTwo[j]=b;
arrayThree[j]=c;
j++;
}
//selectionSort(arrayOne, j);
selectionSort(arrayOne, j);
for(i=0; i<=j; i++) {
if((binarySearch(arrayTwo[i], arrayOne, j)) && (binarySearch(arrayThree[i], arrayOne, j))) printf("%d\n", arrayThree[i]);
}
fclose(fp);
}
int binarySearch(int key, int array[], int n) {
int low, mid, high;
low=0;
high=n-1;
while(low<=high) {
mid=(low+high)/2;
if(key==array[mid]) return 1;
if(key<array[mid]) high=mid-1;
else low=mid+1;
}
return 0;
}
void selectionSort(int array[], int n) {
int i, j, k;
int min;
int where;
for(i=0; i<n-1; i++) {
min=array[i];
where=i;
for(j=i+1; j<n; j++)
if(array[j]<min) {
min=array[j];
where=j;
}
if(i!=where) {
array[where]=array[i];
array[i]=min;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
#define INIFITY 65535
typedef char POINTTYPE;
struct graphyic
{
POINTTYPE points[MAX];
int edges[MAX][MAX];
int pointNum;
int edgeNum;
};
typedef struct graphyic Graphyic;
typedef struct graphyic* pGraphyic;
void initGraphyic(pGraphyic pgraphyic)
{
int i,j;
if(NULL==pgraphyic)
return;
for(i=0; i<MAX; i++){
pgraphyic->points[i] = 0;
}
for(i=0; i<MAX; i++)
{
for(j=0; j<MAX; j++)
{
if(i==j)
pgraphyic->edges[i][j] = 0;
else
pgraphyic->edges[i][j] = INIFITY;
}
}
}
int getPos(pGraphyic pgraphyic, char target)
{
int i;
if(NULL==pgraphyic)
{
return -1;
}
for(i=0; i<pgraphyic->pointNum; i++)
{
if(target==pgraphyic->points[i])
{
return i;
}
}
return -1;
}
void printGraphyic(pGraphyic pgraphyic)
{
int i,j;
for(i=0; i<pgraphyic->pointNum; i++)
{
for(j=0; j<pgraphyic->pointNum; j++)
{
printf("%d", pgraphyic->edges[i][j]);
printf(" ");
}
printf("\n");
}
}
void createGraphyic(pGraphyic pgraphyic)
{
int i,pos1, pos2;
char t1, t2;
if(NULL==pgraphyic)
return;
initGraphyic(pgraphyic);
printf("INPUT THE POINTS:\n");
for(i=0; i<pgraphyic->pointNum; i++)
{
fflush(stdin);
scanf("%c", &(pgraphyic->points[i]) );
}
printf("INPUT EDGES:\n");
for(i=0; i<pgraphyic->edgeNum; i++){
fflush(stdin);
scanf("%c", &t1);
pos1 = getPos(pgraphyic, t1);
fflush(stdin);
scanf("%c", &t2);
pos2 = getPos(pgraphyic, t2);
pgraphyic->edges[pos1][pos2] = 1;
}
printGraphyic(pgraphyic);
}
void main()
{
pGraphyic pgraphyic;
pgraphyic = (pGraphyic)malloc(sizeof(Graphyic));
if(NULL==pgraphyic)
{
return;
}
pgraphyic->pointNum = 6;
pgraphyic->edgeNum = 1;
createGraphyic(pgraphyic);
}
|
C
|
#include <stdio.h>
void main()
{
int i;
enum month
{
JAN,
FEB,
MAR,
APR,
MAY,
JUN,
JUL,
AUG,
SEP,
OCT,
DEC
};
for (i = JAN; i <= DEC; i++)
printf("\n%d", i);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct node
{
int data;
struct node *next;
struct node *prev;
};
struct node *start=NULL;
void display()
{
struct node *p,*temp;
p=start;
do
{
printf("%d",p->data);
p=p->next;
}while(p!=start);
}
void insertatbeg()
{
int item;
struct node *temp,*p;
printf("enter the item to insert at begining\n ");
scanf("%d",&item);
temp=(struct node*)malloc(sizeof(struct node));
temp->data=item;
temp->next=NULL;
temp->next=start;
p=start;
while(p->next!=start)
{
p=p->next;
}
p->next=temp;
start=temp;
}
void insertatend()
{
int item;
struct node *temp,*p;
printf("enter the item to be inseted at end\n");
scanf("%d",&item);
temp=(struct node*)malloc(sizeof(struct node));
temp->data=item;
temp->next=NULL;
p=start;
while(p->next!=start)
{
p=p->next;
}
p->next=temp;
temp->next=start;
}
void insertatloc()
{
struct node *temp,*p,*preptr;
int pos,item;
printf("enter the pos");
scanf("%d",&pos);
printf("enter the data\n");
scanf("%d",&item);
temp=(struct node *)malloc(sizeof(struct node));
temp->data=item;
p=start;
while(p->data!=pos)
{
preptr=p;
p=p->next;
}
temp->next=p;
preptr->next=temp;
}
int main()
{
struct node *p,*temp;
int choice=1,item;
while(choice)
{
printf("enter the data\n");
scanf("%d",&item);
temp=(struct node*)malloc(sizeof(struct node));
temp->data=item;
temp->next=NULL;
if(start == NULL)
{
start=temp;
temp->next=start;
}
else
{
p=start;
while(p->next!=start)
{
p=p->next;
}
p->next=temp;
temp->next=start;
}
printf("continue?");
scanf("%d",&choice);
}
/*insertatbeg();
insertatend();*/
insertatloc();
display();
}
|
C
|
/* Sets the ascii codepage
* Returns 1 if successful or -1 on error
*/
int info_handle_set_ascii_codepage(
info_handle_t *info_handle,
const system_character_t *string,
libcerror_error_t **error )
{
static char *function = "info_handle_set_ascii_codepage";
size_t string_length = 0;
uint32_t feature_flags = 0;
int result = 0;
if( info_handle == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid info handle.",
function );
return( -1 );
}
feature_flags = LIBCLOCALE_CODEPAGE_FEATURE_FLAG_HAVE_WINDOWS;
string_length = system_string_length(
string );
#if defined( HAVE_WIDE_SYSTEM_CHARACTER )
result = libclocale_codepage_copy_from_string_wide(
&( info_handle->ascii_codepage ),
string,
string_length,
feature_flags,
error );
#else
result = libclocale_codepage_copy_from_string(
&( info_handle->ascii_codepage ),
string,
string_length,
feature_flags,
error );
#endif
if( result == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_GET_FAILED,
"%s: unable to determine ASCII codepage.",
function );
return( -1 );
}
return( result );
}
|
C
|
/*
* fat.c
*
* R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
*
* 2002-07-28 - rjones@nexus-tech.net - ported to ppcboot v1.1.6
* 2003-03-10 - kharris@nexus-tech.net - ported to uboot
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <config.h>
#include <exports.h>
#include <fat.h>
#include <asm/byteorder.h>
#include <part.h>
#include <malloc.h>
#include <linux/compiler.h>
#include <linux/ctype.h>
#ifdef CONFIG_SUPPORT_VFAT
static const int vfat_enabled = 1;
#else
static const int vfat_enabled = 0;
#endif
/*
* Convert a string to lowercase.
*/
static void downcase(char *str)
{
while (*str != '\0') {
*str = tolower(*str);
str++;
}
}
static block_dev_desc_t *cur_dev;
static disk_partition_t cur_part_info;
#define DOS_BOOT_MAGIC_OFFSET 0x1fe
#define DOS_FS_TYPE_OFFSET 0x36
#define DOS_FS32_TYPE_OFFSET 0x52
static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
{
if (!cur_dev || !cur_dev->block_read)
return -1;
return cur_dev->block_read(cur_dev->dev,
cur_part_info.start + block, nr_blocks, buf);
}
int fat_set_blk_dev(block_dev_desc_t *dev_desc, disk_partition_t *info)
{
ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
cur_dev = dev_desc;
cur_part_info = *info;
/* Make sure it has a valid FAT header */
if (disk_read(0, 1, buffer) != 1) {
cur_dev = NULL;
return -1;
}
/* Check if it's actually a DOS volume */
if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
cur_dev = NULL;
return -1;
}
/* Check for FAT12/FAT16/FAT32 filesystem */
if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
return 0;
if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
return 0;
cur_dev = NULL;
return -1;
}
int fat_register_device(block_dev_desc_t *dev_desc, int part_no)
{
disk_partition_t info;
/* First close any currently found FAT filesystem */
cur_dev = NULL;
/* Read the partition table, if present */
if (get_partition_info(dev_desc, part_no, &info)) {
if (part_no != 0) {
printf("** Partition %d not valid on device %d **\n",
part_no, dev_desc->dev);
return -1;
}
info.start = 0;
info.size = dev_desc->lba;
info.blksz = dev_desc->blksz;
info.name[0] = 0;
info.type[0] = 0;
info.bootable = 0;
#ifdef CONFIG_PARTITION_UUIDS
info.uuid[0] = 0;
#endif
}
return fat_set_blk_dev(dev_desc, &info);
}
/*
* Get the first occurence of a directory delimiter ('/' or '\') in a string.
* Return index into string if found, -1 otherwise.
*/
static int dirdelim(char *str)
{
char *start = str;
while (*str != '\0') {
if (ISDIRDELIM(*str))
return str - start;
str++;
}
return -1;
}
/*
* Extract zero terminated short name from a directory entry.
*/
static void get_name(dir_entry *dirent, char *s_name)
{
char *ptr;
memcpy(s_name, dirent->name, 8);
s_name[8] = '\0';
ptr = s_name;
while (*ptr && *ptr != ' ')
ptr++;
if (dirent->ext[0] && dirent->ext[0] != ' ') {
*ptr = '.';
ptr++;
memcpy(ptr, dirent->ext, 3);
ptr[3] = '\0';
while (*ptr && *ptr != ' ')
ptr++;
}
*ptr = '\0';
if (*s_name == DELETED_FLAG)
*s_name = '\0';
else if (*s_name == aRING)
*s_name = DELETED_FLAG;
downcase(s_name);
}
/*
* Get the entry at index 'entry' in a FAT (12/16/32) table.
* On failure 0x00 is returned.
*/
static __u32 get_fatent(fsdata *mydata, __u32 entry)
{
__u32 bufnum;
__u32 off16, offset;
__u32 ret = 0x00;
__u16 val1, val2;
switch (mydata->fatsize) {
case 32:
bufnum = entry / FAT32BUFSIZE;
offset = entry - bufnum * FAT32BUFSIZE;
break;
case 16:
bufnum = entry / FAT16BUFSIZE;
offset = entry - bufnum * FAT16BUFSIZE;
break;
case 12:
bufnum = entry / FAT12BUFSIZE;
offset = entry - bufnum * FAT12BUFSIZE;
break;
default:
/* Unsupported FAT size */
return ret;
}
debug("FAT%d: entry: 0x%04x = %d, offset: 0x%04x = %d\n",
mydata->fatsize, entry, entry, offset, offset);
/* Read a new block of FAT entries into the cache. */
if (bufnum != mydata->fatbufnum) {
__u32 getsize = FATBUFBLOCKS;
__u8 *bufptr = mydata->fatbuf;
__u32 fatlength = mydata->fatlength;
__u32 startblock = bufnum * FATBUFBLOCKS;
if (startblock + getsize > fatlength)
getsize = fatlength - startblock;
startblock += mydata->fat_sect; /* Offset from start of disk */
if (disk_read(startblock, getsize, bufptr) < 0) {
debug("Error reading FAT blocks\n");
return ret;
}
mydata->fatbufnum = bufnum;
}
/* Get the actual entry from the table */
switch (mydata->fatsize) {
case 32:
ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
break;
case 16:
ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
break;
case 12:
off16 = (offset * 3) / 4;
switch (offset & 0x3) {
case 0:
ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[off16]);
ret &= 0xfff;
break;
case 1:
val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
val1 &= 0xf000;
val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
val2 &= 0x00ff;
ret = (val2 << 4) | (val1 >> 12);
break;
case 2:
val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
val1 &= 0xff00;
val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
val2 &= 0x000f;
ret = (val2 << 8) | (val1 >> 8);
break;
case 3:
ret = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
ret = (ret & 0xfff0) >> 4;
break;
default:
break;
}
break;
}
debug("FAT%d: ret: %08x, offset: %04x\n",
mydata->fatsize, ret, offset);
return ret;
}
/*
* Read at most 'size' bytes from the specified cluster into 'buffer'.
* Return 0 on success, -1 otherwise.
*/
static int
get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
{
__u32 idx = 0;
__u32 startsect;
int ret;
if (clustnum > 0) {
startsect = mydata->data_begin +
clustnum * mydata->clust_size;
} else {
startsect = mydata->rootdir_sect;
}
debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
printf("FAT: Misaligned buffer address (%p)\n", buffer);
while (size >= mydata->sect_size) {
ret = disk_read(startsect++, 1, tmpbuf);
if (ret != 1) {
debug("Error reading data (got %d)\n", ret);
return -1;
}
memcpy(buffer, tmpbuf, mydata->sect_size);
buffer += mydata->sect_size;
size -= mydata->sect_size;
}
} else {
idx = size / mydata->sect_size;
ret = disk_read(startsect, idx, buffer);
if (ret != idx) {
debug("Error reading data (got %d)\n", ret);
return -1;
}
startsect += idx;
idx *= mydata->sect_size;
buffer += idx;
size -= idx;
}
if (size) {
ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
ret = disk_read(startsect, 1, tmpbuf);
if (ret != 1) {
debug("Error reading data (got %d)\n", ret);
return -1;
}
memcpy(buffer, tmpbuf, size);
}
return 0;
}
/*
* Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
* into 'buffer'.
* Return the number of bytes read or -1 on fatal errors.
*/
__u8 get_contents_vfatname_block[MAX_CLUSTSIZE]
__aligned(ARCH_DMA_MINALIGN);
static long
get_contents(fsdata *mydata, dir_entry *dentptr, unsigned long pos,
__u8 *buffer, unsigned long maxsize)
{
unsigned long filesize = FAT2CPU32(dentptr->size), gotsize = 0;
unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
__u32 curclust = START(dentptr);
__u32 endclust, newclust;
unsigned long actsize;
debug("Filesize: %ld bytes\n", filesize);
if (pos >= filesize) {
debug("Read position past EOF: %lu\n", pos);
return gotsize;
}
if (maxsize > 0 && filesize > pos + maxsize)
filesize = pos + maxsize;
debug("%ld bytes\n", filesize);
actsize = bytesperclust;
/* go to cluster at pos */
while (actsize <= pos) {
curclust = get_fatent(mydata, curclust);
if (CHECK_CLUST(curclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", curclust);
debug("Invalid FAT entry\n");
return gotsize;
}
actsize += bytesperclust;
}
/* actsize > pos */
actsize -= bytesperclust;
filesize -= actsize;
pos -= actsize;
/* align to beginning of next cluster if any */
if (pos) {
actsize = min(filesize, bytesperclust);
if (get_cluster(mydata, curclust, get_contents_vfatname_block,
(int)actsize) != 0) {
printf("Error reading cluster\n");
return -1;
}
filesize -= actsize;
actsize -= pos;
memcpy(buffer, get_contents_vfatname_block + pos, actsize);
gotsize += actsize;
if (!filesize)
return gotsize;
buffer += actsize;
curclust = get_fatent(mydata, curclust);
if (CHECK_CLUST(curclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", curclust);
debug("Invalid FAT entry\n");
return gotsize;
}
}
actsize = bytesperclust;
endclust = curclust;
do {
/* search for consecutive clusters */
while (actsize < filesize) {
newclust = get_fatent(mydata, endclust);
if ((newclust - 1) != endclust)
goto getit;
if (CHECK_CLUST(newclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", newclust);
debug("Invalid FAT entry\n");
return gotsize;
}
endclust = newclust;
actsize += bytesperclust;
}
/* get remaining bytes */
actsize = filesize;
if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
printf("Error reading cluster\n");
return -1;
}
gotsize += actsize;
return gotsize;
getit:
if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
printf("Error reading cluster\n");
return -1;
}
gotsize += (int)actsize;
filesize -= actsize;
buffer += actsize;
curclust = get_fatent(mydata, endclust);
if (CHECK_CLUST(curclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", curclust);
printf("Invalid FAT entry\n");
return gotsize;
}
actsize = bytesperclust;
endclust = curclust;
} while (1);
}
/*
* Extract the file name information from 'slotptr' into 'l_name',
* starting at l_name[*idx].
* Return 1 if terminator (zero byte) is found, 0 otherwise.
*/
static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
{
int j;
for (j = 0; j <= 8; j += 2) {
l_name[*idx] = slotptr->name0_4[j];
if (l_name[*idx] == 0x00)
return 1;
(*idx)++;
}
for (j = 0; j <= 10; j += 2) {
l_name[*idx] = slotptr->name5_10[j];
if (l_name[*idx] == 0x00)
return 1;
(*idx)++;
}
for (j = 0; j <= 2; j += 2) {
l_name[*idx] = slotptr->name11_12[j];
if (l_name[*idx] == 0x00)
return 1;
(*idx)++;
}
return 0;
}
/*
* Extract the full long filename starting at 'retdent' (which is really
* a slot) into 'l_name'. If successful also copy the real directory entry
* into 'retdent'
* Return 0 on success, -1 otherwise.
*/
static int
get_vfatname(fsdata *mydata, int curclust, __u8 *cluster,
dir_entry *retdent, char *l_name)
{
dir_entry *realdent;
dir_slot *slotptr = (dir_slot *)retdent;
__u8 *buflimit = cluster + mydata->sect_size * ((curclust == 0) ?
PREFETCH_BLOCKS :
mydata->clust_size);
__u8 counter = (slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff;
int idx = 0;
if (counter > VFAT_MAXSEQ) {
debug("Error: VFAT name is too long\n");
return -1;
}
while ((__u8 *)slotptr < buflimit) {
if (counter == 0)
break;
if (((slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter)
return -1;
slotptr++;
counter--;
}
if ((__u8 *)slotptr >= buflimit) {
dir_slot *slotptr2;
if (curclust == 0)
return -1;
curclust = get_fatent(mydata, curclust);
if (CHECK_CLUST(curclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", curclust);
printf("Invalid FAT entry\n");
return -1;
}
if (get_cluster(mydata, curclust, get_contents_vfatname_block,
mydata->clust_size * mydata->sect_size) != 0) {
debug("Error: reading directory block\n");
return -1;
}
slotptr2 = (dir_slot *)get_contents_vfatname_block;
while (counter > 0) {
if (((slotptr2->id & ~LAST_LONG_ENTRY_MASK)
& 0xff) != counter)
return -1;
slotptr2++;
counter--;
}
/* Save the real directory entry */
realdent = (dir_entry *)slotptr2;
while ((__u8 *)slotptr2 > get_contents_vfatname_block) {
slotptr2--;
slot2str(slotptr2, l_name, &idx);
}
} else {
/* Save the real directory entry */
realdent = (dir_entry *)slotptr;
}
do {
slotptr--;
if (slot2str(slotptr, l_name, &idx))
break;
} while (!(slotptr->id & LAST_LONG_ENTRY_MASK));
l_name[idx] = '\0';
if (*l_name == DELETED_FLAG)
*l_name = '\0';
else if (*l_name == aRING)
*l_name = DELETED_FLAG;
downcase(l_name);
/* Return the real directory entry */
memcpy(retdent, realdent, sizeof(dir_entry));
return 0;
}
/* Calculate short name checksum */
static __u8 mkcksum(const char name[8], const char ext[3])
{
int i;
__u8 ret = 0;
for (i = 0; i < 8; i++)
ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + name[i];
for (i = 0; i < 3; i++)
ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + ext[i];
return ret;
}
/*
* Get the directory entry associated with 'filename' from the directory
* starting at 'startsect'
*/
__u8 get_dentfromdir_block[MAX_CLUSTSIZE]
__aligned(ARCH_DMA_MINALIGN);
static dir_entry *get_dentfromdir(fsdata *mydata, int startsect,
char *filename, dir_entry *retdent,
int dols)
{
__u16 prevcksum = 0xffff;
__u32 curclust = START(retdent);
int files = 0, dirs = 0;
debug("get_dentfromdir: %s\n", filename);
while (1) {
dir_entry *dentptr;
int i;
if (get_cluster(mydata, curclust, get_dentfromdir_block,
mydata->clust_size * mydata->sect_size) != 0) {
debug("Error: reading directory block\n");
return NULL;
}
dentptr = (dir_entry *)get_dentfromdir_block;
for (i = 0; i < DIRENTSPERCLUST; i++) {
char s_name[14], l_name[VFAT_MAXLEN_BYTES];
l_name[0] = '\0';
if (dentptr->name[0] == DELETED_FLAG) {
dentptr++;
continue;
}
if ((dentptr->attr & ATTR_VOLUME)) {
if (vfat_enabled &&
(dentptr->attr & ATTR_VFAT) == ATTR_VFAT &&
(dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
prevcksum = ((dir_slot *)dentptr)->alias_checksum;
get_vfatname(mydata, curclust,
get_dentfromdir_block,
dentptr, l_name);
if (dols) {
int isdir;
char dirc;
int doit = 0;
isdir = (dentptr->attr & ATTR_DIR);
if (isdir) {
dirs++;
dirc = '/';
doit = 1;
} else {
dirc = ' ';
if (l_name[0] != 0) {
files++;
doit = 1;
}
}
if (doit) {
if (dirc == ' ') {
printf(" %8ld %s%c\n",
(long)FAT2CPU32(dentptr->size),
l_name,
dirc);
} else {
printf(" %s%c\n",
l_name,
dirc);
}
}
dentptr++;
continue;
}
debug("vfatname: |%s|\n", l_name);
} else {
/* Volume label or VFAT entry */
dentptr++;
continue;
}
}
if (dentptr->name[0] == 0) {
if (dols) {
printf("\n%d file(s), %d dir(s)\n\n",
files, dirs);
}
debug("Dentname == NULL - %d\n", i);
return NULL;
}
if (vfat_enabled) {
__u8 csum = mkcksum(dentptr->name, dentptr->ext);
if (dols && csum == prevcksum) {
prevcksum = 0xffff;
dentptr++;
continue;
}
}
get_name(dentptr, s_name);
if (dols) {
int isdir = (dentptr->attr & ATTR_DIR);
char dirc;
int doit = 0;
if (isdir) {
dirs++;
dirc = '/';
doit = 1;
} else {
dirc = ' ';
if (s_name[0] != 0) {
files++;
doit = 1;
}
}
if (doit) {
if (dirc == ' ') {
printf(" %8ld %s%c\n",
(long)FAT2CPU32(dentptr->size),
s_name, dirc);
} else {
printf(" %s%c\n",
s_name, dirc);
}
}
dentptr++;
continue;
}
if (strcmp(filename, s_name)
&& strcmp(filename, l_name)) {
debug("Mismatch: |%s|%s|\n", s_name, l_name);
dentptr++;
continue;
}
memcpy(retdent, dentptr, sizeof(dir_entry));
debug("DentName: %s", s_name);
debug(", start: 0x%x", START(dentptr));
debug(", size: 0x%x %s\n",
FAT2CPU32(dentptr->size),
(dentptr->attr & ATTR_DIR) ? "(DIR)" : "");
return retdent;
}
curclust = get_fatent(mydata, curclust);
if (CHECK_CLUST(curclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", curclust);
printf("Invalid FAT entry\n");
return NULL;
}
}
return NULL;
}
/*
* Read boot sector and volume info from a FAT filesystem
*/
static int
read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
{
__u8 *block;
volume_info *vistart;
int ret = 0;
if (cur_dev == NULL) {
debug("Error: no device selected\n");
return -1;
}
block = memalign(ARCH_DMA_MINALIGN, cur_dev->blksz);
if (block == NULL) {
debug("Error: allocating block\n");
return -1;
}
if (disk_read(0, 1, block) < 0) {
debug("Error: reading block\n");
goto fail;
}
memcpy(bs, block, sizeof(boot_sector));
bs->reserved = FAT2CPU16(bs->reserved);
bs->fat_length = FAT2CPU16(bs->fat_length);
bs->secs_track = FAT2CPU16(bs->secs_track);
bs->heads = FAT2CPU16(bs->heads);
bs->total_sect = FAT2CPU32(bs->total_sect);
/* FAT32 entries */
if (bs->fat_length == 0) {
/* Assume FAT32 */
bs->fat32_length = FAT2CPU32(bs->fat32_length);
bs->flags = FAT2CPU16(bs->flags);
bs->root_cluster = FAT2CPU32(bs->root_cluster);
bs->info_sector = FAT2CPU16(bs->info_sector);
bs->backup_boot = FAT2CPU16(bs->backup_boot);
vistart = (volume_info *)(block + sizeof(boot_sector));
*fatsize = 32;
} else {
vistart = (volume_info *)&(bs->fat32_length);
*fatsize = 0;
}
memcpy(volinfo, vistart, sizeof(volume_info));
if (*fatsize == 32) {
if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
goto exit;
} else {
if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
*fatsize = 12;
goto exit;
}
if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
*fatsize = 16;
goto exit;
}
}
debug("Error: broken fs_type sign\n");
fail:
ret = -1;
exit:
free(block);
return ret;
}
__u8 do_fat_read_at_block[MAX_CLUSTSIZE]
__aligned(ARCH_DMA_MINALIGN);
long
do_fat_read_at(const char *filename, unsigned long pos, void *buffer,
unsigned long maxsize, int dols, int dogetsize)
{
char fnamecopy[2048];
boot_sector bs;
volume_info volinfo;
fsdata datablock;
fsdata *mydata = &datablock;
dir_entry *dentptr = NULL;
__u16 prevcksum = 0xffff;
char *subname = "";
__u32 cursect;
int idx, isdir = 0;
int files = 0, dirs = 0;
long ret = -1;
int firsttime;
__u32 root_cluster = 0;
int rootdir_size = 0;
int j;
if (read_bootsectandvi(&bs, &volinfo, &mydata->fatsize)) {
debug("Error: reading boot sector\n");
return -1;
}
if (mydata->fatsize == 32) {
root_cluster = bs.root_cluster;
mydata->fatlength = bs.fat32_length;
} else {
mydata->fatlength = bs.fat_length;
}
mydata->fat_sect = bs.reserved;
cursect = mydata->rootdir_sect
= mydata->fat_sect + mydata->fatlength * bs.fats;
mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
mydata->clust_size = bs.cluster_size;
if (mydata->sect_size != cur_part_info.blksz) {
printf("Error: FAT sector size mismatch (fs=%hu, dev=%lu)\n",
mydata->sect_size, cur_part_info.blksz);
return -1;
}
if (mydata->fatsize == 32) {
mydata->data_begin = mydata->rootdir_sect -
(mydata->clust_size * 2);
} else {
rootdir_size = ((bs.dir_entries[1] * (int)256 +
bs.dir_entries[0]) *
sizeof(dir_entry)) /
mydata->sect_size;
mydata->data_begin = mydata->rootdir_sect +
rootdir_size -
(mydata->clust_size * 2);
}
mydata->fatbufnum = -1;
mydata->fatbuf = memalign(ARCH_DMA_MINALIGN, FATBUFSIZE);
if (mydata->fatbuf == NULL) {
debug("Error: allocating memory\n");
return -1;
}
if (vfat_enabled)
debug("VFAT Support enabled\n");
debug("FAT%d, fat_sect: %d, fatlength: %d\n",
mydata->fatsize, mydata->fat_sect, mydata->fatlength);
debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
"Data begins at: %d\n",
root_cluster,
mydata->rootdir_sect,
mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
mydata->clust_size);
/* "cwd" is always the root... */
while (ISDIRDELIM(*filename))
filename++;
/* Make a copy of the filename and convert it to lowercase */
strcpy(fnamecopy, filename);
downcase(fnamecopy);
if (*fnamecopy == '\0') {
if (!dols)
goto exit;
dols = LS_ROOT;
} else if ((idx = dirdelim(fnamecopy)) >= 0) {
isdir = 1;
fnamecopy[idx] = '\0';
subname = fnamecopy + idx + 1;
/* Handle multiple delimiters */
while (ISDIRDELIM(*subname))
subname++;
} else if (dols) {
isdir = 1;
}
j = 0;
while (1) {
int i;
if (j == 0) {
debug("FAT read sect=%d, clust_size=%d, DIRENTSPERBLOCK=%zd\n",
cursect, mydata->clust_size, DIRENTSPERBLOCK);
if (disk_read(cursect,
(mydata->fatsize == 32) ?
(mydata->clust_size) :
PREFETCH_BLOCKS,
do_fat_read_at_block) < 0) {
debug("Error: reading rootdir block\n");
goto exit;
}
dentptr = (dir_entry *) do_fat_read_at_block;
}
for (i = 0; i < DIRENTSPERBLOCK; i++) {
char s_name[14], l_name[VFAT_MAXLEN_BYTES];
__u8 csum;
l_name[0] = '\0';
if (dentptr->name[0] == DELETED_FLAG) {
dentptr++;
continue;
}
if (vfat_enabled)
csum = mkcksum(dentptr->name, dentptr->ext);
if (dentptr->attr & ATTR_VOLUME) {
if (vfat_enabled &&
(dentptr->attr & ATTR_VFAT) == ATTR_VFAT &&
(dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
prevcksum =
((dir_slot *)dentptr)->alias_checksum;
get_vfatname(mydata,
root_cluster,
do_fat_read_at_block,
dentptr, l_name);
if (dols == LS_ROOT) {
char dirc;
int doit = 0;
int isdir =
(dentptr->attr & ATTR_DIR);
if (isdir) {
dirs++;
dirc = '/';
doit = 1;
} else {
dirc = ' ';
if (l_name[0] != 0) {
files++;
doit = 1;
}
}
if (doit) {
if (dirc == ' ') {
printf(" %8ld %s%c\n",
(long)FAT2CPU32(dentptr->size),
l_name,
dirc);
} else {
printf(" %s%c\n",
l_name,
dirc);
}
}
dentptr++;
continue;
}
debug("Rootvfatname: |%s|\n",
l_name);
} else {
/* Volume label or VFAT entry */
dentptr++;
continue;
}
} else if (dentptr->name[0] == 0) {
debug("RootDentname == NULL - %d\n", i);
if (dols == LS_ROOT) {
printf("\n%d file(s), %d dir(s)\n\n",
files, dirs);
ret = 0;
}
goto exit;
}
else if (vfat_enabled &&
dols == LS_ROOT && csum == prevcksum) {
prevcksum = 0xffff;
dentptr++;
continue;
}
get_name(dentptr, s_name);
if (dols == LS_ROOT) {
int isdir = (dentptr->attr & ATTR_DIR);
char dirc;
int doit = 0;
if (isdir) {
dirc = '/';
if (s_name[0] != 0) {
dirs++;
doit = 1;
}
} else {
dirc = ' ';
if (s_name[0] != 0) {
files++;
doit = 1;
}
}
if (doit) {
if (dirc == ' ') {
printf(" %8ld %s%c\n",
(long)FAT2CPU32(dentptr->size),
s_name, dirc);
} else {
printf(" %s%c\n",
s_name, dirc);
}
}
dentptr++;
continue;
}
if (strcmp(fnamecopy, s_name)
&& strcmp(fnamecopy, l_name)) {
debug("RootMismatch: |%s|%s|\n", s_name,
l_name);
dentptr++;
continue;
}
if (isdir && !(dentptr->attr & ATTR_DIR))
goto exit;
debug("RootName: %s", s_name);
debug(", start: 0x%x", START(dentptr));
debug(", size: 0x%x %s\n",
FAT2CPU32(dentptr->size),
isdir ? "(DIR)" : "");
goto rootdir_done; /* We got a match */
}
debug("END LOOP: j=%d clust_size=%d\n", j,
mydata->clust_size);
/*
* On FAT32 we must fetch the FAT entries for the next
* root directory clusters when a cluster has been
* completely processed.
*/
++j;
int rootdir_end = 0;
if (mydata->fatsize == 32) {
if (j == mydata->clust_size) {
int nxtsect = 0;
int nxt_clust = 0;
nxt_clust = get_fatent(mydata, root_cluster);
rootdir_end = CHECK_CLUST(nxt_clust, 32);
nxtsect = mydata->data_begin +
(nxt_clust * mydata->clust_size);
root_cluster = nxt_clust;
cursect = nxtsect;
j = 0;
}
} else {
if (j == PREFETCH_BLOCKS)
j = 0;
rootdir_end = (++cursect - mydata->rootdir_sect >=
rootdir_size);
}
/* If end of rootdir reached */
if (rootdir_end) {
if (dols == LS_ROOT) {
printf("\n%d file(s), %d dir(s)\n\n",
files, dirs);
ret = 0;
}
goto exit;
}
}
rootdir_done:
firsttime = 1;
while (isdir) {
int startsect = mydata->data_begin
+ START(dentptr) * mydata->clust_size;
dir_entry dent;
char *nextname = NULL;
dent = *dentptr;
dentptr = &dent;
idx = dirdelim(subname);
if (idx >= 0) {
subname[idx] = '\0';
nextname = subname + idx + 1;
/* Handle multiple delimiters */
while (ISDIRDELIM(*nextname))
nextname++;
if (dols && *nextname == '\0')
firsttime = 0;
} else {
if (dols && firsttime) {
firsttime = 0;
} else {
isdir = 0;
}
}
if (get_dentfromdir(mydata, startsect, subname, dentptr,
isdir ? 0 : dols) == NULL) {
if (dols && !isdir)
ret = 0;
goto exit;
}
if (isdir && !(dentptr->attr & ATTR_DIR))
goto exit;
if (idx >= 0)
subname = nextname;
}
if (dogetsize)
ret = FAT2CPU32(dentptr->size);
else
ret = get_contents(mydata, dentptr, pos, buffer, maxsize);
debug("Size: %d, got: %ld\n", FAT2CPU32(dentptr->size), ret);
exit:
free(mydata->fatbuf);
return ret;
}
long
do_fat_read(const char *filename, void *buffer, unsigned long maxsize, int dols)
{
return do_fat_read_at(filename, 0, buffer, maxsize, dols, 0);
}
int file_fat_detectfs(void)
{
boot_sector bs;
volume_info volinfo;
int fatsize;
char vol_label[12];
if (cur_dev == NULL) {
printf("No current device\n");
return 1;
}
#if defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_SATA) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC)
printf("Interface: ");
switch (cur_dev->if_type) {
case IF_TYPE_IDE:
printf("IDE");
break;
case IF_TYPE_SATA:
printf("SATA");
break;
case IF_TYPE_SCSI:
printf("SCSI");
break;
case IF_TYPE_ATAPI:
printf("ATAPI");
break;
case IF_TYPE_USB:
printf("USB");
break;
case IF_TYPE_DOC:
printf("DOC");
break;
case IF_TYPE_MMC:
printf("MMC");
break;
default:
printf("Unknown");
}
printf("\n Device %d: ", cur_dev->dev);
dev_print(cur_dev);
#endif
if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
printf("\nNo valid FAT fs found\n");
return 1;
}
memcpy(vol_label, volinfo.volume_label, 11);
vol_label[11] = '\0';
volinfo.fs_type[5] = '\0';
printf("Filesystem: %s \"%s\"\n", volinfo.fs_type, vol_label);
return 0;
}
int file_fat_ls(const char *dir)
{
return do_fat_read(dir, NULL, 0, LS_YES);
}
int fat_exists(const char *filename)
{
int sz;
sz = do_fat_read_at(filename, 0, NULL, 0, LS_NO, 1);
return sz >= 0;
}
long file_fat_read_at(const char *filename, unsigned long pos, void *buffer,
unsigned long maxsize)
{
printf("reading %s\n", filename);
return do_fat_read_at(filename, pos, buffer, maxsize, LS_NO, 0);
}
long file_fat_read(const char *filename, void *buffer, unsigned long maxsize)
{
return file_fat_read_at(filename, 0, buffer, maxsize);
}
int fat_read_file(const char *filename, void *buf, int offset, int len)
{
int len_read;
len_read = file_fat_read_at(filename, offset, buf, len);
if (len_read == -1) {
printf("** Unable to read file %s **\n", filename);
return -1;
}
return len_read;
}
void fat_close(void)
{
}
|
C
|
#include <stdio.h>
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
int main (int argc, char const *argv[]) {
printf(ANSI_COLOR_RED "This text is RED!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_GREEN "This text is GREEN!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_YELLOW "This text is YELLOW!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_BLUE "This text is BLUE!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_MAGENTA "This text is MAGENTA!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_CYAN "This text is CYAN!" ANSI_COLOR_RESET "\n");
return 0;
}
|
C
|
/**
* \file doubly_linked_list_insert_before.c
*
* Implementation of doubly_linked_list_insert_before
*
* \copyright 2019 Velo Payments, Inc. All rights reserved.
*/
#include <cbmc/model_assert.h>
#include <vpr/doubly_linked_list.h>
/**
* \brief Insert a new element before a specified element in a doubly linked
* list.
*
* If successful, then this data will be encapsulated in an element and placed
* before the specified element in the linked list.
*
* WARNING: this function is not thread safe!
*
* \param dll The doubly linked list
* \param element The existing element, which will succeed the
* new element.
* \param data An opaque pointer to some data that should be
* encapsulated in a new element and inserted in the
* list.
*
* \returns a status code indicating success or failure.
* - \ref VPR_STATUS_SUCCESS if successful.
* - \ref VPR_ERROR_DLL_BEFORE_ELEMENT_ALLOCATION_FAILED if
* memory could not be allocated for a new element
* - \ref VPR_ERROR_DLL_BEFORE_BUFFER_ALLOCATION_FAILED if
* memory could not be allocated to copy the data
*/
int doubly_linked_list_insert_before(doubly_linked_list_t* dll,
doubly_linked_list_element_t* element, void* data)
{
MODEL_ASSERT(NULL != dll);
MODEL_ASSERT(NULL != dll->first);
MODEL_ASSERT(NULL != dll->last);
MODEL_ASSERT(dll->elements > 0);
MODEL_ASSERT(NULL != dll->options);
MODEL_ASSERT(NULL != dll->options->alloc_opts);
MODEL_ASSERT(NULL != element);
MODEL_ASSERT(NULL != element->data);
MODEL_ASSERT(NULL != data);
/* create the element */
doubly_linked_list_element_t* new_element =
(doubly_linked_list_element_t*)allocate(
dll->options->alloc_opts,
sizeof(doubly_linked_list_element_t));
if (NULL == new_element)
{
return VPR_ERROR_DLL_BEFORE_ELEMENT_ALLOCATION_FAILED;
}
/* set the pointers */
new_element->next = element;
new_element->prev = element->prev;
if (NULL == element->prev)
{
dll->first = new_element;
}
else
{
element->prev->next = new_element;
}
element->prev = new_element;
/* increment the number of elements in this list*/
++dll->elements;
/* if this is a copy-on-insert, then allocate space for the data
* and copy it into that buffer. Otherwise, set the pointer to
* the original data. */
if (NULL != dll->options->doubly_linked_list_element_copy)
{
uint8_t* data_buffer = (uint8_t*)allocate(
dll->options->alloc_opts,
dll->options->element_size);
new_element->data = data_buffer;
if (NULL == data_buffer)
{
return VPR_ERROR_DLL_BEFORE_BUFFER_ALLOCATION_FAILED;
}
/* copy the data into the buffer */
dll->options->doubly_linked_list_element_copy(
new_element->data, data, dll->options->element_size);
}
else
{
new_element->data = data;
}
//success
return VPR_STATUS_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
#include "float_linked_list.h"
#define TARGET_LIST_SIZE 10
int main(int argc, char** argv) {
printf("float_linked_list|start\n");
//ia simple float list
ListHead float_list;
List_init(&float_list);
for (u_int16_t i = 0; i < TARGET_LIST_SIZE; ++i) {
FloatListItem* f_item = (FloatListItem*)(malloc(sizeof(FloatListItem)));
f_item->value = i + 0.5f;
assert(f_item && "ERROR, cannot instanciate item");
List_insert(&float_list, float_list.last, (ListItem*)f_item);
}
FloatList_print(&float_list);
//ia list of lists (float)
ListHead float_matrix;
List_init(&float_matrix);
FloatListList_init(3, 3, &float_matrix);
FloatListItem* m_item = FloatListList_at(&float_matrix, 0 , 0);
m_item->value = 5.0;
m_item = FloatListList_at(&float_matrix, 0 , 2);
m_item->value = 2.0;
m_item = FloatListList_at(&float_matrix, 1 , 1);
m_item->value = 3.0;
m_item = FloatListList_at(&float_matrix, 1 , 0);
m_item->value = 2.6;
m_item = FloatListList_at(&float_matrix, 2 , 0);
m_item->value = 4.0;
m_item = FloatListList_at(&float_matrix, 2 , 2);
m_item->value = 0.6;
FloatListList_print(&float_matrix);
//ia sum rows
ListHead sum_list;
List_init(&sum_list);
FloatListList_sumRows(&float_matrix, &sum_list);
FloatList_print(&sum_list);
//ia checkout
FloatList_destroy(&float_list);
FloatListList_destroy(&float_matrix);
FloatList_destroy(&sum_list);
printf("float_linked_list|end\n");
return 0;
}
|
C
|
#include<stdio.h>
typedef long long int ll;
int main()
{
int tes;
scanf("%d",&tes);
while(tes--)
{
ll a[10110],n,k,j,i,min;
scanf("%Ld %Ld",&n,&k);
for(i=0;i<n;i++)
{
scanf("%Ld",a+i);
}
ll tmp=0;
min=a[0];
for(i=0;i<k;i++)
{
if(a[i]<min)
{
min=a[i];
}
}
if(k==n)
{
printf("%Ld",min);
}
else
{
printf("%Ld ",min);
}
for(i=k;i<n;i++)
{
if(min==a[tmp]&&a[i]>=min)
{
min=a[i];
for(j=tmp+1;j<=i;j++)
{
if(a[j]<min)
{
min=a[j];
}
}
if(i==n-1)
{
printf("%Ld",min);
}
else
{
printf("%Ld ",min);
}
}
else if(a[i]<min)
{
min=a[i];
if(i==n-1)
{
printf("%Ld",min);
}
else
{
printf("%Ld ",min);
}
}
else
{
if(i==n-1)
{
printf("%Ld",min);
}
else
{
printf("%Ld ",min);
}
}
tmp++;
}
printf("\n");
}
}
|
C
|
/*
main.c
Created : 7/21/2020 12:07:21 PM
Author : eisendani
*/
#include "AT89C51AC3.h"
void write_port(unsigned char this){
P4 = this;
}
void main(void)
{
/* Replace with your application code */
unsigned char test = 0b11111111;
while (1)
{
write_port(test);
}
}
|
C
|
// struct untuk node
struct node{
char data;
struct node *next;
};
typedef struct node node;
// struct untuk front back dan count
struct queue{
node *front;
node *back;
};
typedef struct queue queue;
// Alvito Ikramu Walidain <2006577624>
// inisialisasi nilai front, back, dan count 0
void initialize(queue *q){
q->front = NULL;
q->back = NULL;
}
// Alvito Ikramu Walidain <2006577624>
// cek jika queue kosong
int isempty(queue *q){
return (q->back == NULL);
}
// Alvito Ikramu Walidain <2006577624>
// fungsi untuk menambahkan char ke queue
void enqueue(queue *q, char value){
node *tmp;
tmp = malloc(sizeof(node));
tmp->data = value;
tmp->next = NULL;
if(!isempty(q)){
q->back->next = tmp;
q->back = tmp;
}
else{
q->front = q->back = tmp;
}
}
// Alvito Ikramu Walidain <2006577624>
// fungsi untuk menghapus char dengan prinsip FIFO
char dequeue(queue *q){
node *tmp;
char n = q->front->data;
tmp = q->front;
q->front = q->front->next;
free(tmp);
return(n);
}
// Alvito Ikramu Walidain <2006577624>
// fungsi untuk menghitung nilai user berdasarkan jumlah benar dan total soal
// dengan menggunakan queue
float grade_test(char jawaban[]){
// init jawaban yang benar dengan queue
queue *answer;
answer = malloc(sizeof(queue));
initialize(answer);
enqueue(answer, 'a'); // 1
enqueue(answer, 'd'); // 2
enqueue(answer, 'b'); // 3
enqueue(answer, 'd'); // 4
enqueue(answer, 'b'); // 5
enqueue(answer, 'a'); // 6
enqueue(answer, 'c'); // 7
enqueue(answer, 'b'); // 8
enqueue(answer, 'a'); // 9
enqueue(answer, 'b'); // 10
// ubah 1-4 ke a-d
int i;
char filename[] = "sample.txt";
int banyak_soal = count_lines(filename)/5;
// compare dengan jawaban user
float correctAns = 0;
for(i = 0; i < banyak_soal; i++){
if (jawaban[i] == answer->front->data){
correctAns++;
}
dequeue(answer);
}
return (correctAns/banyak_soal)*100;
}
// Alvito Ikramu Walidain <2006577624>
// fungsi untuk menyimpan hasil dari ujian ke dalam teks file
void write_jawaban_to_file(char username[], char jawaban_sementara[], float nilai){
time_t currentTime;
time(¤tTime);
char filename[] = "credential/skor.txt";
FILE *file = fopen(filename, "a");
if (file == NULL){
printf("Gagal untuk membuka %s.\n", filename);
exit(0);
}
// DATE
struct tm *myTime = localtime(¤tTime);
fprintf(file, "%d/%d/%d, ", myTime->tm_mday, myTime->tm_mon+1, myTime->tm_year+1900);
fprintf(file, "%02d:%02d; ", myTime->tm_hour, myTime->tm_min);
// biodata dan nilai
fprintf(file, "%s; %s; %.2f\n", username, jawaban_sementara, nilai);
printf("Submitted %d/%d/%d, ", myTime->tm_mday, myTime->tm_mon+1, myTime->tm_year+1900);
printf("%02d:%02d.\n", myTime->tm_hour, myTime->tm_min);
printf("Username: %s\n", username);
printf("Grade = %.2f/100\n", nilai);
fclose(file);
}
|
C
|
//nome:Layanne Roberta Silva Oliveira
//matrícula: 11811ETE012
#include <stdio.h>
int main ()
{
int estado=0, i=0;
char bits[256];
printf("\nDigite um numero binario: ");
scanf("%[^\n]",bits);
while (bits[i] != '\0')
{
if (bits[i]=='0')
{
if (estado==0)
estado=0;
else
if (estado==1)
estado=2;
else
if (estado==2)
estado=1;
}
if (bits[i]=='1')
{
if (estado==0)
estado=1;
else
if (estado==1)
estado=0;
else
if (estado==2)
estado=2;
}
i++;
}
if (estado==0)
printf ("\nO binario e multiplo de 3");
else
printf ("\nO binario nao e multiplo de 3");
return 0;
}
|
C
|
///////////////////////////////////////////////////////////////////////////////
// File Name: test.c
//
// Author: Varun Naik
// CS email: vnaik@cs.wisc.edu
//
// Description: Unit tests for a4. As a reminder, even if you pass all of
// these tests, you are not yet guaranteed 90/90 on the
// autograder portion. But if you do not pass these tests, you
// will probably receive a very low score on the autograder.
//
// Sources: Google Test, cppreference.com
//
// URL(s) of sources:
// https://github.com/google/googletest
// http://en.cppreference.com/w/
///////////////////////////////////////////////////////////////////////////////
#include <complex>
#include <fstream>
#include <type_traits>
#include "gtest/gtest.h"
#include "Matrix.hpp"
/**
* @brief Empties the contents of the buffer, and clears its error state flags.
*
* @param buff The buffer containing the lines written to cout
*/
void clearBuff(std::stringstream &buff) {
buff.str("");
buff.clear();
}
/**
* @brief Helper function that returns an AssertionResult for MATCH_NEXT_LINE.
*
* Do not call this function directly. Call MATCH_NEXT_LINE instead.
*
* @param expr0 The first expression passed to MATCH_NEXT_LINE
* @param expr1 The second expression passed to MATCH_NEXT_LINE
* @param buff See comment for MATCH_NEXT_LINE
* @param str See comment for MATCH_NEXT_LINE
* @return AssertionSuccess() on success or AssertionFailure() on failure
*/
::testing::AssertionResult matchNextLine(const std::string &expr0,
const std::string &expr1,
std::stringstream &buff,
const std::string &str) {
std::string line;
std::getline(buff, line);
if (buff.eof()) {
return ::testing::AssertionFailure()
<< "Line printed to cout is incorrect" << std::endl
<< " Printed: (end of printed output)" << std::endl
<< "Expected: \"" << str << "\"";
} else {
if (line == str) {
return ::testing::AssertionSuccess();
} else {
return ::testing::AssertionFailure()
<< "Line printed to cout is incorrect" << std::endl
<< " Printed: \"" << line << "\"" << std::endl
<< "Expected: \"" << str << "\"";
}
}
}
/**
* @brief Reads the next line from buff and checks that it is equal to str.
* Raises a non-fatal failure with the correct line number if we have
* reached the end of file, or if the pattern does not match.
*
* @param buff The buffer containing the lines written to cout
* @param str The exact string to compare to
*/
#define MATCH_NEXT_LINE(buff, str) \
EXPECT_PRED_FORMAT2(matchNextLine, buff, str)
/**
* @brief Helper function that returns an AssertionResult for MATCH_END.
*
* Do not call this function directly. Call MATCH_END instead.
*
* @param expr0 The first expression passed to MATCH_END
* @param buff See comment for MATCH_END
* @return AssertionSuccess() on success or AssertionFailure() on failure
*/
::testing::AssertionResult matchEnd(const std::string &expr0, std::stringstream &buff) {
std::string line;
getline(buff, line);
if (buff.eof()) {
return ::testing::AssertionSuccess();
} else {
return ::testing::AssertionFailure()
<< "Line printed to cout is incorrect" << std::endl
<< " Printed: \"" << line << "\"" << std::endl
<< "Expected: (end of printed output)";
}
}
/**
* @brief Reads the next line from buff and checks that the end of the stream
* has been reached. Raises a non-fatal failure with the correct line
* number otherwise.
*
* @param buff The buffer containing the lines written to cout
*/
#define MATCH_END(buff) \
EXPECT_PRED_FORMAT1(matchEnd, buff)
/**
* @brief A test fixture class for all a4 tests.
*/
class A4Test : public ::testing::Test {
protected:
std::stringstream buff;
// cout_buff is a pointer. Don't worry, we will cover this later in the semester.
std::streambuf *cout_buff;
/**
* @brief Code to run before each unit test.
*
* Redirects std::cout to the in-memory variable buff.
* See: http://en.cppreference.com/w/cpp/io/basic_ios/rdbuf
*/
virtual void SetUp() override {
cout_buff = std::cout.rdbuf(buff.rdbuf());
}
/**
* @brief Code to run after each unit test.
*
* Resets std::cout so that calls to cout print to the screen again.
*/
virtual void TearDown() override {
std::cout.rdbuf(cout_buff);
}
};
// Define a type IntegerMatrix, depending on the value of a command-line
// argument to the compiler
#if UseTemplate == 0
typedef Matrix IntegerMatrix;
#elif UseTemplate == 1
typedef Matrix<int> IntegerMatrix;
#endif
#ifdef RunBasicMatrixTest
/**
* @brief Test case to make sure the constructor, getRows() and getCols()
* behave as desired.
*/
TEST_F(A4Test, BasicMatrixTest) {
IntegerMatrix a(2, 4);
EXPECT_EQ(a.getRows(), 2);
EXPECT_EQ(a.getCols(), 4);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunConstMatrixTest
/**
* @brief Test case to make sure the constructor, getRows() and getCols()
* behave as desired for a const reference to a Matrix.
*/
TEST_F(A4Test, ConstMatrixTest) {
IntegerMatrix a(2, 4);
const IntegerMatrix &a2 = a;
EXPECT_EQ(a2.getRows(), 2);
EXPECT_EQ(a2.getCols(), 4);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicBracketTest
/**
* @brief Test case to make sure bracket notation behaves as desired.
*/
TEST_F(A4Test, BasicBracketTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
EXPECT_EQ(m[0][0], 1);
EXPECT_EQ(m[0][1], 2);
EXPECT_EQ(m[1][0], 3);
EXPECT_EQ(m[1][1], 4);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunConstBracketTest
/**
* @brief Test case to make sure bracket notation behaves as desired for a
* const reference to a Matrix.
*/
TEST_F(A4Test, ConstBracketTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
const IntegerMatrix &m2 = m;
EXPECT_EQ(m2[0][0], 1);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicPrintTest
/**
* @brief Test case to make sure the << operator behaves as desired.
*/
TEST_F(A4Test, BasicPrintTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
MATCH_END(buff);
clearBuff(buff);
std::cout << m << std::endl;
MATCH_NEXT_LINE(buff, "1 2");
MATCH_NEXT_LINE(buff, "3 4");
MATCH_NEXT_LINE(buff, "");
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunConstPrintTest
/**
* @brief Test case to make sure the << operator behaves as desired for a const
* reference to a Matrix.
*/
TEST_F(A4Test, ConstPrintTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
MATCH_END(buff);
clearBuff(buff);
const IntegerMatrix &m2 = m;
std::cout << m2 << std::endl;
MATCH_NEXT_LINE(buff, "1 2");
MATCH_NEXT_LINE(buff, "3 4");
MATCH_NEXT_LINE(buff, "");
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicComparisonTest
/**
* @brief Test case to make sure the == and != operators behave as desired.
*/
TEST_F(A4Test, BasicComparisonTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
IntegerMatrix mCopy(2, 2);
mCopy[0][0] = 1;
mCopy[0][1] = 2;
mCopy[1][0] = 3;
mCopy[1][1] = 4;
// These call == and !=, respectively
EXPECT_EQ(m, mCopy);
EXPECT_NE(m, n);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunConstComparisonTest
/**
* @brief Test case to make sure the == and != operators behave as desired for
* const references to Matrices.
*/
TEST_F(A4Test, ConstComparisonTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
IntegerMatrix mCopy(2, 2);
mCopy[0][0] = 1;
mCopy[0][1] = 2;
mCopy[1][0] = 3;
mCopy[1][1] = 4;
const IntegerMatrix &m2 = m;
const IntegerMatrix &n2 = n;
const IntegerMatrix &mCopy2 = mCopy;
EXPECT_EQ(m2, mCopy2);
EXPECT_NE(m2, n2);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunMismatchedComparisonTest
/**
* @brief Test case to make sure the != operator behaves as desired for
* Matrices of different dimensions.
*/
TEST_F(A4Test, MismatchedComparisonTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 3);
n[0][0] = 1;
n[0][1] = 2;
n[1][0] = 3;
n[1][1] = 4;
n[0][2] = 0;
n[0][3] = 0;
IntegerMatrix o(3, 2);
o[0][0] = 1;
o[0][1] = 2;
o[1][0] = 3;
o[1][1] = 4;
o[2][0] = 0;
o[2][1] = 0;
EXPECT_NE(m, n);
EXPECT_NE(m, o);
EXPECT_NE(n, o);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicAdditionTest
/**
* @brief Test case to make sure the + operator behaves as desired.
*/
TEST_F(A4Test, BasicAdditionTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
IntegerMatrix iAdd = m + n;
EXPECT_EQ(iAdd[0][0], 4);
EXPECT_EQ(iAdd[0][1], 3);
EXPECT_EQ(iAdd[1][0], 10);
EXPECT_EQ(iAdd[1][1], 6);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunConstAdditionTest
/**
* @brief Test case to make sure the + operator return type is const. This test
* should fail to compile.
*/
TEST_F(A4Test, ConstAdditionTest) {
IntegerMatrix m(2, 2);
IntegerMatrix n(2, 2);
(m + n) = n;
}
#endif
#ifdef RunMismatchedAdditionTest
/**
* @brief Test case to make sure the + operator behaves as desired for Matrices
* of different dimensions.
*/
TEST_F(A4Test, MismatchedAdditionTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 1);
n[0][0] = 3;
n[1][0] = 7;
// The following line should crash with any error message
EXPECT_DEATH(m + n, ".*");
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicSubtractionTest
/**
* @brief Test case to make sure the - operator behaves as desired.
*/
TEST_F(A4Test, BasicSubtractionTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
IntegerMatrix iSub = m - n;
EXPECT_EQ(iSub[0][0], -2);
EXPECT_EQ(iSub[0][1], 1);
EXPECT_EQ(iSub[1][0], -4);
EXPECT_EQ(iSub[1][1], 2);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicMatrixMultiplicationTest
/**
* @brief Test case to make sure the * operator for matrix multiplication
* behaves as desired.
*/
TEST_F(A4Test, BasicMatrixMultiplicationTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
IntegerMatrix iMul = m * n;
EXPECT_EQ(iMul[0][0], 17);
EXPECT_EQ(iMul[0][1], 5);
EXPECT_EQ(iMul[1][0], 37);
EXPECT_EQ(iMul[1][1], 11);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicScalarMultiplicationTest
/**
* @brief Test case to make sure the * operator for scalar multiplication
* behaves as desired.
*/
TEST_F(A4Test, BasicScalarMultiplicationTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix iScalarMul = 2 * m;
EXPECT_EQ(iScalarMul[0][0], 2);
EXPECT_EQ(iScalarMul[0][1], 4);
EXPECT_EQ(iScalarMul[1][0], 6);
EXPECT_EQ(iScalarMul[1][1], 8);
iScalarMul = 3 * m;
EXPECT_EQ(iScalarMul[0][0], 3);
EXPECT_EQ(iScalarMul[0][1], 6);
EXPECT_EQ(iScalarMul[1][0], 9);
EXPECT_EQ(iScalarMul[1][1], 12);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicCompoundAdditionTest
/**
* @brief Test case to make sure the += operator behaves as desired.
*/
TEST_F(A4Test, BasicCompoundAdditionTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
m += n;
EXPECT_EQ(m[0][0], 4);
EXPECT_EQ(m[0][1], 3);
EXPECT_EQ(m[1][0], 10);
EXPECT_EQ(m[1][1], 6);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunConstCompoundAdditionTest
/**
* @brief Test case to make sure the += operator behaves as desired for a const
* reference to a Matrix.
*/
TEST_F(A4Test, ConstCompoundAdditionTest) {
IntegerMatrix m(2, 2);
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
const IntegerMatrix &n2 = n;
(m += n2) += n2;
EXPECT_EQ(m[0][0], 7);
EXPECT_EQ(m[0][1], 4);
EXPECT_EQ(m[1][0], 17);
EXPECT_EQ(m[1][1], 8);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicCompoundSubtractionTest
/**
* @brief Test case to make sure the -= operator behaves as desired.
*/
TEST_F(A4Test, BasicCompoundSubtractionTest) {
IntegerMatrix m(2, 2);
m[0][0] = 4;
m[0][1] = 3;
m[1][0] = 10;
m[1][1] = 6;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
m -= 2 * n;
EXPECT_EQ(m[0][0], -2);
EXPECT_EQ(m[0][1], 1);
EXPECT_EQ(m[1][0], -4);
EXPECT_EQ(m[1][1], 2);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicCompoundMatrixMultiplicationTest
/**
* @brief Test case to make sure the *= operator behaves as desired for matrix
* multiplication.
*/
TEST_F(A4Test, BasicCompoundMatrixMultiplicationTest) {
IntegerMatrix m(2, 2);
m[0][0] = -2;
m[0][1] = 1;
m[1][0] = -4;
m[1][1] = 2;
IntegerMatrix n(2, 2);
n[0][0] = 3;
n[0][1] = 1;
n[1][0] = 7;
n[1][1] = 2;
m += n;
m *= n;
EXPECT_EQ(m[0][0], 17);
EXPECT_EQ(m[0][1], 5);
EXPECT_EQ(m[1][0], 37);
EXPECT_EQ(m[1][1], 11);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunBasicCompoundScalarMultiplicationTest
/**
* @brief Test case to make sure the *= operator behaves as desired for scalar
* multiplication.
*/
TEST_F(A4Test, BasicCompoundScalarMultiplicationTest) {
IntegerMatrix m(2, 2);
m[0][0] = 17;
m[0][1] = 5;
m[1][0] = 37;
m[1][1] = 11;
m *= 10;
EXPECT_EQ(m[0][0], 170);
EXPECT_EQ(m[0][1], 50);
EXPECT_EQ(m[1][0], 370);
EXPECT_EQ(m[1][1], 110);
MATCH_END(buff);
clearBuff(buff);
}
#endif
#ifdef RunComplexTest
/**
* @brief Test case for complex numbers. This is almost the same as the second
* half of main().
*/
TEST_F(A4Test, ComplexTest) {
// create 5 complex numbers.
std::complex<int> c1(1, 0);
std::complex<int> c2(0, 1);
std::complex<int> c3(-1, 0);
std::complex<int> c4(0, -1);
std::complex<int> c5(1, 2);
// create a 2 x 2 matrix of complex numbers.
Matrix<std::complex<int>> cm(2, 2);
cm[0][0] = c1;
cm[0][1] = c2;
cm[1][0] = c3;
cm[1][1] = c4;
EXPECT_EQ(cm[0][0], c1);
EXPECT_EQ(cm[0][1], c2);
EXPECT_EQ(cm[1][0], c3);
EXPECT_EQ(cm[1][1], c4);
// create another 2 x 2 matrix of complex numbers.
Matrix<std::complex<int>> cn(2, 2);
cn[0][0] = c2;
cn[0][1] = c3;
cn[1][0] = c4;
cn[1][1] = c5;
EXPECT_EQ(cn[0][0], c2);
EXPECT_EQ(cn[0][1], c3);
EXPECT_EQ(cn[1][0], c4);
EXPECT_EQ(cn[1][1], c5);
// add 2 matrices of complex numbers.
Matrix<std::complex<int>> cAdd = cm + cn;
EXPECT_EQ(cAdd[0][0], c1 + c2);
EXPECT_EQ(cAdd[0][1], c2 + c3);
EXPECT_EQ(cAdd[1][0], c3 + c4);
EXPECT_EQ(cAdd[1][1], c4 + c5);
// subtract 2 matrices of complex numbers.
Matrix<std::complex<int>> cSub = cm - cn;
EXPECT_EQ(cSub[0][0], c1 - c2);
EXPECT_EQ(cSub[0][1], c2 - c3);
EXPECT_EQ(cSub[1][0], c3 - c4);
EXPECT_EQ(cSub[1][1], c4 - c5);
// multiply 2 matrices of complex numbers.
Matrix<std::complex<int>> cMul = cm * cn;
EXPECT_EQ(cMul[0][0], c1*c2 + c2*c4);
EXPECT_EQ(cMul[0][1], c1*c3 + c2*c5);
EXPECT_EQ(cMul[1][0], c3*c2 + c4*c4);
EXPECT_EQ(cMul[1][1], c3*c3 + c4*c5);
// create 2 complex numbers.
std::complex<int> cScalar1(4, 0);
std::complex<int> cScalar2(5, 0);
// multiply a complex number with a matrix of complex numbers.
Matrix<std::complex<int>> cScalarMul = cScalar1 * cm;
EXPECT_EQ(cScalarMul[0][0], cScalar1 * c1);
EXPECT_EQ(cScalarMul[0][1], cScalar1 * c2);
EXPECT_EQ(cScalarMul[1][0], cScalar1 * c3);
EXPECT_EQ(cScalarMul[1][1], cScalar1 * c4);
cScalarMul = cn * cScalar2;
EXPECT_EQ(cScalarMul[0][0], cScalar2 * c2);
EXPECT_EQ(cScalarMul[0][1], cScalar2 * c3);
EXPECT_EQ(cScalarMul[1][0], cScalar2 * c4);
EXPECT_EQ(cScalarMul[1][1], cScalar2 * c5);
// compound addition of matrix of complex numbers.
cm += cn;
EXPECT_EQ(cm, cAdd);
// compound subtraction of matrix of complex numbers.
std::complex<int> cScalar3 = 2;
cm -= cScalar3 * cn;
EXPECT_EQ(cm, cSub);
// compound addition and multiplication of matrix of complex numbers.
cm += cn;
cm *= cn;
EXPECT_EQ(cm, cMul);
// compound multiplication of matrix of complex numbers with a complex number.
std::complex<int> cScalar4(10, 0);
cm *= cScalar4;
EXPECT_EQ(cm[0][0], cScalar4 * cMul[0][0]);
EXPECT_EQ(cm[0][1], cScalar4 * cMul[0][1]);
EXPECT_EQ(cm[1][0], cScalar4 * cMul[1][0]);
EXPECT_EQ(cm[1][1], cScalar4 * cMul[1][1]);
MATCH_END(buff);
clearBuff(buff);
}
#endif
/**
* @brief Unit test execution begins here.
*
* @param argc Number of command-line arguments
* @param argv Command line arguments
* @return 0 for normal program termination, other error code for abnormal termination
*/
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ value ;
typedef int quad_t ;
/* Variables and functions */
int /*<<< orphan*/ KENV_MNAMELEN ;
scalar_t__ KENV_MVALLEN ;
int /*<<< orphan*/ getenv_string (char const*,char*,int) ;
int strtoq (char*,char**,int /*<<< orphan*/ ) ;
int
getenv_quad(const char *name, quad_t *data)
{
char value[KENV_MNAMELEN + 1 + KENV_MVALLEN + 1];
char *vtp;
quad_t iv;
if (!getenv_string(name, value, sizeof(value)))
return (0);
iv = strtoq(value, &vtp, 0);
if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0'))
return (0);
switch (vtp[0]) {
case 't': case 'T':
iv *= 1024;
/* FALLTHROUGH */
case 'g': case 'G':
iv *= 1024;
/* FALLTHROUGH */
case 'm': case 'M':
iv *= 1024;
/* FALLTHROUGH */
case 'k': case 'K':
iv *= 1024;
case '\0':
break;
default:
return (0);
}
*data = iv;
return (1);
}
|
C
|
#include <stdio.h>
main()
{
long num[1000], digit[1000], factor[1000], rem[1000], r[1000], count[1000], remainder[1000], bin[1000], pdrem[1000], biny[1000], temp[1000], rev[1000], key[1000];
long range, i, real,b, x, n, t, j, y, base, a , pdrange ;
clrscr();
printf("ENTER RANGE:");
scanf(" %ld", &range);
real=2;
for (i=2; i<range; i++)
{
num[i]=real;
real++;
}
for (i=2; i<range; i++)
{
n=num[i];
x=n;
digit[i]=0;
for (;n!=0;)
{
n=n/10;
digit[i]++;
}
t=0;
b=0;
j=2;
factor[i]=0;
for (;x!=0;)
{
if (x%j==0)
{
x=x/j;
rem[t]=j;
r[b]=rem[t];
t++;
b++;
factor[i]++;
if (x==1)
{
break;
}
}
else
{
j++;
}
}
if (factor[i]>digit[i])
{
printf("\nWASTEFUL NUMBER: %ld ", num[i]);
for (j=0; j<factor[i]; j++)
{
printf("\nFACTOR: %ld", r[j]);
bin[j]=0;
base=1;
for (;r[j]!=0;)
{
remainder[j]=r[j]%2;
bin[j]=bin[j]+remainder[j]*base;
base=base*10;
r[j]=r[j]/2;
}
key[j]=bin[j];
temp[j]=0;
rev[j]=0;
for (;key[j]!=0;)
{
temp[j]=key[j]%10;
key[j]=key[j]/10;
rev[j]=temp[j]+(rev[j]*10);
}
if (rev[j]==bin[j])
{
printf(" - %ld = PALINDROMIC PRIME FACTOR/BINARY", rev[j]);
}
}
}
}
getch();
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <modbus.h>
#include "sensorhandler.h"
extern void sensors_poll(void);
modbus_t *mb1 = NULL;
modbus_t *mb2 = NULL;
modbus_t *initModbus_RTU(char *pdevpath, uint32_t sec, uint32_t usec)
{
modbus_t *mb = NULL;
//1-打开端口
if(NULL == (mb=modbus_new_rtu(pdevpath, 9600,'N',8, 1)))
{
printf("modbus-RTU serial open failed\r\n");
return NULL;
}
//2-设置从地址
modbus_set_slave(mb, 1);
//3-建立连接
modbus_connect(mb);
//4-设置应答延时
modbus_set_response_timeout(mb, sec, usec);
return mb;
}
void releaseModbus_RTU(modbus_t *mb)
{
if(mb == NULL)
return ;
//7-关闭modbus端口
modbus_close(mb);
//8-释放modbus资源
modbus_free(mb);
}
//温湿度传感器初始化
static void temperature_humidity_initial(void)
{
mb1 = initModbus_RTU("/dev/ttyUSB1", 0, 1000000);
if(mb1)
{
printf("mb1 open successed \r\n");
}
}
//噪声传感器初始化
static void noise_initial(void)
{
mb2 = initModbus_RTU("/dev/ttyUSB0", 0, 1000000);
if(mb2)
{
printf("mb2 open successed \r\n");
}
}
//温湿度传感器处理函数
static void temperature_humidity_handler(void *data)
{
uint16_t *tab_reg = (uint16_t*)data;
//6-读寄存器设置:寄存器地址、数量、数据缓冲
modbus_read_registers(mb1, 0, 2, tab_reg);
}
static void noise_handler(void *data)
{
uint16_t *tab_reg = (uint16_t*)data;
//6-读寄存器设置:寄存器地址、数量、数据缓冲
modbus_read_registers(mb2, 0, 1, tab_reg);
}
int main(int argc, char *argv[])
{
uint16_t tab_reg[2] = {0};
uint16_t noise = 0;
initial_sensoritem();
addto_sensoritem("temperature-humidity", temperature_humidity_initial, temperature_humidity_handler, tab_reg);
addto_sensoritem("noise-humidity", noise_initial, noise_handler, &noise);
sensors_initial();
//5-循环读
while(1)
{
sensors_poll();
printf("-------------------------------------------\n");
for(int i=0; i<2; i++)
{
printf("<%.2f>",tab_reg[i]*0.01);
}
printf("\n");
printf("=========noise: %.1f\r\n",noise*0.1);
sleep(3);
}
releaseModbus_RTU(mb1);
releaseModbus_RTU(mb2);
return 0;
}
|
C
|
#include "vm.h"
#include <stdlib.h>
#include <assert.h>
#include <string.h>
ArResult arCreateVirtualMachine(ArVirtualMachine* pVirtualMachine, const ArVirtualMachineCreateInfo* pInfo)
{
assert(pVirtualMachine);
assert(pInfo);
assert(pInfo->sType == AR_STRUCTURE_TYPE_VIRTUAl_MACHINE_CREATE_INFO);
const ArVirtualMachine output = malloc(sizeof(ArVirtualMachine_T));
if(!output)
{
return AR_ERROR_HOST_OUT_OF_MEMORY;
}
memset(output, 0, sizeof(ArVirtualMachine_T));
*pVirtualMachine = output;
(void)pInfo;
return AR_SUCCESS;
}
static void insertProcessor(ArVirtualMachine virtualMachine, ArProcessor processor)
{
ArProcessor previous = virtualMachine->processor;
if(previous)
{
while(previous->next) //Find last processor in virtual machine
{
previous = previous->next;
}
previous->next = processor;
}
else
{
virtualMachine->processor = processor; //Its the first processor
}
}
ArResult arCreateProcessor(ArVirtualMachine virtualMachine, const ArProcessorCreateInfo* pInfo, ArProcessor* pProcessor)
{
assert(virtualMachine);
assert(pInfo);
assert(pInfo->sType == AR_STRUCTURE_TYPE_PROCESSOR_CREATE_INFO);
assert(pInfo->pBootCode);
assert(pInfo->bootCodeSize % 2 == 0); //if not true then input is obviously truncated
assert(pProcessor);
const ArProcessor output = malloc(sizeof(ArProcessor_T));
if(!output)
{
return AR_ERROR_HOST_OUT_OF_MEMORY;
}
memset(output, 0, sizeof(ArProcessor_T));
output->parent = virtualMachine;
memcpy(output->isram, pInfo->pBootCode, pInfo->bootCodeSize * sizeof(uint32_t));
insertProcessor(virtualMachine, output);
*pProcessor = output;
return AR_SUCCESS;
}
ArResult arCreatePhysicalMemory(ArVirtualMachine virtualMachine, const ArPhysicalMemoryCreateInfo* pInfo, ArPhysicalMemory* pMemory)
{
assert(virtualMachine);
assert(pInfo);
assert(pInfo->sType == AR_STRUCTURE_TYPE_PHYSICAL_MEMORY_CREATE_INFO);
assert(pInfo->size > 0);
assert(pInfo->pMemory);
assert(pMemory);
if(virtualMachine->memory)
{
return AR_ERROR_TOO_MANY_OBJECTS;
}
const ArPhysicalMemory output = malloc(sizeof(ArPhysicalMemory_T));
if(!output)
{
return AR_ERROR_HOST_OUT_OF_MEMORY;
}
output->parent = virtualMachine;
output->memory = pInfo->pMemory;
output->size = pInfo->size;
*pMemory = output;
return AR_SUCCESS;
}
void arDestroyVirtualMachine(ArVirtualMachine virtualMachine)
{
assert(virtualMachine);
assert(!virtualMachine->memory);
assert(!virtualMachine->processor);
free(virtualMachine);
}
void arDestroyProcessor(ArVirtualMachine virtualMachine, ArProcessor processor)
{
assert(virtualMachine);
assert(virtualMachine->processor);
assert(processor);
if(virtualMachine->processor == processor)
{
virtualMachine->processor = processor->next;
}
else
{
ArProcessor previous = virtualMachine->processor;
while(previous->next && previous->next != processor)
{
previous = previous->next;
}
previous->next = processor->next;
}
free(processor);
}
void arDestroyPhysicalMemory(ArVirtualMachine virtualMachine, ArPhysicalMemory memory)
{
assert(virtualMachine);
assert(virtualMachine->memory);
assert(memory);
if(virtualMachine->memory == memory)
{
virtualMachine->memory = memory->next;
}
else
{
ArPhysicalMemory previous = virtualMachine->memory;
while(previous->next && previous->next != memory)
{
previous = previous->next;
}
previous->next = memory->next;
}
free(memory);
}
|
C
|
#include <unistd.h>
#include <stdint.h>
#include <types.h>
#include <stdio.h>
#include <sys/vmm.h>
/* This must be initialized data because commons can't have aliases. */
static void *__curbrk = NULL;
/**
* brk - 设置断点值
* @addr: 设置的地址
*
* 成功返回0,失败返回-1
*/
int brk(void *addr)
{
void *newbrk;
/* 保存新的brk值 */
__curbrk = newbrk = (void *) heap(addr);
//printf("__brk: %x\n", __curbrk);
/* 检测执行后的结果 */
if (newbrk < addr) {
return -1;
}
return 0;
}
/**
* __sbrk - 让断点移动位置
* @increment: 移动的距离,可正可负
*
* 返回移动前的brk指针位置
* 成功则返回brk地址,失败则返回-1指针,而不是NULL
*/
void *sbrk(int increment)
{
void *oldbrk;
/* If this is not part of the dynamic library or the library is used
via dynamic loading in a statically linked program update
__curbrk from the kernel's brk value. That way two separate
instances of brk and sbrk can lib the heap, returning
interleaved pieces of it. */
/* If have not Initialized */
if (__curbrk == NULL)
if (brk (0) < 0) /* Initialize the break. */
return (void *) -1;
/* If no increment, return current brk. */
if (increment == 0)
return __curbrk;
/* Get brk */
oldbrk = __curbrk;
/* If brk not right or __brk failed, return -1. */
if ((increment > 0 ?
((uint32_t) oldbrk + (uint32_t) increment < (uint32_t) oldbrk) :
((int32_t)oldbrk < -((int32_t)increment))) ||
brk ((void *)((int32_t)oldbrk + (int32_t)increment)) < 0)
return (void *) -1;
// printf("__sbrk: %x\n", oldbrk);
return oldbrk;
}
|
C
|
#include"stdio.h"
#define n 3
void main()
{
int m[n][n],m1[n][n],sub[n][n],i,j;
printf("enter the element in an array:-");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&m[i][j]);
}
}
printf("enter the element in second in an array:-");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&m1[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
sub[i][j]=m[i][j]-m1[i][j];
}
}
printf("After substraction array is:-\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d, ",sub[i][j]);
}
}
}
|
C
|
/*
* graph.c
* Copyright (C) 2016 DerShokus <lily.coder@gmail.com>
*
* Distributed under terms of the MIT license.
*/
#include <string.h>
#include "../src/lexer.h"
int main(int argc, char *argv[])
{
if (argc != 2)
return -1;
const char *source = argv[1];
const char *end = source + strlen(source);
struct FSM fsm = {
.p = source, .pe = end, .eof = end, .parser = ParseAlloc(malloc),
};
struct ast_node *root = NULL;
if (!lexer(&fsm, &root)) {
return -1;
}
FILE *file = fopen("out.dot", "w");
ast_node_graph(file, root);
fclose(file);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdbool.h>
#include "lib/contracts.h"
#include "lib/xalloc.h"
#include "queue.h"
//implementation
typedef struct list_node list;
struct list_node {
void* data;
list* next;
};
typedef struct queue_header queue;
struct queue_header {
list* front;
list* back;
int size;
};
bool is_inclusive_segment(list* start, list* end, int i) {
if(start == NULL && i == 0) return true;
if(end == NULL || end->next != NULL) return false;
if((start == end) && start->next == NULL && i == 1) return true;
int k = 1;
list* s = start;
while(s != NULL && s != end){
if(k > i) return false;
k++;
s = s->next;
}
if(s == NULL || k != i) return false;
return true;
}
bool is_queue(queue* Q) {
if (Q == NULL || Q->size < 0) return false;
return is_inclusive_segment(Q->front, Q->back, Q->size);
}
queue_t queue_new()
{
queue_t Q = xmalloc(sizeof(queue));
Q->front = NULL;
Q->size = 0;
ENSURES(Q != NULL);
ENSURES(is_queue(Q));
return Q;
}
size_t queue_size(queue_t Q)
{
REQUIRES(Q != NULL);
REQUIRES(is_queue(Q));
ENSURES(Q->size >= 0);
return Q->size;
}
void enq(queue_t Q, void* x)
{
REQUIRES(is_queue(Q));
REQUIRES(Q != NULL);
list* node = xmalloc(sizeof(list));
node->data = x;
if(Q->size == 0){
Q->front = node;
Q->back = node;
}
else{
Q->back->next = node;
Q->back = Q->back->next;
}
Q->size++;
ENSURES(is_queue(Q));
}
void* deq(queue_t Q)
{
REQUIRES(is_queue(Q));
REQUIRES(Q != NULL);
REQUIRES(queue_size(Q) > 0);
void* x = Q->front->data;
list* temp = Q->front;
Q->front = Q->front->next;
free(temp);
Q->size--;
ENSURES(is_queue(Q));
return x;
}
void *queue_peek(queue_t Q, size_t i)
{
REQUIRES(is_queue(Q));
REQUIRES(Q != NULL);
REQUIRES(i < queue_size(Q));
list* f = Q->front;
for(size_t k = 0; k < i; k++){
f = f->next;
}
ENSURES(is_queue(Q));
return f->data;
}
void queue_reverse(queue_t Q)
{
REQUIRES(is_queue(Q));
REQUIRES(Q != NULL);
if(queue_size(Q) <= 1) return;
list* prev = NULL;
list* f = Q->front;
while(f != NULL){
list* node = f->next;
f->next = prev;
prev = f;
f = node;
}
list* new = Q->front;
Q->front = Q->back;
Q->back = new;
ENSURES(is_queue(Q));
}
bool queue_all(queue_t Q, check_property_fn* P)
{
REQUIRES(Q != NULL);
REQUIRES(P != NULL);
REQUIRES(is_queue(Q));
list* f = Q->front;
while(f != NULL){
if(!(*P)(f->data)) return false;
f = f->next;
}
return true;
}
void* queue_iterate(queue_t Q, void* base, iterate_fn* F)
{
REQUIRES(Q != NULL);
REQUIRES(F != NULL);
REQUIRES(is_queue(Q));
if(queue_size(Q) == 0) return base;
list* f = Q->front;
void* B = base;
while(f != NULL){
B = (*F)(B, f->data);
f = f->next;
}
return B;
}
void queue_free(queue *Q, free_fn* F)
{
REQUIRES(Q != NULL);
REQUIRES(is_queue(Q));
REQUIRES(F != NULL);
list *f = Q->front;
while (f != NULL)
{
list* temp = f->next;
if (F != NULL) (*F)(f->data);
free(f);
f = temp;
}
free(Q);
}
|
C
|
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
// see man CPU_SET
int main() {
int cpu=0;
cpu_set_t mask[1];
// cpu=sched_getaffinity(getpid(),size,cpu_set_t);
cpu=sched_getaffinity(0,sizeof(cpu_set_t), mask);
// see man CPU_SET
fprintf(stderr,"Process/Thread affinity is CPU #%x.\n", *mask);
return 0;
}
|
C
|
#ifndef _SINGLELL_H
#define _SINGLELL_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct node {
uint8_t data;
struct node *next;
} node_t;
uint8_t list_length(node_t*);
void print_list(node_t*);
void add_first(node_t**, uint8_t);
void add_last(node_t**, uint8_t);
void add_element(node_t**, uint8_t, uint8_t);
int remove_first(node_t**);
int remove_last(node_t**);
int8_t remove_by_index(node_t**, uint8_t);
int remove_by_value(node_t**, uint8_t);
#endif
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
int a, b;
float c;
scanf("%f", &c);
a = (int)c;
c -= (float)a;
printf("%f\n",c);
if (c < 0)
{
for (int i = 1; i < 6; i++)
c *= 10;
}
else
{
for (int i = 1; i < 7; i++)
c *= 10;
}
if (c >= 0)
{
c = c + 0.5;
c = floor(c);
}
b = (int)c;
while (b % 10 == 0)
{
if (b == 0)
break;
b /= 10;
}
if (b < 0)
b *= -1;
printf("%d\n%d", a, b);
return 0;
}
|
C
|
/*
* numtowords.c
*
* Copyright (c) 2012 Cihangir Akturk
*
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
static char *out_buf;
static char *out_ptr;
static size_t out_buf_size;
static int digit_count = 0;
static char *numbers[] = {
"bir", "iki", "uc", "dort",
"bes", "alti", "yedi", "sekiz",
"dokuz", "on", "yirmi", "otuz",
"kirk", "elli", "altmis", "yetmis",
"seksen", "doksan", "yuz", "bin",
"milyon", "milyar", "trilyon"
};
static int prepend_str(const char *str)
{
size_t len = strlen(str);
if (out_ptr - len < out_buf)
return -ERANGE;
out_ptr -= len;
memcpy(out_ptr, str, len);
return 0;
}
static inline int prepend_char(char ch)
{
if (out_ptr - 1 < out_buf)
return -ERANGE;
--out_ptr;
*out_ptr = ch;
return 0;
}
static const char *numstr(unsigned long long digit, int place_val)
{
char *ret = NULL;
long long num = digit * place_val;
if (num < 11 && num > 0) {
ret = numbers[num - 1];
return ret;
}
switch (num) {
case 20:
ret = numbers[10];
break;
case 30:
ret = numbers[11];
break;
case 40:
ret = numbers[12];
break;
case 50:
ret = numbers[13];
break;
case 60:
ret = numbers[14];
break;
case 70:
ret = numbers[15];
break;
case 80:
ret = numbers[16];
break;
case 90:
ret = numbers[17];
break;
case 100:
ret = numbers[18];
break;
case 1000:
ret = numbers[19];
break;
case 1000000:
ret = numbers[20];
break;
case 1000000000:
ret = numbers[21];
break;
case 1000000000000:
ret = numbers[22];
break;
}
return ret;
}
static int __num_to_words(long num, char sep_char);
static inline unsigned long long _pow(int x, int y);
static int __numstr(int digit, int pos)
{
const char *str = NULL;
int ret = 0;
int triple = pos / 3;
int place_val = _pow(10, pos % 3);
switch (pos % 3) {
case 0:
if (triple) {
str = numstr(_pow(10, triple * 3), 1);
if ((ret = prepend_str(str)) != 0)
goto err_out;
if (digit &&
(digit > 1 ||
(triple > 0 && pos != digit_count - 1) ||
(triple > 1 && pos == digit_count - 1))) {
str = numstr(digit, 1);
if ((ret = prepend_str(str)) != 0)
goto err_out;
}
} else {
str = numstr(digit ,1);
if ((ret = prepend_str(str)) != 0)
goto err_out;
}
break;
case 1:
str = numstr(digit * place_val, 1);
if ((ret = prepend_str(str)) != 0)
goto err_out;
break;
case 2:
str = numstr(place_val, 1);
if ((ret = prepend_str(str)) != 0)
goto err_out;
if (digit > 1) {
str = numstr(digit, 1);
ret = prepend_str(str);
}
break;
}
err_out:
return ret;
}
static inline int numofdigits(long num)
{
int digits = 1;
if (num == 0) return 0;
while (num /= 10) ++digits;
return digits;
}
int num_to_words(char **buf, size_t size, double num, char sep_char)
{
int ret = 0;
long integer = (long)num;
long fraction = (num - integer) * 1000;
(void)fraction;
digit_count = numofdigits(integer);
out_buf = *buf;
out_buf_size = size;
out_ptr = out_buf + out_buf_size - 1;
*out_ptr = '\0';
ret = __num_to_words(integer, sep_char);
*buf = out_ptr;
return ret;
}
static int __num_to_words(long num, char sep_char)
{
unsigned char rmost_digit;
int pos = 0;
int triple = 0;
int result = 0;
/* Extract rightmost digit and shift right */
do {
rmost_digit = num % 10;
num /= 10;
if ((result = __numstr(rmost_digit, pos)))
break;
if (num && sep_char)
if((result = prepend_char(sep_char)))
break;
if (pos % 3 == 0)
++triple;
++pos;
} while (num);
return result;
}
static inline unsigned long long _pow(int x, int y)
{
unsigned long long result = 1;
if (!x)
return result;
while (y--)
result *= x;
return result;
}
|
C
|
//4 - Utilizando a mesma matriz, exiba a soma dos elementos da diagonal principal.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void){
srand(time(NULL));
int matrizInteiros[20][20];
int somaLinha = 0;
int maiorLinha;
int posicaoMaiorLinha = 0;
int somaDiagonal = 0;
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
matrizInteiros[i][j] = rand() % 89 + 10;
printf("%d ", matrizInteiros[i][j]);
if(i == j)
{
somaDiagonal += matrizInteiros[i][j];
}
}
if (i == 0)
{
for(int colunas = 0; colunas < 20; colunas++)
{
somaLinha += matrizInteiros[i][colunas];
}
maiorLinha = somaLinha;
posicaoMaiorLinha = i;
} else {
somaLinha = 0;
for(int colunas = 0; colunas < 20; colunas++)
{
somaLinha += matrizInteiros[i][colunas];
}
if (somaLinha > maiorLinha)
{
maiorLinha = somaLinha;
posicaoMaiorLinha = i;
}
}
printf("\n");
}
printf("A maior linha e %d com a soma %d\n", posicaoMaiorLinha, maiorLinha);
printf("A soma da diagonal principal e %d\n", somaDiagonal);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.