language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/*
Exemplo0101 - v0.0. - __ / __ / _____
Author: Matheus Augusto Moreira
Para compilar em terminal (janela de comandos):
Linux : gcc -o exemplo0101 exemplo0101.c
Windows: gcc -o exemplo0101.exe exemplo0101.c
Para executar em terminal (janela de comandos):
Linux : ./exemplo0101
Windows: exemplo0101
*/
// dependencias
#include <stdio.h> // para as entradas e saidas
/*
Funcao principal.
@return codigo de encerramento
@param argc - quantidade de parametros na linha de comandos
@param argv - arranjo com o grupo de parametros na linha de comandos
*/
int main ( int argc, char* argv [ ] )
{
// definir dado
int x = 0; // definir variavel com valor inicial
// identificar
printf ( "%s\n", "Exemplo0101 - Programa = v0.0" );
printf ( "%s\n", "Autor: Matheus Augusto Moreira" );
printf ( "\n" ); // mudar de linha
// mostrar valor inicial
printf ( "%s%d\n", "x = ", x );
// OBS.: O formato para int -> %d (ou %i)
// ler do teclado
printf ( "Entrar com um valor inteiro: " );
scanf ( "%d", &x );
// OBS.: Necessario indicar o endereco -> &
// mostrar valor lido
printf ( "%s%i\n", "x = ", x );
// encerrar
printf ( "\n\nApertar ENTER para terminar." );
fflush ( stdin ); // limpar a entrada de dados
getchar( ); // aguardar por ENTER
return ( 0 ); // voltar ao SO (sem erros)
} // fim main( )
/*
---------------------------------------------- documentacao complementar
---------------------------------------------- notas / observacoes / comentarios
---------------------------------------------- previsao de testes
a.) 5 apresentou o valor 5
b.) -5 apresentou o valor -5
c.) 123456789 apresentou o valor 123456789
---------------------------------------------- historico
Versao Data Modificacao
0.1 __/__ esboco
---------------------------------------------- testes
Versao Teste
0.1 01. ( ___ ) identificacao de programa
leitura e exibicao de inteiro
*/
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(){
int *A;
int size, sum = 0;
scanf("%d",&size);
A = (int* )malloc(sizeof(int)*size);
for(int i=0;i<size;i++){
scanf("%d",&A[i]);
}
for(int i=0;i<size;i++){
sum = sum + A[i];
}
printf("sum of Array: %d",sum);
return 0;
}
|
C
|
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include "procarray.h"
#include "master.h"
#include "type.h"
#include "master_data.h"
int nodenum;
int threadnum;
int client_port;
int master_port;
int message_port;
int param_port;
char master_ip[20];
// send buffer for server respond.
uint64_t ** msend_buffer;
uint64_t ** mrecv_buffer;
pthread_t * master_tid;
void* MasterRespond(void *sockp);
int ReadConfig(char * find_string, char * result)
{
int i;
int j;
int k;
FILE * fp;
char buffer[30];
char * p;
if ((fp = fopen("config.txt", "r")) == NULL)
{
printf("can not open the configure file.\n");
fclose(fp);
return -1;
}
for (i = 0; i < LINEMAX; i++)
{
if (fgets(buffer, sizeof(buffer), fp) == NULL)
continue;
for (p = find_string, j = 0; *p != '\0'; p++, j++)
{
if (*p != buffer[j])
break;
}
if (*p != '\0' || buffer[j] != ':')
{
continue;
}
else
{
k = 0;
// jump over the character ':' and the space character.
j = j + 2;
while (buffer[j] != '\0')
{
*(result+k) = buffer[j];
k++;
j++;
}
*(result+k) = '\0';
fclose(fp);
return 1;
}
}
fclose(fp);
printf("can not find the configure you need\n");
return -1;
}
void InitMasterBuffer(void)
{
int i;
msend_buffer = (uint64_t **) malloc (NODENUM*(THREADNUM+1) * sizeof(uint64_t *));
mrecv_buffer = (uint64_t **) malloc (NODENUM*(THREADNUM+1) * sizeof(uint64_t *));
if (msend_buffer == NULL || mrecv_buffer == NULL)
printf("master buffer pointer malloc error\n");
for (i = 0; i < NODENUM*(THREADNUM+1); i++)
{
msend_buffer[i] = (uint64_t *) malloc (MSEND_BUFFER_MAXSIZE * sizeof(uint64_t));
mrecv_buffer[i] = (uint64_t *) malloc (MRECV_BUFFER_MAXSIZE * sizeof(uint64_t));
if ((msend_buffer[i] == NULL) || mrecv_buffer[i] == NULL)
printf("master buffer malloc error\n");
}
}
void InitParam(void)
{
// record the accept socket fd of the connected client
int conn;
int param_connect;
int param_send_buffer[3];
int param_recv_buffer[1];
int master_sockfd;
int port = param_port;
// use the TCP protocol
master_sockfd = socket(AF_INET, SOCK_STREAM, 0);
// bind
struct sockaddr_in mastersock_addr;
memset(&mastersock_addr, 0, sizeof(mastersock_addr));
mastersock_addr.sin_family = AF_INET;
mastersock_addr.sin_port = htons(port);
mastersock_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(master_sockfd, (struct sockaddr *)&mastersock_addr, sizeof(mastersock_addr)) == -1)
{
printf("parameter server bind error!\n");
exit(1);
}
//listen
if(listen(master_sockfd, LISTEN_QUEUE) == -1)
{
printf("parameter server listen error!\n");
exit(1);
}
socklen_t slave_length;
struct sockaddr_in slave_addr;
slave_length = sizeof(slave_addr);
int i = 0;
while(i < NODENUM)
{
int ret;
conn = accept(master_sockfd, (struct sockaddr*)&slave_addr, &slave_length);
param_connect = conn;
if(conn < 0)
{
printf("param master accept connect error!\n");
exit(1);
}
i++;
param_send_buffer[0] = NODENUM;
param_send_buffer[1] = THREADNUM;
param_send_buffer[2] = client_port;
ret = recv(param_connect, param_recv_buffer, sizeof(param_recv_buffer), 0);
if (ret == -1)
printf("param master recv error\n");
ret = send(param_connect, param_send_buffer, sizeof(param_send_buffer), 0);
if (ret == -1)
printf("param naster send error\n");
close(param_connect);
}
}
void InitMessage(void)
{
// record the accept socket fd of the connected client
int conn;
int message_connect[NODENUM];
int message_buffer[1];
int master_sockfd;
int port = message_port;
// use the TCP protocol
master_sockfd = socket(AF_INET, SOCK_STREAM, 0);
//bind
struct sockaddr_in mastersock_addr;
memset(&mastersock_addr, 0, sizeof(mastersock_addr));
mastersock_addr.sin_family = AF_INET;
mastersock_addr.sin_port = htons(port);
mastersock_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(master_sockfd, (struct sockaddr *)&mastersock_addr, sizeof(mastersock_addr)) == -1)
{
printf("message server bind error!\n");
exit(1);
}
//listen
if(listen(master_sockfd, LISTEN_QUEUE) == -1)
{
printf("message server listen error!\n");
exit(1);
}
socklen_t slave_length;
struct sockaddr_in slave_addr;
slave_length = sizeof(slave_addr);
int i = 0;
while(i < NODENUM)
{
conn = accept(master_sockfd, (struct sockaddr*)&slave_addr, &slave_length);
message_connect[i] = conn;
if(conn < 0)
{
printf("message master accept connect error!\n");
exit(1);
}
i++;
}
int j;
int ret;
// inform the node in the system begin start the transaction process.
for (j = 0; j < NODENUM; j++)
{
ret = recv(message_connect[j], message_buffer, sizeof(message_buffer), 0);
if (ret == -1)
printf("message master recv error\n");
}
for (j = 0; j < NODENUM; j++)
{
message_buffer[0] = 999;
ret = send(message_connect[j], message_buffer, sizeof(message_buffer), 0);
if (ret == -1)
printf("message master send error\n");
close(message_connect[j]);
}
//now we can reform the node to begin to run the transaction.
}
void InitMaster(void)
{
int status;
//record the accept socket fd of the connected client
int conn;
master_arg *argu = (master_arg *) malloc (NODENUM*(THREADNUM+1)*sizeof(master_arg));
master_tid = (pthread_t *) malloc (NODENUM*(THREADNUM+1)*sizeof(pthread_t));
int master_sockfd;
void * pstatus;
int port = master_port;
// use the TCP protocol
master_sockfd = socket(AF_INET, SOCK_STREAM, 0);
//bind
struct sockaddr_in mastersock_addr;
memset(&mastersock_addr, 0, sizeof(mastersock_addr));
mastersock_addr.sin_family = AF_INET;
mastersock_addr.sin_port = htons(port);
mastersock_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(master_sockfd, (struct sockaddr *)&mastersock_addr, sizeof(mastersock_addr)) == -1)
{
printf("master server bind error!\n");
exit(1);
}
//listen
if(listen(master_sockfd, LISTEN_QUEUE) == -1)
{
printf("master server listen error!\n");
exit(1);
}
//receive or transfer data
socklen_t slave_length;
struct sockaddr_in slave_addr;
slave_length = sizeof(slave_addr);
int i = 0;
while(i < NODENUM*(THREADNUM+1))
{
conn = accept(master_sockfd, (struct sockaddr*)&slave_addr, &slave_length);
argu[i].conn = conn;
argu[i].index = i;
if(conn < 0)
{
printf("master accept connect error!\n");
exit(1);
}
status = pthread_create(&master_tid[i], NULL, MasterRespond, &(argu[i]));
if (status != 0)
printf("create thread %d error %d!\n", i, status);
i++;
}
for (i = 0; i < NODENUM*(THREADNUM+1); i++)
pthread_join(master_tid[i],&pstatus);
}
void* MasterRespond(void *pargu)
{
int conn;
int index;
master_arg * temp;
temp = (master_arg *) pargu;
conn = temp->conn;
index = temp->index;
memset(mrecv_buffer[index], 0, MRECV_BUFFER_MAXSIZE*sizeof(uint64_t));
int ret;
master_command type;
do
{
ret = recv(conn, mrecv_buffer[index], MRECV_BUFFER_MAXSIZE*sizeof(uint64_t), 0);
if (ret == -1)
{
printf("master receive error!\n");
}
type = (master_command)(*(mrecv_buffer[index]));
switch(type)
{
case cmd_starttransaction:
ProcessStartTransaction(mrecv_buffer[index], conn, index);
break;
case cmd_getendtimestamp:
ProcessEndTimestamp(mrecv_buffer[index], conn, index);
break;
case cmd_updateprocarray:
ProcessUpdateProcarray(mrecv_buffer[index], conn, index);
break;
case cmd_release_master:
printf("enter release master conncet\n");
break;
default:
printf("error route, never here!\n");
break;
}
} while (type != cmd_release_master);
close(conn);
pthread_exit(NULL);
return (void*)NULL;
}
void InitNetworkParam(void)
{
char buffer[5];
ReadConfig("threadnum", buffer);
threadnum = atoi(buffer);
ReadConfig("nodenum", buffer);
nodenum = atoi(buffer);
ReadConfig("clientport", buffer);
client_port = atoi(buffer);
ReadConfig("masterport", buffer);
master_port = atoi(buffer);
ReadConfig("paramport", buffer);
param_port = atoi(buffer);
ReadConfig("messageport", buffer);
message_port = atoi(buffer);
ReadConfig("masterip", master_ip);
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int fd;
if(argc != 2) {
printf("\n Usage: please provide the file to open\n");
return 1;
}
errno = 0;
//attempt to open a file or create if not present
fd = open(argv[1], O_RDONLY | O_CREAT);
if(fd == -1) {
printf("\n open() failed with error [%s]\n", strerror(errno));
return 1;
}
else printf("\n open() Successful\n");
//attempt to read the opened file
size_t bytes = 10;
char buffer[bytes];
bytes = read(fd, buffer, bytes);
if(bytes == -1) {
printf("\n read() failed with error [%s]\n", strerror(errno));
return 1;
}
else printf("\n read() Successful: %zd bytes have been read\n", bytes);
//attempt to close the read file
int closeSuccess;
closeSuccess = close(fd);
if(closeSuccess == -1) {
printf("\n close() failed with error [%s]\n", strerror(errno));
return 1;
}
else printf("\n close() Successful\n");
return 0;
}
|
C
|
#ifndef CreateFlag
#define CreateFlag(name,type, count,...) \
struct name\
{\
static const type __VA_ARGS__;\
static const unsigned int NUM_FLAGS = count;\
name() : _flags(type()) {}\
name(const type& singleFlag) : _flags(singleFlag) {}\
name(const name& original) : _flags(original._flags) {}\
bool operator==(const name& rhs) const { return _flags == rhs._flags; }\
name& operator =(const type& addValue) { this->_flags = addValue; return *this; }\
name& operator |=(const type& addValue) { _flags |= addValue; return *this; }\
name& operator |=(const name& addValue) { _flags |= addValue._flags; return *this; }\
name operator |(const type& addValue)const { name result(*this); result |= addValue; return result; }\
name& operator &=(const type& maskValue) { _flags &= maskValue; return *this; }\
name operator &(const type& maskValue)const { name result(*this); result &= maskValue; return result; }\
name operator ~()const { name result(*this); result._flags = ~result._flags; return result; }\
bool operator<(const name& other)const{ if(_flags < other._flags) return true; return false;}\
bool operator!=(const name& other)const{return _flags != other._flags;}\
operator type() { return _flags; }\
type _flags;\
}
#endif
|
C
|
#include "main.h"
#include <unistd.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
#include <stdint.h>
/**
* print_char - copies a char to a buffer
* @c: the char
* @buff: the buffer
* Return: number of char printed = 1
*/
char *print_char(char c, char *buff)
{
return (memcpy(buff, &c, 1));
}
/**
* print_str - copies a string to a buffer
* @s: the string
* @buff: the buffer
* Return: the number of chars written
*/
char *print_str(char *s, char *buff)
{
if (s == NULL)
{
memcpy(buff, "(null)", 6);
return (buff + 5);
}
if (*s == 0)
return (buff);
memcpy(buff, s, len(s));
return (buff + len(s) - 1);
}
/**
* print_strcap - prints a string, with non-printables as \x+hex value
* @s: string
* @buff: buffer save to
* Return: pointer to buffer
*/
char *print_strcap(char *s, char *buff)
{
int i;
if (s == NULL || *s == 0)
return (buff + 1);
for (i = 0; i < len(s); i++)
{
if (*(s + i) > 0 && (*(s + i) < 32 || *(s + i) >= 127))
{
memcpy(buff, "\\x", 2);
if (*(s + i) >= 1 && *(s + i) <= 15)
{
memcpy(buff + 2, "0", 1);
buff++;
}
buff += print_base(*(s + i), 16, 'X', (buff + 2), 0) + 1;
}
else
memcpy(buff, s + i, 1);
buff++;
}
return (buff);
}
/**
* print_int - copies an integer to a buffer
* @num: the integer
* @buff: the buffer
* Return: number of digits written
*/
char *print_int(int num, char *buff)
{
unsigned int len_s;
if (num < 0)
len_s = len_int(num * -1) + 1;
else
len_s = len_int(num);
return (save_int(buff, num, len_s));
}
/**
* print_uint - prints unsigned ints to a buffer
* @num: the number
* @buff: the buffer for saving
* Return: pointer to the start of the strings
*/
char *print_uint(int num, char *buff)
{
unsigned int len_s, u_num;
if (num < 0)
{
u_num = UINT_MAX + 1 + num;
len_s = len_int(u_num);
return (save_uint(buff, u_num, len_s));
}
else
len_s = len_int(num);
return (save_int(buff, num, len_s));
}
/**
* print_base - converts a decimal to a base and save in a buffer
* @num: the integer passed
* @base: the base to be converted to
* @f: a flag to specify upper or lower case letter in base 16 (x or X)
* @buff: the buffer
* @pos: current position in the result
* Return: number of digits printed
*/
int print_base(unsigned long int num, unsigned int base, char f,
char *buff, unsigned int pos)
{
char d;
if (num / base == 0)
{
if (base == 16 && num > 9)
d = hex(num, f);
else
d = num + '0';
(memcpy(buff, &d, 1));
return (1);
}
pos += print_base(num / base, base, f, buff, pos);
if (base == 16 && num % base > 9)
d = hex(num % base, f);
else
d = (num % base) + '0';
memcpy(buff + pos, &d, 1);
return (pos + 1);
}
/**
* print_p - prints a pointer to buff
* @p: the pointer
* @buff: the buffer
* Return: pointer to buffer
*/
char *print_p(size_t p, char *buff)
{
if (!p)
{
memcpy(buff, "(nil)", 5);
return (buff + 4);
}
memcpy(buff, "0x", 2);
buff += print_base(p, 16, 'x', (buff + 2), 0) + 1;
return (buff);
}
|
C
|
/* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */
#include "util.h"
int main(void) {
int fd;
fd = fcntl(1, F_DUPFD, 3);
test_assert(fd >= 3);
close(1);
fd = dup2(fd, 1);
test_assert(fd == 1);
atomic_puts("EXIT-SUCCESS");
return 0;
}
|
C
|
#include <stdio.h>
#define MAX 50
#define true 1
#define false 0
typedef int bool;
typedef struct {
int chave;
} REGISTRO;
typedef struct {
REGISTRO A[MAX];
int nroElem;
} LISTA;
void inicializarListaSequencial(LISTA* l) {
l->nroElem = 0;
}
void exibirListaSequencial (LISTA l) {
for (int i = 0; i < l.nroElem; i++) {
printf("%d ", l.A[i].chave);
}
}
int tamanhoLista (LISTA l) {
return(l.nroElem);
}
int primeiroElem (LISTA l) {
if (l.nroElem > 0) return l.A[0].chave;
else return -1;
}
int ultimoElem (LISTA l) {
if (l.nroElem > 0) return l.A[l.nroElem-1].chave;
else return -1;
}
int enesimoElem (LISTA l, int n) {
if (n <= l.nroElem) return l.A[n-1].chave;
else return -1;
}
void destruirLista (LISTA* l) {
l->nroElem = 0;
}
bool inserirElemListaSeq (int ch, int i, LISTA* l) {
if (l->nroElem >= MAX || l->nroElem < 0 || i < 0 || i > l->nroElem) return false;
for (int j = l->nroElem; j > i; j--) {
l->A[j] = l->A[j-1];
}
l->A[i].chave = ch;
l->nroElem++;
return true;
}
int buscaSeq (int ch, LISTA l) {
if (l.nroElem <= 0) return -1;
for (int i = 0; i < l.nroElem; i++) {
if (l.A[i].chave == ch) return i;
}
return -1;
}
int buscaSent (int ch, LISTA l) {
int i = 0;
l.A[l.nroElem].chave = ch;
while (l.A[i].chave < ch) i++;
if (i >= l.nroElem || l.A[i].chave != ch) return -1;
else return i;
}
int buscaBin (int ch, LISTA l) {
int ini = 0, fim = l.nroElem-1;
while (ini <= fim) {
if (l.A[(ini+fim)/2].chave > ch) {
fim = -1 + (ini+fim)/2;
} else if (l.A[(ini+fim)/2].chave < ch) {
ini = 1 + (ini+fim)/2;
} else if (l.A[(ini+fim)/2].chave == ch) {
return (ini+fim)/2;
}
}
return -1;
}
//sem duplicao com sentinela
bool inserirElemListOrd (int ch, LISTA* l) {
if (l->nroElem >= MAX) return false;
l->A[l->nroElem].chave = ch;
int i = 0;
while (l->A[i].chave < ch) i++;
if (l->A[i].chave == ch && i < l->nroElem) return false;
else return inserirElemListaSeq (ch, i, l);
}
bool excluirElemLista (int ch, LISTA* l) {
if(l->nroElem <= 0) return false;
for (int i = 0; i < l->nroElem; i++) {
if (l->A[i].chave == ch) {
for (int j = i; i < l->nroElem-1; j++) {
l->A[j] = l->A[j+1];
}
l->nroElem--;
return true;
}
}
return false;
}
int main(){
LISTA l;
int ch, i, n = l.nroElem;
bool condicao = true;
inicializarListaSequencial(&l);
while(condicao) {
int comando = 0;
printf("Escolha um comando: \n");
printf("1- Inserir \n");
printf("2- Excluir \n");
printf("3- Exibir \n");
printf("4- Buscar \n");
printf("5- Tamanho \n");
printf("6- Ultimo elemento \n");
printf("7- Enesimo elemento \n");
printf("8- Fechar \n");
printf("9- Primeiro elemento \n");
printf("10- Destruir lista \n");
printf("11- Busca com sentinela \n");
printf("12- Busca binaria \n");
printf("13- Inserir sem duplicacao com sentinela \n");
printf("Digite o numero: ");
scanf("%d", &comando);
switch(comando) {
case 1:
printf("Digite a chave: ");
scanf("%d", &ch);
printf("Digite a posicao: ");
scanf("%d", &i);
inserirElemListaSeq (ch, i, &l);
break;
case 2:
printf("Digite a chave: ");
scanf("%d", &ch);
excluirElemLista (ch, &l);
break;
case 3:
exibirListaSequencial (l);
printf("\n");
break;
case 4:
printf("Digite a chave: " );
scanf("%d", &ch);
printf ("%d\n", buscaSeq (ch, l));
break;
case 5:
printf ("%d\n", tamanhoLista (l));
break;
case 6:
printf ("%d\n", ultimoElem (l));
break;
case 7:
scanf("%d", &i);
printf("%d\n", enesimoElem(l, n));
break;
case 8:
condicao = false;
break;
case 9:
printf("%d\n", primeiroElem (l));
break;
case 10:
destruirLista (&l);
break;
case 11:
printf("Digite a chave: ");
scanf("%d", &ch);
printf("%d\n", buscaSeq (ch, l));
break;
case 12:
printf("Digite a chave: ");
scanf("%d", &ch);
printf("%d\n", buscaBin (ch, l));
break;
case 13:
printf("Digite a chave: ");
scanf("%d", &ch);
printf("%d\n", inserirElemListOrd (ch, &l));
break;
default:
printf("Digite um comando valido: ");
scanf("%d", &comando);
printf("\n");
break;
}
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>
#include <time.h>
#include "cz_API.h"
/* VARIABLES GLOBALES */
char disk[1000];
/////////////////////////
/* FUNCIONES GENERALES */
/////////////////////////
// FUNCIONANDO
void cz_mount(const char* diskname)
{
strcpy(disk, diskname);
}
// FUNCIONANDO
void cz_bitmap()
{
int used_blocks = 0;
int size = 8192;
unsigned char buffer[size];
FILE* ptr;
ptr = fopen(disk,"rb");
int n = 1;
fseek(ptr, n * 2048, SEEK_SET);
fread(buffer,sizeof(buffer),1,ptr);
for (int k = 0; k < 4; k++) {
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 16; j++) {
int byte_array[8] = { 0 };
byte_to_bits(buffer[(k * 2048) + (i * 16) + j], byte_array);
for (int q = 0; q < 8; q++){
if (byte_array[q] == 1) used_blocks++;
fprintf( stderr, "%d", byte_array[q]);
}
fprintf(stderr, " ");
}
fprintf(stderr, "\n");
}
fprintf(stderr, "\n");
}
fprintf(stderr, "Used blocks: %d\n", used_blocks);
fprintf(stderr, "Free blocks: %d\n", 65536 - used_blocks);
fprintf(stderr, "\n");
fclose(ptr);
}
// FUNCIONANDO
int cz_exists(const char* path)
{
int pointer = search_path(path);
return pointer != -1;
}
// FUNCIONANDO
void cz_ls(const char* path)
{
if (is_folder(path) == 0) {
fprintf(stderr, "[ERROR] La ruta no es un directorio.\n");
return;
}
int pointer = search_path(path);
if (pointer == -1) {
fprintf(stderr, "[ERROR] Directorio no existe.\n");
return;
}
else {
unsigned char current_block[2048];
get_block(pointer, current_block);
for (int j = 0; j < 128; j++) {
if (current_block[j * 16] == 0x02 || current_block[j * 16] == 0x04) {
print_name(current_block, j * 16);
}
}
}
}
//////////////////////////////////
/* FUNCIONES MANEJO DE ARCHIVOS */
//////////////////////////////////
czFILE* cz_open(const char* abs_path, const char mode)
{
char path[1000];
strcpy(path, abs_path);
if (is_folder(path)) {
fprintf(stderr, "[ERROR] La ruta entregada indica a un directorio.\n");
return NULL;
}
char file_name[1000];
strcpy(file_name, "");
get_child_name(file_name, path);
char parent_path[1000];
strcpy(parent_path, "");
get_parent_path(parent_path, path);
int file_pointer = search_path(path);
if (mode == 'r') {
if (file_pointer == -1) {
fprintf(stderr, "[ERROR] El archivo no existe.\n");
return NULL;
}
czFILE* file = malloc(sizeof(czFILE));
file->is_open = true;
file->mode = 'r';
file->index_pointer = file_pointer;
file->last_byte_read = 0;
file->last_byte_written = 0;
strcpy(file->path, abs_path);
return file;
}
else if (mode == 'w') {
if (file_pointer != -1) {
fprintf(stderr, "[ERROR] El archivo ya existe.\n");
return NULL;
}
if (strlen(file_name) > 11)
{
fprintf(stderr, "[ERROR] El archivo tiene un nombre muy largo.\n");
return NULL;
}
czFILE* file = malloc(sizeof(czFILE));
file->is_open = true;
file->mode = 'w';
file->index_pointer = create_file_at_block(file_name, search_path(parent_path));
file->last_byte_read = 0;
file->last_byte_written = 0;
strcpy(file->path, abs_path);
return file;
}
return NULL;
}
int cz_read(czFILE* file_desc, unsigned char* buffer, const int nbytes)
{
if (file_desc->mode != 'r') {
fprintf(stderr, "[ERROR] El archivo no se encuentra en modo lectura.\n");
return -1;
}
if (!file_desc->is_open) {
fprintf(stderr, "[ERROR] El archivo no se encuentra abierto.\n");
return -1;
}
if (file_desc == NULL) {
fprintf(stderr, "[ERROR] El archivo no pudo abrirse.\n");
return -1;
}
int bytes_read = 0;
int blocks_read = 0;
//accede al bloque indice y desde ahí a los bloques de datos:
unsigned char index_block[2048];
get_block(file_desc->index_pointer, index_block);
for (int n = 2; n < 511; n++) {
unsigned char data_block[2048];
int block_int = (index_block[n * 4 + 2] << 8) | index_block[n * 4 + 3];
get_block(block_int, data_block);
read_data_block(file_desc, buffer, nbytes, data_block, &bytes_read, &blocks_read);
if (bytes_read >= nbytes) break;
}
// Si le faltan bytes, va al bloque de direccionamiento indirecto
if (bytes_read < nbytes) {
unsigned char indirect_block[2048];
int indirect_block_int = (index_block[2046] << 8) | index_block[2047];
get_block(indirect_block_int, indirect_block);
for (int n = 0; n < 512; n++){
unsigned char data_block[2048];
int block_int = (indirect_block[n * 4 + 2] << 8) | indirect_block[n * 4 + 3];
get_block(block_int, data_block);
read_data_block(file_desc, buffer, nbytes, data_block, &bytes_read, &blocks_read);
if (bytes_read >= nbytes) break;
}
}
return bytes_read;
}
int cz_write(czFILE* file_desc, unsigned char* buffer, const int nbytes)
{
if(file_desc == NULL){
fprintf(stderr, "[ERROR] El archivo no existe.\n");
return -1;
}
if (file_desc->mode != 'w') {
fprintf(stderr, "[ERROR] El archivo no se encuentra en modo escritura.\n");
return -1;
}
if (!file_desc->is_open) {
fprintf(stderr, "[ERROR] El archivo no se encuentra abierto\n");
return -1;
}
int bytes_written = 0;
int blocks_written = 0;
//accede al bloque indice y desde ahí a los bloques de datos:
unsigned char index_block[2048];
get_block(file_desc->index_pointer, index_block);
for (int n = 2; n < 511; n++) {
int pointer = get_free_block();
if (pointer == -1) {
fprintf(stderr, "[ERROR] El disco está lleno.\n");
return -1;
}
clean_block(pointer);
unsigned char data_block[2048];
get_block(pointer, data_block);
change_block_in_bitmap(pointer, 1);
unsigned char digits[2];
digits[0] = pointer & 0xFF;
digits[1] = (pointer >> 8) & 0xFF;
write_byte(file_desc->index_pointer, (4 * n) + 2, digits[1]);
write_byte(file_desc->index_pointer, (4 * n) + 3, digits[0]);
write_data_block(file_desc, buffer, nbytes, pointer, &bytes_written, &blocks_written);
if (bytes_written >= nbytes) break;
}
// Si le faltan bytes, va al bloque de direccionamiento indirecto
if (bytes_written < nbytes) {
int indirect_pointer = get_free_block();
if (indirect_pointer == -1) {
fprintf(stderr, "[ERROR] El disco está lleno.\n");
return -1;
}
clean_block(indirect_pointer);
unsigned char indirect_block[2048];
get_block(indirect_pointer, indirect_block);
change_block_in_bitmap(indirect_pointer, 1);
unsigned char digits[2];
digits[0] = indirect_pointer & 0xFF;
digits[1] = (indirect_pointer >> 8) & 0xFF;
write_byte(file_desc->index_pointer, 2046, digits[1]);
write_byte(file_desc->index_pointer, 2047, digits[0]);
for (int n = 0; n < 512; n++) {
int pointer = get_free_block();
if (pointer == -1) {
fprintf(stderr, "[ERROR] El disco está lleno.\n");
return -1;
}
clean_block(pointer);
unsigned char data_block[2048];
get_block(pointer, data_block);
change_block_in_bitmap(pointer, 1);
unsigned char digits[2];
digits[0] = pointer & 0xFF;
digits[1] = (pointer >> 8) & 0xFF;
write_byte(indirect_pointer, (n * 4) + 2, digits[1]);
write_byte(indirect_pointer, (n * 4) + 3, digits[0]);
write_data_block(file_desc, buffer, nbytes, pointer, &bytes_written, &blocks_written);
if (bytes_written >= nbytes) break;
}
if (bytes_written < nbytes) {
fprintf(stderr, "[ERROR] El archivo no puede crecer más.\n");
unsigned char file_size[4];
file_size[0] = file_desc->last_byte_written & 0xFF;
file_size[1] = (file_desc->last_byte_written >> 8) & 0xFF;
file_size[2] = (file_desc->last_byte_written >> 16) & 0xFF;
file_size[3] = (file_desc->last_byte_written >> 24) & 0xFF;
write_byte(file_desc->index_pointer, 0, file_size[3]);
write_byte(file_desc->index_pointer, 1, file_size[2]);
write_byte(file_desc->index_pointer, 2, file_size[1]);
write_byte(file_desc->index_pointer, 3, file_size[0]);
unsigned char timestamp[4];
time_t current_time = time(NULL);
timestamp[0] = current_time & 0xFF;
timestamp[1] = (current_time >> 8) & 0xFF;
timestamp[2] = (current_time >> 16) & 0xFF;
timestamp[3] = (current_time >> 24) & 0xFF;
write_byte(file_desc->index_pointer, 4, timestamp[3]);
write_byte(file_desc->index_pointer, 5, timestamp[2]);
write_byte(file_desc->index_pointer, 6, timestamp[1]);
write_byte(file_desc->index_pointer, 7, timestamp[0]);
return bytes_written;
}
}
unsigned char file_size[4];
file_size[0] = file_desc->last_byte_written & 0xFF;
file_size[1] = (file_desc->last_byte_written >> 8) & 0xFF;
file_size[2] = (file_desc->last_byte_written >> 16) & 0xFF;
file_size[3] = (file_desc->last_byte_written >> 24) & 0xFF;
write_byte(file_desc->index_pointer, 0, file_size[3]);
write_byte(file_desc->index_pointer, 1, file_size[2]);
write_byte(file_desc->index_pointer, 2, file_size[1]);
write_byte(file_desc->index_pointer, 3, file_size[0]);
unsigned char timestamp[4];
time_t current_time = time(0);
timestamp[0] = current_time & 0xFF;
timestamp[1] = (current_time >> 8) & 0xFF;
timestamp[2] = (current_time >> 16) & 0xFF;
timestamp[3] = (current_time >> 24) & 0xFF;
write_byte(file_desc->index_pointer, 4, timestamp[3]);
write_byte(file_desc->index_pointer, 5, timestamp[2]);
write_byte(file_desc->index_pointer, 6, timestamp[1]);
write_byte(file_desc->index_pointer, 7, timestamp[0]);
return bytes_written;
}
int cz_close(czFILE* file_desc)
{
if (file_desc == NULL) {
fprintf(stderr, "[ERROR] Archivo no existe. \n");
return -1;
}
file_desc->is_open = false;
file_desc->mode = 'x';
free(file_desc);
return 0;
}
int cz_mv(const char* orig, const char *dest) {
if (orig[strlen(orig) - 1] == '/') {
fprintf(stderr, "[ERROR] Ruta origen debe ser un archivo. \n");
return 1;
}
if (dest[strlen(dest) - 1] == '/') {
fprintf(stderr, "[ERROR] Ruta destino debe ser un archivo. \n");
return 1;
}
if (!cz_exists(orig)) {
fprintf(stderr, "[ERROR] Archivo no encontrado. \n");
return 1;
}
if (cz_exists(dest)) {
fprintf(stderr, "[ERROR] Destino ya está en uso. \n");
return 1;
}
char orig_parent_path[1000];
char orig_file_name[1000];
strcpy(orig_file_name, "");
get_parent_path(orig_parent_path, orig);
get_child_name(orig_file_name, orig);
char dest_parent_path[1000];
char dest_file_name[1000];
strcpy(dest_file_name, "");
get_parent_path(dest_parent_path, dest);
get_child_name(dest_file_name, dest);
if (strlen(dest_file_name) > 11) {
fprintf(stderr, "[ERROR] Nombre archivo destino muy largo. \n");
return 1;
}
if (!cz_exists(dest_parent_path)) {
fprintf(stderr, "[ERROR] Carpeta destino incorrecta. \n");
return 1;
}
bool change_name = (strcmp(orig_parent_path, dest_parent_path) == 0);
int orig_parent_pointer = search_path(orig_parent_path);
unsigned char parent_block[2048];
get_block(orig_parent_pointer, parent_block);
int dest_parent_pointer = search_path(dest_parent_path);
unsigned char dest_parent_block[2048];
get_block(dest_parent_pointer, dest_parent_block);
for (int j = 0; j < 128; j++){
if (get_byte_in_block(parent_block, j, 0) == 0x04){
char file_name[1000];
strcpy(file_name, "");
get_name(parent_block, file_name, j * 16);
char orig_file_name[1000];
strcpy(orig_file_name, "");
get_child_name(orig_file_name, orig);
if (strcmp(orig_file_name, file_name) == 0) { //Si encuentro mi archivo
strcpy(dest_file_name, "");
get_child_name(dest_file_name, dest);
unsigned char byte_1 = get_byte_in_block(parent_block, j, 14);
unsigned char byte_2 = get_byte_in_block(parent_block, j, 15);
int bytes_pointer = (byte_1 << 8) | byte_2;
if (change_name == 1) {
write_line(orig_parent_pointer, j, 0x04, dest_file_name, bytes_pointer);
return 0;
}
else {
dest_parent_pointer = search_path(dest_parent_path);
unsigned char dest_parent_block[2048];
get_block(dest_parent_pointer, dest_parent_block);
for (int k = 0; k < 128; k++) {
if (dest_parent_block[k * 16] == 0x01 || dest_parent_block[k * 16] == 0x00) {
write_line(dest_parent_pointer, k, 0x04, dest_file_name, bytes_pointer);
write_line(orig_parent_pointer, j, 0x01, dest_file_name, bytes_pointer);
return 0;
}
}
}
}
}
}
fprintf(stderr, "[ERROR] No hay espacio en el bloque. \n");
return 1;
}
int cz_cp(const char* orig, const char* dest)
{
char parent_path[1000];
strcpy(parent_path, "");
get_parent_path(parent_path, dest);
if (search_path(parent_path) == -1) {
fprintf(stderr, "[ERROR] No existe la carpeta en la que quiere copiar el archivo. \n");
return -1;
}
czFILE* read_file;
read_file = cz_open(orig, 'r');
if (read_file == NULL) {
fprintf(stderr, "[ERROR] El archivo a copiar es nulo. \n");
cz_close(read_file);
return -1;
}
char dest_name[1000];
strcpy(dest_name, "");
get_child_name(dest_name, dest);
if (strlen(dest_name) > 11) {
fprintf(stderr, "[ERROR] Nombre del archivo es muy largo. \n");
cz_close(read_file);
return -1;
}
unsigned char index_block[2048];
get_block(read_file->index_pointer, index_block);
const int size = (index_block[0] << 24) | (index_block[1] << 16) | (index_block[2] << 8) | index_block[3];
// unsigned char buffer[size];
unsigned char* buffer = calloc(size, sizeof(unsigned char));
if (cz_read(read_file, buffer, size) == -1) return -1;
cz_close(read_file);
czFILE* write_file;
if ((write_file = cz_open(dest, 'w')) == NULL) {
fprintf(stderr, "[ERROR] El archivo a escribir no existe. \n");
free(buffer);
return -1;
}
if (cz_write(write_file, buffer, size) == -1) {
fprintf(stderr, "[ERROR] Se acabó el espacio de escritura. \n");
cz_close(write_file);
free(buffer);
return -1;
}
cz_close(write_file);
free(buffer);
return 0;
}
int cz_rm(const char* path) {
if (is_folder(path) == 1) {
fprintf(stderr, "[ERROR] Este comando solo borra archivos. \n");
return 1;
}
int pointer = search_path(path);
if (pointer == -1) {
fprintf(stderr, "[ERROR] Ruta incorrecta. \n");
return 2;
}
char parent_path[1000];
char file_name[1000];
get_parent_path(parent_path, path);
get_child_name(file_name, path);
unsigned char current_block[2048];
get_block(pointer, current_block);
const int parent_pointer = search_path(parent_path);
unsigned char parent_block[2048];
get_block(parent_pointer, parent_block);
for (int j = 0; j < 128; j++) {
if (parent_block[j * 16] == 0x04){
char name[12];
strcpy(name, "");
for (int l=1;l < 12;l++) {
sprintf(name + strlen(name), "%c", parent_block[j*16 + l]);
}
if (strcmp(file_name, name) == 0) {
write_byte(parent_pointer, j*16, 0x01);
break;
}
}
}
for (int j = 0; j < 509; j++) {
int data_pointer = (current_block[8 + j*4 + 2] << 8) | current_block[8 + j*4 + 3];
if (data_pointer != 0) {
change_block_in_bitmap(data_pointer,0);
}
}
int indirect_block_pointer = (current_block[2046] << 8) | current_block[2047];
unsigned char indirect_block[2048];
get_block(indirect_block_pointer, indirect_block);
if(indirect_block_pointer != 0) {
for (int j = 0; j < 512; j++) {
int data_pointer = (indirect_block[j*4 + 2] << 8) | indirect_block[j*4 + 3];
if (data_pointer != 0) {
change_block_in_bitmap(data_pointer, 0);
}
}
if ((indirect_block_pointer) != 0) {
change_block_in_bitmap(indirect_block_pointer, 0);
}
}
change_block_in_bitmap(pointer, 0);
return 0;
}
/////////////////////////////////////
/* FUNCIONES MANEJO DE DIRECTORIOS */
/////////////////////////////////////
// FUNCIONANDO
int cz_mkdir(const char* foldername)
{
// MANEJO DE ERRORES
if (cz_exists(foldername) && is_folder(foldername)) {
fprintf(stderr, "[ERROR] Carpeta ya existe. \n");
return 1;
}
if (!is_folder(foldername)) {
fprintf(stderr, "[ERROR] Este comando solo crea carpetas, no archivos. \n");
return 2;
}
if (get_free_block() == -1) {
fprintf(stderr, "[ERROR] No queda memoria para asignar un bloque. \n");
return 3;
}
char parent_path[1000];
strcpy(parent_path, "");
get_parent_path(parent_path, foldername);
if (search_path(parent_path) == -1) {
fprintf(stderr, "[ERROR] No se encuentra la carpeta padre de la carpeta a crear. \n");
return 4;
}
char child_name[1000];
strcpy(child_name, "");
get_child_name(child_name, foldername);
if (strlen(child_name) > 11) {
fprintf(stderr, "[ERROR] El nombre de la carpeta es muy largo. \n");
}
// FIN MANEJO DE ERRORES
char real_path[1000];
int i;
strcpy(real_path, foldername);
char last_available_directory[1000];
char current_directory[1000];
strcpy(last_available_directory, "");
strcpy(current_directory, "");
int pointer = -1;
for(i= 0; i < strlen(foldername); i++)
{
strncat(last_available_directory, &foldername[i], 1);
strncat(current_directory, &foldername[i], 1);
if(foldername[i] == 47)
{
if(cz_exists(last_available_directory) == 0)
{
current_directory[strlen(current_directory) - 1] = 0;
for(int j = i; j < strlen(foldername); j++)
{
strncat(current_directory, &foldername[j], 1);
}
int result = create_folder_at_block(current_directory, pointer);
return result;
}else{
strcpy(current_directory, "");
pointer = search_path(last_available_directory);
}
}
}
return 1;
}
int cz_mvdir(const char* foldername, const char* dest)
{
// MANEJO DE ERRORES
if (!is_folder(foldername)) {
fprintf(stderr, "[ERROR] carpeta original no es directorio. \n");
return 1;
}
if (!is_folder(dest)) {
fprintf(stderr, "[ERROR] carpeta destino no es directorio. \n");
return 1;
}
if (search_path(foldername) == -1) {
fprintf(stderr, "[ERROR] carpeta original no existe. \n");
return 2;
}
char origin[1000];
char origin_cmp[1000];
char destine[1000];
char destine_child[1000];
strcpy(destine_child, "");
get_child_name(destine_child, dest);
if (strlen(destine_child) > 11) {
fprintf(stderr, "[ERROR] carpeta de destino tiene un nombre muy largo. \n");
return 3;
}
char destine_cmp[1000];
char destine_parent[1000];
strcpy(origin, foldername);
strcpy(destine, dest);
get_parent_path(destine_parent, destine);
if (search_path(destine_parent) == -1) {
fprintf(stderr, "[ERROR] existen carpetas intermedias en el destino que no han sido creadas. \n");
return 4;
}
strcpy(origin_cmp, "");
strcpy(destine_cmp, "");
int start = 0;
for (start = 0; start < strlen(origin); start++) {
strncat(origin_cmp, &origin[start], 1);
strncat(destine_cmp, &destine[start], 1);
}
if (strcmp(origin_cmp, destine_cmp) == 0) {
fprintf(stderr, "[ERROR] No se puede mover la carpeta origen a una carpeta dentro de la carpeta origen. \n");
return 5;
}
int result = cz_mkdir(destine);
if (result != 0) {
fprintf(stderr, "[ERROR] No hay espacio suficiente en disco para crear la carpeta. \n");
return 6;
}
// FIN MANEJO DE ERRORES
int origin_pointer = search_path(origin);
int destine_pointer = search_path(destine);
unsigned char origin_block[2048];
get_block(origin_pointer, origin_block);
for (int j = 0; j < 2048; j++) write_byte(destine_pointer, j, origin_block[j]);
change_block_in_bitmap(origin_pointer, 0);
char parent_folder[1000];
char child_name[1000];
strcpy(parent_folder, "");
strcpy(child_name, "");
get_parent_path(parent_folder, origin);
get_child_name(child_name, origin);
int parent_pointer = search_path(parent_folder);
unsigned char parent_block[2048];
get_block(parent_pointer, parent_block);
for (int i = 0; i < 128; i++) {
if (get_byte_in_block(parent_block, i, 0) == 0x02) {
char name[1000];
strcpy(name, "");
get_name(parent_block, name, i * 16);
if (strcmp(child_name, name) == 0) {
write_byte(parent_pointer, i * 16, 0x01);
}
}
}
return 0;
}
int cz_cpdir(const char* foldername, const char* dest)
{
// MANEJO DE ERRORES
if (!is_folder(foldername)) {
fprintf(stderr, "[ERROR] Ruta de origen no es carpeta.\n");
return 1;
}
if (!is_folder(dest)) {
fprintf(stderr, "[ERROR] Ruta de destino no es carpeta.\n");
return 1;
}
char parent_folder[1000];
strcpy(parent_folder, "");
get_parent_path(parent_folder, dest);
if (search_path(parent_folder) == -1) {
fprintf(stderr, "[ERROR] Carpeta pariente de destino no existe.\n");
return 2;
}
if (search_path(foldername) == -1) {
fprintf(stderr, "[ERROR] Ruta de origen no existe.\n");
return 3;
}
char child_path[1000];
strcpy(child_path, "");
get_child_name(child_path, dest);
if (strlen(child_path) > 11) {
fprintf(stderr, "[ERROR] nombre muy largo\n");
return 4;
}
if (is_inside_itself(foldername, dest) == 1) {
fprintf(stderr, "[ERROR] No puede copiar una carpeta dentro de sí misma.\n");
return 5;
}
// FIN MANEJO DE ERRORES
char dest_name[1000];
strcpy(dest_name, "");
get_child_name(dest_name, dest);
int origin_pointer = search_path(foldername);
unsigned char origin_block[2048];
unsigned char dest_parent_block[2048];
get_block(origin_pointer, origin_block);
int free_block = get_free_block();
change_block_in_bitmap(free_block, 1);
int dest_parent_pointer = search_path(parent_folder);
get_block(dest_parent_pointer, dest_parent_block);
for (int i = 0; i < 128;i++) {
if (get_byte_in_block(dest_parent_block, i, 0) != 0x02 && get_byte_in_block(dest_parent_block, i, 0) != 0x04) {
write_line(dest_parent_pointer, i, 0x02, dest_name, free_block);
break;
}
}
for (int i = 0; i < 128; i++) {
if (get_byte_in_block(origin_block, i, 0) == 0x02) {
char name[1000];
char old_folder_path[1000];
char new_folder_path[1000];
strcpy(name, "");
strcpy(new_folder_path, "");
strcpy(old_folder_path, "");
strcpy(new_folder_path, dest);
strcpy(old_folder_path, foldername);
get_name(origin_block, name, i * 16);
strcat(new_folder_path, name);
strcat(old_folder_path, name);
strcat(new_folder_path, "/");
strcat(old_folder_path, "/");
int cpdir_result = cz_cpdir(old_folder_path, new_folder_path);
if (cpdir_result != 0) return 1;
}
else if(get_byte_in_block(origin_block, i, 0) == 0x04) {
char name[1000];
char old_file_path[1000];
char new_file_path[1000];
strcpy(name, "");
strcpy(new_file_path, "");
strcpy(old_file_path, "");
strcpy(new_file_path, dest);
strcpy(old_file_path, foldername);
get_name(origin_block, name, i * 16);
strcat(new_file_path, name);
strcat(old_file_path, name);
int cp_result = cz_cp(old_file_path, new_file_path);
if (cp_result != 0) return 1;
}
}
return 0;
}
int cz_rmdir(const char* path)
{
// MANEJO DE ERRORES
if (!is_folder(path)) {
fprintf(stderr, "[ERROR] ruta no corresponde a una carpeta. \n");
return 1;
}
int pointer = search_path(path);
if (pointer == -1) {
fprintf(stderr, "[ERROR] ruta no encontrada. \n");
return 2;
}
char real_path[1000];
strcpy(real_path, path);
if (strcmp(real_path, "/") == 0) {
fprintf(stderr, "[ERROR] No se puede eliminar el directorio raíz\n");
return 3;
}
// FIN MANEJO DE ERRORES
unsigned char block[2048];
unsigned char parent_block[2048];
get_block(pointer, block);
char parent[1000];
char child[1000];
strcpy(parent, "");
strcpy(child, "");
get_parent_path(parent, real_path);
get_child_name(child, real_path);
int parent_pointer = search_path(parent);
get_block(parent_pointer, parent_block);
for (int i = 0; i < 128; i++) {
char name[1000];
char file_path[1000];
strcpy(name, "");
strcpy(file_path, "");
strcpy(file_path, real_path);
unsigned char byte = get_byte_in_block(block, i, 0);
if (byte == 0x02) { // Si es directorio…
get_name(block, name, i * 16);
strcat(file_path, name);
strcat(file_path, "/");
cz_rmdir(file_path);
}
else if (byte == 0x04) { // Si es archivo…
get_name(block, name, i * 16);
strcat(file_path, name);
cz_rm(file_path);
strcpy(file_path, real_path);
}
}
for (int i = 0; i < 128; i++) {
if (get_byte_in_block(parent_block, i, 0) == 0x02) {
char directory[1000];
strcpy(directory, "");
get_name(parent_block, directory, i * 16);
if (strcmp(directory, child) == 0) write_byte(parent_pointer, i * 16, 0x01);
}
}
change_block_in_bitmap(pointer, 0);
return 0;
}
//////////////////////
/* FUNCIONES EXTRAS */
//////////////////////
void byte_to_bits(unsigned char byte, int* buff)
{
for (int i = sizeof(unsigned char) * 8; i; byte >>= 1) buff[--i] = byte & 1;
}
unsigned char bits_to_byte(int* array)
{
int final = 0;
for (int i = 0; i < 8; i++) {
int power = 1;
for (int j = 6 - i; j >= 0; j--) power *= 2;
final += power * array[i];
}
return (unsigned char) final;
}
void get_block(int n, unsigned char* block)
{
int size = 2048;
unsigned char buffer[size];
FILE* ptr;
ptr = fopen(disk,"rb");
fseek(ptr, n * 2048, SEEK_SET);
fread(buffer,sizeof(buffer),1,ptr);
for (int i = 0; i < 128; i++) {
for(int j = 0; j < 16; j++) {
block[i * 16 + j] = buffer[i * 16 + j];
}
}
fclose(ptr);
}
void print_name(unsigned char* block, int position)
{
char name[12];
strcpy(name, "");
for (int l = 1; l < 12; l++) {
sprintf(name + strlen(name), "%c", block[position + l]);
}
printf("%s \n", name);
}
int search_path(const char* path)
{
int found = 0;
int pointer = -1;
unsigned char current_block[2048];
get_block(0, current_block);
char real_path[1000];
strcpy(real_path, path);
if (strlen(real_path) == 1 && real_path[0] == 47) return 0;
int count = 0;
for (int i = 0; real_path[i]; i++) count += (real_path[i] == '/');
count--;
char* pch = strtok(real_path, "/" );
while (pch != NULL) {
found = 0;
int i = 0;
while (i < 128) {
if (current_block[i * 16] == 0x02 && count > 0) {
char found_folder[12];
strcpy(found_folder, "");
for (int l = 1; l < 12; l++) {
sprintf(found_folder + strlen(found_folder), "%c", current_block[i * 16 + l]);
}
if (strcmp(found_folder, pch) == 0) {
pointer = (current_block[i * 16 + 14]<<8) | current_block[i * 16 + 15];
get_block(pointer, current_block);
i = 127;
found = 1;
}
}
else {
if (current_block[i * 16] == 0x04 && count == 0) {
char found_file[12];
strcpy(found_file, "");
for (int l = 1; l < 12; l++) {
sprintf(found_file + strlen(found_file), "%c", current_block[i * 16 + l]);
}
if (strcmp(found_file, pch) == 0) {
pointer = (current_block[i * 16 + 14]<<8) | current_block[i * 16 + 15];
get_block(pointer, current_block);
i = 127;
found = 1;
}
}
}
i++;
}
if (found == 1) {
pch = strtok (NULL, "/");
count--;
}
else {
break;
}
}
return found == 1 ? pointer : -1;
}
int is_folder(const char* path)
{
char real_path[1000];
strcpy(real_path, path);
if (real_path[(strlen(real_path)-1)] == 47) return 1; // Es carpeta
return 0;
}
void change_block_in_bitmap(int block, int value)
{
// unsigned char byte_to_change;
FILE *ptr;
ptr = fopen(disk,"rb");
int byte_position = block/8;
int array_position = block%8;
unsigned char byte[1];
fseek(ptr, byte_position + 2048, SEEK_SET);
fread(byte,sizeof(byte),1,ptr);
int byte_array[8] = {0,0,0,0,0,0,0,0};
byte_to_bits(byte[0], byte_array);
fclose(ptr);
byte_array[array_position] = value;
unsigned char new_byte = bits_to_byte(byte_array);
ptr = fopen(disk,"r+b");
fseek(ptr, 2048 + byte_position, SEEK_SET);
fwrite(&new_byte, 1, 1, ptr);
fclose(ptr);
}
int get_free_block()
{
int size = 8192;
unsigned char buffer[size];
FILE *ptr;
ptr = fopen(disk,"rb");
int n = 1;
fseek(ptr, n * 2048, SEEK_SET);
fread(buffer,sizeof(buffer),1,ptr);
for (int k = 0; k < 4; k++) {
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 16; j++) {
int byte_array[8] = {0,0,0,0,0,0,0,0};
byte_to_bits(buffer[(k * 2048) + (i * 16) + j], byte_array);
for (int q = 0; q < 8; q++) {
if (byte_array[q] == 0) {
fclose(ptr);
return (k*2048 + (i*16) + j)*8 + q;
}
}
}
}
}
fclose(ptr);
return -1;
}
int create_folder_at_block(const char *foldername, int pointer)
{
// foldername: es la carpeta que crearé. pointer: la carpeta en donde crearé foldername.
int block_to_be_assigned = get_free_block();
if (block_to_be_assigned == -1) {
fprintf(stderr, "[ERROR] No queda espacio para crear carpeta.\n");
return 1;
}
// Calculamos largo de la carpeta:
unsigned char block[2048];
get_block(pointer, block);
FILE *ptr;
ptr = fopen(disk, "r+b");
for (int i = 0; i < 128; i++) {
if (get_byte_in_block(block, i, 0) != 0x02 && get_byte_in_block(block, i, 0) != 0x04) {
clean_block(block_to_be_assigned);
char folder_name[1000];
strcpy(folder_name, "");
get_child_name(folder_name, foldername);
write_line(pointer, i, 0x02, folder_name, block_to_be_assigned);
change_block_in_bitmap(block_to_be_assigned, 1);
fclose(ptr);
return 0;
}
}
fprintf(stderr, "[ERROR] No queda espacio en la carpeta para crear otra carpeta.\n");
return 1;
}
void write_byte(int block, int byte_position, unsigned char byte)
{
FILE* ptr;
ptr = fopen(disk, "r+b");
fseek(ptr, 2048* block + byte_position, SEEK_SET);
fwrite(&byte, 1, 1, ptr);
fclose(ptr);
}
void clean_block(int block)
{
FILE* ptr;
ptr = fopen(disk,"r+b");
int start = block * 2048;
fseek(ptr, start, SEEK_SET);
for (int i = 0; i < 2048; i++) write_byte(block, i, 0x00);
fclose(ptr);
}
void get_name(unsigned char *block, char *string, int line)
{
char name[12];
strcpy(name, "");
for (int l = 1; l < 12; l++) {
sprintf(name + strlen(name), "%c", block[line + l]);
}
strcpy(string, name);
}
void get_parent_path(char* file_name, const char* abs_path)
{
char path[1000];
strcpy(path, abs_path);
char parent_path[1000];
strcpy(parent_path, "");
char* current_level = strtok(path, "/");
int count = -2;
for (int i = 0; abs_path[i]; i++) {
count += (abs_path[i] == '/');
}
while (current_level != NULL) {
if ((count > 0 && is_folder(abs_path)) || (count >= 0 && !is_folder(abs_path))) {
strcat(parent_path, "/");
strcat(parent_path, current_level);
count--;
}
current_level = strtok(NULL, "/");
}
strcat(parent_path, "/");
strcpy(file_name, parent_path);
}
void get_child_name(char* file_name, const char* abs_path)
{
char path[1000];
strcpy(path, "");
strcpy(path, abs_path);
char last_name[1000];
char* current_level = strtok(path, "/");
while (current_level != NULL) {
strcpy(last_name, current_level);
current_level = strtok(NULL, "/");
}
strcpy(file_name, last_name);
}
void recursive_ls(char* path, int recursion_depth)
{
int k = 0;
char start[1000];
char folder_start[1000];
char real_name[1000];
strcpy(start, "");
strcpy(folder_start, "");
strcpy(real_name, "");
get_child_name(real_name, path);
if (recursion_depth == 0) printf("\n");
while (k < recursion_depth) {
strcat(start, " ");
if (k < recursion_depth -1) strcat(folder_start, " ");
k++;
}
printf("%s", folder_start);
char real_path[1000];
strcpy(real_path, path);
printf("%s\n", real_name);
if (is_folder(path) == 0) {
printf("[ERROR] No es directorio. \n");
return;
}
int pointer = search_path(path);
if (pointer == -1) {
printf("[ERROR] Directorio no existe. \n");
return;
}
else {
unsigned char current_block[2048];
get_block(pointer, current_block);
char child[1000];
for (int j = 0; j < 128; j++) {
if(current_block[j * 16] == 0x02){
get_name(current_block, child, j * 16);
strcat(real_path, child);
strcat(real_path, "/");
recursive_ls(real_path, recursion_depth + 1);
strcpy(real_path, path);
}
if ((int) current_block[j * 16] == 4) {
printf("%s", start);
print_name(current_block, j * 16);
}
}
}
if (recursion_depth == 0) printf("\n");
}
void print_folder(char* folder)
{
printf("FOLDER FOR %s:\n", folder);
int pointer = search_path(folder);
unsigned char block[2048];
get_block(pointer, block);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 16; j++) {
printf("%x ", block[i * 16 + j]);
}
printf("\n");
}
printf("\n");
}
unsigned char get_byte_in_block(unsigned char* block, int line, int index)
{
return block[line * 16 + index];
}
int create_file_at_block(const char* file_name, const int pointer)
{
int block_to_be_assigned = get_free_block();
if (block_to_be_assigned == -1) {
fprintf(stderr, "[ERROR] No queda espacio para crear archivo.\n");
return -1;
}
unsigned char block[2048];
get_block(pointer, block);
FILE* ptr;
ptr = fopen(disk, "r+b");
for (int i = 0; i < 128; i++) {
if (block[i * 16] != 0x02 && block[i * 16] != 0x04) {
clean_block(block_to_be_assigned);
change_block_in_bitmap(block_to_be_assigned, 1);
write_line(pointer, i, 0x04, file_name, block_to_be_assigned);
fclose(ptr);
return block_to_be_assigned;
}
}
return -1;
}
void read_data_block(czFILE* file_desc, unsigned char* buffer, int nbytes, unsigned char* data_block, int* bytes_read, int* blocks_read)
{
for (int i = 0; i < 2048; i++) {
if (file_desc->last_byte_read > 2048 * (*blocks_read) + i) continue;
buffer[2048 * (*blocks_read) + i] = data_block[i];
(*bytes_read)++;
if (*bytes_read >= nbytes) break;
}
(*blocks_read)++;
}
void write_data_block(czFILE* file_desc, unsigned char* buffer, int nbytes, int pointer, int* bytes_written, int* blocks_written)
{
for (int i = 0; i < 2048; i++) {
write_byte(pointer, i, buffer[file_desc->last_byte_written]);
(*bytes_written)++;
(file_desc->last_byte_written)++;
if (file_desc->last_byte_written >= nbytes) break;
}
(*blocks_written)++;
}
void write_line(int block_pointer, int line, unsigned char byte, const char* name, int pointer)
{
write_byte(block_pointer, line * 16, byte);
int len = strlen(name);
for (int i = 0; i < 11 - len; i++) write_byte(block_pointer, line * 16 + i + 1, 0x00);
for (int i = 0; i < len; i++) write_byte(block_pointer, line * 16 + i + 1 + (11 - len), name[i]);
unsigned char digits[2];
digits[0] = pointer & 0xFF;
digits[1] = (pointer >> 8) & 0xFF;
write_byte(block_pointer, line * 16 + 14, digits[1]);
write_byte(block_pointer, line * 16 + 15, digits[0]);
}
int is_inside_itself(const char* orig, const char* dest)
{
char origin_cmp[1000];
char dest_cmp[1000];
strcpy(origin_cmp, "");
strcpy(dest_cmp, "");
for (int start = 0; start < strlen(orig); start++){
strncat(origin_cmp, &orig[start], 1);
strncat(dest_cmp, &dest[start], 1);
}
if (strcmp(origin_cmp, dest_cmp) == 0) return 1;
return 0;
}
int compare_dir(const char* dest1, const char* dest2)
{
unsigned char block1[2048];
unsigned char block2[2048];
get_block(search_path(dest1), block1);
get_block(search_path(dest2), block2);
for (int i = 0; i < 128; i++) {
if (get_byte_in_block(block1, i, 0) == 0x04) { //FILE
char name1[1000];
char name2[1000];
char path1[1000];
char path2[1000];
strcpy(name1, "");
strcpy(name2, "");
strcpy(path1, "");
strcpy(path2, "");
strcpy(path1, dest1);
strcpy(path2, dest2);
get_name(block1, name1, i * 16);
get_name(block2, name2, i * 16);
strcat(path1, name1);
strcat(path2, name2);
if (compare_file(path1, path2) == 0) {
printf("COMPARE DIR FAILED WITH FILE AT LINE %d\n", i);
return 0;
}
}
else if (get_byte_in_block(block1, i, 0) == 0x02) {
char name1[1000];
char name2[1000];
char path1[1000];
char path2[1000];
strcpy(name1, "");
strcpy(name2, "");
strcpy(path1, "");
strcpy(path2, "");
strcpy(path1, dest1);
strcpy(path2, dest2);
get_name(block1, name1, i * 16);
get_name(block2, name2, i * 16);
strcat(path1, name1);
strcat(path2, name2);
strcat(path1, "/");
strcat(path2, "/");
if (compare_dir(path1, path2) == 0) {
printf("COMPARE DIR FAILED WITH DIR AT LINE %d\n", i);
return 0;
}
}
}
return 1;
}
int compare_file(const char* dest1, const char* dest2)
{
unsigned char block1[2048];
unsigned char block2[2048];
unsigned char block3[2048];
unsigned char block4[2048];
int path_1 = search_path(dest1);
int path_2 = search_path(dest2);
get_block(path_1, block1);
get_block(path_2, block2);
for (int i = 2; i < 511;i++) {
int pointer_1 = (block1[i * 4 + 2] << 8) | block1[i * 4 + 3];
int pointer_2 = (block2[i * 4 + 2] << 8) | block2[i * 4 + 3];
if (pointer_1 != 0 && (compare_block(pointer_1, pointer_2) == 0)) {
printf("COMPARE FILE FAILED AT POINTER %d\n", i - 2);
return 0;
}
}
int indirect_pointer_1 = (block1[511 * 4 + 2] << 8) | block1[511 * 4 + 3];
int indirect_pointer_2 = (block2[511 * 4 + 2] << 8) | block2[511 * 4 + 3];
if (((indirect_pointer_1 == 0) && (indirect_pointer_2 != 0)) || ((indirect_pointer_2 == 0) && (indirect_pointer_1 != 0))) {
printf("COMPARE FILE FAILED AT INDIRECT POINTER\n");
return 0;
}
if (indirect_pointer_1 == 0 && indirect_pointer_2 == 0) return 1;
get_block(indirect_pointer_1, block3);
get_block(indirect_pointer_2, block4);
for (int i = 0; i < 512;i++) {
int pointer_1 = (block3[i * 4 + 2] << 8) | block3[i * 4 + 3];
int pointer_2 = (block4[i * 4 + 2] << 8) | block4[i * 4 + 3];
if (compare_block(pointer_1, pointer_2) == 0) {
printf("COMPARE FILE FAILED AT INDIRECT POINTER BLOCK %d\n", i);
return 0;
}
}
return 1;
}
int compare_block(int pointer_1, int pointer_2)
{
unsigned char block1[2048];
unsigned char block2[2048];
get_block(pointer_1, block1);
get_block(pointer_2, block2);
for (int i = 0; i < 2048;i++) {
if (block1[i] != block2[i]) {
printf("COMPARE BLOCK FAILED AT BYTE %d\n", i);
return 0;
}
}
return 1;
}
int get_size(unsigned char* block)
{
int result = (block[0] << 24) | (block[1] << 16) | (block[2] << 8) | block[3];
return result;
}
|
C
|
/* RAHMANI TAHA ABDELAZIZ */
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <math.h>
#define NSTEPS 100000000000000
#define NTHREADS 4
int main(){
float pi = 0;
float pi_prime = 0;
printf(" ------------ Le calcul de pi en sequentiel ---------------\n");
double start = omp_get_wtime();
for (long i = 0; i <= NSTEPS; i++){
pi += pow(-1,i)/(2*i+1)* 4;
}
double fin = omp_get_wtime() - start;
printf(" la valeur de pi = %f \n", pi);
printf(" le temps sequentiel = %f \n", fin);
pi = 0;
fin = start = 0;
printf("------------ Le calcul de pi en parrallel -------------\n");
start = omp_get_wtime();
#pragma omp parallel private(pi_prime) reduction(+: pi) num_threads(NTHREADS)
{
#pragma omp for
for (long i = 0; i <= NSTEPS; i++)
pi_prime += pow(-1,i)/(2*i+1)* 4;
pi += pi_prime;
}
fin = omp_get_wtime() - start;
printf(" La valeur de pi = %f \n", fin);
printf(" le temps parallel = %f \n", pi);
return 0;
}
|
C
|
#ifndef H_SCHEDULER
#define H_SCHEDULER
#include <pcb.h>
#include <utilities/types.h>
#define TIME_SLICE 3000 /* Time slice in microsecondi di CPU dedicato ad ogni processo */
/*
Ciclo di vita dello scheduler:
(Per # si intende un evento che genera l'interruzione dell'esecuzione )
(Per @ si intende una possibile gestione dell'evento)
-> scheduler_init()
-> scheduler_main()
-> scheduler_schedule() -> # -> scheduler_UpdateContext() -> V
^ |
| @ ----> scheduler_StateToTerminate()
-------------------------------scheduler_StateToReady<-@
^ :
| :
scheduler_StateToWaiting<-@
*/
struct scheduler_t {
/* coda dei processi in stato ready */
struct list_head ready_queue;
/* puntatore al descrittore del processo in esecuzione */
pcb_t* running_p;
/* booleano indicante se il processo attuale non può continuare lo scheduling (TRUE) oppure continuare mantenere il processo schedulato (FALSE) */
int b_force_switch;
/* Pcb utilizzato per mettere la macchina in stato di idle */
pcb_t idlePcb;
int b_has_idle;
};
typedef struct scheduler_t scheduler_t;
/**
* @brief Inizializza lo scheduler
*
*/
void scheduler_init();
/**
* @brief Avvia lo scheduler, da richiamare solo per il primo avvio dello scheduler
* @PreCondition Deve essere richiamato dopo scheduler_init() dopo aver inserito almeno il primo processo
*
* @return int
*/
int scheduler_main();
/**
* @brief Aggiorna lo stato del processo tracciato in esecuzione, con quello fornito
*
* @param state
*/
void scheduler_UpdateContext( state_t* state );
/**
* @brief Avvia l'esecuzione dell'algoritmo dello scheduler che in base alle circostanze può:
* - continuare l'esecuzione del processo attuale;
* - sospendere il processo attuale e scegliere ed avviare il prossimo processo nella ready queue per un TIME_SLICE, impostando tale valore al Interrupt Timer
* Se la coda dei processi ready non è vuota,
* Sceglie il processo dalla ready queue con priorità più alta
* Imposta l' interrupt timer a TIME_SLICE
* e carica lo stato del processo sul processore
* Dopo questo la funzione non dovrebbe restituire poichè il controllo dell'esecuzione è passato al processo
* Se ciò avviene è dovuto ad un errore di LDST.
* @PreCondition Prima di chiamare questa funzione, è necessario chiamare scheduler_UpdateContext() per aggiornare il contesto del processo attuale
*
* @param b_force_switch se TRUE lo scheduler è forzato a cambiare il processo da eseguire
* @return int
* * manda Il sistema in HALT se la coda dei processi è vuota
* * -1 se non è stato caricato lo stato di un nuovo processo, senza cambiare il controllo di esecuzione ( malfunzionamento LDST )
*/
int scheduler_schedule( int b_force_switch );
/**
* @brief Ripristina la priorità originale del processo che era in esecuzione
* Disassocia il processo in esecuzione dallo scheduler
* @PreCondition Prima di chiamare questa funzione, è necessario chiamare scheduler_UpdateContext() per aggiornare il contesto del processo attuale
* @PostCondition Dopo questo stato è necessario richiamare scheduler_schedule per procedere con la schedulazione dei processi
*
* @param state stato del processo che era in esecuzione
* @return int
* * 1 se non c'è alcun processo tracciato dallo scheduler in esecuzione
* * 0 altrimenti se l'inserimento in ready queue è avvenuto correttamente
*/
int scheduler_StateToReady();
/**
* @brief aggiunge il processo corrente alla ASL con associato la chiave fornita
*
* @PreCondition Prima di chiamare questa funzione, è necessario chiamare scheduler_UpdateContext() per aggiornare il contesto del processo attuale.
* Inoltre il processo deve essere nella ready queue oppure o deve essere il processo in esecuzione
* @PostCondition se p == NULL sarà preso in considerazione il processo corrente. Dopo questo stato è necessario richiamare scheduler_schedule per procedere con la schedulazione dei processi
* @param semKey chiave da associare al semaforo
* @param p processo da sospendere sulla coda del semaforo
* @return int
* * -1 se nessun processo è attualmente assegnato come processo corrente
* * 0 se l'operazione è stata effettuata correttamente
* * 1 se non è stato possibile aggiungere il processo corrente alla ASL (impossibile allocare semaforo)
*/
int scheduler_StateToWaiting( pcb_t* p, int* semKey );
/**
* @brief Dealloca il descrittore del processo associato al pid fornito, rimuovendo eventualmente la sua progenie
* @PreCondition Prima di chiamare questa funzione, è necessario chiamare scheduler_UpdateContext() per aggiornare il contesto del processo attuale
* @PostCondition Dopo questo stato è necessario richiamare scheduler_schedule per procedere con la schedulazione dei processi
* @return int
* * !=0 se pid == NULL o non c'è alcun processo tracciato dallo scheduler in esecuzione, o non è stato possibile trovare il processo in nessuna coda
* * 0 altrimenti se è avvenuto tutto correttamente
* @param pid identificatore del processo da terminare, se == NULL sarà considerato il processo attualmente in esecuzione
* @param b_flag_terminate_progeny Se TRUE rimuove e dealloca dalla ready queue o dalla semd wait queue il descrittore del processo in esecuzione e tutta la sua progenie,
* Se FALSE rimuove e dealloca solo il descrittore in esecuzione, ma tutti i suoi figli non avranno padre e ogni figlio non avrà fratelli
* cioè saranno indipendenti tra loro
*/
int scheduler_StateToTerminate( pcb_t* pid, int b_flag_terminate_progeny );
/**
* @brief Restituisce il puntatore dell'attuale pcb_t in esecuzione
*
* @return state_t*
*/
pcb_t *scheduler_GetRunningProcess();
/**
* @brief Inserisce un descrittore di processo nella ready queue
* @PreCondition Da utilizzare solo se p non è presente nella ready queue
* @param p descrittore del processo
*/
void scheduler_AddProcess( pcb_t *p );
/**
* @brief Rimuove il descrittore di processo dalla ready queue ed eventualmente disassocia il processo attuale, se è lo stesso pcb fornito
*
* @param p pcb da rimuovere dallo scheduler
* @return int
* TRUE se è stato rimosso con successo
* FALSE se non è presente nella ready queue
*/
int scheduler_RemoveProcess( pcb_t *p );
/**
* @brief Dealloca dopo aver rimosso il descrittore fornito e tutta la sua progenie dalla ready queue o dalla wait queue del semaforo associato al pcb
* Non avviene alcuna rimozione nella lista dei fratelli e del padre di p.
* @PostCondition Se p o uno della sua progenie è il processo in esecuzione allora viene deassociato nella struttura dello scheduler e deallocato anche esso.
*
* @param p descrittore del processo da cui partire a rimuovere la progenie
* @return int
* * 1 Se p == NULL
* * -1 Se p non si trova in alcuna coda ( ready, wait queue, o processo corrente )
* * 0 altrimenti
*/
int scheduler_RemoveProgeny( pcb_t* p );
/**
* @brief Aggiorna il TOD dell'ultimo start di cronometro
* Se è la prima volta che il processo viene avviato, aggiorna anche il TOD di primo avvio
*/
void scheduler_StartProcessChronometer();
/**
* @brief Aggiorna il tempo totale trascorso dall'ultima chiamata di scheduler_StartProcessChronometer fino a questa funzione.
* incrementando il timelapse kernel o user del processo in esecuzione ( se presente )
*
* @param b_isKernelTime se FALSE il timelapse è aggiunto al tempo passato del processo (user)
* altrimenti a quello passato nel kernel
*/
void scheduler_UpdateProcessRunningTime( int b_isKernelTime );
#endif
|
C
|
#pragma once
#define N 3
typedef int SDataType;
//̬ջ
typedef struct Stack
{
SDataType*_array;
int _capacity;//ЧԪص
int _top;//ջ
}Stack;
void StackInit(Stack*ps);//ջijʼ
void _Checkcapacity(Stack*ps);//
void StackPush(Stack*ps, SDataType data);//ѹջջdata)
void StackPop(Stack*ps);//ջջdata
SDataType StackTop(Stack*ps);//ȡջԪ
int StackSize(Stack*ps);//ȡջЧԪصĸ
int StackEmpty(Stack*ps);//ջǷΪ
void StackDeatory(Stack*ps);//ջ
void StackPrint(Stack*ps);//ӡ
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
const double eps = 1e-12;
double sin_count(double x) {
int count = 0;
double tek = x;
double sum = 0.0;
while (fabs(tek) > eps) {
sum += tek;
count += 1;
tek *= -x * x / (2 * count * (2 * count + 1));
}
return sum;
}
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n;
scanf("%d\n", &n);
double x;
for (int i = 0; i < n; i++) {
scanf("%lf\n", &x);
printf("%0.15lf\n", sin_count(x));
}
return 0;
}
|
C
|
#ifndef GCD
#define GCD
inline long unsigned int gcd (long unsigned int a, long unsigned int b)
/* Euclid algorithm gcd */
{
long unsigned int c;
while(a!=0)
{
c=a;
a=b%a;
b=c;
};
return(b);
};
inline int co_prime(long unsigned int a, long unsigned int b)
{
return(gcd(a,b)==1);
};
#endif
|
C
|
#include <stdio.h>
#include <locale.h>
/*Faça um programa que calcule reajustes
salariais de acordos com faixas pré-estabelecidas
e mostre os valores reajustados, o diferencial
de reajuste e o equivalente em percentual
*/
int main() {
setlocale (LC_ALL, "Portuguese");
float salario, novo_salario;
printf("Insira o valor do salário R$ ");
scanf("%f", &salario);
if(salario > 0 && salario <= 400){
novo_salario = salario * 0.15 + salario;
printf("Novo salário: R$ %.2f\nReajuste ganho: R$ %.2f\nEm percentual: 15 %%\n", novo_salario, novo_salario - salario);
}
else{
if(salario > 400.01 && salario <= 800){
novo_salario = salario * 0.12 + salario;
printf("Novo salário: R$ %.2f\nReajuste ganho: R$ %.2f\nEm percentual: 12 %%\n", novo_salario, novo_salario - salario);
}
else{
if(salario > 800.01 && salario <= 1200){
novo_salario = salario * 0.10 + salario;
printf("Novo salário: R$ %.2f\nReajuste ganho: R$ %.2f\nEm percentual: 10 %%\n", novo_salario, novo_salario - salario);
}
else{
if(salario > 1200.01 && salario <= 2000){
novo_salario = salario * 0.07 + salario;
printf("Novo salário: R$ %.2f\nReajuste ganho: R$ %.2f\nEm percentual: 7 %%\n", novo_salario, novo_salario - salario);
}
else{
novo_salario = salario * 0.04 + salario;
printf("Novo salário: R$ %.2f\nReajuste ganho: R$ %.2f\nEm percentual: 4 %%\n", novo_salario, novo_salario - salario);
}
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#define CHECK_MENO_1(p,str) if((p) == -1){ perror(str); exit(EXIT_FAILURE); }
/* stampa il pid dei processi zombie presenti nel sistema utiliazzando una pipeline di 3 processi. il primo processo esegue il comando 'ps -A -ostat,pid' e fornisce l'input la secondo processo che esegue il comando 'grep -e [zZ]' e che a sua volta fornisce l'input al terzo processo che esegue il comando 'awk {print $2}'.
ps -A -ostat,pid | grep -e [zZ] | awk '{print $2}' */
int main(){
int pipe1[2];
int pipe2[2];
int pid1, pid2, pid3;
int status;
CHECK_MENO_1(pipe(pipe1), "pipe1");
CHECK_MENO_1(pid1 = fork(), "fork");
/* figlio 1 */
if(!pid1){
CHECK_MENO_1(dup2(pipe1[1],1),"dup2"); // redirigo stdout sull'ingresso di scrittura di pipe1
CHECK_MENO_1(close(pipe1[0]), "close"); // chiude lettura
CHECK_MENO_1(close(pipe1[1]), "close");
execlp("ps", "ps", "-A", "-ostat,ppid", NULL);
perror("execlp1");
exit(errno);
}else{ // padre
CHECK_MENO_1(dup2(pipe1[0],0), "dup2"); // redigo lo stdin sull'ingresso di lettura di pipe1
CHECK_MENO_1(close(pipe1[1]), "close"); // chiude scrittura
CHECK_MENO_1(pipe(pipe2), "pipe2"); // crea pipe2
CHECK_MENO_1(pid2 = fork(), "fork"); // crea un altro figlio
if(!pid2){ // figlio 2
CHECK_MENO_1(dup2(pipe2[1],1), "dup2"); //redirige stdout nell'ingresso scrittura pipe2
CHECK_MENO_1(close(pipe2[0]), "close"); // chiude lettura
execlp("grep", "grep", "-e", "[zZ]", NULL);
perror("execvp2");
exit(errno);
}else{ // padre
CHECK_MENO_1(dup2(pipe2[0],0), "dup2");
CHECK_MENO_1(close(pipe2[1]), "close");
CHECK_MENO_1(pid3 = fork(), "fork"); // fa un altro figlio
if(!pid3){ /* figlio 3 */
execlp("awk", "awk", "\"{print $2}\"", NULL);
perror("execlp3");
exit(errno);
}
}
}
// chiudo descrittori padre inutilizzati
// fai le waitpid
CHECK_MENO_1(waitpid(pid1, &status, 0), "waitpid1");
CHECK_MENO_1(waitpid(pid2, &status, 0), "waitpid2");
CHECK_MENO_1(waitpid(pid3, &status, 0), "waitpid3");
return 0;
}
|
C
|
#include <stdio.h>
int max2(int a,int b) /*返回较大数值*/
{
if (a>b)
return a;
else
return b;
}
int max4(int a,int b,int c,int d)
{
return max2(max2(a,b),max2(c,d));
}
int main(void)
{
int n1,n2,n3,n4;
puts("请输入4个整数。");
printf("整数1:"); scanf("%d",&n1);
printf("整数2:"); scanf("%d",&n2);
printf("整数3:"); scanf("%d",&n3);
printf("整数4:"); scanf("%d",&n4);
printf("最大的整数是:%d .\n",max4(n1,n2,n3,n4));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 10;
size_t t = sizeof(int);
printf("%z \n",t);
return 0;
}
unsigned long convert(char *arr){
int n = strlen(arr);
if(n > 19) return -1;
unsigned long res = 0;
for(int i = 0; i < n; i++){
int x = arr[i] - '0';
if(('0' <= arr[i]) && (arr[i] <= '9'))
res = (res * 10) + ((arr[i]) - ('0'));
else return -1;
}
return res;
}
void input(){
char input[100];
scanf("%s",input);
unsigned long n = convert(input);
}
|
C
|
#include <Arduino.h>
#include <WiFi.h>
#include <ser.h>
#define PINGHOSTS 2
#define WEBSETIES 2
const char* ssid = "<NETWORK NAME>";
const char* password = "<PASSWORD>";
/*
This scruct for hosts you want to ping. NB: you should use IP address
*/
struct HostToPing {
const char* name; // Name to show on rectangle, e.g. "Google"
IPAddress host_ip; // IP address, e.g. 8.8.8.8 to ping Google
unsigned int avg_delay; // How many ms is "normal" for your ping, e.g. 25
unsigned int position; // Position of this rectangle on screen
};
/*
This struct for web-sites you want to ping. Use pases with HTTP 200 responce
*/
struct SiteToCheck {
const char* name; // Name to show on rectangle, e.g. "Google"
const char* host; // Hostname, e.g. google.com
const char* get_string; // What to use as HTTP request
const char* hst_string; // What to use as hostname
const char* crt; // SSL certificate to verify host
unsigned int position; // Position of this rectangle on screen
};
/*
Here are examples
*/
struct HostToPing hosts[PINGHOSTS] = {
"Gateway", IPAddress(192, 168, 107, 1), 25, 1, // this will ping local gateway
"Google", IPAddress(8, 8, 8, 8), 50, 2 // this will ping Google
};
/*
Certs (and how to make 'em see in ser.h
*/
struct SiteToCheck websites[WEBSETIES] = {
"Yandex", "yandex.ru", "GET https://yandex.ru/ HTTP/1.0", "Host: yandex.ru", crtR3, 3,
"Google", "google.com", "GET https://google.com/ HTTP/1.0", "Host: google.com", crtSectigo, 4
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "EspaciosBD.h"
#include "../Sqlite3/sqlite3.h"
sqlite3* conexionEspacios(){
sqlite3 *db;
int e = sqlite3_open("database.db", &db);
if( e) {
fprintf(stderr, "Se ha producido un error en la conexion con la BD. %s\n", sqlite3_errmsg(db));
}
return db;
}
void crearTablaEspacios(){
sqlite3 *db = conexionEspacios();
char *mensageError;
int e= sqlite3_exec(db,"CREATE TABLE IF NOT EXISTS Espacios"
"(codigo integer primary key not null,"
"nombre varchar(20) not null,"
"metrosCuadrados integer not null,"
"capacidad integer not null,"
" descripcion varchar(50));" ,0,0,&mensageError);
if(e){
fprintf(stderr,"No se ha podido crear la tabla ESPACIOS.%s\n", sqlite3_errmsg(db));
}
sqlite3_close(db);
}
void reguistrarEspacio(Espacios newEsp){
sqlite3 *db = conexionEspacios();
char* sql="INSERT INTO Espacios VALUES(?,?,?,?,?);";
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db,sql,-1,&stmt,0);
sqlite3_bind_int(stmt,1,newEsp.codigo);
sqlite3_bind_text(stmt,2,newEsp.nombre,strlen(newEsp.nombre),SQLITE_STATIC);
sqlite3_bind_int(stmt,3,newEsp.metrosCuadrados);
sqlite3_bind_int(stmt,4,newEsp.capacidad);
sqlite3_bind_text(stmt,5,newEsp.descripcion,strlen(newEsp.descripcion),SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_close(db);
}
void eliminacionEspacio(int codigo){
sqlite3 *db = conexionEspacios();
char *sql = "DELETE FROM Espacios WHERE codigo =?;";
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db,sql,-1,&stmt,0);
sqlite3_bind_int(stmt,1,codigo);
sqlite3_step(stmt);
sqlite3_close(db);
}
int larguraEspacios(){
sqlite3 *db = conexionEspacios();
sqlite3_stmt *stmt;
int length=0;
sqlite3_prepare_v2(db,"SELECT * FROM Espacios;", -1, &stmt, NULL);
while (sqlite3_step(stmt) != SQLITE_DONE) {
length++;
}
sqlite3_close(db);
return length;
}
void seleccionEspacios(Espacios arrayLectura[]){
sqlite3 *db = conexionEspacios();
int i = 0;
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db,"SELECT * FROM Espacios;", -1, &stmt, NULL);
while (sqlite3_step(stmt) != SQLITE_DONE) {
arrayLectura[i].codigo =(int) sqlite3_column_int(stmt, 0);
arrayLectura[i].nombre =(char*)malloc((strlen((char*) sqlite3_column_text(stmt, 1))+1)*sizeof(char));
strcpy((arrayLectura[i]).nombre,(char*) sqlite3_column_text(stmt, 1));
arrayLectura[i].metrosCuadrados =(int) sqlite3_column_int(stmt, 2);
arrayLectura[i].capacidad =(int) sqlite3_column_int(stmt, 3);
arrayLectura[i].descripcion =(char*)malloc((strlen((char*) sqlite3_column_text(stmt,4))+1)*sizeof(char));
strcpy((arrayLectura[i]).descripcion,(char*) sqlite3_column_text(stmt, 4));
i++;
}
sqlite3_close(db);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
// funcao selectionSort
void selectionSort (int num[], int n){
int i, j, o, x = 0;
int menValor = 0;
int aux = 0;
for (i = 0; i < n; i++){ // 01
menValor = i;
for(j = i+1; j < n; j++){ // 02
// verifica
if (num[j] < num[menValor]){
menValor = j;
}
}
// realiza a troca
aux = num[i];
num[i] = num[menValor];
num[menValor] = aux;
// EXIBIR
for (x = 0; x < n; x++){
printf("%d ", num[x]);
}
printf("\n");
// EXIBIR
}
} //fim funcao
// metodo principal
int main(){
// array para ordenar
int num[5] = {9, 1, 6, 10, 4};
selectionSort(num,5);
}
|
C
|
#include "inner.h"
/* ====================================================================== */
/* see curve9767.h */
int
curve9767_point_encode(void *dst, const curve9767_point *Q)
{
int i;
uint8_t *buf;
uint8_t m;
curve9767_inner_gf_encode(dst, Q->x);
buf = dst;
buf[31] |= curve9767_inner_gf_is_neg(Q->y) << 6;
m = (uint8_t)-Q->neutral;
for (i = 0; i < 31; i ++) {
buf[i] |= m;
}
buf[31] |= m & 0x7F;
return 1 - Q->neutral;
}
/* see curve9767.h */
int
curve9767_point_encode_X(void *dst, const curve9767_point *Q)
{
int i;
uint8_t *buf;
uint8_t m;
curve9767_inner_gf_encode(dst, Q->x);
buf = dst;
m = (uint8_t)-Q->neutral;
for (i = 0; i < 31; i ++) {
buf[i] |= m;
}
buf[31] |= m & 0x3F;
return 1 - Q->neutral;
}
/* see curve9767.h */
int
curve9767_point_decode(curve9767_point *Q, const void *src)
{
uint32_t tb, r;
/*
* Check that the top bit of the top byte is 0.
*/
tb = ((const uint8_t *)src)[31];
r = 1 - (tb >> 7);
/*
* Decode the X coordinate.
*/
r &= curve9767_inner_gf_decode(Q->x, src);
/*
* Obtain the Y coordinate.
*/
r &= curve9767_inner_make_y(Q->y, Q->x, (tb >> 6) & 0x01);
/*
* If one of the step failed, then the value is turned into the
* point-at-infinity.
*/
Q->neutral = 1 - r;
return r;
}
/* see curve9767.h */
void
curve9767_point_neg(curve9767_point *Q2, const curve9767_point *Q1)
{
if (Q2 != Q1) {
Q2->neutral = Q1->neutral;
memcpy(Q2->x, Q1->x, sizeof Q1->x);
}
curve9767_inner_gf_neg(Q2->y, Q1->y);
}
/* see curve9767.h */
void
curve9767_point_sub(curve9767_point *Q3,
const curve9767_point *Q1, const curve9767_point *Q2)
{
curve9767_point T;
curve9767_point_neg(&T, Q2);
curve9767_point_add(Q3, Q1, &T);
}
|
C
|
/////////////////////////////////////////////////////////////////////////////
//
// Program 4 - keygen - Operating System
// Created By Jakob Eslinger
// [email protected]
//
// Code outputs a random key that is generated with a length of n,
// being the legth that is an input. Output is sent to stdout. Key
// contains a newline at the end.
//
////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ASCII_OFFSET 65
/******************************* Main Function *******************************/
int main(int argc, char *argv[])
{
/* Check if there are enough inputs */
if(argc < 2)
{
perror("Error: Too Few Arguments");
return 1;
}
/* Setup seed for random fucntion */
srand(time(NULL));
/* Get length */
int length = atoi(argv[1]); //Convert first argument from string to int
/* Generate Key */
char* key = malloc(sizeof(char) * (length + 1)); //allocate space for key +1 for endline
int i;
for(i = 0; i < length; i++)
{
int randomChar = rand() % 27; //27 diffetned options for characters
randomChar += ASCII_OFFSET; //Offset the option to equeal a letter in ASCII
if(randomChar == 91) //If randomChar is 91, then replace to with a spcae
{
randomChar = 32; //Space is 32 in ASCII
}
key[i] = (char) randomChar; //Typecast output to a char and save it in the key array
}
key[i] = '\n'; //add newline character
/* Output Key*/
printf("%s", key);
/* Free Memory */
free(key);
return 0;
}
|
C
|
/*
* The function recieves a String type value and then performs on it
* to check for any characters present in the formate.. is thier are only numerical
* value present in the given String value the function returns 1 or else 0
* */
#include "header.h"
int isInputValid(char testString[]){
unsigned long newValue;
char *ptr;
// strol(String, (pointer to first character), any number->[2,36])
newValue = strtol(testString, &ptr, 10);
if(*ptr ==NULL)
return 1;
else if(newValue <= 0)
return 0;
return 0;
}
void showError(){
freopen("CON","w",stdout);
printf("\n\nNot Valid Input! :(\n\n");
}
|
C
|
#include "passcode.h"
#include <string.h>
//Compares entered password with stored passwords
int checkValid(char *str, char passWord[passwords][wordLen]){
int i = 0;
int j = 0;
int match = 0;
int temp = 0;
for (i = 0; i < passwords; i ++){
for (j = 0; j < wordLen; j++){
if (str[j] == passWord[i][j]){
temp = temp + 1;
}
}
if (temp == wordLen){
match = 1;
temp = 0;
}
else {
temp = 0;
}
}
//return 1 for valid, return 0 for not valid
return match;
}
// checks a string to make sure it is a valid pw entry
int addNewPw(char *str, char passWord[passwords][wordLen]){
int i = 0;
int match = 0;
int temp = 0;
for (i = 0; i < passwords; i++){
temp = strcmp(str, passWord[i]); //returns 0 for match
if (temp == 0){
match = 0; //match becomes 1 for any match
}
}
return match;
}
//Clears the temp str buffer
void clearBuff(int len, char *str){
int i = 0;
for(i = 0; i < len; i++){
str[i] = NULL;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "hacking.h"
#include <unistd.h>
#define PORT 1337
char buffer1[128];
int copying (int l)
{
int i;
unsigned int j=1;
char buffer2[8];
printf("No Canary Found, %d\n",l);
for(i=0; i<l; i++)
{
buffer2[i]=buffer1[i];
}
return 0;
}
int main()
{
int s_server, s_client;
struct sockaddr_in s_addr, c_addr;
socklen_t size;
int len_r=1;
int yes=1;
int x,l, i;
char a;
pid_t pid;
if((s_server=socket(PF_INET, SOCK_STREAM, 0))== -1)
fatal("In Socket");
if (setsockopt(s_server, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
fatal("In Socket Options");
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(PORT);
s_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(s_addr.sin_zero), '\0', 8);
if(bind(s_server, (struct sockaddr *)&s_addr, sizeof (struct sockaddr))==-1)
fatal("In Bind");
if (listen(s_server, 5) == -1)
fatal("In Listen");
bzero(buffer1,128);
while(1)
{
size = sizeof(struct sockaddr_in);
s_client = accept(s_server, (struct sockaddr *)&c_addr, &size);
if(s_client == -1)
fatal("In Accept");
pid = fork();
if (pid < 0)
{
perror("ERROR on fork");
exit(1);
}
if(pid==0)
{
close(s_server);
len_r = recv(s_client, buffer1, 60, 0);
dump(buffer1,len_r);
x=copying(len_r);
printf("Canary Found\n");
send(s_client, "found", 5,0);
break;
}
}
return 0;
}
|
C
|
#include <math.h>
#include <stdio.h>
extern double boysGaussJacobi(int m, double z);
/***************************************************
* @brief compute a value with the program and compare it with a correct one.
* @param[in] m The integer index of Boys function.
* @param[in] z The argument of Boys function.
* @param[in] value The correct (expected) value.
* @param[in] errMarg A relative error margin to produce verbose output.
* @return 0 if the computed value is within 3 times the error margin.
* So this is considered a test passed.
* Otherwise 1.
*/
static int boysGaussJacobiComp(int m, double z, double value, double errMarg) {
/* value generated by theprogram
*/
double F = boysGaussJacobi(m, z);
/* relative error
*/
double err = fabs(1. - F / value);
if (err > errMarg)
printf("m=%d z=%f %.17e expected %.17e rel err %.3e\n", m, z, F, value, err);
return (err > 3 * errMarg) ? 1 : 0;
}
/***************************************
* @brief Test main function for the boysGaussJacobi subroutine.
* For 175 pairs of m and z we compute the numerical value and
* compare it with a known result that was obtained with high precision.
* @param[in] argc Number of arguments in the command line.
* Dummy parameter. Not used.
* @param[in] argv The vector of command line arguments.
* Dummy parameter. Not used.
* @since 2017-09-17
* @author Richard J. Mathar
*/
int main(int argc, char *argv[]) {
/* print results if the relative error in the computed value exceeds this number
*/
double errMarg = 1.e-15;
int err = 0;
/* m = 0 .. 10, z= 0.000000e+00 .. 5.000000e+00 */
err += boysGaussJacobiComp(3, 1.10185120525508566e+00, 6.18766542175746446e-02, errMarg);
err += boysGaussJacobiComp(2, 1.76577119262604747e+00, 6.11825639426621793e-02, errMarg);
err += boysGaussJacobiComp(4, 3.23037524963850408e+00, 9.12059472487586327e-03, errMarg);
err += boysGaussJacobiComp(0, 3.08608408426085971e+00, 4.97929773714634554e-01, errMarg);
err += boysGaussJacobiComp(4, 3.22317208440663363e+00, 9.16815839139274350e-03, errMarg);
err += boysGaussJacobiComp(1, 1.05782425556418974e+00, 1.83784360820336149e-01, errMarg);
err += boysGaussJacobiComp(7, 1.16240645029399288e-01, 6.01724161273037453e-02, errMarg);
err += boysGaussJacobiComp(0, 4.69364098297121447e+00, 4.08169033593379339e-01, errMarg);
err += boysGaussJacobiComp(7, 1.67085426805529170e+00, 1.55179557273704668e-02, errMarg);
err += boysGaussJacobiComp(5, 4.39642388637500865e+00, 2.72813318450120458e-03, errMarg);
err += boysGaussJacobiComp(9, 4.59060542843920716e-01, 3.47709144661698761e-02, errMarg);
err += boysGaussJacobiComp(0, 1.56064093021955635e+00, 6.54583832433497471e-01, errMarg);
err += boysGaussJacobiComp(4, 9.11886468618789914e-01, 5.32214686889205691e-02, errMarg);
err += boysGaussJacobiComp(1, 2.81084401770867673e+00, 8.16601636195038075e-02, errMarg);
err += boysGaussJacobiComp(7, 2.81363558170664424e+00, 5.85296951907279933e-03, errMarg);
err += boysGaussJacobiComp(1, 3.51776621659429321e+00, 6.24073761837337416e-02, errMarg);
err += boysGaussJacobiComp(6, 2.54481034876241880e+00, 8.91456880247929484e-03, errMarg);
err += boysGaussJacobiComp(2, 1.71097775420966734e-02, 1.97571934031116749e-01, errMarg);
err += boysGaussJacobiComp(0, 2.62990041558805845e+00, 5.34555136098613369e-01, errMarg);
err += boysGaussJacobiComp(0, 2.78853346207363049e+00, 5.21052265143433045e-01, errMarg);
err += boysGaussJacobiComp(0, 4.93413454710710736e+00, 3.98298389255380287e-01, errMarg);
err += boysGaussJacobiComp(3, 3.20655684117901929e+00, 1.42860523385369159e-02, errMarg);
err += boysGaussJacobiComp(3, 6.40894462299422263e-01, 8.73622913508490626e-02, errMarg);
err += boysGaussJacobiComp(7, 4.93617748799008009e+00, 1.01619982345831285e-03, errMarg);
err += boysGaussJacobiComp(0, 1.18165384269143953e+00, 7.13995613900412723e-01, errMarg);
err += boysGaussJacobiComp(7, 2.55090351987942377e+00, 7.31067587218400585e-03, errMarg);
err += boysGaussJacobiComp(6, 1.43808078860566576e+00, 2.24575690498485180e-02, errMarg);
err += boysGaussJacobiComp(1, 4.35417133561288676e+00, 4.71400052658071444e-02, errMarg);
err += boysGaussJacobiComp(1, 1.67247487969853155e+00, 1.34919268673417994e-01, errMarg);
err += boysGaussJacobiComp(6, 2.44572821278028255e-01, 6.22559783625824615e-02, errMarg);
err += boysGaussJacobiComp(4, 2.14843573474138502e+00, 2.03351671820967326e-02, errMarg);
err += boysGaussJacobiComp(8, 2.50113793296766264e+00, 6.47719310910455897e-03, errMarg);
err += boysGaussJacobiComp(8, 2.01268788057210367e+00, 9.91151761669940898e-03, errMarg);
err += boysGaussJacobiComp(3, 4.85494664062866054e+00, 5.23515888992428097e-03, errMarg);
err += boysGaussJacobiComp(2, 4.94472597757495695e+00, 1.12662528797242100e-02, errMarg);
/* m = 10 .. 90, z= 0.000000e+00 .. 5.000000e+00 */
err += boysGaussJacobiComp(17, 4.12310997736165195e+00, 5.93024056274768668e-04, errMarg);
err += boysGaussJacobiComp(28, 1.98260147027554227e-01, 1.44860444295897823e-02, errMarg);
err += boysGaussJacobiComp(15, 2.25700445900700971e+00, 3.90584744716254340e-03, errMarg);
err += boysGaussJacobiComp(17, 2.15090246014902853e+00, 3.75932258163156043e-03, errMarg);
err += boysGaussJacobiComp(14, 1.25940467381241843e+00, 1.06475929028584714e-02, errMarg);
err += boysGaussJacobiComp(55, 3.00725393541662858e+00, 4.70297867669921504e-04, errMarg);
err += boysGaussJacobiComp(22, 2.91371146222695857e+00, 1.37569333191435058e-03, errMarg);
err += boysGaussJacobiComp(19, 3.16525550726132215e-02, 2.48805453513582370e-02, errMarg);
err += boysGaussJacobiComp(12, 2.09417587700846377e+00, 5.81858736736084268e-03, errMarg);
err += boysGaussJacobiComp(15, 2.87551358544984288e+00, 2.19750412249902217e-03, errMarg);
err += boysGaussJacobiComp(11, 3.74357652003135060e-01, 3.08223366525322295e-02, errMarg);
err += boysGaussJacobiComp(53, 2.97673095480940332e-01, 6.97777200019610124e-03, errMarg);
err += boysGaussJacobiComp(65, 4.90397348342779461e+00, 6.11207175631414014e-05, errMarg);
err += boysGaussJacobiComp(54, 4.17423983260431233e-01, 6.08929296295050040e-03, errMarg);
err += boysGaussJacobiComp(62, 4.39994423618739994e-01, 5.18826594624253255e-03, errMarg);
err += boysGaussJacobiComp(29, 1.57948604933454441e+00, 3.68331536266984844e-03, errMarg);
err += boysGaussJacobiComp(77, 1.81879063121180401e+00, 1.07140877845038293e-03, errMarg);
err += boysGaussJacobiComp(23, 4.63625162127909347e+00, 2.53872610366915764e-04, errMarg);
err += boysGaussJacobiComp(51, 4.87568421409986594e-01, 6.01819053619613609e-03, errMarg);
err += boysGaussJacobiComp(73, 2.84196161837828456e+00, 4.12398185135804522e-04, errMarg);
err += boysGaussJacobiComp(85, 4.06475152021454688e+00, 1.05340615181350278e-04, errMarg);
err += boysGaussJacobiComp(78, 2.13142635325963588e+00, 7.76662065115703828e-04, errMarg);
err += boysGaussJacobiComp(14, 2.01830152382404778e-01, 2.85519604234165442e-02, errMarg);
err += boysGaussJacobiComp(50, 7.29043849884289609e-01, 4.84450142459049873e-03, errMarg);
err += boysGaussJacobiComp(24, 1.47664189263935161e+00, 4.94711045443220289e-03, errMarg);
err += boysGaussJacobiComp(53, 4.16172462051881343e+00, 1.57633019307205248e-04, errMarg);
err += boysGaussJacobiComp(22, 2.42623931680481501e+00, 2.18867058696143604e-03, errMarg);
err += boysGaussJacobiComp(13, 1.10565025449478208e+00, 1.32653211100037921e-02, errMarg);
err += boysGaussJacobiComp(49, 2.93905358850750125e+00, 5.67490889243916638e-04, errMarg);
err += boysGaussJacobiComp(65, 2.22552675391620917e+00, 8.53041455156413569e-04, errMarg);
err += boysGaussJacobiComp(88, 3.63491225768344867e+00, 1.55382545424575028e-04, errMarg);
err += boysGaussJacobiComp(52, 7.29165391695675117e-01, 4.65689551703295511e-03, errMarg);
err += boysGaussJacobiComp(12, 4.14640028555270438e+00, 9.02549877393784755e-04, errMarg);
err += boysGaussJacobiComp(20, 3.99067842845876298e+00, 5.52451856943125083e-04, errMarg);
err += boysGaussJacobiComp(16, 4.22737818308918280e+00, 5.79995569122797833e-04, errMarg);
/* m = 0 .. 10, z= 5.000000e+00 .. 3.000000e+01 */
err += boysGaussJacobiComp(7, 2.65299030717728560e+01, 1.96373873064420139e-08, errMarg);
err += boysGaussJacobiComp(7, 1.27105157249199337e+01, 4.67820545465691176e-06, errMarg);
err += boysGaussJacobiComp(9, 1.11230584738534261e+01, 4.99433178569089635e-06, errMarg);
err += boysGaussJacobiComp(8, 5.37129458692201611e+00, 5.69739758450416983e-04, errMarg);
err += boysGaussJacobiComp(1, 1.56312886945312452e+01, 7.17005428497372215e-03, errMarg);
err += boysGaussJacobiComp(4, 1.07145123323015585e+01, 1.33348833937758246e-04, errMarg);
err += boysGaussJacobiComp(1, 1.91059645713545582e+01, 5.30592958078778906e-03, errMarg);
err += boysGaussJacobiComp(2, 2.08588016336415864e+01, 3.34489731491456038e-04, errMarg);
err += boysGaussJacobiComp(3, 2.40110717976441027e+01, 2.44965985555732651e-05, errMarg);
err += boysGaussJacobiComp(2, 1.05760917718943296e+01, 1.82584453104787371e-03, errMarg);
err += boysGaussJacobiComp(4, 1.07517634824251921e+01, 1.31319923018956300e-04, errMarg);
err += boysGaussJacobiComp(6, 1.00358282923656341e+01, 4.03172678289962034e-05, errMarg);
err += boysGaussJacobiComp(0, 5.47892906868342847e+00, 3.78261480395963582e-01, errMarg);
err += boysGaussJacobiComp(0, 1.36097073739555537e+01, 2.40226253436670254e-01, errMarg);
err += boysGaussJacobiComp(5, 5.78760718891000480e+00, 1.01117939674783074e-03, errMarg);
err += boysGaussJacobiComp(2, 2.37105717448630061e+01, 2.42801371668631682e-04, errMarg);
err += boysGaussJacobiComp(3, 8.61958659153599469e+00, 8.69711577833474938e-04, errMarg);
err += boysGaussJacobiComp(1, 1.75161748481979937e+01, 6.04443880924752762e-03, errMarg);
err += boysGaussJacobiComp(7, 1.78005408144260599e+01, 3.90819942959252242e-07, errMarg);
err += boysGaussJacobiComp(4, 1.60309583027948742e+01, 2.19893399718623621e-05, errMarg);
err += boysGaussJacobiComp(1, 5.81891629977826995e+00, 3.12926689388285139e-02, errMarg);
err += boysGaussJacobiComp(2, 2.23206874068650339e+01, 2.82382177734836615e-04, errMarg);
err += boysGaussJacobiComp(3, 2.11111773917220969e+01, 3.84372594790543070e-05, errMarg);
err += boysGaussJacobiComp(5, 1.78385193363418439e+01, 3.42981096851515732e-06, errMarg);
err += boysGaussJacobiComp(0, 2.98533710073760069e+01, 1.62199029584505578e-01, errMarg);
err += boysGaussJacobiComp(1, 1.37043093906448141e+01, 8.73428007209458796e-03, errMarg);
err += boysGaussJacobiComp(0, 2.39053812214143036e+01, 1.81257966648478835e-01, errMarg);
err += boysGaussJacobiComp(8, 9.33114880537891119e+00, 2.60490669849565536e-05, errMarg);
err += boysGaussJacobiComp(0, 1.04258048892890095e+01, 2.74465643391503084e-01, errMarg);
err += boysGaussJacobiComp(9, 1.65377357672650522e+01, 1.54776455775331250e-07, errMarg);
err += boysGaussJacobiComp(2, 2.19722029227043184e+01, 2.93712338162186753e-04, errMarg);
err += boysGaussJacobiComp(5, 2.64168048956758169e+01, 3.95808484621800808e-07, errMarg);
err += boysGaussJacobiComp(8, 2.52388894296045645e+01, 8.48304110900746019e-09, errMarg);
err += boysGaussJacobiComp(0, 9.98875844810448816e+00, 2.80405018534803785e-01, errMarg);
err += boysGaussJacobiComp(1, 2.23679305265493216e+01, 4.18867087312500282e-03, errMarg);
/* m = 10 .. 90, z= 5.000000e+00 .. 3.000000e+01 */
err += boysGaussJacobiComp(70, 1.92245328618759941e+01, 4.33400554688531631e-11, errMarg);
err += boysGaussJacobiComp(10, 9.89181912066122254e+00, 9.34026818696273425e-06, errMarg);
err += boysGaussJacobiComp(30, 8.17974671103959913e+00, 6.18389295694653863e-06, errMarg);
err += boysGaussJacobiComp(24, 7.52007969252186202e+00, 1.55939418218495283e-05, errMarg);
err += boysGaussJacobiComp(89, 2.54189905423002868e+01, 7.08442441366052987e-14, errMarg);
err += boysGaussJacobiComp(32, 1.06376081356388596e+01, 5.37769175151009233e-07, errMarg);
err += boysGaussJacobiComp(73, 2.61650738841696614e+01, 4.52485888428729547e-14, errMarg);
err += boysGaussJacobiComp(30, 1.92700054813983659e+01, 1.70373988628827959e-10, errMarg);
err += boysGaussJacobiComp(42, 1.26468300154490580e+01, 5.31803587334539247e-08, errMarg);
err += boysGaussJacobiComp(86, 2.97716788006918767e+01, 1.02714044786350082e-15, errMarg);
err += boysGaussJacobiComp(74, 2.76356818783211442e+01, 1.04931031070858934e-14, errMarg);
err += boysGaussJacobiComp(67, 1.62116123010556519e+01, 8.82570259643614001e-10, errMarg);
err += boysGaussJacobiComp(63, 1.03306569323112328e+01, 3.05644793556233076e-07, errMarg);
err += boysGaussJacobiComp(29, 6.17715921556351228e+00, 4.40421493459611961e-05, errMarg);
err += boysGaussJacobiComp(70, 1.76084179953994054e+01, 2.11690286808927728e-10, errMarg);
err += boysGaussJacobiComp(11, 5.97799067324183133e+00, 2.01532348445969970e-04, errMarg);
err += boysGaussJacobiComp(27, 5.85183297777326192e+00, 6.56271926777048995e-05, errMarg);
err += boysGaussJacobiComp(20, 1.68404763229879117e+01, 4.21895070541460645e-09, errMarg);
err += boysGaussJacobiComp(67, 6.05435081778860514e+00, 1.90732660307018927e-05, errMarg);
err += boysGaussJacobiComp(72, 1.23100354484967509e+01, 3.73100224549654081e-08, errMarg);
err += boysGaussJacobiComp(83, 1.25057752602362257e+01, 2.60316364186279509e-08, errMarg);
err += boysGaussJacobiComp(59, 6.33316826874109368e+00, 1.66693696353589451e-05, errMarg);
err += boysGaussJacobiComp(24, 2.90446124234768099e+01, 7.42119974291119758e-14, errMarg);
err += boysGaussJacobiComp(57, 6.69112892994784952e+00, 1.21902576280553909e-05, errMarg);
err += boysGaussJacobiComp(62, 2.07665413465024307e+01, 1.13440730876788935e-11, errMarg);
err += boysGaussJacobiComp(41, 1.70068185735957695e+01, 8.18101391457461557e-10, errMarg);
err += boysGaussJacobiComp(70, 2.69520487045060350e+01, 2.23374125592427837e-14, errMarg);
err += boysGaussJacobiComp(65, 1.11632755299639244e+01, 1.30055731097039240e-07, errMarg);
err += boysGaussJacobiComp(31, 6.09577719352733688e+00, 4.39375873039425086e-05, errMarg);
err += boysGaussJacobiComp(18, 1.64570399155563417e+01, 7.98505124997823672e-09, errMarg);
err += boysGaussJacobiComp(11, 2.43251147381966542e+01, 6.82754680869066021e-10, errMarg);
err += boysGaussJacobiComp(41, 5.21502235033788227e+00, 7.45982800292774695e-05, errMarg);
err += boysGaussJacobiComp(20, 2.45659220513966159e+01, 6.98414431764812995e-12, errMarg);
err += boysGaussJacobiComp(50, 9.75586608161083425e+00, 7.07177649909072579e-07, errMarg);
err += boysGaussJacobiComp(11, 7.23138483724284237e+00, 6.81896973412850151e-05, errMarg);
/* m = 90 .. 200, z= 0.000000e+00 .. 3.000000e+01 */
err += boysGaussJacobiComp(108, 6.55555005167576446e+00, 6.97102008917135754e-06, errMarg);
err += boysGaussJacobiComp(138, 6.66759831436095616e+00, 4.82038227900499749e-06, errMarg);
err += boysGaussJacobiComp(112, 1.14988413593726942e+01, 5.01506867491939310e-08, errMarg);
err += boysGaussJacobiComp(116, 4.56796400550042503e+00, 4.63465315929140115e-05, errMarg);
err += boysGaussJacobiComp(139, 6.38578709196594329e+00, 6.32817193540230137e-06, errMarg);
err += boysGaussJacobiComp(160, 7.37446306022909160e+00, 2.04690726067200503e-06, errMarg);
err += boysGaussJacobiComp(106, 1.46404149411062849e+01, 2.38150680413150456e-09, errMarg);
err += boysGaussJacobiComp(159, 1.66660991508910510e+01, 2.02205146218256831e-10, errMarg);
err += boysGaussJacobiComp(114, 2.03525525968990355e+01, 7.67677644208968252e-12, errMarg);
err += boysGaussJacobiComp(196, 6.40048424486130103e+00, 4.36734520934262999e-06, errMarg);
err += boysGaussJacobiComp(118, 5.23602228046214460e+00, 2.34815673000039485e-05, errMarg);
err += boysGaussJacobiComp(163, 1.06074954538447118e+01, 8.08372430578271002e-08, errMarg);
err += boysGaussJacobiComp(94, 2.14515757471513257e+01, 3.29118466761506144e-12, errMarg);
err += boysGaussJacobiComp(97, 8.96303687444297643e+00, 7.22367583152890804e-07, errMarg);
err += boysGaussJacobiComp(124, 1.02727051007033680e+01, 1.51175936003237791e-07, errMarg);
err += boysGaussJacobiComp(99, 1.02296009351812653e+01, 2.01861592793258461e-07, errMarg);
err += boysGaussJacobiComp(98, 2.64192406530599626e+01, 2.31882622144869504e-14, errMarg);
err += boysGaussJacobiComp(132, 2.25883086312445769e+01, 7.03310720988087134e-13, errMarg);
err += boysGaussJacobiComp(146, 1.36934767097831084e+01, 4.25025708748869363e-09, errMarg);
err += boysGaussJacobiComp(100, 3.17317419895544135e+00, 2.15031217342827884e-04, errMarg);
err += boysGaussJacobiComp(109, 2.82247755365686974e+01, 3.38324192002785972e-15, errMarg);
err += boysGaussJacobiComp(123, 1.40925053172813733e+01, 3.46035305938193238e-09, errMarg);
err += boysGaussJacobiComp(109, 1.23992480930093206e+01, 2.11962423349140964e-08, errMarg);
err += boysGaussJacobiComp(126, 3.27921757293449336e+00, 1.52773121743971348e-04, errMarg);
err += boysGaussJacobiComp(167, 1.07110916453745925e+00, 1.02931379543230710e-03, errMarg);
err += boysGaussJacobiComp(114, 2.88366489749167010e+00, 2.50485688367471183e-04, errMarg);
err += boysGaussJacobiComp(98, 2.54578724506953317e+01, 5.98634516854993775e-14, errMarg);
err += boysGaussJacobiComp(110, 2.21544084158236273e+00, 5.03695964233241741e-04, errMarg);
err += boysGaussJacobiComp(145, 1.73317578758603899e+01, 1.15784193417679468e-10, errMarg);
err += boysGaussJacobiComp(170, 7.85351293212905868e+00, 1.19360309611942457e-06, errMarg);
err += boysGaussJacobiComp(128, 7.42899264236361151e+00, 2.45098867135004395e-06, errMarg);
err += boysGaussJacobiComp(176, 1.59979455797387281e+01, 3.51076933075999839e-10, errMarg);
err += boysGaussJacobiComp(100, 2.15376165876964989e+00, 5.89861110120164300e-04, errMarg);
err += boysGaussJacobiComp(186, 2.14998208547183632e+01, 1.39280972402024329e-12, errMarg);
err += boysGaussJacobiComp(140, 3.26552015899235240e+00, 1.39070383439031829e-04, errMarg);
return err;
} /* main */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/time.h>
#include "lib/defines.h"
#include "lib/lock.h"
#include "lib/sem.h"
#include "fs.h"
#define MAX_COMMANDS 10
#define MAX_INPUT_SIZE 100
#define USAGE "Usage: %s inputfile outputfile numthreads numbuckets\n"
#define TIME_MSG "TecnicoFS completed in [%.4Lf] seconds.\n"
char inputCommands[MAX_COMMANDS][MAX_INPUT_SIZE];
int conptr = 0;
int proptr = 0;
#ifdef MUTEX
pthread_mutex_t lockConsumidor;
#elif RWLOCK
pthread_rwlock_t lockConsumidor;
#endif
sem_t semProdutor;
sem_t semConsumidor;
void errorParse(int test, char * errMsg) {
if(!test) {
return;
}
fputs(errMsg, stderr);
exit(EXIT_FAILURE);
}
static void displayUsage (const char* appName){
printf(USAGE, appName);
exit(EXIT_FAILURE);
}
static void parseArgs (int argc, char* const argv[]) {
if(argc != 5) {
displayUsage(argv[0]);
}
errorParse(THREAD_CONDITION((atoi(argv[3]))), "Error: invalid number of threads\n");
errorParse(atoi(argv[4]) <= 0, "Error: invalid number of buckets\n");
}
int insertCommand(char* data) {
semEnter(&semProdutor);
strncpy(inputCommands[proptr], data, MAX_INPUT_SIZE);
proptr = (proptr + 1) % MAX_COMMANDS;
semLeave(&semConsumidor);
return 1;
}
int removeCommand(char command[]) {
if(!inputCommands[conptr])
return -1;
strncpy(command, inputCommands[conptr], MAX_INPUT_SIZE);
if(*command != 'q')
conptr = (conptr + 1) % MAX_COMMANDS;
else
semLeave(&semConsumidor);
return 0;
}
void * processInput(void * file){
char line[MAX_INPUT_SIZE];
file = (FILE *) file;
while (fgets(line, MAX_INPUT_SIZE, file)) {
char token;
char name[MAX_INPUT_SIZE];
int numTokens = sscanf(line, "%c %s %s", &token, name, name);
/* perform minimal validation */
if (numTokens < 1) {
continue;
}
switch (token) {
case 'c':
case 'l':
case 'd':
errorParse(numTokens != 2, "Error: command invalid\n");
if(insertCommand(line))
break;
return NULL;
case 'r':
errorParse(numTokens != 3, "Error: command invalid\n");
if(insertCommand(line))
break;
return NULL;
case '#':
break;
default: { /* error */
errorParse(1,"Error: command invalid\n");
}
}
}
insertCommand("q\n");
return NULL;
}
void * applyCommands(void * arg){
while(1){
int iNumber;
semEnter(&semConsumidor);
lockWRlock(LOCK_CONSUMIDOR);
char command[MAX_INPUT_SIZE];
if( removeCommand(command) == -1 ) {
lockUnlock(LOCK_CONSUMIDOR);
continue;
}
if( *command == 'c' )
iNumber = obtainNewInumber(fs);
lockUnlock(LOCK_CONSUMIDOR);
semLeave(&semProdutor);
char token;
char name[MAX_INPUT_SIZE];
char rename[MAX_INPUT_SIZE];
int numTokens = sscanf(command, "%c %s %s", &token, name, rename);
int searchResult;
switch (token) {
case 'c':
errorParse(numTokens != 2, "Error: invalid command in Queue\n");
create(fs, name, iNumber);
break;
case 'l':
errorParse(numTokens != 2, "Error: invalid command in Queue\n");
searchResult = lookup(fs, name);
if(!searchResult)
printf("%s not found\n", name);
else
printf("%s found with inumber %d\n", name, searchResult);
break;
case 'd':
errorParse(numTokens != 2, "Error: invalid command in Queue\n");
delete(fs, name);
break;
case 'r':
errorParse(numTokens != 3, "Error: invalid command in Queue\n");
renameFile(fs, name, rename);
break;
case 'q':
errorParse(numTokens != 1, "Error: invalid command in Queue\n");
return NULL;
default: { /* error */
errorParse(1, "Error: command to apply\n");
return NULL;
}
}
}
return NULL;
}
static void runthreads(FILE * inputFile, int numberThreads) {
pthread_t tid[numberThreads+1];
// Create threads
for(int x = 0; x < numberThreads; x++) {
errorParse(pthread_create(tid + x + 1, 0, applyCommands, NULL),"Error: Thread creation failed\n");
}
errorParse(pthread_create(tid, 0, processInput, inputFile),"Error: Thread creation failed\n");
// Join threads
for(int x = 0; x < numberThreads + 1; x++) {
errorParse(pthread_join(tid[x],NULL),"Error: Thread merge failed\n");
}
}
int main(int argc, char* argv[]) {
struct timeval start, end;
parseArgs(argc, argv);
FILE * inputFile = fopen(argv[1],"r");
FILE * outputFile = fopen(argv[2],"w");
/*Perform minimal file validation*/
errorParse(inputFile == NULL,"Error: Input file non-existant\n");
fs = new_tecnicofs(atoi(argv[4]));
lockInit(LOCK_CONSUMIDOR);
semInit(&semProdutor, MAX_COMMANDS);
semInit(&semConsumidor, 0);
//Start time
errorParse(gettimeofday(&start,NULL),"Error: Checking time failed\n");
runthreads(inputFile, atoi(argv[3]));
print_tecnicofs_tree(outputFile, fs);
//End time
errorParse(gettimeofday(&end,NULL),"Error: Checking time failed\n");
errorParse(fclose(inputFile),"Error: Closing file failed\n");
lockDestroy(LOCK_CONSUMIDOR);
semDestroy(&semProdutor);
semDestroy(&semConsumidor);
free_tecnicofs(fs);
errorParse(fflush(outputFile),"Error: Flushing file failed\n");
errorParse(fclose(outputFile),"Error: Closing file failed\n");
printf(TIME_MSG,(long double)(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6);
exit(EXIT_SUCCESS);
}
|
C
|
#include <avr/io.h>
#include "sht1x.h"
static void sht1x_delay()
{
// 1 us (at 1MHz clock ??)
asm volatile ("nop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop");
asm volatile ("nop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop");
asm volatile ("nop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop");
asm volatile ("nop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop");
asm volatile ("nop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop");
asm volatile ("nop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop");
asm volatile ("nop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop");
asm volatile ("nop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop\nnop");
}
void sht1x_init(void)
{
/* Clock output, normally low */
SHT_SCK_DDR |= SHT_SCK_BIT;
SHT_SCK_PORT &= ~SHT_SCK_BIT;
/* Clock as input, with pullup */
SHT_DATA_DDR &= ~SHT_DATA_BIT;
SHT_DATA_PORT |= SHT_DATA_BIT;
}
static void sht1x_pull_data()
{
/* Disable pullup first in order to pull
* when we change the direction to output */
SHT_DATA_PORT &= ~SHT_DATA_BIT;
SHT_DATA_DDR |= SHT_DATA_BIT;
}
static void sht1x_release_data()
{
SHT_DATA_DDR &= ~SHT_DATA_BIT;
SHT_DATA_PORT |= SHT_DATA_BIT;
}
static void sht1x_clock_high()
{
SHT_SCK_PORT |= SHT_SCK_BIT;
}
static void sht1x_clock_low()
{
SHT_SCK_PORT &= ~SHT_SCK_BIT;
}
int sht1x_cmd(unsigned char cmd)
{
char i;
char ack;
/* Transmission Start */
sht1x_clock_high();
sht1x_delay();
sht1x_pull_data();
sht1x_delay();
sht1x_clock_low();
sht1x_delay();
sht1x_clock_high();
sht1x_delay();
sht1x_release_data();
sht1x_delay();
sht1x_clock_low();
sht1x_delay();
/* 3 address bits + 5 command bits */
for (i=0; i<8; i++)
{
if (cmd & 0x80)
sht1x_release_data();
else
sht1x_pull_data();
sht1x_delay();
sht1x_clock_high();
sht1x_delay();
sht1x_clock_low();
cmd <<= 1;
}
sht1x_release_data();
/* ack */
sht1x_delay();
sht1x_clock_high();
sht1x_delay();
ack = SHT_DATA_PIN & SHT_DATA_BIT;
sht1x_clock_low();
if (ack) {
return -1; // no ack!
}
// let the slave relase data
while (!(SHT_DATA_PIN & SHT_DATA_BIT))
{ /* empty */ }
return 0;
}
/** \brief Read and ack a byte from the sensor
*
* Note: This should be called after the transmission
* start, address and commands are sent and after the slave
* has pulled data low again indicating that the conversion
* is completed. */
int sht1x_read_byte(unsigned char *dst, char skip_ack)
{
unsigned char tmp;
int i;
for (tmp=0,i=0; i<8; i++) {
sht1x_delay();
sht1x_clock_high();
sht1x_delay();
tmp <<= 1;
if (SHT_DATA_PIN & SHT_DATA_BIT) {
tmp |= 1;
} else {
// tmp &= ~1;
}
sht1x_clock_low();
}
*dst = tmp;
/* Ack the byte by pulling data low during a 9th clock cycle */
if (!skip_ack)
sht1x_pull_data();
sht1x_delay();
sht1x_clock_high();
sht1x_delay();
sht1x_clock_low();
sht1x_release_data();
sht1x_delay();
return 0;
}
int sht1x_measure(unsigned char cmd, unsigned char dst[2])
{
if (sht1x_cmd(cmd))
return -1;
/* The slave pulls data low when conversion is done */
while ((SHT_DATA_PIN & SHT_DATA_BIT))
{ /* empty */ }
sht1x_read_byte(&dst[0], 0);
sht1x_read_byte(&dst[1], 1);
// sht1x_read_byte(&crc, 1);
return 0;
}
|
C
|
/****
Develop your owx functions for performing following operations on strings:
(a) copying one string to another
(b) comparing two strings
(c) adding a string to the end of another string
Write a driver program to test your functions. functions.
***/
//un complete
(A)
#include<stdio.h>
#include<string.h>
char *strcpy(char *str1,char *str2);
void main(){
char *str1;
char *str2;
strcpy(str1,str2);
return(str1,str2);
}
char *strcpy(char*str1,char*str2){
char str1[10];
char str2[10]="Hi Jhon";
puts(str1);
puts(str2);
}
|
C
|
#include <stdio.h>
void solve()
{
int no_of_numbers, no_of_ones = 0, number, no_of_zeroes = 0, i, no_of_ways_to_erase = 0;
scanf("%d", &no_of_numbers);
for(i = 1; i <= no_of_numbers; i++)
{
scanf("%d", &number);
number == 0 ? no_of_zeroes++ : no_of_ones++;
}
no_of_ways_to_erase += (no_of_ones%2 == 1 ? no_of_ones : no_of_zeroes);
printf("%d\n", no_of_ways_to_erase);
}
int main()
{
int no_of_test_cases;
scanf("%d", &no_of_test_cases);
while(no_of_test_cases-- != 0)
solve();
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct uni_msg {size_t b_rptr; size_t b_wptr; } ;
/* Variables and functions */
int /*<<< orphan*/ memcpy (int /*<<< orphan*/ ,size_t,int /*<<< orphan*/ ) ;
scalar_t__ uni_msg_ensure (struct uni_msg*,size_t) ;
size_t uni_msg_leading (struct uni_msg*) ;
int /*<<< orphan*/ uni_msg_len (struct uni_msg*) ;
int
uni_msg_prepend(struct uni_msg *msg, size_t len)
{
size_t need;
if (uni_msg_leading(msg) >= len) {
msg->b_rptr -= len;
return (0);
}
need = len - uni_msg_leading(msg);
if (uni_msg_ensure(msg, need))
return (-1);
memcpy(msg->b_rptr + need, msg->b_rptr, uni_msg_len(msg));
msg->b_rptr += need - len;
msg->b_wptr += need;
return (0);
}
|
C
|
/*
** exec.c for minishell1 in /home/nicolaspolomack/shell/PSU_2016_minishell1
**
** Made by Nicolas Polomack
** Login <[email protected]>
**
** Started on Mon Jan 9 11:14:09 2017 Nicolas Polomack
** Last update Fri Nov 2 03:39:20 2017 nicolaspolomack
*/
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include "shell.h"
#include "my.h"
#include "get_next_line.h"
void exec_child(t_shell *shell, int i)
{
if (!is_path(shell->cur->av[0]))
execve(cat_path(shell->path, shell->cur->av[0], i), shell->cur->av,
environ);
else
execve(shell->cur->av[0], shell->cur->av, environ);
if (errno == ENOEXEC)
exit(my_print_err(shell->cur->av[0]) +
my_print_err(": Exec format error. Binary \
file not executable.\n") - 1);
exit(my_print_err(shell->cur->av[0]) +
my_print_err(": Command not found.\n") - 1);
exit(0);
}
int check_access(char **final, t_shell *shell)
{
int i;
int ret;
struct stat stats;
i = -1;
if (is_path(final[0]))
{
if (stat(final[0], &stats) == 0)
return (compare_stats(&stats));
}
else
while (shell->path != NULL &&
shell->path[++i] != NULL)
if (stat(cat_path(shell->path, final[0], i), &stats) == 0)
{
ret = compare_stats(&stats);
return ((ret == 0) ? i : -2);
}
return (-1);
}
unsigned int exec_action(t_shell *shell, unsigned int args)
{
unsigned int r;
int i;
(void)args;
r = exec_pipeline(shell);
i = -1;
if (shell->is_done)
{
free_shell(shell);
exit(r);
}
while (shell->final[++i])
free(shell->final[i]);
free(shell->final);
free_commands(shell);
free(shell->line);
if (shell->exit_str)
free(shell->exit_str);
if ((shell->exit_str = my_unsigned_to_char(r)) == NULL)
exit(84);
return (r);
}
int format_commands(t_shell *shell)
{
t_command *head;
int i;
head = shell->commands;
while (head)
{
i = -1;
while (head->av[++i])
if ((head->av[i] = format_arg(head->av[i])) == NULL)
return (-1);
head = head->next;
}
return (0);
}
unsigned int exec_line(t_shell *shell, unsigned int args)
{
if (parse_history(shell, args) == -1 || parse_alias(shell) == -1 ||
parse_vars(shell) == -1 || magic(shell) == -1 ||
(shell->line = my_epurcommand(shell->line)) == NULL ||
parse_stars(shell) == 1 ||
(shell->line = my_epurstr(shell->line)) == NULL)
return (set_error(shell, 1));
if (is_line_empty(shell->line))
return (0);
free(shell->last);
shell->last = NULL;
if ((shell->final = bufferize(shell->line,
args = count_args(shell->line))) == NULL)
return (1);
if (set_commands(shell) == -1 || set_redirects(shell) == -1 ||
check_error(shell) == -1 || format_commands(shell) == -1)
return (shell->exit = 1);
shell->cur = shell->commands;
args = exec_action(shell, args);
return (args);
}
|
C
|
#include "output.h"
#include <stdio.h>
float sum_float(float *, int);
// bitwise convert unsigned(32) to float(32)
float u2f(unsigned x) {
return *((float *)&x);
} // u2f
// 3(a): insert supporting code for qsort(.., .., .., ..) here:
int compar(const void * val1, const void * val2)
{
float arg1 = *(float*) val1;
float arg2 = *(float*) val2;
return (arg1 > arg2) - (arg1 < arg2);
}
/*
Return value meaning
<0 The element pointed by val1 goes before the element pointed by val2
0 The element pointed by val1 is equivalent to the element pointed by val2
>0 The element pointed by val1 goes after the element pointed by val2
Source: http://www.cplusplus.com/reference/cstdlib/qsort/
*/
void main () {
float arr1[24], arr2[50];
float tot1, tot2;
int i;
//.-.-.-.-.-.-.-.-.-.-.-.-.-.//
//. . . Test case 1 . . .//
//.-.-.-.-.-.-.-.-.-.-.-.-.-.//
puts("Test Case 1:\n");
arr1[0] = u2f(0x7060000f); // 3(b): change this value
tot1 = arr1[0];
for (i = 1; i < 24; i++) {
arr1[i] = u2f(0x63800005); // 3(b): change this value
tot1 += arr1[i];
}
printf("The total before sorting: ");
f_printbits(tot1); putchar('\n');
printf(" The total after sorting: ");
// 3(a): insert code for sorting of arr1[] here:
qsort(arr1, 24, sizeof(float), compar);
f_printbits(sum_float(arr1, 24)); putchar('\n');
//.-.-.-.-.-.-.-.-.-.-.-.-.-.//
//. . . Test case 2 . . .//
//.-.-.-.-.-.-.-.-.-.-.-.-.-.//
puts("\nTest Case 2:\n");
tot2 = 0.0;
for (i = 0; i < 50; i++) {
arr2[i] = 0.1 * ((float)(1 + (i % 3 == 0) + (i % 7 == 0)));
tot2 += arr2[i];
}
printf("The total before sorting: ");
f_printbits(tot2); putchar('\n');
printf(" The total after sorting: ");
// 3(a): insert code for sorting of arr2[] here:
qsort(arr2, 50, sizeof(float), compar);
f_printbits(sum_float(arr2, 50)); putchar('\n');
puts("");
return;
}
|
C
|
#include <stdio.h>
#define FIRST_TIPO "INT","FLOAT","CHAR"
#define FIRST_COMMAND "READ","PRINT","WHILE","FOR"
#define FIRST_TOTAL FIRST_TIPO,FIRST_COMMAND
char tokens[][30] = {FIRST_TOTAL};
int toCharMatrix(char mat[][30], int size){
int i;
for(i = 0; i < size; i++){
printf("%s\n",mat[i]);
}
return 1;
}
int main(){
int i;
char conjunto_first[][30] =
{FIRST_TOTAL};
toCharMatrix((char [][30]){FIRST_TIPO},
sizeof((char [][30]){FIRST_TIPO}) / 30);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tokens_translate.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: afaraji <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/03 17:17:32 by afaraji #+# #+# */
/* Updated: 2020/11/03 17:17:37 by afaraji ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/ft_21sh.h"
#include "../inc/builtins.h"
#include "../inc/parse.h"
#include "../inc/ast.h"
#include "../inc/exec.h"
#include "../inc/ft_free.h"
#include "../inc/readline.h"
int is_op_2(char c, char c2)
{
if (c == '<' && c2 == '<')
return (SMLSML);
if (c == '>')
return (GRT);
if (c == '<')
return (SML);
if (c == '&')
return (BGJOB);
return (0);
}
int is_op(char *str, int i)
{
if (ft_isspace(str[i]))
return (SPACE);
if (str[i] == 39)
return (QUOTE);
if (str[i] == '"')
return (DQUOTE);
if (str[i] == ';')
return (SMCLN);
if (str[i] == '&' && str[i + 1] == '&')
return (ANDLG);
if (str[i] == '|' && str[i + 1] == '|')
return (ORLG);
if (str[i] == '|')
return (PIP);
if (str[i] == 92)
return (ESCAPE);
if ((str[i] == '>' && str[i + 1] == '&') ||
(str[i] == '&' && str[i + 1] == '>'))
return (GRTAND);
if (str[i] == '>' && str[i + 1] == '>')
return (GRTGRT);
if ((str[i] == '<' && str[i + 1] == '&'))
return (SMLAND);
return (is_op_2(str[i], str[i + 1]));
}
char *tokentoa_2(int token)
{
if (token == SMLSML)
return ("<<");
if (token == SMLAND)
return ("<&");
if (token == GRTAND)
return (">&");
return (ft_itoa(token));
}
char *tokentoa(int token)
{
if (token == SPACE)
return (" ");
if (token == QUOTE)
return ("'");
if (token == DQUOTE)
return ("\"");
if (token == SMCLN)
return (";");
if (token == ANDLG)
return ("&&");
if (token == ORLG)
return ("||");
if (token == PIP)
return ("|");
if (token == BGJOB)
return ("&");
if (token == ESCAPE)
return ("\\");
if (token == GRT)
return (">");
if (token == GRTGRT)
return (">>");
if (token == SML)
return ("<");
return (tokentoa_2(token));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int X,Y,i,aux, COUNT=0;
scanf("%d %d", &X,&Y);
if(X>Y){
aux = Y;
Y = X;
X = aux;
}
for(i=X;i<=Y;i++){
if(i%13 !=0){
COUNT+=i;
}
}
printf("%d\n",COUNT);
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fd;
char *buf;
int i;
struct stat statbuf;
if(stat("test.txt",&statbuf)==-1)
{
perror("fail to get stat");
exit(1);
}
fd=open("test.txt",O_RDONLY);
if(fd==-1)
{
perror("fail to open");
exit(1);
}
buf=(char *)mmap(NULL,statbuf.st_size,PROT_READ,MAP_PRIVATE,fd,0);
if(buf==MAP_FAILED)
{
perror("fail to mmap");
exit(1);
}
i=0;
while(i<statbuf.st_size)
{
printf("%c",buf[i]);
i++;
}
printf("\n");
if(munmap(buf,statbuf.st_size)==-1)
{
perror("fail to munmap");
exit(1);
}
close(fd);
return 0;
}
|
C
|
#include "sources/dijkstra.h"
#include <stdlib.h>
#include "sources/utils/boolean.h"
#include <math.h>
// Dijkstra from index start : return vector of distances to every other vertex
// TODO: use a good priority queue, and pass NI instead of pDistsIn (+ linear preprocessing)
double* dijkstra_core(double* pDistsIn, int start, int n) {
// initalisations
double* pDistsOut = (double*)malloc(n*sizeof(double));
bool* visited = (bool*)malloc(n*sizeof(bool));
for (int i=0; i<n; i++) {
pDistsOut[i] = INFINITY;
visited[i] = S_FALSE; // nothing seen so far
}
pDistsOut[start] = 0.0; // we are at distance 0 from self
while (S_TRUE)
{
double minGeodDist = INFINITY;
// n1 <-- node in "unseen" with smallest geodesic distance
// NOTE: on first loop, n1 == start
int n1 = 0;
for (int i=0; i<n; i++)
{
if (!visited[i] && pDistsOut[i] < minGeodDist)
{
n1 = i;
minGeodDist = pDistsOut[i];
}
}
if (minGeodDist == INFINITY)
break; // all is explored
visited[n1] = S_TRUE; // n1 is expanded
// For n2 running through neighbors of n1
for (int n2 = 0; n2<n; n2++)
{
int ind_n12 = n1*n+n2; // or n1+n*n2 (symmetry)
if (!isnan(pDistsIn[ind_n12]))
{
// check if we'd better go through n1 (on the way from start to n2)
if (pDistsOut[n2] > pDistsOut[n1] + pDistsIn[ind_n12])
pDistsOut[n2] = pDistsOut[n1] + pDistsIn[ind_n12];
}
}
}
free(visited);
return pDistsOut;
}
|
C
|
#include "temp_tool.h"
void adcInitialize () {
ADC_InitTypeDef adc_init_s;
ADC_CommonInitTypeDef adc_common_init_s;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); //Clock Gating. Enables the ADC interface clock
//Configure the ADC Prescaler, conversion resolution and data alignment using the ADC_Init() function.
adc_common_init_s.v = ADC_Mode_Independent;
adc_common_init_s.ADC_Prescaler = ADC_Prescaler_Div2;
adc_common_init_s.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
adc_common_init_s.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
ADC_CommonInit(&adc_common_init_s); //Initialization
adc_init_s.ADC_Resolution = ADC_Resolution_12b;
adc_init_s.ADC_ScanConvMode = DISABLE;
adc_init_s.ADC_ContinuousConvMode = DISABLE;
adc_init_s.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
adc_init_s.ADC_DataAlign = ADC_DataAlign_Right;
adc_init_s.ADC_NbrOfConversion = 1;
ADC_Init(ADC1, &adc_init_s); //Initialization
ADC_Cmd(ADC1, ENABLE); //Enable ADC
}
void sensorInitialize () {
ADC_TempSensorVrefintCmd(ENABLE); //Enable temperature sensor
ADC_RegularChannelConfig(ADC1, ADC_Channel_16, 1, ADC_SampleTime_480Cycles);
}
void getVoltage () {
ADC_SoftwareStartConv(ADC1); //Starting Conversion, waiting for it to finish, clearing the flag, reading the result
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET); //Could be through interrupts (Later)
ADC_ClearFlag (ADC1, ADC_FLAG_EOC); //EOC means End Of Conversion
ADC_GetConversionValue(ADC1); // Result available in ADC1->DR
}
float getCelcius (float volts) {
return (((volts/1000) - 0.0076f)/0.0025f) +25;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#define MAX 1000000000 //整数范围 1 ~ MAX
#define N 100 //创建N 个子线程求和
#define AVE (MAX/N) //每个子线程处理的整数个数
long long *sum = NULL; //保存各个子线程计算的结果
//获取当前时间
double get_time()
{
struct timeval t;
gettimeofday(&t,NULL);
return t.tv_sec + t.tv_usec/1000000.0;
}
//求和子线程
void* sum_work(void* arg)
{
int n = (int)arg; //第n部分
long long start = n*AVE+1;
long long end = start + AVE -1;
long long i;
sum[n] = 0;
//计算start ~ end 范围的整数和
for(i=start; i <= end;i++)
{
sum[n] = sum[n] + i;
}
pthread_exit(0);
}
int main()
{
double t1,t2;
pthread_t *pthread_id = NULL; //保存子线程id
int i;
long long result = 0; //总和
pthread_id = (pthread_t*)malloc(N * sizeof(pthread_t));
sum = (long long*)malloc(N * sizeof(long long));
//开始计算
t1 = get_time();
//创建N个子线程
for(i=0;i<N;i++)
{
pthread_create(pthread_id+i,NULL,sum_work,i);
}
//将各个子线程的求和结果综合到一起
for(i=0;i<N;i++)
{
//等待子线程结束,如果该子线程已经结束,则立即返回
pthread_join(pthread_id[i],NULL);
result += sum[i];
}
//求和结束
t2 = get_time();
//输出求和结果和运行时间
printf("sum of 1 ~ %lld is %lld runtime is %f\n",(long long)MAX,result,t2-t1);
free(pthread_id);
free(sum);
return 0;
}
|
C
|
#include "hashtab.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
double wtime()
{
struct timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + (double)t.tv_usec * 1E-6;
}
int main()
{
collision hash_;
srand(time(NULL));
listnode* hashtab[HASHTAB_SIZE];
// printf("%ld\n", sizeof(listnode) * N);
hashtab_init(hashtab);
memset(&hash_, 0, sizeof(collision));
FILE* myfile;
myfile = fopen("words.txt", "r");
if (myfile == NULL) {
printf("No file\n");
return 1;
}
char key[100];
int k = 0;
// выбираем рандомный элемент
char buf[256];
int j = rand() % N;
// printf("%d\n", j);
while (k < N) {
fscanf(myfile, "%s", key);
if (k == j)
strcpy(buf, key);
hashtab_add(hashtab, key, k++, &hash_);
}
double t;
t = wtime();
hashtab_lookup(hashtab, buf);
t = wtime() - t;
work(&hash_);
// print_stats_HT(hashtab);
/*printf("Число коллизий:\t\t\t\t\t\t%d\nЧисло незадействованных "
"ячеек:\t\t\t\t%d\nЧисло "
"ячеек, в которых лежит только один элемент:\t%d\nМаксимальное "
"число коллизий на одну ячейку:\t\t%d\n",
hash_.collisi,
hash_.zero_elements,
hash_.one_elements,
hash_.max);*/
printf("%d\t%f\t%d\n", N, t, hash_.collisi);
fclose(myfile);
return 0;
}
|
C
|
/*
============================================================================
Name : hal_timer.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include "hal/hal_timer.h"
#include "hal/hal_system_errors.h"
#include <avr/io.h>
int main(void) {
gcfg_hal_timer_t my_timer =
{
TIMER_0,
WITHOUT_PRESACLER,
NORMAL_MODE,
};
gcfg_hal_timer_t my_timer2 =
{
.ins_timer = TIMER_0,
.freq = WITHOUT_PRESACLER,
.timer_fun = NORMAL_MODE,
};
hal_init_timer(&my_timer);
while(1){
}
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
double f(double x,double y)
{
if(x==0) return 0;
else return 1-y;
}
void rk(float y0,float yy[])
{
float x=0.2,y=0.181,k1,k2,k3,k4;
float h=0.2;
int i;
yy[0]=0.181;
for(i=2;i<=3;i++)
{
k1=f(x,y);
k2=f(x+h/2,y+h*k1/2);
k3=f(x+h/2,y+h*k2/2);
k4=f(x+h,y+h*k3);
y=y+h*(k1+2*k2+2*k3+k4)/6;
x=i*h;
yy[i-1]=y;
}
}
void adams(float y0)
{
int i;
float y1,y2,y,yp,yc,yy[3],h,x;
printf("x[0]=0.000000 y[0]=%f\n",y0);
rk(y0,yy);
y1=yy[0];
y2=yy[1];
y=yy[2];
h=0.2;
for(i=1;i<=3;i++)
{
printf("x[%d]=%f y[%d]=%f\n",i,i*h,i,yy[i-1]);
for(i=3;x+h<1;i++)
{
x=i*h;
yp=y+h*(55*f(x,y)-59*f(x-h,y2)+37*f(x-2*h,y1)-9*f(x-3*h,y0))/24;
yc=y+h*(9*f(x+h,yp)+19*f(x,y)-5*f(x-h,y2)+f(x-2*h,y1))/24;
printf("x[%d]=%f ",i+1,x+h);
printf("ʽ: y[%d]=%f ",i+1,yc);
printf("ʽy[%d]=%f\n",i+1,yp);
y0=y1;
y1=y2;
y2=y;
y=yc;
}
}
}
int main()
{
float y0=0;
adams(y0);
}
|
C
|
/*
* Copyright (C) 2006-2012 by Benedict Paten ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
//Cache functions
#include "sonLibGlobalsInternal.h"
struct stCache {
stSortedSet *cache;
};
typedef struct _cacheRecord {
/*
* A little object for storing records in the cache.
*/
int64_t key, start, size;
char *record;
} stCacheRecord;
static int cacheRecord_cmp(const void *a, const void *b) {
const stCacheRecord *i = a;
const stCacheRecord *j = b;
if (i->key > j->key) {
return 1;
}
if (i->key < j->key) {
return -1;
}
if (i->start > j->start) {
return 1;
}
if (i->start < j->start) {
return -1;
}
return 0;
}
static void cacheRecord_destruct(stCacheRecord *i) {
free(i->record);
free(i);
}
static stCacheRecord getTempRecord(int64_t key, int64_t start, int64_t size) {
stCacheRecord record;
record.key = key;
record.start = start;
record.size = size;
record.record = NULL;
return record;
}
static stCacheRecord *cacheRecord_construct(int64_t key,
const void *value, int64_t start, int64_t size, bool copyMemory) {
assert(value != NULL);
assert(size >= 0);
assert(start >= 0);
stCacheRecord *record = st_malloc(sizeof(stCacheRecord));
record->key = key;
record->start = start;
record->size = size;
record->record = copyMemory ? memcpy(st_malloc(size), value, size)
: (char *) value;
return record;
}
static stCacheRecord *getLessThanOrEqualRecord(stCache *cache,
int64_t key, int64_t start, int64_t size) {
stCacheRecord record = getTempRecord(key, start, size);
return stSortedSet_searchLessThanOrEqual(cache->cache, &record);
}
static stCacheRecord *getGreaterThanOrEqualRecord(stCache *cache,
int64_t key, int64_t start, int64_t size) {
stCacheRecord record = getTempRecord(key, start, size);
return stSortedSet_searchGreaterThanOrEqual(cache->cache, &record);
}
static bool recordContainedIn(stCacheRecord *record, int64_t key,
int64_t start, int64_t size) {
/*
* Returns non zero if the record is contained in the given range.
*/
return record->key == key && record->start >= start && record->start
+ record->size <= start + size;
}
static bool recordOverlapsWith(stCacheRecord *record, int64_t key,
int64_t start, int64_t size) {
/*
* Returns non zero if the record overlaps with the given range.
*/
if (record->key != key) {
return 0;
}
if (record->start >= start) {
return record->start < start + size;
}
return record->start + record->size > start;
}
static bool recordsAdjacent(stCacheRecord *record1, stCacheRecord *record2) {
/*
* Returns non-zero if the records abut with record1 immediately before record2.
*/
assert(cacheRecord_cmp(record1, record2) <= 0);
assert(!recordOverlapsWith(record1, record2->key, record2->start, record2->size));
assert(!recordContainedIn(record1, record2->key, record2->start, record2->size));
return record1->key == record2->key && record1->start + record1->size
== record2->start;
}
static stCacheRecord *mergeRecords(stCacheRecord *record1,
stCacheRecord *record2) {
/*
* Merges two adjacenct records.
*/
assert(recordsAdjacent(record1, record2));
int64_t i = record1->size + record2->size;
char *j = memcpy(st_malloc(i), record1->record, record1->size);
memcpy(j + record1->size, record2->record, record2->size);
stCacheRecord *record3 = cacheRecord_construct(record1->key, j,
record1->start, i, 0);
return record3;
}
void deleteRecord(stCache *cache, int64_t key,
int64_t start, int64_t size) {
assert(!stCache_containsRecord(cache, key, start, size)); //Will not delete a record wholly contained in.
stCacheRecord *record = getLessThanOrEqualRecord(cache, key, start,
size);
while (record != NULL && recordOverlapsWith(record, key, start, size)) { //could have multiple fragments in there to remove.
if (recordContainedIn(record, key, start, size)) { //We get rid of the record because it is contained in the range
stSortedSet_remove(cache->cache, record);
cacheRecord_destruct(record);
record = getLessThanOrEqualRecord(cache, key, start, size);
} else { //The range overlaps with, but is not fully contained in, so we trim it..
assert(record->start < start);
assert(record->start + record->size > start);
record->size = start - record->start;
assert(record->size >= 0);
break;
}
}
record = getGreaterThanOrEqualRecord(cache, key, start, size);
while (record != NULL && recordOverlapsWith(record, key, start, size)) { //could have multiple fragments in there to remove.
if (recordContainedIn(record, key, start, size)) { //We get rid of the record because it is contained in the range
stSortedSet_remove(cache->cache, record);
cacheRecord_destruct(record);
record = getGreaterThanOrEqualRecord(cache, key, start, size);
} else { //The range overlaps with, but is not fully contained in, so we trim it..
assert(record->start < start + size);
assert(record->start > start);
int64_t newSize = record->size - (start + size - record->start);
int64_t newStart = start + size;
assert(newSize >= 0);
char *newMem = memcpy(st_malloc(newSize),
record->record + start + size - record->start, newSize);
free(record->record);
record->record = newMem;
record->start = newStart;
record->size = newSize;
break; //We can break at this point as we have reached the end of the range (as the record overlapped)
}
}
}
/*
* Public functions
*/
stCache *stCache_construct(void) {
stCache *cache = st_malloc(sizeof(stCache));
cache->cache = stSortedSet_construct3(cacheRecord_cmp,
(void(*)(void *)) cacheRecord_destruct);
return cache;
}
void stCache_destruct(stCache *cache) {
stSortedSet_destruct(cache->cache);
free(cache);
}
void stCache_clear(stCache *cache) {
stSortedSet_destruct(cache->cache);
cache->cache = stSortedSet_construct3(cacheRecord_cmp,
(void(*)(void *)) cacheRecord_destruct);
}
void stCache_setRecord(stCache *cache, int64_t key,
int64_t start, int64_t size, const void *value) {
//If the record is already contained we update a portion of it.
assert(value != NULL);
if (stCache_containsRecord(cache, key, start, size)) {
stCacheRecord *record = getLessThanOrEqualRecord(cache, key,
start, size);
assert(record != NULL);
assert(record->key == key);
assert(record->start <= start);
assert(record->start + record->size >= start + size);
memcpy(record->record + start - record->start, value, size);
return;
}
//Get rid of bits that are contained in this record..
deleteRecord(cache, key, start, size);
//Now get any left and right bits
stCacheRecord *record1 = getLessThanOrEqualRecord(cache, key, start,
size);
stCacheRecord *record2 = cacheRecord_construct(key, value, start,
size, 1);
assert(record2 != NULL);
if (record1 != NULL && recordsAdjacent(record1, record2)) {
stCacheRecord *i = mergeRecords(record1, record2);
stSortedSet_remove(cache->cache, record1);
cacheRecord_destruct(record1);
cacheRecord_destruct(record2);
record2 = i;
}
stCacheRecord *record3 = getGreaterThanOrEqualRecord(cache, key,
start, size);
if (record3 != NULL && recordsAdjacent(record2, record3)) {
stCacheRecord *i = mergeRecords(record2, record3);
stSortedSet_remove(cache->cache, record3);
cacheRecord_destruct(record2);
cacheRecord_destruct(record3);
record2 = i;
}
stSortedSet_insert(cache->cache, record2);
}
bool stCache_containsRecord(stCache *cache, int64_t key,
int64_t start, int64_t size) {
assert(start >= 0);
assert(size >= 0);
stCacheRecord *record = getLessThanOrEqualRecord(cache, key, start,
size);
if (record == NULL) {
return 0;
}
if (record->key != key) {
return 0;
}
assert(record->start <= start);
if (size != INT64_MAX && start + size > record->start + record->size) { //If the record has a known length check we have all that we want.
return 0;
}
return 1;
}
void *stCache_getRecord(stCache *cache, int64_t key,
int64_t start, int64_t size, int64_t *sizeRead) {
if (stCache_containsRecord(cache, key, start, size)) {
stCacheRecord *record = getLessThanOrEqualRecord(cache, key,
start, size);
assert(record != NULL);
int64_t j = start - record->start;
int64_t i = size == INT64_MAX ? (record->size - j) : size;
assert(record->start <= start);
assert(j >= 0);
assert(j <= record->size);
assert(i >= 0);
assert(j + i <= record->size);
*sizeRead = i;
char *cA = st_malloc(i);
memcpy(cA, record->record + j, i);
return cA;
}
return NULL;
}
bool stCache_recordsIdentical(const char *value, int64_t sizeOfRecord,
const char *updatedValue, int64_t updatedSizeOfRecord) {
if (sizeOfRecord != updatedSizeOfRecord) {
return 0;
}
for (int64_t j = 0; j < sizeOfRecord; j++) {
if (value[j] != updatedValue[j]) {
return 0;
}
}
return 1;
}
|
C
|
#include "delay.h"
#include "uart4.h"
//ջ
u8 UART4_RX_BUF[64]; //ջ,64ֽ.
//յݳ
u8 UART4_RX_CNT=0;
void UART4_IRQHandler(void)
{
u8 res;
if(USART_GetITStatus(UART4, USART_IT_RXNE) != RESET)//յ
{
res =USART_ReceiveData(UART4);//;ȡյ
UART4_RX_BUF[UART4_RX_CNT]=res; //¼յֵ
UART4_RX_CNT++; //1
}
}
//ʼIO 2
//pclk1:PCLK1ʱƵ(Mhz)
//bound:
void uart4_init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);//ʹGPIOCʱ
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4,ENABLE);//ʹUART4ʱ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
//UART-RX-PC11
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
USART_InitStructure.USART_BaudRate = bound;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(UART4, &USART_InitStructure);
USART_Cmd(UART4, ENABLE);
USART_ClearFlag(UART4,USART_FLAG_TC);
NVIC_InitStructure.NVIC_IRQChannel = UART4_IRQn; //ʹܴ4ж
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3; //ռȼ2
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //ȼ2
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //ʹⲿжͨ
NVIC_Init(&NVIC_InitStructure); //NVIC_InitStructָIJʼNVICĴ
USART_ITConfig(UART4, USART_IT_RXNE, ENABLE);//ж
USART_Cmd(UART4, ENABLE); //ʹܴ
}
|
C
|
/*
* dec.c
*
* Created: 17/05/2021 09:46:02 a. m.
* Author: ManuelNeri
*/
#include <io.h>
void main(void)
{
#asm
.EQU DDRD = 0x0A
.EQU PORTC = 8
.EQU PINC = 6
.EQU PORTD = 0x0B
Inicio:
LDI R16,0xFF
OUT DDRD,R16 ;Salida en PDO A PD7
LDI R16,0x0F
OUT PORTC,R16 ;Pull-ups en PC0 A PC3
CLR R1
Ciclo:
LDI R31,high(Tabla*2)
LDI R30,low(Tabla*2) ;Z apunta al primer elemento de la tabla (dir de 8 bits)
IN R17,PINC
ANDI R17,0x0F
ADD R30,R17
ADC R31,R1
LPM ;Leer tabla (z en 8 bits) -> R0
OUT PORTD, R0
RJMP Ciclo
Tabla:
.db 0xFC,0x60,0xDB,0xF3,0x66,0xB7,0xBE,0xE1,0xFE,0xF6,0xEE,0x3F,0x9C,0x7B,0x9E,0x8E
#endasm
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *fp;
char *myfile="test.txt";
char c;
char line[40];
int i=0;
int busy_time[13]={0};
char param1[10],param2[10],param3[10],timing[10];
if( 0 == (fp=(FILE*)fopen(myfile,"r")))
{
perror("fopen() failed");
exit(EXIT_FAILURE);
}
i=0;
while(fscanf(fp,"%79[^\n]\n",line)==1)
{
if(strstr(line,"busy")){
sscanf(line, "%s%s%s%s",param1,param2,param3,timing);
busy_time[i]=atoi(timing);
printf("This is i : %d\n",i);
printf("%d\n",atoi(timing));
i=i+1;
}
}
for(int i=0;i<13;i++)
{
printf("%d\n",busy_time[i]);
}
// while(fread(&c,sizeof c, 1 ,fp))
// {
// printf("%c",c);
// }
fclose(fp);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
int main(){
int n,x,i,sumaPares=0,cantPares=0;
int sumaImpares=0,cantImpares=0,cantCero=0;
float promPares,promImpares;
do{
printf("Ingrese la cantidad: ");
scanf("%d",&n);
}while(n<=0);
for(i=0;i<n;i++){
printf("Ingrese un valor: ");
scanf("%d",&x);
if(x==0){
cantCero=cantCero+1;
}else if(x % 2 == 0){
cantPares=cantPares+1;
sumaPares=sumaPares+x;
}else{
cantImpares=cantImpares+1;
sumaImpares=sumaImpares+x;
}
}
if(cantPares != 0){
promPares=sumaPares/cantPares;
printf("\nEl promedio de los pares: %f",promPares);
}
if(cantImpares != 0){
promImpares=sumaImpares/cantImpares;
printf("\nEl promedio de los impares es: %f",promImpares);
}
printf("\nLa cantidad de 0 es: %d",cantCero);
}
|
C
|
// OSMAN BOZOĞLU 220201048
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
#include <stdbool.h>
/* Struct for list nodes */
struct lst_node_s {
int data;
struct lst_node_s* next;
};
/* Struct for task nodes */
struct tsk_node_s {
int task_num; //starting from 0
int task_type; // insert:0, delete:1, search:2
int value;
struct tsk_node_s* next;
};
/* List operations */
int Insert(int value);
int Search(int value);
int Delete(int value);
void print_task();
/* Task queue functions */
void Task_queue(int n); //generate n random tasks for the task queue
void Task_enqueue(int task_num, int task_type, int value); //insert a new task into task queue
int Task_dequeue(); //take a task from task queue
struct tsk_node_s *head_tsk = NULL; //define head of the task nodes
struct lst_node_s *head_lst = NULL; //define head of the list nodes
int main(int argc, char const *argv[])
{
head_tsk = (struct tsk_node_s*)malloc(sizeof(struct tsk_node_s)); // head of the task queue allocation
head_lst = (struct lst_node_s*)malloc(sizeof(struct lst_node_s)); // first node of the linked list
int n = atoi(argv[1]); // n is number of how many task will be created. it takes from Command line
Task_queue(n); // generates tasks
Task_dequeue(); //
return 0;
}
bool is_contain(int type, int value){ // just checks there is no duplicated item in the task queue
struct tsk_node_s *temp;
temp = head_tsk->next;
while(temp != NULL){
if(temp->task_type == type && temp->value == value)
return true;
temp = temp->next;
}
return false;
}
void Task_enqueue(int task_num, int task_type, int value) { //insert a new task into task queue
struct tsk_node_s *new_task = (struct tsk_node_s*)malloc(sizeof(struct tsk_node_s)); // creating new task
new_task->task_num = task_num; // assign task num
new_task->task_type = task_type; // assign task type
new_task->value = value; //assign value
new_task->next = NULL; // assing next pointer
if (head_tsk->next == NULL) // if head->next equals null, that mean is task list is empty
{
head_tsk->next = new_task; // assigning the first element
}
else{
struct tsk_node_s *tmp;
tmp = head_tsk->next; // tmp is the first element
while(tmp->next != NULL)
tmp = tmp->next;
tmp->next = new_task; // add new task to last item
}
}
void Task_queue(int n){
srand(time(0));
int task_num = 0;
for (int i = 0; i < n; ++i)
{
int task_type = rand() %3; // select random task between 0 to 2
int value = rand() %50; // select the random value between 0 to 49
Task_enqueue(task_num,task_type,value); // creating task
task_num++;
}
}
int Search(int value){
struct lst_node_s *temp;
temp = head_lst->next; // temp is the first of the list
while(temp != NULL){
if (temp->data == value){ // if temp->data is equals the given value, the search function returns 1
return 1;
}
temp = temp->next;
}
return 0; // if the value is not found, search function returns 0
}
int Insert(int value){
if(Search(value))
return 0;
struct lst_node_s *new_task = (struct lst_node_s*)malloc(sizeof(struct lst_node_s)); // creating new task
new_task->data = value;
if (head_lst->next == NULL) // if head->next equals null, that mean is task list is empty
{
head_lst->next = new_task;
new_task->next = NULL;
}
else{
struct lst_node_s *tmp, *prev;
tmp = head_lst->next;
prev = head_lst;
while(tmp->data < value && tmp->next != NULL){ // finds location of the given value in linked list
prev = tmp;
tmp = tmp->next;
}
if (tmp->next == NULL && tmp->data < value) // If the value is the biggest from the list element, this adds it to the last.
{
tmp->next = new_task;
new_task->next = NULL;
return 1;
}
new_task->next = tmp;
prev->next = new_task;
}
return 1;
}
int Delete(int value){
if (!Search(value)) // checks the given value is in list or not. If not, delete function returns 0
return 0;
struct lst_node_s *prev, *temp; // struct definitions
temp = head_lst->next;
prev = head_lst;
while(temp != NULL){
if (temp->data == value)
{
prev->next = temp->next;
free(temp);
return 1;
}
prev = temp;
temp = temp->next;
}
}
void print_final_list(){ // prints the final list
struct lst_node_s *tmp;
tmp = head_lst->next;
printf("Final List :\n");
while(tmp != NULL){
printf("%d\t", tmp->data);
tmp = tmp->next;
}
printf("\n");
}
/*
Task_dequeue
It calls the Insert function if the task type 0. Then prints the result and the task removed from the task queue.
It calls the Insert function if the task type 0. Then prints the result and the task removed from the task queue.
It calls the Insert function if the task type 0. Then prints the result and the task removed from the task queue.
*/
int Task_dequeue(){
struct tsk_node_s *tmp;
head_tsk = head_tsk->next;
while(head_tsk != NULL){
switch(head_tsk->task_type){
case 0:
printf("task %d insert %d :",head_tsk->task_num,head_tsk->value);
if(Insert(head_tsk->value))
printf("%d is inserted\n", head_tsk->value);
else
printf("%d can not be inserted\n", head_tsk->value);
break;
case 1:
printf("task %d delete %d :",head_tsk->task_num,head_tsk->value);
if(Delete(head_tsk->value))
printf("%d is deleted\n", head_tsk->value);
else
printf("%d can not be deleted\n", head_tsk->value);
break;
case 2:
printf("task %d search %d :",head_tsk->task_num,head_tsk->value);
if(Search(head_tsk->value))
printf("%d is found\n", head_tsk->value);
else
printf("%d is not found\n", head_tsk->value);
break;
default: break;
}
tmp = head_tsk;
head_tsk = head_tsk->next;
free(tmp); // deleting the task
}
free(head_tsk);
print_final_list();
return 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_parse_options.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: laranda <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/10 16:58:43 by laranda #+# #+# */
/* Updated: 2019/04/11 16:28:50 by laranda ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_PARSE_OPTIONS_H
# define FT_PARSE_OPTIONS_H
# ifdef DEV
# define D(x) x
# else
# define D(x)
# endif
# define OPTION_SHORT_PREFIX "-"
# define OPTION_LONG_PREFIX "--"
# define END_OF_OPTION_STR "--"
typedef struct s_option t_option;
typedef struct s_parsing_context t_parsing_context;
typedef enum e_opt_type t_opt_type;
typedef enum e_arg_type t_arg_type;
enum e_arg_type
{
OPTION_SHORT,
OPTION_LONG,
OPTION_ERROR,
END_OF_OPTION,
PARAM
};
enum e_opt_type
{
OPTION_END = 0,
OPTION_BIT,
};
struct s_option
{
t_opt_type type;
char short_name;
char *long_name;
void *value;
};
struct s_parsing_context
{
int argc;
char **argv;
t_option *options;
char *usage;
void (*error_callback)(char *arg);
};
int ft_parse_options(t_parsing_context *ctxt);
#endif
|
C
|
#include "../src/base64.c"
#include "test.h"
#include <string.h>
static int test_X(const char *input, const char *output)
{
char encoded[80];
char decoded[80];
unsigned int input_len, output_len;
unsigned int encoded_len, decoded_len;
input_len = strlen(input);
output_len = strlen(output);
encoded_len = base64_encoded_length(input_len);
if (assert_uint("base64_encoded_length", encoded_len, output_len) < 0) {
return 1;
}
base64_encode(input, encoded, input_len);
*(encoded + encoded_len) = 0;
if (assert_string("base64_encode", encoded, output) < 0) {
return 1;
}
decoded_len = base64_decode(encoded, decoded, encoded_len);
*(decoded + decoded_len) = 0;
if (assert_string("base64_decode", decoded, input) < 0) {
return 1;
}
return 0;
}
static int test_without(void)
{
char *encoded = "TQ";
char decoded[80];
unsigned int decoded_len;
decoded_len = base64_decode(encoded, decoded, 2);
*(decoded + decoded_len) = 0;
if (assert_string("base64_decode", decoded, "M") < 0) {
return 1;
}
return 0;
}
int main(void)
{
test_title("Testing BASE64");
if (test_X("M", "TQ==") < 0 || test_X("Ma", "TWE=") < 0 || test_X("Man", "TWFu") < 0) {
return 1;
}
if (test_X("liblibre.so", "bGlibGlicmUuc28=") < 0) {
return 1;
}
if (test_without() < 0) {
return 1;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int* aprovados (int n, int *mat, float *notas, int *tam)
{
int i, contadorAprov = 0;
for(i = 0; i < n; i++) //Contando a quantidade de aprovados
{
if(notas[i] >= 5.0)
contadorAprov++;
}
int *vetorAprov = (int *) malloc(contadorAprov); //Alocando um vetor do tamanho da quantidade de aprovados previsto
int indiceAprov = 0;
for(i = 0; i < n; i++) //Revisitando o vetor de notas para atribuir as matrculas aprovadas para o vetor de aprovados
{
if(notas[i] >= 5.0)
{
vetorAprov[indiceAprov] = mat[i];
indiceAprov++;
}
}
*tam = contadorAprov; //Atribuindo o ponteiro tamanho para a varivel contadorAprov
return &vetorAprov[0]; //Retornando o primeiro elemento do vetor de aprovados
}
int main()
{
//Criando as variveis da turma
int mat [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
float notas [10] = { 4.9 , 5.1, 0.5, 8.0, 3.5, 9.0, 3.0, 7.0, 2.87, 9.0};
int tam = 0;
int *vetorDeAprovados = aprovados(10, &mat[0], ¬as[0], &tam);
printf("Alunos Aprovados: %d. \n", tam);
int i;
for ( i = 0; i < tam; i++ )
{
printf("Aluno <%d> foi aprovado. \n", *(vetorDeAprovados + i) );
}
return 0;
}
|
C
|
#include <stdio.h>
void printDown(int n)
{
while (1)
{
printf("%d", n);
if (n > 1)
n--;
else
break;
}
}
|
C
|
#include<stdio.h>
//int main() {
// int a = 0x11223344;
// int b = 010;
// printf("%d %d", a, b);
// return 0;
//
//
//}
//int sz(int n){
// int count = 0;
// for (n=n; n % 2 == 0; n = n / 2)
// {
// if (n % 2 == 1)
// {
// count++;
// }
// }
// return count;
//}
//
//int main() {
// int tem = 0;
//
// scanf_s("%d",&tem);
// int count = sz(tem);
// printf("%d ", count);
// return 0;
//}
//int main() {
// int i = 0;
// int count = 0;
// for (i = 1; i <= 12;i=i*2)
// {
// count++;
// }
// printf("%d ", count);
// return 0;
//}
|
C
|
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#define BUFSIZE 100
int bufp = 0;
int buf[BUFSIZE];
int getch(void);
void ungetch(int);
int getfloat( double *pn);
int main() {
double val = 0;
int c;
while((c = getfloat(&val)) != EOF) {
switch (c) {
case '\n':
printf("this is the double %f", val);
break;
}
}
}
int getch(void) {
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) {
if(bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
int getfloat(double *pn) {
int c, sign;
double deci = 1.0;
while(isspace(c = getch()));
if(!isdigit(c) && c != EOF && c != '+' && c != '-') {
ungetch(c);
return 0;
}
sign = (c == '-') ? -1:1;
if(c == '+' || c == '-')
c = getch();
if(isdigit(c)) {
for(*pn = 0.0; isdigit(c); c = getch())
*pn = 10.0 * *pn + (c-'0');
}
else {
return c;
}
if(c == '.' && isdigit(c=getch())) {
for(deci = 1.0; isdigit(c); c=getch()) {
*pn = 10.0 * *pn + (c-'0');
deci *= 10.0;
}
}
*pn = sign * *pn / deci;
if(c != EOF)
ungetch(c);
return c;
}
|
C
|
//***************************************************************************
// File name: TCP_Lab.c
// Author: chadd williams
// Date: September 10, 2018
// Class: CS 360
// Assignment: In Class TCP Lab
// Purpose: Practice using TCP sockets
//***************************************************************************
#define _GNU_SOURCE
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// wireshark
// tcp.dstport == 36001 || tcp.srcport == 36001
// start the echo server
// ncat -l 36001 --keep-open --exec "/bin/cat" # tcp
// /usr/sbin/ss -l -t -4 -p
// run your code
// bin/TCP_Lab 127.0.0.1 36001
// alternative nc commands to run the echo server:
// nc -l 36001
// nc 127.0.0.1 36001
/****************************************************************************
Function: main
Description: send a 4 byte integer to an echo server and display the returned
4 byte int
Parameters: int argc: number of command line arguments
char **argv: the command line arguments
Returned: EXIT_SUCCESS
****************************************************************************/
int main(int argc, char **argv)
{
int socketfd;
int value = 42;
int result;
char *pBuf = (char*) &value;
struct sockaddr_in sAddr;
// use inet_pton() to transform argv[2],
// a text representation of an IPv4 address,
// to a network-order, binary representation
// stored in sAddr.sin_addr
// be sure to the family and port in
// sAddr.
// create an AF_INET Stream socket.
// make sure the socket was created.
// otherwise, exit with an error message.
// display the integer in value
printf("%d\n\n", value);
// convert value to network-order
// display the integer in value, now in network order
printf("Network Byte Order (send): %x\n\n", value);
// create a connection
//send
// reset the value to 0
value = 0;
// recv a 4 byte int from the socket.
// make sure all 4 bytes were read
// otherwise, display an error message
// display the integer in value, now in network order
printf("Network Byte Order (receive): %x\n\n", value);
// convert value to host-order
// display the integer in value
printf("%d\n\n", value);
// close the socket.
return EXIT_SUCCESS;
}
|
C
|
/*
* This file is an example named ``This example``.
*
* ``This example`` is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ``This example`` is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with ``This example``. If not, see <http://www.gnu.org/licenses/>.
*
*
* Copyright 2012 Vicente Ruiz Rodríguez <[email protected]>. All rights reserved.
* http://www.menudoproblema.com/
*
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
void do_something()
{
printf("Do somenthing\n");
sleep(3);
}
int main()
{
struct timeval tim;
int keepalive = 5, elapsed_seconds;
double t1, t2;
gettimeofday(&tim, NULL);
t1 = tim.tv_sec + (tim.tv_usec/1000000.0);
while(1)
{
gettimeofday(&tim, NULL);
t2 = tim.tv_sec + (tim.tv_usec/1000000.0);
elapsed_seconds = (int)(t2 - t1);
if(elapsed_seconds > keepalive)
{
printf("Timeout! Elapsed time: %d\n", elapsed_seconds);
gettimeofday(&tim, NULL);
t1 = tim.tv_sec + (tim.tv_usec/1000000.0);
}
do_something();
}
return 0;
}
|
C
|
#include "read_size.h"
#include <stdio.h>
int read_size()
{
int consol_input;
printf("Please, type a number!\n");
scanf("%d", &consol_input);
return consol_input;
}
|
C
|
#include "symbol.h"
void init_st()
{
length = 0;
max_size = N;
st = (Symbol *) malloc (N * sizeof (strSymbol));
int i;
for(i=0;i < N;i++)
{
st[i] = (Symbol) malloc (sizeof (strSymbol)) ; // symbol eux meme sont des structures, il faut aussi les allouer
}
// next_quad = 0;
// id_temp = 0;
}
void print_st()
{
if (st != NULL)
{
int i;
for(i=0;i < length;i++)
{
if(st[i]->type = 'i')
{
printf ("INDEX: %d LABEL: %s VALUE: %d \n"
, i, st[i]->label, st[i]->val.i);
}
else // affichage des stencil
{
// printf ("INDEX: %d LABEL: %s VALUE: %d \n"
// , i, st[i]->label, st[i]->val->i);
}
}
}
else
{
printf ("Empty symbol table\n") ;
}
}
int get_index(char* label)
{
int index = -1;
int i;
for(i=0; i < length; i++)
{
if(!strcmp(st[i]->label, label))
{
index = i;
i = length;
}
}
return index;
}
Symbol get_symbol(char* label) // utilise get_index
{
int index = get_index(label);
return index == -1 ? NULL : st[index];
}
Symbol add_or_replace(char* label, value v, char t)
{
int index = get_index(label);
if(index != -1)
{
st[index]->val = v;
}
else
{
index = length;
if(length == max_size)
{
max_size += N;
st = (Symbol*) realloc(st, max_size * sizeof(Symbol) );
}
length++;
st[index]->label = strdup(label);
st[index]->val = v;
st[index]->type = t;
}
return st[index];
}
void free_st()
{
int i;
for(i=0;i < max_size;i++)
{
free(st[i]);
}
free(st);
}
|
C
|
#include "TimeManager.h"
static Status SetCreateRange(Timer *pTimer, float theIniMinX, float theIniMaxX, float theIniMinY, float theIniMaxY, float theIniMinVx, float theIniMaxVx, float theIniMinVy, float theIniMaxVy, float theIniMinDir, float theIniMaxDir);
static Status SetBaseObjToCreate(Timer *pTimer, unsigned long theType, AEGfxVertexList* theMesh, AEGfxTexture* theTexture, GameObjBaseList L);
static Status SetObjToCreate(Timer *pTimer, unsigned long theType, float scale, GameObjBaseList L, int thePropertyCount, Property* theProperties);
static float GetRanFloatFromTo(float min, float max);
static Status GetRandomPosVelAndDir(Vector2D* thePos, Vector2D* theVel, float *theDir, float theIniMinX, float theIniMaxX, float theIniMinY, float theIniMaxY, float theIniMinVx, float theIniMaxVx, float theIniMinVy, float theIniMaxVy, float theIniMinDir, float theIniMaxDir);
Status TimerIni(time_t* LevelTime)
{
int i;
time(LevelTime);
for (i = 0; i < MaxTimers; i++)
Timers[i].flag = FLAG_INACTIVE;
timerCount = 0;
srand(time(0));
return OK;
}
static Status SetCreateRange(Timer *pTimer, float theIniMinX, float theIniMaxX, float theIniMinY, float theIniMaxY, float theIniMinVx, float theIniMaxVx, float theIniMinVy, float theIniMaxVy, float theIniMinDir, float theIniMaxDir)
{
pTimer->properties.iniMaxX = theIniMinX;
pTimer->properties.iniMaxX = theIniMaxX;
pTimer->properties.iniMinY = theIniMinY;
pTimer->properties.iniMaxY = theIniMaxY;
pTimer->properties.iniMinVx = theIniMinVx;
pTimer->properties.iniMaxVx = theIniMaxVx;
pTimer->properties.iniMinVy = theIniMinVy;
pTimer->properties.iniMaxVy = theIniMaxVy;
pTimer->properties.iniMinDir = theIniMinDir;
pTimer->properties.iniMaxDir = theIniMaxDir;
return OK;
}
static Status SetBaseObjToCreate(Timer *pTimer, unsigned long theType, AEGfxVertexList* theMesh, AEGfxTexture* theTexture, GameObjBaseList L)
{
pTimer->properties.t_BaseType = theType;
pTimer->properties.t_Mesh = theMesh;
pTimer->properties.t_Texture = theTexture;
pTimer->properties.t_L = L;
return OK;
}
Status CreateBaseObjAtTime(unsigned long theType, AEGfxVertexList* theMesh, AEGfxTexture* theTexture, GameObjBaseList L, float theTime)
{
int i;
for (i = 0; i < MaxTimers; i++)
{
if (Timers[i].flag == FLAG_INACTIVE)
{
timerCount++;
Timers[i].flag = FLAG_ACTIVE;
Timers[i].type = TTYPE_BASEOBJ;
Timers[i].time = theTime;
SetBaseObjToCreate(&Timers[i], theType, theMesh, theTexture, L);
}
}
return ERROR;
}
static Status SetObjToCreate(Timer *pTimer, unsigned long theType, float scale, GameObjBaseList L, int thePropertyCount, Property* theProperties)
{
int i;
pTimer->properties.t_Type = theType;
pTimer->properties.t_Scale = scale;
pTimer->properties.t_L = L;
pTimer->properties.t_PropertyCount = thePropertyCount;
for (i = 0; i < thePropertyCount; i++)
pTimer->properties.t_Properties[i] = theProperties[i];
return OK;
}
Status CreateOneObjAtTime(float theTime, unsigned long theType, float scale, Vector2D Pos, Vector2D Vel, float dir, GameObjBaseList L, int thePropertyCount, Property* theProperties)
{
int i;
for (i = 0; i < MaxTimers; i++)
{
if (Timers[i].flag == FLAG_INACTIVE)
{
timerCount++;
Timers[i].flag = FLAG_ACTIVE;
Timers[i].type = TTYPE_OBJ;
Timers[i].time = theTime;
Timers[i].properties.t_Pos = Pos;
Timers[i].properties.t_Vel = Vel;
Timers[i].properties.t_Dir = dir;
SetObjToCreate(&Timers[i], theType, scale, L, thePropertyCount, theProperties);
return OK;
}
}
return ERROR;
}
Status CreateOneObjAtTimeWithRange(float theTime, unsigned long theType, float scale, GameObjBaseList L, int thePropertyCount, Property* theProperties, float theIniMinX, float theIniMaxX, float theIniMinY, float theIniMaxY, float theIniMinVx, float theIniMaxVx, float theIniMinVy, float theIniMaxVy, float theIniMinDir, float theIniMaxDir)
{
int i;
for (i = 0; i < MaxTimers; i++)
{
if (Timers[i].flag == FLAG_INACTIVE)
{
timerCount++;
Timers[i].flag = FLAG_ACTIVE;
Timers[i].type = TTYPE_OBJ_RANDOM;
Timers[i].time = theTime;
SetCreateRange(&Timers[i], theIniMinX, theIniMaxX, theIniMinY, theIniMaxY, theIniMinVx, theIniMaxVx, theIniMinVy, theIniMaxVy, theIniMinDir, theIniMaxDir);
SetObjToCreate(&Timers[i], theType, scale, L, thePropertyCount, theProperties);
return OK;
}
}
return ERROR;
}
Status CreateSomeObjAtSameTimeWithRange(float theTime, int theAmountToCreate, unsigned long theType, float scale, GameObjBaseList L, int thePropertyCount, Property* theProperties, float theIniMinX, float theIniMaxX, float theIniMinY, float theIniMaxY, float theIniMinVx, float theIniMaxVx, float theIniMinVy, float theIniMaxVy, float theIniMinDir, float theIniMaxDir)
{
int i;
for (i = 0; i < MaxTimers; i++)
{
if (Timers[i].flag == FLAG_INACTIVE)
{
timerCount++;
Timers[i].flag = FLAG_ACTIVE;
Timers[i].type = TTYPE_SOMEOBJ;
Timers[i].time = theTime;
Timers[i].properties.amountToCreate = theAmountToCreate;
SetCreateRange(&Timers[i], theIniMinX, theIniMaxX, theIniMinY, theIniMaxY, theIniMinVx, theIniMaxVx, theIniMinVy, theIniMaxVy, theIniMinDir, theIniMaxDir);
SetObjToCreate(&Timers[i], theType, scale, L, thePropertyCount, theProperties);
return OK;
}
}
return ERROR;
}
static float GetRanFloatFromTo(float min, float max)
{
float f;
int i;
i = rand() % 1000;
f = min + (max - min) * ((float)i / 1000.0f);
return f;
}
static Status GetRandomPosVelAndDir(Vector2D* thePos, Vector2D* theVel, float *theDir, float theIniMinX, float theIniMaxX, float theIniMinY, float theIniMaxY, float theIniMinVx, float theIniMaxVx, float theIniMinVy, float theIniMaxVy, float theIniMinDir, float theIniMaxDir)
{
thePos->x = GetRanFloatFromTo(theIniMinX, theIniMaxX);
thePos->y = GetRanFloatFromTo(theIniMinY, theIniMaxY);
theVel->x = GetRanFloatFromTo(theIniMinVx, theIniMaxVx);
theVel->y = GetRanFloatFromTo(theIniMinVy, theIniMaxVy);
*theDir = GetRanFloatFromTo(theIniMinDir, theIniMaxDir);
return OK;
}
Status TimerUpdate(time_t LevelTime)
{
int i, dealTimers = 0, j;
double passTime;
time_t poiTime;
Vector2D iniPos, iniVel;
float iniDir;
time(&poiTime);
passTime = difftime(poiTime, LevelTime);
for (i = 0; i < MaxTimers && dealTimers < timerCount; i++)
{
if (Timers[i].flag == FLAG_INACTIVE)
continue;
else
{
dealTimers++;
if (passTime >= Timers[i].time)
{
switch (Timers[i].type)
{
case TTYPE_BASEOBJ:
{
CreateGameObjBase(Timers[i].properties.t_Type, Timers[i].properties.t_Mesh, Timers[i].properties.t_Texture, Timers[i].properties.t_L);
Timers[i].flag = FLAG_INACTIVE;
break;
}
case TTYPE_OBJ:
{
CreateGameObj(Timers[i].properties.t_Type, Timers[i].properties.t_Scale, Timers[i].properties.t_Pos, Timers[i].properties.t_Vel, Timers[i].properties.t_Dir, Timers[i].properties.t_L, Timers[i].properties.t_PropertyCount, Timers[i].properties.t_Properties);
Timers[i].flag = FLAG_INACTIVE;
break;
}
case TTYPE_OBJ_RANDOM:
{
GetRandomPosVelAndDir(&iniPos, &iniVel, &iniDir, Timers[i].properties.iniMinX, Timers[i].properties.iniMaxX, Timers[i].properties.iniMinY, Timers[i].properties.iniMaxY, Timers[i].properties.iniMinVx, Timers[i].properties.iniMaxVx, Timers[i].properties.iniMinVy, Timers[i].properties.iniMaxVy, Timers[i].properties.iniMinDir, Timers[i].properties.iniMaxDir);
CreateGameObj(Timers[i].properties.t_Type, Timers[i].properties.t_Scale, iniPos, iniVel, iniDir, Timers[i].properties.t_L, Timers[i].properties.t_PropertyCount, Timers[i].properties.t_Properties);
Timers[i].flag = FLAG_INACTIVE;
break;
}
case TTYPE_SOMEOBJ:
{
for (j = 0; j < Timers[i].properties.amountToCreate; j++)
{
GetRandomPosVelAndDir(&iniPos, &iniVel, &iniDir, Timers[i].properties.iniMinX, Timers[i].properties.iniMaxX, Timers[i].properties.iniMinY, Timers[i].properties.iniMaxY, Timers[i].properties.iniMinVx, Timers[i].properties.iniMaxVx, Timers[i].properties.iniMinVy, Timers[i].properties.iniMaxVy, Timers[i].properties.iniMinDir, Timers[i].properties.iniMaxDir);
CreateGameObj(Timers[i].properties.t_Type, Timers[i].properties.t_Scale, iniPos, iniVel, iniDir, Timers[i].properties.t_L, Timers[i].properties.t_PropertyCount, Timers[i].properties.t_Properties);
}
Timers[i].flag = FLAG_INACTIVE;
break;
}
default:
break;
}
}
}
}
return OK;
}
Status TimerFree()
{
int i;
timerCount = 0;
for (i = 0; i < MaxTimers; i++)
Timers[i].flag = FLAG_INACTIVE;
return OK;
}
|
C
|
#ifndef COORD_H
#define COORD_H
struct coord {
double x;
double y;
double z;
coord operator-(const coord& sub)
{
return {x-sub.x, y-sub.y, z-sub.z};
}
};
#endif
|
C
|
#include<stdio.h>
int removeElement(int* nums, int numsSize, int val){
int i,j;
for(i=0,j=0;j<numsSize;++j){
if (nums[j]!=val){
nums[i++]=nums[j];
}
}
return i;
}
int main(void) {
int nums[3]={3,2,2,3};
int numsSize = sizeof(nums)/sizeof(nums[0]);
int val = 3;
int n = removeElement(nums,numsSize,val);
int i;
for (i=0;i<n;++i){
printf("%d,",numsSize);
}
return 0;
}
|
C
|
#include <stdio.h>
#include "sort.c"
#include "search.c"
int main(void)
{
int a[10] = {0,20,2,6,1,98,32,56,78,21};
int n = 10;
// quickSort(a,0,n-1);
insert(a,n);
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
return 0;
}
|
C
|
// Squarewaves.c
// Runs on MSP432
// Initialize P2.1 and P2.2 as outputs with different initial values,
// then toggle them to produce two out of phase square waves.
// Daniel Valvano
// April 23, 2015
/*
This example accompanies the book
"Embedded Systems: Introduction to the MSP432 Microcontroller",
ISBN: 978-1512185676, Jonathan Valvano, copyright (c) 2015
Program 4.4
Copyright 2015 by Jonathan W. Valvano, [email protected]
You may use, edit, run or distribute this file
as long as the above copyright notice remains
THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
VALVANO SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
For more information about my classes, my research, and my books, see
http://users.ece.utexas.edu/~valvano/
*/
// built-in LED1 connected to P1.0
// negative logic built-in Button 1 connected to P1.1
// negative logic built-in Button 2 connected to P1.4
// built-in red LED connected to P2.0
// built-in green LED connected to P2.1
// built-in blue LED connected to P2.2
#include <stdint.h>
#include "..\inc\msp432p401r.h"
int main(void){
P2SEL0 &= ~0x06;
P2SEL1 &= ~0x06; // configure built-in RGB LEDs as GPIO
P2DS |= 0x06; // make built-in RGB LEDs high drive strength
P2DIR |= 0x06; // make built-in RGB LEDs out
P2OUT |= 0x02; // P2.1 on (green LED on)
P2OUT &= ~0x04; // P2.2 off (blue LED off)
while(1){
P2OUT ^= 0x06; // toggle P2.1 and P2.2
}
}
// Color LED(s) Port2
// dark --- 0
// red R-- 0x01
// blue --B 0x04
// green -G- 0x02
// yellow RG- 0x03
// sky blue -GB 0x06
// white RGB 0x07
// pink R-B 0x05
|
C
|
#include <stdio.h>
#define N 200
int n;
int queue[N];
int top_queue, tail_queue;
int stack1[N], stack5[N], stack60[N];
int top_stack1, top_stack5, top_stack60;
int perm[N];
int ans;
int
gcd(int x, int y)
{
if (y == 0) return x;
else return gcd(y, x % y);
}
int
main()
{
int i, j, k;
while (scanf("%d", &n), n)
{
top_queue = 0;
tail_queue = n - 1;
for (i = 0; i < n; i++) queue[i] = i;
top_stack1 = top_stack5 = top_stack60 = -1;
for (i = 1; i <= 1440; i++)
{
top_stack1++;
stack1[top_stack1] = queue[top_queue];
top_queue++;
top_queue %= N;
if (i % 5 == 0)
{
top_stack5++;
stack5[top_stack5] = stack1[top_stack1];
top_stack1--;
while (top_stack1 >= 0)
{
tail_queue++;
tail_queue %= N;
queue[tail_queue] = stack1[top_stack1];
top_stack1--;
}
}
if (i % 60 == 0)
{
top_stack60++;
stack60[top_stack60] = stack5[top_stack5];
top_stack5--;
while (top_stack5 >= 0)
{
tail_queue++;
tail_queue %= N;
queue[tail_queue] = stack5[top_stack5];
top_stack5--;
}
}
if (i % 720 == 0)
{
j = stack60[top_stack60];
top_stack60--;
while (top_stack60 >= 0)
{
tail_queue++;
tail_queue %= N;
queue[tail_queue] = stack60[top_stack60];
top_stack60--;
}
tail_queue++;
tail_queue %= N;
queue[tail_queue] = j;
}
}
for (i = 0; i < n; i++) perm[i] = queue[(top_queue + i) % N];
ans = 1;
for (i = 0; i < n; i++)
{
j = 1;
k = i;
while (perm[k] != i)
{
k = perm[k];
j++;
}
ans = ans * j / gcd(j, ans);
}
printf("%d balls cycle after %d days.\n", n, ans);
}
return 0;
}
|
C
|
/* ************************************ */
/* */
/* vc_sort_params.c */
/* */
/* By: Charles, EmreA, Kenta */
/* */
/* ************************************ */
#include <stdio.h>
int length(char *str)
{
int counter = 0;
while (*str)
{
str++;
counter++;
}
return counter;
}
char *vc_strcpy(char *dest, const char *src)
{
int i;
i = 0;
while (src[i])
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return dest;
}
int vc_charcmp(char s1, char s2)
{
int result = 0;
if (s1 > s2)
{
result = 1;
}
else if (s1 < s2)
{
result = -1;
}
return result;
}
void vc_swapchar(char *a, char *b)
{
char temp = *a;
*a = *b;
*b = temp;
}
int main(int argc, char const *argv[])
{
int i;
int j;
int k;
int size;
int result;
char dest[100];
char *p;
int counter;
p = dest;
for (i = 1; i < argc; i++)
{
vc_strcpy(p, argv[i]);
size = length(p);
for (j = 0; j < size-1; j++)
{
for (k = j + 1; k < size; k++)
{
result = vc_charcmp(p[j], p[k]);
if (result == 1)
{
vc_swapchar(&p[j], &p[k]);
}
}
}
printf("argv[%d] = \"%s\"\n", i, p);
}
return 0;
}
|
C
|
#include <stdio.h>
/**
* binary_search - Searches for a value in an array (Binary search)
* @array: int array.
* @size: size of array.
* @value: value to search in the array.
* Return: index of occurrence or -1 if not found or array is NULL.
*/
int binary_search(int *array, size_t size, int value)
{
size_t right = size - 1, left = 0, mid, i;
if (!array || size == 0)
return (-1);
while (left <= right)
{
printf("Searching in array: ");
for (i = left; i < right + 1; i++)
{
if (i == right)
printf("%d", array[i]);
else
printf("%d, ", array[i]);
}
printf("\n");
mid = (left + right) / 2;
if (array[mid] == value)
return (mid);
else if (value < array[mid])
right = mid - 1;
else
left = mid + 1;
}
return (-1);
}
|
C
|
#pragma warning(disable : 4996)
#include <stdio.h>
struct person {
char name[20];
char phoneNum[20];
int age;
};
int main45(void)
{
struct person arr[3] = {
{"̽±"},
{"", "010-1313-0002", 22},
{"", "010-1717-0003", 19}
};
int i;
for (i = 0; i < 3; i++) {
printf("%s %s %d \n", arr[i].name, arr[i].phoneNum, arr[i].age);
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS //رհȫ
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main() {
char path[100] = "C:\\Users\\Ollydebug\\Desktop\\CodeCStudy\\07\\ļIJʾ-test";
char outputpath[100] = "F:\\list.txt";
remove(outputpath); //ÿִ Ҫɾļ
char CMD[100];
//ʽַָ鿴еtxtļ
sprintf(CMD, "dir /b %s\\*.txt > %s",path,outputpath);
system(CMD);
//ִָļУļбһļ
char show[50];
sprintf(show, "type %s", outputpath); //ʽַָʾļ
system(show); //ʾļ
FILE *pf = fopen(outputpath, "r"); //նķʽlistбļ
if (pf == NULL) {
printf("ļʧ");
return;
}
char filename[128]; //ַڱļ
while (fgets(filename, 128, pf)) { //ֻҪܶȡһֱȡȥȡʧܷ0ֹѭ
char temppath[100]; //ȡļ·
int length = strlen(filename); //ȡַij
filename[length - 1] = '\0'; //һس滻Ϊ'\0'
sprintf(temppath, "%s\\%s",path,filename); //ʽַ
printf("\n%s\n", temppath); //·
//ʵβ й
{
FILE *fp = fopen(temppath, "a+"); //дģʽ
fputs("\nй", fp); //дַβд룩
fclose(fp); //رļ
}
char cmdShow[100]; //ʾļַָ
sprintf(cmdShow, "type %s", temppath); //ַӡ
system(cmdShow);
}
fclose(pf); //رļ
system("pause");
}
|
C
|
/* David LaMartina
* [email protected]
* Utilities for Program 4
* CS344 Spr2019
*/
#ifndef UTILITIES_H
#define UTILITIES_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "boolean.h"
// Simple utilities for reducing code in Program 3 main
// Set all top-level (input buffer lines) of string array to NULL
void nullifyStringArray( char** buffer, int bufSize );
// Free all top-level (input buffer lines) of string array
void freeStringArray( char** buffer, int bufSize );
// Check whether line can be ignored (blank or comment)
enum boolean canIgnore( char** buffer );
// Re-entrant output using write() and fflush()
void printSafe( const char* message, int location );
// Replace word (required to replace $$ with shell PID)
char* replaceWord( const char*, const char*, const char* );
// Determine number of digits in integer (Required for int - string conversion)
int numDigits( int );
// Convert integer to string for $$ expansion
char* intToString( int num );
// Check whether string is empty
enum boolean isStringEmpty( char* );
// Print error message
void error( const char* );
// Get number of characters in a file
int fileNumChars( const char* fileName );
#endif
|
C
|
#include <stdio.h>
float alg_quadratico(float v[], int n) {
float max_ate_agora = 0.0;
float soma;
int i;
int u;
for (i = 1; i < n + 1; ++i) {
soma = 0.0;
for (u = i; u < n + 1; ++u) {
soma += v[u - 1];
max_ate_agora = max_ate_agora > soma ? max_ate_agora : soma;
}
}
return max_ate_agora;
}
int main() {
float v[] = {10, 5, -15, 20, 50, -1, 3, -30, 10};
printf("max = %f\n", alg_quadratico(v, 9));
return 0;
}
|
C
|
/*
-- eerom_dump.c
-- Copyright (c) 2017 Shinichiro Nagasato
--
-- This software is released under the MIT License.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
*/
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include<stdlib.h>
#include<string.h>
#include <time.h>
int main(int argc, char **argv) {
unsigned char rcv_dat[100000];
unsigned int i,c;
int f_size;
unsigned long addr=0;
FILE *fp;
fp = fopen(argv[1], "rb");
if (!fp) {
return -1;
}
f_size = fread( rcv_dat, sizeof( unsigned char ), 100000, fp );
printf("address +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F -- ASCII --\r\n");
printf("-------------------------------------------------------- ------------\r\n");
for( i=0 ; i < f_size ; i++ ){
printf( "%07lx: ",addr );
for(c=0;c<16;c++){
printf( "%02X ", rcv_dat[i+c] );
}
printf( " " );
for(c=0;c<16;c++){
if(rcv_dat[i+c] < 0x20 || rcv_dat[i+c] >= 0x70){
rcv_dat[i+c] = '.';
}
printf( "%c", rcv_dat[i+c] );
}
printf( "\n" );
addr+=16;
i+=15;
}
fclose(fp);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define BUFSIZE 512
static void bail(const char *on_what)
{
fputs(strerror(errno),stderr);
fputs(":",stderr);
fputs(on_what, stderr);
fputc('\n',stderr);
exit(1);
}
int main(int argc, char *argv[])
{
int client;
struct sockaddr_in server_addr;
int portnumber;
struct hostent *host;
int z;
char reqBuf[BUFSIZE];
char stdBuf[BUFSIZE];
fd_set orfds,rfds;
int ret, maxfd = -1;
if(argc != 3)
{
fprintf(stderr,"Usage :%s hostname portnumber.\n",argv[0]);
exit(1);
}
if((host = gethostbyname(argv[1])) == NULL)
{
fprintf(stderr,"Gethostbyname error.\n",argv[0]);
exit(1);
}
if((portnumber = atoi(argv[2])) < 0)
{
fprintf(stderr,"Usage : %s hostname portnumber.\n",argv[0]);
exit(1);
}
if((client = socket(PF_INET,SOCK_STREAM,0)) == -1)
{
fprintf(stderr,"Socket error: %s\n",strerror(errno));
exit(1);
}
memset(&server_addr, 0, sizeof server_addr);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(portnumber);
server_addr.sin_addr = *((struct in_addr*)(host->h_addr));
if((connect(client, (struct sockaddr*)(&server_addr), sizeof server_addr)) == -1)
{
fprintf(stderr,"Connect error: %s\n",strerror(errno));
exit(1);
}
FD_ZERO(&orfds);
FD_SET(STDIN_FILENO, &orfds);
maxfd = STDIN_FILENO;
FD_SET(client,&orfds);
if(client > maxfd)
maxfd = client;
printf("Connected to server...\n");
for(;;)
{
rfds = orfds;
printf("\nEntering some message to send to the server.\n");
fflush(stdout);
ret = select(maxfd + 1, &rfds, NULL, NULL, NULL);
if(ret == -1)
{
fprintf(stderr,"Select error : %s\n",strerror(errno));
break;
}
else
{
if(FD_ISSET(client,&rfds))
{
if((z = read(client, reqBuf, BUFSIZE)) <0)
{
bail("Read()");
}
printf("The message from server is :\n");
printf("%s\n",reqBuf);
if(z == 0)
{
printf("\nserver has closed the socket.\n");
printf("Press any key to exit\n");
getchar();
break;
}
}
else if(FD_ISSET(STDIN_FILENO, &rfds))
{
if(!fgets(stdBuf, BUFSIZE, stdin))
{
printf("\n");
break;
}
z = strlen(stdBuf);
if(z > 0 && stdBuf[--z] == '\n')
stdBuf[z] = 0;
if(z == 0)
continue;
z = write(client, stdBuf, strlen(stdBuf));
if(z < 0)
bail("Write()");
}
}
}
close(client);
return 0;
}
|
C
|
/* Partner 1 Name & Email: Catherine Lai [email protected]
* Lab Section: 28
* Assignment: Final Project
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "bit.h"
#include <stdio.h>
#include "timer.h"
//#include "usart.h"
enum Sound_Sensor {S_start,/* S_low,*/ S_high, S_reset, S_wait} sound_state;
unsigned short S_count = 0;
unsigned short sound = 0;
unsigned char lights = 0;
unsigned char reset = 0x00;
void ADC_init() {
ADCSRA |= (1 << ADEN) | (1 << ADSC) | (1 << ADATE);
}
void Sound_Tick(){
reset = ~PINA & 0x02;
switch(sound_state){ // transitions
case S_start:
sound_state = S_wait;
/*
while(!USART_IsSendReady(0));
USART_Send(0, 0);
while(!USART_HasTransmitted(0));
*/
break;
case S_wait:
if ( ((PINA&0x01) == 1) && (S_count >= 500) && !reset ){
sound_state = S_high;
}
else if ( reset && S_count >= 500 ){
sound_state = S_reset;
}
/*
else if (((PINA&0x01) == 0) && (S_count >= 500)){ // go to S_low
sound_state = S_low;
}
*/
else {
S_count++;
sound_state = S_wait;
}
break;
case S_high:
S_count = 0;
sound_state = S_wait;
break;
/*
case S_low: // might not need this state bc once warning is sent, won't return to low until reset
S_count = 0;
//
if (S_count < 500){
S_count++;
}
else if (S_count >= 500){
sound_state = S_wait;
}
//
sound_state = S_wait;
break;
*/
case S_reset:
S_count = 0;
sound_state = S_wait;
break;
default:
break;
}
switch(sound_state){ // actions
case S_start:
break;
case S_wait:
sound = ADC;
break;
case S_high:
sound = 0;
lights = lights | 0x04;
PORTB = lights;
break;
/*
case S_low:
sound = 0;
lights = 0;//lights & 0x03;
PORTB = lights;
break;
*/
case S_reset:
sound = 0;
lights = 0;
PORTB = lights;
break;
default:
break;
}
}
int main(void)
{
DDRA = 0x00; PORTA = 0xFF; // taking input
DDRB = 0xFF; PORTB = 0x00; // output
sound_state = S_start;
ADC_init();
TimerSet(1);
TimerOn();
//initUSART(0);
//USART_Flush(0);
while(1)
{
Sound_Tick();
/*
while(!USART_IsSendReady(0));
USART_Send((sound & 0x00FF, 0);
while(!USART_HasTransmitted(0));
*/
while(!TimerFlag){}
TimerFlag = 0;
}
}
|
C
|
#if DEBUG > 0
#include <stdio.h>
#endif
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "smedl_types.h"
#include "monitor_map.h"
#include "Collect_global_wrapper.h"
#include "Collect_local_wrapper.h"
#include "Collect_mon.h"
/* Singleton monitor */
static CollectMonitor *monitor;
/* Register the global wrapper's export callbacks with the monitor */
static void setup_Collect_callbacks(CollectMonitor *mon) {
register_Collect_result(mon, raise_Collect_result);
}
/* Initialization interface - Initialize the local wrapper. Must be called once
* before creating any monitors or importing any events.
* Return nonzero on success, zero on failure. */
int init_Collect_local_wrapper() {
/* Initialize the singleton */
monitor = init_Collect_monitor(NULL);
if (monitor == NULL) {
return 0;
}
setup_Collect_callbacks(monitor);
return 1;
}
/* Cleanup interface - Tear down and free the resources used by this local
* wrapper and all the monitors it manages */
void free_Collect_local_wrapper() {
free_Collect_monitor(monitor);
}
/* Creation interface - Instantiate a new Collect monitor.
* Return nonzero on success or if monitor already exists, zero on failure.
*
* Parameters:
* identites - An array of SMEDLValue of the proper length for this monitor.
* Must be fully specified; no wildcards.
* init_state - A pointer to a CollectState containing
* the initial state variable values for this monitor. A default initial
* state can be retrieved with default_Collect_state()
* and then just the desired variables can be updated. */
int create_Collect_monitor(SMEDLValue *identities, CollectState *init_state) {
/* Singleton monitor - This is a no-op */
return 1;
}
/* Event import interfaces - Send the respective event to the monitor(s) and
* potentially perform dynamic instantiation.
* Return nonzero on success, zero on failure.
*
* Parameters:
* identites - An array of SMEDLValue of the proper length for this monitor.
* Wildcards can be represented with a SMEDLValue of type SMEDL_NULL.
* params - An array of SMEDLValue, one for each parameter of the event.
* aux - Extra data that is passed through to exported events unchanged. */
int process_Collect_addV(SMEDLValue *identities, SMEDLValue *params, void *aux) {
#if DEBUG >= 4
fprintf(stderr, "Local wrapper 'Collect' processing event 'addV'\n");
#endif
/* Send event to the singleton monitor */
return execute_Collect_addV(monitor, params, aux);
}
int process_Collect_inRes(SMEDLValue *identities, SMEDLValue *params, void *aux) {
#if DEBUG >= 4
fprintf(stderr, "Local wrapper 'Collect' processing event 'inRes'\n");
#endif
/* Send event to the singleton monitor */
return execute_Collect_inRes(monitor, params, aux);
}
|
C
|
//accept string from return count of string do not consider repeated character
//input: abcabccbba
//output:2 bcs =abc this 3 character in our string comes repeatedly
#include<stdio.h>
int lengthOfLongestSubstring(char arr[])
{
char brr[26];
int i=0,icnt=0;
char temp='\0';
printf("Non-Repeated Characters\n");
while(arr[i]!='\0')
{
temp=arr[i];
if(temp != ' ')
{
printf("%c ",arr[i]);
int j=i;
icnt++;
while(arr[j]!='\0')
{
if(arr[j]==temp)
{
arr[j]=' ';
}
j++;
}
}
i++;
}
return icnt;
}
int main()
{
int size=50;
printf("Enter string:\n");
char arr[size];
scanf("%[^'\n']s",arr);
int iret=lengthOfLongestSubstring(arr);
printf("\n%d \n",iret);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
typedef struct {
float x;
float y;
} point;
int main(int argc, int *argv) {
point p;
p.x = 0.1;
p.y = 10.0;
printf("%f is the sqrt!\n", sqrt(p.x * p.x + p.y + p.y));
};
|
C
|
#include "fila.h"
//=============================================================================
int main() {
Fila f;
int i, x1, x2, x3;
printf("==== FILA FLEXIVEL ====\n");
f = new_fila();
for(i=0; i < 10; i++)
enqueue_fila(&f, i);
printf("Apos inserrir os dados: \n");
print_fila(&f);
x1 = dequeue_fila(&f);
x2 = dequeue_fila(&f);
x3 = dequeue_fila(&f);
printf("Apos as remocoes (%d, %d, %d) \n", x1, x2, x3);
print_fila(&f);
delete_fila(&f);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>/* memset */
#define MAX_SYMBOLS 256
#define MAX_LEN 256
struct tnode
{
struct tnode* left; /*used when in tree*/
struct tnode*right; /*used when in tree*/
struct tnode*parent;/*used when in tree*/
struct tnode* next; /*used when in list*/
int appear;
int isleaf;
unsigned char symbol;
};
/*global variables*/
char code[MAX_SYMBOLS][MAX_LEN];
struct tnode* root = NULL; /*tree of symbols*/
struct tnode* qhead = NULL; /*list of current symbols*/
unsigned long int streamLength;
unsigned char bufferBS;
unsigned int fillCountBS;
/*
@function talloc
@desc allocates new node
*/
struct tnode* talloc(int symbol, int appear)
{
struct tnode* p = (struct tnode*)malloc(sizeof(struct tnode));
if (p != NULL)
{
p->left = p->right = p->parent = p->next = NULL;
p->symbol = symbol;
p->appear = appear;
p->isleaf = 1;
}
return p;
}
void print_bit(char c) {
int m, i;
//putc('b', stdout);
for (i = 7; i >= 0; i--) {
m = 1 << i;
if ((c & m) == 0) {
putc('0', stdout);
}
else {
putc('1', stdout);
}
}
}
/*
@function display_tnode_list
@desc displays the list of tnodes during code construction
*/
void pq_display(struct tnode* head)
{
struct tnode* p = NULL;
printf("list:");
for (p = head; p != NULL; p = p->next)
{
printf("(%c,%d) ", p->symbol, p->appear);
}
printf("\n");
}
/*
@function pq_insert
@desc inserts an element into the priority queue
NOTE: makes use of global variable qhead
*/
void pq_insert(struct tnode* p)
{
struct tnode* curr = NULL;
struct tnode* prev = NULL;
if (qhead == NULL){
//ϴ ̴
qhead = p;
}
else {
// ڸ ãư ڴ
//ϴ qhead ƾ Ѵ
curr = qhead;
while (1) {
//ڸ ã Ϲ
if (p->appear <= curr->appear) {
// Ŀ ũ
// ̰
//⼭
//ϴ Ŀ parent prev Ѵ
prev = curr->parent;
if (prev == NULL) {
// prev NULL ̸ տ ־ ϰ ..
//root üؾ
//qhead p ϰ
qhead = p;
//p θ NULL ְ
p->parent = NULL;
//p Ŀ ְ
p->next = curr;
//Ŀ θ p
curr->parent = p;
//װɷ
break;
}
else {
// NULL ƴϸ ִ°Ŵ prev curr ̿ ֱ
//prev->next p
prev->next = p;
//curr->parent p
curr->parent = p;
//p->next curr
p->next = curr;
//p->parent prev
p->parent = prev;
//̾
break;
}
}
else if (p->appear > curr->appear) {
// Ŀ ۴
// ڷ Ѵ
if (curr->next == NULL) {
// curr->next NULL ̶ ڸ ű
//ٲٰ
//curr->next p δ
curr->next = p;
//p θ Ŀ ִ´
p->parent = curr;
//p NULL ִ´
p->next = NULL;
//װɷ (Ƹ)
break;
}
else {
//NULL ƴ϶ ٰ ϰ ̷
curr = curr->next;
continue;
}
}
else {
}
}
}
}
/*
@function pq_pop
@desc removes the first element
NOTE: makes use of global variable qhead
*/
struct tnode* pq_pop()
{
struct tnode* p = NULL;
/*TODO: write code to remove front of the queue*/
// ť տ ִ p Űܳ´
p = qhead;
// ť տ ִ next ť (qhead) ִ´
qhead = qhead->next;
if (qhead == NULL) {
// ť տ ִ θ NULL Ѵ
return p;
}
else {
// ť տ ִ θ NULL Ѵ
qhead->parent = NULL;
return p;
}
}
/*
@function generate_code
@desc generates the string codes given the tree
NOTE: makes use of the global variable root
*/
void generate_code(struct tnode* root, int depth)
{
int symbol;
int len; /*length of code*/
int i = 0;
struct tnode * curr;
if (root->isleaf)
{
symbol = root->symbol;
len = depth;
/*start backwards*/
code[symbol][len] = 0;
/*
TODO: follow parent pointer to the top
to generate the code string
*/
curr = root;
while (!(curr->parent == NULL)) {
//Ʈ (θ NULL ̸ Ʈ)
if (curr->parent->left == curr) {
// Ŀ θ ڽİ ϴ : '0'
code[symbol][--len] = '0';
}
else if (curr->parent->right == curr) {
// Ŀ θ ڽİ ϴ : '1'
code[symbol][--len] = '1';
}
else {
//̰ ߲ٴ
}
curr = curr->parent;
}
}
else
{
generate_code(root->left, depth + 1);
generate_code(root->right, depth + 1);
}
}
/*
@func dump_code
@desc output code file
*/
void dump_code(FILE* fp)
{
int i = 0;
for (i = 0; i<MAX_SYMBOLS; i++)
{
if (code[i][0]) /*non empty*/
fprintf_s(fp, "%d %s\n", i, code[i]);
}
}
void dump_code_bin(FILE* fp)
{
unsigned int i = 0;
unsigned int shift_count = 0;
unsigned char c = 0;
unsigned short entry_count = 0;
unsigned char bitstream_token = 0;
unsigned char bitstream_length = 0;
unsigned char bitstream_length_byte = 0;
for (c = 0; c < MAX_SYMBOLS; c++) {
if (code[c][0])
entry_count++;
if (c == 255)
break;
}
fwrite(&entry_count, sizeof(unsigned short), 1, fp);
for (c = 0; c < MAX_SYMBOLS; c++) {
if (code[c][0]) {
fwrite(&c, sizeof(unsigned char), 1, fp);
bitstream_length = strlen(code[c]);
bitstream_length_byte = bitstream_length / 8;
if (bitstream_length % 8)
bitstream_length_byte++;
fwrite(&bitstream_length, sizeof(unsigned char), 1, fp);
fwrite(&bitstream_length_byte, sizeof(unsigned char), 1, fp);
//debug
printf("%d ", c);
//debug
for (i = 0; i < bitstream_length; i++) {
if (code[c][i] == '1')
bitstream_token |= 1;
if (shift_count == 7) {
fwrite(&bitstream_token, sizeof(unsigned char), 1, fp);
//debug
print_bit(bitstream_token);
putc(' ', stdout);
//debug
bitstream_token = 0;
shift_count = 0;
}
else {
bitstream_token <<= 1;
shift_count++;
}
}
if (shift_count) {
bitstream_token <<= (7 - shift_count);
fwrite(&bitstream_token, sizeof(unsigned char), 1, fp);
//debug
print_bit(bitstream_token);
putc(' ', stdout);
//debug
bitstream_token = 0;
shift_count = 0;
}
}
//debug
if (code[c][0]) {
putc('\n', stdout);
//printf("%d %s\n", c, code[c]);
printf("%d", c);
for (i = 0; i < strlen(code[c]); i++) {
if (!(i % 8))
putc(' ', stdout);
putc(code[c][i], stdout);
}
putc('\n', stdout);
}
//debug
if (c == 255)
break;
}
}
void beginBS(FILE* fout) {
fwrite(&streamLength, sizeof(unsigned long int), 1, fout);
fillCountBS = 0;
}
void appendBS(FILE* fout, unsigned char c) {
bufferBS <<= 1;
if (c == '1')
bufferBS |= 1;
fillCountBS++;
if (fillCountBS == 8) {
fwrite(&bufferBS, sizeof(unsigned char), 1, fout);
bufferBS = 0;
fillCountBS = 0;
}
}
void endBS(FILE* fout) {
while (fillCountBS < 8) {
bufferBS <<= 1;
fillCountBS++;
}
fwrite(&bufferBS, sizeof(unsigned char), 1, fout);
}
/*
@func encode
@desc outputs compressed stream
*/
void encode(FILE* fin, FILE* fout)
{
int c;
while ((c = getc(fin)) != EOF) {
fprintf_s(fout, "%s", code[c]);
}
}
void encodeBin(FILE* fin, FILE* fout)
{
unsigned char c;
int i;
int codeLength;
beginBS(fout);
while (1) {
if (feof(fin))
break;
fread_s(&c, sizeof(unsigned char), sizeof(unsigned char), 1, fin);
codeLength = strlen(code[c]);
for (i = 0; i < codeLength; i++)
appendBS(fout, code[c][i]);
}
endBS(fout);
}
void freetree(struct tnode* root)
{
if (root == NULL)
return;
freetree(root->right);
freetree(root->left);
free(root);
}
void freequeue(struct tnode* root)
{
if (root == NULL)
return;
freequeue(root->next);
free(root);
}
/*
@function main
*/
int main(int argc, char** argv)
{
/*test pq*/
struct tnode* p = NULL;
struct tnode* lc, *rc;
int NCHAR = 256; /*number of characters*/
int i = 0;
unsigned char c = 0;
int usedAsciiKind = 0;
float totalCount = 0.f;
int count[256] = { 0 };
float freq[256] = { 0.f };
char INPUT_FILE[256];
char CODE_FILE[256];
char OUTPUT_FILE[256];
FILE* fin = NULL;
FILE* fout = NULL;
FILE* fcode = NULL;
/*zero out code*/
memset(code, 0, sizeof(code));
if (argc == 1) {
printf("USAGE : %s file_to_compress", argv[0]);
return 0;
}
else {
strcpy_s(INPUT_FILE, _countof(INPUT_FILE), argv[1]);
strcpy_s(OUTPUT_FILE, _countof(OUTPUT_FILE), argv[1]);
strcat_s(OUTPUT_FILE, _countof(OUTPUT_FILE), ".huff");
strcpy_s(CODE_FILE, _countof(CODE_FILE), argv[1]);
strcat_s(CODE_FILE, _countof(CODE_FILE), ".code");
}
fopen_s(&fin, INPUT_FILE, "rb");
fseek(fin, 0, SEEK_END);
streamLength = ftell(fin);
rewind(fin);
//ϴ 踦 ϹǷ ó о ƽŰ ij͵
//streamLength = 0;
while (1) {
if (feof(fin))
break;
fread_s(&c, sizeof(unsigned char), sizeof(unsigned char), 1, fin);
totalCount += 1.;
count[c]++;
//streamLength++;
}
fclose(fin);
qhead = NULL;
/*initialize with freq*/
for (i = 0; i<NCHAR; i++)
{
if (count[i] > 0) {
pq_insert(talloc(i, count[i]));
usedAsciiKind++;
}
}
/*build tree*/
for (i = 0; i < (usedAsciiKind - 1); i++)
{
lc = pq_pop();
rc = pq_pop();
/*create parent*/
p = talloc(0, lc->appear + rc->appear);
/*set parent link*/
lc->parent = rc->parent = p;
/*set child link*/
p->right = rc; p->left = lc;
/*make it non-leaf*/
p->isleaf = 0;
/*add the new node to the queue*/
pq_insert(p);
}
/*get root*/
root = pq_pop();
/*build code*/
generate_code(root, 0);
/*output code*/
fopen_s(&fout, CODE_FILE, "wb");
//dump_code(fout);
dump_code_bin(fout);
fclose(fout);
/*encode a sample string*/
fopen_s(&fin, INPUT_FILE, "rb");
fopen_s(&fout, OUTPUT_FILE, "wb");
encodeBin(fin, fout);
fclose(fin);
fclose(fout);
/*TODO: clear resources*/
freetree(root);
freequeue(qhead);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
void 1mymenu();
void 2gamemenu();
void 3registe(char * name,char *passwd);
void 4mygets(char * str,int size);
void 5login(char *name,char *passwd);
void 6attack(int * user,int *com,int flag);
void 7judge(int * arr);
int main()
{
srand((unsigned)time(NULL));
menu()
return 0;
}
void 7judge(int * arr)
{
int i=0;
int sum =0;
for(i =0 ;i<15;i++)
{
if(arr[i]==1)
sum++;
}
printf("牺牲了:%d个士兵\n",sum);
}
void 6attack(int * user,int *com)
{
int i=0;
if(flag==0)//用户打电脑
{
for(i=0;i<3;i++)
{
int index=rand()%15;
com[index]=1;
}
}else{//电脑打用户
for(i<0;i<3;i++)
{
int index=rand()%15;
void menu()
{
printf("1-->进攻\n"
"2-->撤退\n"
"请输入你的选择:");
char ch='\';
scanf("%c",&ch);
switch(ch)
{
case '1':
//注册功能
break;
case '2':
//
}
}
|
C
|
#ifndef _IPCPROTOCOL_H
#define _IPCPROTOCOL_H
#define MAX_INFOS 50 //Max number of infos that can be displayed at one time.
#define MAX_INFO_LENGTH 1024 //Max size of the text for each info.
#define INFO_SCREEN_PADDING 10 //The padding between info text and the screen border.
#define INFO_CONSECUTIVE_PADDING -2 //The padding between consecutive infos.
#include <windows.h>
//-----------------------------------------------------
enum InfoState
{
info_Invalid = 0,
info_New,
info_Displaying,
info_Fading
};
//The position at which the info will be placed. If it is specified
//as absolute, then the nX and nY parameters are used to position the
//info. If any of the auto ones are used, then text will be automatically
//place based on other infos that are currently there.
enum InfoPosition
{
pos_Absolute = 0,
pos_AutoTopLeft,
pos_AutoTopRight,
pos_AutoTopCenter,
pos_AutoBottomLeft,
pos_AutoBottomRight,
pos_AutoBottomCenter,
pos_AutoCenterCenter
};
//The options for each info.
typedef struct {
InfoPosition position;
RECT rect;
DWORD dwColor;
int nAlpha;
DWORD dwOutlineColor;
int nOutlineAlpha;
DWORD dwHoldTime; //How long to stay on screen (in miliseconds)
int nFadeRate; //The rate at which text will fade
} AIOVERLAY_InfoOptions, *LPAIOVERLAY_InfoOptions;
//-Not to be used by the user.-
typedef struct {
DWORD dwStartTime;
} AIOVERLAY_Calculations, *LPAIOVERLAY_Calculations;
//The info.
typedef struct {
InfoState nState;
AIOVERLAY_InfoOptions options;
AIOVERLAY_Calculations calculations;
char szData[MAX_INFO_LENGTH];
} AIOVERLAY_Info, *LPAIOVERLAY_Info;
typedef struct {
AIOVERLAY_Info infos[MAX_INFOS];
} IpcStruct, *LPIpcStruct;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
void InitIpcStruct (LPIpcStruct pStruct);
void ResetInfo (LPAIOVERLAY_Info pInfo);
#endif
|
C
|
/**
@file board.h
@author Aurora Tiffany-Davis (attiffan)
Function prototypes and macro definitions to support a generalized game of connect four.
*/
#include <stdbool.h>
// This trick will let us define the length of a winning
// run when we compile the program, if we want to.
#ifndef RUNLEN
/** Number of markers in a row required for a win. */
#define RUNLEN 4
#endif
// An offset, which when added to RUNLEN, gives the maximum board size
#define MAX_BOARD_SIZE_OFFSET 16
// Game status ints
#define STATUS_WINNER 1
#define STATUS_STALEMATE 2
#define STATUS_OTHER 0
// Streak of symbols status ints
#define STREAK_NOT_FOUND 0
#define STREAK_VERTICAL 1
#define STREAK_HORIZONTAL 2
#define STREAK_DIAGONAL_LEFT 3
#define STREAK_DIAGONAL_RIGHT 4
// Divisors for modulos, to shut Jenkins up about magic numbers :)
#define HELPER_DIGIT_DIVISOR 10
#define RANDOM_COLUMN_DIVISOR 3
/** Ask for the size of the board, measured in rows and columns.
Store this information using the provided pointers.
The board size will be determined by this initial user input.
@param rows Pointer to desired number of rows
@param cols Pointer to desired number of columns
*/
void getBoardSize( int * rows, int * cols );
/** Print the given board (of the given rows/cols size) to standard output.
Example of a 6x7 board with three moves already made:
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |X| | | |
| |O| |X| | | |
+-+-+-+-+-+-+-+
1 2 3 4 5 6 7
@param rows Number of rows to print
@param cols Number of columns to print
@param board Pointer to array of characters to print on board
*/
void printBoard( int rows, int cols, char board[ rows ][ cols ] );
/** Set the board to its initial state, filled with spaces.
@param row Number of rows on the board
@param cols Number of columns on the board
@param board Pointer to board array
*/
void clearBoard( int rows, int cols, char board[ rows ][ cols ] );
/** Repeatedly prompt the user for their next move until they provide a legal move.
Then make that move by putting their player symbol in the board array.
@param player 'X' or 'O'
@param rows Number of rows on the board
@param cols Number of columns on the board
@param board Pointer to the board array
*/
void makeMove( char player, int rows, int cols, char board[ rows ][ cols ] );
/** Make a move on behalf of 'O'
First, try to win.
Then, try to keep 'X' from winning.
Finally, just pick a spot and go.
@param rows Number of rows on the board
@param cols Number of columns on the board
@param board Pointer to the board array
*/
void makeComputerMove( int rows, int cols, char board[ rows ][ cols ] );
/** Determine if the given spot on the board is available.
Is it on the board?
Empty?
Supported by a "checker" beneath it?
@param rows Number of rows on the board
@param cols Number of columns on the board
@param board Pointer to the board array
@param spotRow Position of row caller is interested in
@param spotCol Position of column caller is interested in
@return True if spot is available, False otherwise
*/
bool isSpotAvailable( int rows, int cols, char board[ rows ][ cols ],
int spotRow, int spotCol );
/** Check to see if the game is over.
Look for vertical, horizontal, and diagonal (two ways) wins.
Only look in spots where there is enough room on the board to possibly have a win.
Stop if/when a win is found.
@param rows Number of rows on the board
@param cols Number of columns on the board
@param board Pointer to the board array
@return Number indicating game status (won, stalemate, other)
*/
int gameStatus( int rows, int cols, char board[ rows ][ cols ] );
/** Try to find a "streak" of the given player symbol.
Start at the given board location.
Try vertically (up), horizontally (right),
diagonal-left (up), and diagonal-right (up).
@param rows Number of rows the board has.
@param cols Number of columns the board has.
@param board The game board.
@param startRow Row start position to look for a streak.
@param startCol Column start position to look for a streak.
@param playerSymbol The symbol to look for a "streak" of.
@param streakLen The length of streak to look for (# of board locations).
@return status Determination about streak (none, or what type).
*/
int findStreak( int rows, int cols, char board[ rows ][ cols ],
int startRow, int startCol, char playerSymbol, int streakLen );
/** Return true if there's a "streak" of the given player symbol.
Start at the given board location.
The dRow and dCol parameters indicate what direction to look,
with dRow giving change-in-row for each step and dCol giving the change-in-column.
For example, if dRow and dCol are both 1 would look diagonally.
@param rows Number of rows the board has.
@param cols Number of columns the board has.
@param board The game board.
@param startRow Row start position to look for a streak.
@param startCol Column start position to look for a streak.
@param dRow Direction to move vertically looking for a streak.
@param dCol Direction to move horizontally looking for a streak.
@param playerSymbol The symbol to look for a "streak" of.
@param streakLen The length of streak to look for (# of board locations).
@return true if there's a streak in the given board location.
*/
bool isStreak( int rows, int cols, char board[ rows ][ cols ],
int startRow, int startCol, int dRow, int dCol,
char playerSymbol, int streakLen );
|
C
|
#ifndef TRANSITION_H
#define TRANSITION_H
#include "State.h"
typedef struct Trans Transition;
typedef struct List ListTransition;
struct Trans
{
State* from;
State* to;
char* label;
bool lower;
ListTransition* list; /* for listing all transitions in the FA */
ListTransition* postList;
};
struct List
{
struct List* next; /* for listing all transitions in the FA */
Transition* transition;
};
Transition* CreateTransition(State* from, State* to,char* label,bool lower);
/* insert */
void AddNextTransition(Transition* T, Transition* next);
void AddPostTransition(Transition* T, Transition* post);
/* ************************* */
/* affichage */
void PrintTransition(Transition* T);
void PrintNextTransition(Transition* T);
void PrintPostTransition(Transition* T);
void PrintListTransition(ListTransition* list);
/* ************************* */
/* verification */
bool isSelfLoop(Transition* t);
/* ************************* */
/* Manipulation */
ListState* getPostListState(Transition* T);
/* ******************** */
void DeleteTranistion(Transition* T);
ListTransition* CreateListTransition(Transition* T);
void AddToListTransition(ListTransition* list, Transition* t);
ListTransition* DeleteFromListTransition(ListTransition* list, Transition* t);
Transition* GetTheFirstTransition(ListTransition* list);
int IsTheSameTransition(Transition* t1 , Transition* t2);
int ExistTransition(ListTransition* list, Transition* t);
#endif
|
C
|
/*
** EPITECH PROJECT, 2019
** my_revstr.c
** File description:
** No file there just an epitech header example
*/
#include <stdio.h>
char *my_revstr(char *str)
{
int i;
int len;
char swap;
int j = 0;
i = 0;
len = my_strlen(str) - 1;
while (i < (my_strlen(str) / 2)) {
swap = str[i];
str[i] = str[len];
str[len] = swap;
i++;
len--;
}
my_putstr(str);
return (str);
}
|
C
|
#include "Funct.h"
#include <math.h>
double siny(double x, int i)//
{
double y;
y = (pow(-1, i) * (pow(x, 2 * i + 1) / factorial(2 * i + 1)));
return y;
}
double cosy(double x, int i)//
{
double y;
y = (pow(-1, i) * (pow(x, 2 * i) / factorial(2 * i)));
return y;
}
double expy(double x, int i)// exp
{
double y;
y = (pow(x, i) / factorial(i));
return y;
}
double sinhy(double x, int i)// .
{
double y;
y = (pow(x, 2 * i + 1) / factorial(2 * i + 1));
return y;
}
double factorial(int n)// ,
{
if (n == 0 || n == 1) return 1;
return (n * factorial(n - 1));
}
void funct(int m, int n, double t, int k, double x,double kx, double (*fun)(double, int))// x, ,
{//m-,n-- ,t- ,k- t,x-
double* ch;// 2,
ch = (double*)malloc(n * sizeof(double));
double y = 0, yx = 0;//y- ,yx- ()
int i, j = 0;//,j- 1
for (i = 0; i < n; i++)
{
yx = fun(x, i);
if (m == 2)
{
y = y + yx;
ch[i] = y;
}
if (m == 1)
{
if (fabs(yx) < t)
break;
else
{
y = y + yx;
j++;
}
}
}
if (m == 2)
mode2(ch, kx, n);
if (m == 1)
mode1(kx, y, j, n, k);
if (m==2)
free(ch);
}
|
C
|
/**
* Implements a dictionary's functionality.
*/
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include "dictionary.h"
/**
* Declare the structure used in each element of the trie_node's array
*
* The two structs are circular dependant so they both need to be declared in the header file or we just can declare the trie_node struct up here
* They are only declared and not defined since they'll both be called using pointers
* more about this in this link : https://stackoverflow.com/questions/2732978/c-how-to-declare-a-struct-in-a-header-file
*/
struct trie_node;
typedef struct element
{
bool x; // Word marker
struct trie_node *_ptr; // Pointer to another Trie node
} element;
/**
* Declare the Trie data structure
*/
typedef struct trie_node{
struct element *arr[27];
}trie_node;
/**
* Declare a global trie_node pointer to point at the root node of the trie and an int counter to count the words in the dic
*/
trie_node *root; int counter;
/** Recursivly unload the trie
*/
bool rec_unload(trie_node *ptr)
{
// Iterate through all the elements of a specific node's array
for(int i = 0 ; i < 27 ; i++)
{
// Recurse all the way until we find a node having all its array pointers pointing to null
if(ptr->arr[i]->_ptr!=NULL) rec_unload(ptr->arr[i]->_ptr);
// Free the elements of this array
free(ptr->arr[i]);
}
// Free the pointer to this array
free(ptr);
return true;
}
/**
* Initialize all the values in the array of the given trie_node to NULL
*/
void init(trie_node *ptr)
{
for(int i=0 ; i < 27 ; i++)
{
// Alocate the space needed for element in the trie_node
ptr->arr[i] = malloc(sizeof(element));
// Set all the pointers to other nodes to null
ptr->arr[i]->_ptr=NULL;
// Set all the word markers to 0
ptr->arr[i]->x = 0;
}
}
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char *word)
{
trie_node *ptr = root;
// The apostrophe is indicated at index 26, so we will replace it in temp by a '}' which the character that follows 'z' ie. '}'-'a' = 26.
char temp[50];
strcpy(temp,word);
for(int i = 0 , size = strlen(word) ; i <size ; i++)
{
//replace the apotrophe with a '{'.
if(temp[i]==39) temp[i]='{';
if(ptr->arr[ tolower(temp[i])-'a']->_ptr == NULL && ptr->arr[ tolower(temp[i])-'a']->x==0) return false;
if(i==size-1 && ptr->arr[ tolower(temp[i])-'a']->x==0) return false;
ptr = ptr->arr[ tolower(temp[i])-'a']->_ptr;
if(ptr == NULL && i != size-1) return false;
}
return true;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char *dictionary)
{
FILE *open_dir = fopen(dictionary , "r");
if(open_dir == NULL) return false;
root = malloc(sizeof(trie_node));
init (root);
char word[50];
while( fscanf(open_dir , "%s" , word)!=EOF )
{
counter++;
trie_node *ptr = root;
for(int i = 0 , size = strlen(word) ; i < size ; i++)
{
// All apostrophes will be stored in the dictionary as '{'.
if(word[i]==39) word[i]='{';
// If this is the first word to be encountered that starts with a specific letter
if( ptr->arr[ word[i]-'a']->_ptr == NULL && i!= size-1)
{
ptr->arr[ word[i]-'a']->_ptr = malloc (sizeof(trie_node));
ptr = ptr->arr[ word[i]-'a']->_ptr;
init (ptr);
}
// If this is the last letter
else if (i == size-1)
ptr->arr[ word[i]-'a']->x=1;
// Else if this letter appeared before
else
ptr = ptr->arr[ word[i]-'a']->_ptr;
}
}
fclose (open_dir);
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
return counter;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
return rec_unload(root);
}
|
C
|
/* A formatted file master.txt contains the employee code, name and basic pay of employees of an
organization. Write a program to calculate the D.A(dearness allowance),
H.R.A (House rent allowance) and gross income of each employee and store employee code, name,
basic pay, D.A, H.R.A and gross income to the file emp.txt, where D.A is the 32% of basic pay,
H.R.A is 15% of basic pay and gross pay is the sum of basic pay, D.A and H.R.A. */
#include <stdio.h>
int main() {
//variable of type file for input and output files
FILE* fin, * fout;
//open input file in read mode
fin = fopen("master.txt", "r");
//open output file in write mode
fout = fopen("emp.txt", "w");
char code[20], name[20];
float da, hra, gross, basic;
while (!feof(fin)) {
//read a line from input file
fscanf(fin, "%s%s%f", code, name, &basic);
fprintf(fout, "Code Name Basic DA HRA Gross\n");
da = basic * 0.32; //calculate DA
hra = basic * 0.15; //calculate HRA
gross = basic + da + hra; //calculate gross pay
//write output record into file
fprintf(fout, "%-6s %-6s %-6.2f %-6.2f %-6.2f %-6.2f\n", code, name, basic, da, hra, gross);
}
fclose(fin); //close input file
fclose(fout); //close output file
//print a message at the end
printf("The entire processing has been completed. Thankyou\n\n");
return 0;
}
|
C
|
//
// Created by rqsir on 3/24/19.
//
#include "CLinkListInsert.h"
Status CLinkListInsert(CLinkList *L,int position,ElemType e){
CLinkList walker = *L;
int length = CLinkList_getLength(*L);
int absPos = 0;
// calculate the absolute position of the inserted element
if(position > 0){
absPos = position % length;
if(absPos == 0){
absPos = length;
}
}else if(position < 0){
position = -position;
absPos = length - position % length + 1;
if(position % length == 0){
absPos = 1;
}
} else{
absPos = length;
}
/* if(position < 1 || position > length){
printf("\nthe position is illegal!!");
}*/
for(int i=1; i<absPos;i++){
walker = walker->next;
}
CLinkList newNode = (CLinkList)malloc(sizeof(Node));
newNode->data = e;
newNode->next = walker->next;
walker->next = newNode;
if(position == 0){
*L = newNode;
}
return OK;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int firstNumber, secondNumber, result;
char operation;
do
{
system("cls");
scanf("%d", &firstNumber);
result = firstNumber;
do
{
scanf(" %c", &operation);
switch (operation)
{
case '+':
scanf("%d", &secondNumber);
result += secondNumber;
break;
case '-':
scanf("%d", &secondNumber);
result -= secondNumber;
break;
case '*':
scanf("%d", &secondNumber);
result *= secondNumber;
break;
case '/':
scanf("%d", &secondNumber);
result /= secondNumber;
break;
case '=':
for (int i = 1; i <= 2000; ++i)
{
printf("%d\r", result);
}
break;
}
} while (operation != '=' && operation != 'c' && operation != 'e');
} while (operation == 'c' || operation == '=');
return 0;
}
|
C
|
#include "files_operations.h"
/*
* Escribir un programa ANSI C que procese el archivo "b.bin" sobre sí mismo. El
* mismo posee enteros de 16 bits sin signo con valores entre 0 y 255. El
* proceso consiste en reemplazar cada entero por sus correspondientes símbolos
* hexadecimales (2 caracteres ASCII). Ej: 00000000 00001010, se reemplazará por
* "0A".
*/
void replazar0A() {
FILE *fp = fopen("files/test.bin", "r+");
if (fp != NULL) {
fseek(fp, 0L, SEEK_END);
int fileSize = ftell(fp);
rewind(fp);
char *reemplazo = malloc(2 * fileSize * sizeof (unsigned char));
unsigned char c = '\0';
char aux = '\0';
int counter = 0;
while (counter < 2 * fileSize) {
c = fgetc(fp);
aux = (c & 240) >> 4; // 240 == 0b11110000
if (aux <= 9) {
aux += 48;
} else {
aux += 55;
}
strcpy(reemplazo, &aux);
++reemplazo;
++counter;
aux = c & 15; // 15 == 0b00001111
if (aux <= 9) {
aux += 48;
} else {
aux += 55;
}
strcpy(reemplazo, &aux);
++reemplazo;
++counter;
}
rewind(fp);
reemplazo -= counter;
printf("%s", reemplazo);
fprintf(fp, "%s", reemplazo);
fclose(fp);
free(reemplazo);
}
}
/*
* Escribir un programa ISO C que procese el archivo "nros1byte.dat" sobre si
* mismo, eliminando los bytes multiplos de 6.
*/
void remove6Mult() {
FILE *fpRead = fopen("files/nros1byte.dat", "r");
FILE *fpWrite = fopen("files/nros1byte.dat", "r+");
char c;
int counter = 0;
if (fpRead != NULL && fpWrite != NULL) {
while ((c = fgetc(fpRead)) != EOF) {
if ((c % 6) == 0) {
++counter;
} else {
fputc(c, fpWrite);
}
}
ftruncate(fileno(fpWrite), ftell(fpWrite));
fclose(fpWrite);
fclose(fpRead);
}
}
/*
* Escribir un programa ISO C que procese el archivo "valuesword.dat" sobre sí
* mismo, eliminando los words (2 bytes) múltplos de 16.
*/
void removeMult16() {
FILE *fpIn = fopen("files/valuesword.dat", "r");
FILE *fpOut = fopen("files/valuesword.dat", "r+");
char word[3] = {0}; // cantidad de bytes que quiero leer + caracter nulo
int number;
if (fpIn != NULL) {
while (!feof(fpIn)) {
// cantidad de bytes que quiero leer + caracter nulo
if (fgets(word, 3, fpIn) != NULL) {
number = word[1] | word[0] << 8;
puts(word);
printf("%d\n", number);
if ((number % 16) != 0) {
fputs(word, fpOut);
}
}
}
ftruncate(fileno(fpOut), ftell(fpOut));
fclose(fpOut);
fclose(fpIn);
}
}
/*
Escribir un programa ANSI C que procese el archivo datos.txt sobre sí mismo. El
procesamiento consiste en convertir los números encontrados (de 1 o más cifras
decimales) a hexadecimal.
*/
void pasarAHexa() {
printf("pasarAHexa");
FILE *fpInput;
FILE *fpOutput;
char *inputFilename = "files/datos.txt";
char *outputFilename = "files/output.txt";
char c;
char numberChar[2048];
char numberHexa[2048];
int number = 0;
int numberPos = 0;
fpInput = fopen(inputFilename, "r");
if (fpInput != NULL) {
fpOutput = fopen(outputFilename, "w+");
while ((c = fgetc(fpInput)) != EOF) {
LOG(c);
if (c <= '9' && c >= '0') {
numberChar[numberPos] = c;
++numberPos;
} else if (numberPos > 0) {
numberChar[numberPos] = '\0';
numberPos = 0;
number = atoi(numberChar);
int temp = 0;
int i = 0;
while (number != 0) {
temp = number % 16;
if (temp < 10) {
numberHexa[i] = temp + 48;
} else {
numberHexa[i] = temp + 55;
}
++i;
number /= 16;
}
for (; i > 0; --i) {
fprintf(fpOutput, "%c", numberHexa[i - 1]);
}
} else {
fprintf(fpOutput, "%c", c);
}
}
fclose(fpInput);
if (fpInput != NULL) {
fclose(fpOutput);
}
}
}
/*
* Escribir un programa que procese un archivo binario de enteros sin signo
* sobre si mismo. El procesamiento consiste en leer pares de enteros de 1 byte
* cada uno y reemplazarlos por 3 enteros (el archivo se agranda): su suma, su
* resta y el OR logico entre ambos.
*/
void operacionesAritmeticas() {
FILE *fpIn = fopen("unsignedints.dat", "r");
FILE *fpOut = fopen("unsignedints.dat", "r+");
if (fpIn != NULL && fpOut != NULL) {
fseek(fpIn, 0L, SEEK_END);
int sizeofFileInitial = ftell(fpIn);
int sizeofFileFinal;
char c1, c2;
char r1, r2, r3;
if ((sizeofFileInitial % 2) == 0) {
sizeofFileFinal = sizeofFileInitial * 1.5;
} else {
sizeofFileFinal = (sizeofFileInitial - 1)*1.5 + 1;
}
ftruncate(fileno(fpOut), sizeofFileFinal);
fseek(fpOut, 0L, SEEK_END);
int pos = sizeofFileInitial;
if ((sizeofFileInitial % 2) != 0) {
fseek(fpIn, -1, SEEK_CUR);
fseek(fpOut, -1, SEEK_CUR);
c1 = fgetc(fpIn);
fputc(c1, fpOut);
fseek(fpIn, -1, SEEK_CUR);
fseek(fpOut, -1, SEEK_CUR);
--pos;
}
while (pos > 0) {
fseek(fpIn, -2, SEEK_CUR);
fseek(fpOut, -3, SEEK_CUR);
c1 = fgetc(fpIn);
c2 = fgetc(fpIn);
r1 = c1 + c2;
r2 = c1 - c2;
r3 = c1 | c2;
fputc(r1, fpOut);
fputc(r2, fpOut);
fputc(r3, fpOut);
fseek(fpIn, -2, SEEK_CUR);
fseek(fpOut, -3, SEEK_CUR);
pos -= 2;
}
fclose(fpIn);
fclose(fpOut);
}
}
/*
* Escriba una rutina que procese un archivo binario indicado por parametro
* sobre si mismo sumarizando los listados de numeros que posee almacenado.
* La sumarizacion consiste en recorrer los valores enteros de 32 bits con signo
* grabados en formato big-endian y acumular sus valores hasta encontrar el
* valor 0xffffffff que se considera un separador entre listados.
* Todos los valores enteros detectados son reemplazados por su sumatoria (en el
* mismo formati) manteniendo luego el elemento separador. Considere archivos
* bien formados.
*/
void sumarizarListados(const char *fileName) {
FILE* fpIn = fopen(fileName, "r");
FILE* fpOut = fopen(fileName, "r+");
int32_t number;
int32_t sum = 0;
if (fpIn != NULL) {
if (fpOut != NULL) {
while (fread((void*) &number, sizeof (int32_t), 1, fpIn) > 0) {
number = ntohl(number);
if (number == -1 /* == 0xffffffff */) {
sum = htonl(sum);
number = htonl(number);
fwrite((void*) &sum, sizeof (int32_t), 1, fpOut);
fwrite((void*) &number, sizeof (int32_t), 1, fpOut);
sum = 0;
} else {
sum += number;
}
}
fclose(fpIn);
ftruncate(fileno(fpOut), ftell(fpOut));
fclose(fpOut);
}
fclose(fpIn);
}
}
void pruebasSumarizado() {
sumarizarListados("files/listadoNumeros.dat");
}
/*
* Escriba un programa C que reciba por argumento el nombre de un archivo de
* numeros binarios de 16 bits y lo procese sobre si mismo.
* El procesamiento consiste en repetir los numeros que sean
* "multiplos de 5 + 1" (6, 11, 16...) (El archivo se agranda)
*/
void multiplosDe5mas1() {
FILE *fpIn = fopen("files/multiplos5mas1.bin", "r");
FILE *fpOut = fopen("files/multiplos5mas1.bin", "r+");
uint16_t value;
int cont = 0;
if (fpIn != NULL) {
while (fread((void*) &value, sizeof (uint16_t), 1, fpIn) > 0) {
if ((value - 1) % 5 == 0) {
++cont;
}
}
if (fpOut != NULL) {
fseek(fpIn, 0L, SEEK_END);
int initSize = ftell(fpIn);
ftruncate(fileno(fpOut), initSize + (cont * sizeof (uint16_t)));
fseek(fpOut, 0L, SEEK_END);
ftell(fpOut);
int auxCont = initSize / sizeof (uint16_t);
do {
fseek(fpIn, -sizeof (uint16_t), SEEK_CUR);
fread((void*) &value, sizeof (uint16_t), 1, fpIn);
fseek(fpIn, -sizeof (uint16_t), SEEK_CUR);
fseek(fpOut, -sizeof (uint16_t), SEEK_CUR);
if ((value - 1) % 5 == 0) {
fseek(fpOut, -sizeof (uint16_t), SEEK_CUR);
fwrite((void*) &value, sizeof (uint16_t), 1, fpOut);
}
fwrite((void*) &value, sizeof (uint16_t), 1, fpOut);
--auxCont;
} while (auxCont > 0);
fclose(fpOut);
}
fclose(fpIn);
}
}
/*
* Escribir un programa ISO C que, sin crear archivos intermedios, altere el
* archivo "data.bin" reemplazando todas las secuencias de 3 bytes
* 0x34 0x43 0x44 por la secuencia de 2 bytes 0x34 0x43. Cabe destacar que el
* programa debe reprocesar el reemplazo efectuado.
* (Ejemplo: 0x34 0x43 0x44 0x44 ---> 0x34 0x43 0x44 ---> 0x34 0x43).
*/
void procesarReprocesar() {
FILE* fpI = fopen("files/data.bin", "r");
FILE* fpO = fopen("files/data.bin", "r+");
char c1, c2;
while ((c1 = fgetc(fpI)) != EOF) {
fputc(c1, fpO);
printf("%d\n", c1);
if (c1 == 52) {//0x34
c2 = fgetc(fpI);
fputc(c2, fpO);
if (c2 == 67) {//0x43
while (fgetc(fpI) == 68);
}
}
}
fclose(fpI);
ftruncate(fileno(fpO), ftell(fpO));
fclose(fpO);
}
/*
* Escribir un programa ISO C que procese el archivo palabras.txt sobre sí
* mismo. El proceso consiste en duplicar las palabras que tengan más de 2
* consonantes.
*/
char consonantes[] = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz";
int contarConsonantes(char *p) {
int i = 0;
int c = 0;
while (p[i] != 0 && c < 3){
if (strchr(consonantes,p[i]) != NULL){
++c;
}
++i;
}
return c;
}
void procesar2Consonantes() {
FILE *fpI = fopen("files/palabras.txt", "r");
FILE *fpO = fopen("files/palabras.txt", "r+");
fseek(fpO, 0L, SEEK_END);
char l;
char p[1024] = {0};
int i = 0;
while ((l = fgetc(fpI)) != EOF){
if (l != ' ') {
p[i] = l;
++i;
} else {
if (contarConsonantes(p)>2){
fputc(' ', fpO);
fputs(&p[0], fpO);
}
memset((void*)&p[0], 0, sizeof(char)*1024);
i = 0;
}
}
fclose(fpI);
fclose(fpO);
}
|
C
|
/*
/Xianxing Zhang
/ driver.c
/ This file contains implementation of sending requests to timer process
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h> //socket
#include<sys/types.h> //socket
#include<netinet/in.h> //sockaddr_in
#include<netdb.h>
#include<unistd.h>
#define BUFFER_SIZE 9
//#define HostIP 164.107.113.22
#define portNo 1100
int main(){
int sockfd; //initial socket descriptor
struct sockaddr_in timer_addr; //set up socket struct
char buf[BUFFER_SIZE]; //create buffer
//struct hostent *hostIP;
int port=portNo;
/* Create a socket to communicate with timer process */
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0){
perror("Create Socket Failed!");
exit(1);
}
/* hostIP=gethostbyname("164.107.113.22");
if(hostIP==0){
printf("Unknown host\n");
exit(2);
}
*/
timer_addr.sin_family=AF_INET;
timer_addr.sin_port=htons(port); //set the port number of 1100
// bcopy((void*)hostIP->h_addr,(void*)&timer_addr.sin_addr,hostIP->h_length);
timer_addr.sinaddr.s_addr=INADDR_ANY; //let the kernel fill this in
if(connect(sockfd,(struct sockaddr*)&timer_addr,sizeof(struct sockaddr_in))<0)
{
perror("Cannot send!\n");
exit(2);
}
//define starttimer
int starttimer(float timer,int seqNo){
bzero(buf,BUFFER_SIZE);
buf[0]='A';
memcpy(&buf[1],&timer,4);
memcpy(&buf[5],&seqNo,4);
if(send(sockfd,buf,9,0)<0){
printf("Send Add Request Failed!\n");
exit(1);
}
return 0;
}
//define canceltimer()
int canceltimer(int seqNo){
bzero(buf,BUFFER_SIZE);
buf[0]='D';
memcpy(&buf[5],&seqNo,4);
if(send(sockfd,buf,9,0)<0){
printf("Send Delete Request Failed!\n");
exit(1);
}
return 0;
}
starttimer(20.0,1);
starttimer(10.0,2);
starttimer(30.0,3);
sleep(5);
canceltimer(2);
starttimer(20.0,4);
sleep(5);
starttimer(18.0,5);
sleep(2);
canceltimer(4);
canceltimer(8);
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
int n,count=1;
scanf("%d",&n);
while(n!=0)
{
n=n/10;
if(n!=0)
{
count=count+1;
}
}
printf("%d",count);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int uid_t ;
struct stat {int st_uid; int st_gid; } ;
/* Variables and functions */
int /*<<< orphan*/ EINVAL ;
int /*<<< orphan*/ SYNTHETIC_ERRNO (int /*<<< orphan*/ ) ;
int UID_INVALID ;
int UINT32_C (int) ;
scalar_t__ USER_NAMESPACE_NO ;
int arg_uid_range ;
int arg_uid_shift ;
scalar_t__ arg_userns_mode ;
int /*<<< orphan*/ errno ;
int log_error_errno (int /*<<< orphan*/ ,char*,...) ;
int stat (char const*,struct stat*) ;
__attribute__((used)) static int determine_uid_shift(const char *directory) {
int r;
if (arg_userns_mode == USER_NAMESPACE_NO) {
arg_uid_shift = 0;
return 0;
}
if (arg_uid_shift == UID_INVALID) {
struct stat st;
r = stat(directory, &st);
if (r < 0)
return log_error_errno(errno, "Failed to determine UID base of %s: %m", directory);
arg_uid_shift = st.st_uid & UINT32_C(0xffff0000);
if (arg_uid_shift != (st.st_gid & UINT32_C(0xffff0000)))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"UID and GID base of %s don't match.", directory);
arg_uid_range = UINT32_C(0x10000);
}
if (arg_uid_shift > (uid_t) -1 - arg_uid_range)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"UID base too high for UID range.");
return 0;
}
|
C
|
#include "arch/libc/config.h"
#ifndef HAVE_ARCH_MEMCHR
#include <string.h>
void *memchr(const void *s, int _c, size_t n)
{
const unsigned char *p = s;
unsigned char c = _c;
while (n--) {
if (c == *p)
return (void *)p;
p++;
}
return NULL;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions_declarations.h"
#include "hash_declarations.h"
#include "queue_declarations.h"
#define MAX_SIZE 8
/*
ESTRUTURAS NECESSRIAS:
- HASH
- LIST
- TREE
FUNES NECESSRIAS:
- HuffTree
- CreateEmptyList
- AddListNode
*/
///text_size armazenado em uma variavel global logo qd ler o arquivo
long int codeSize(FILE* uncompressedFile){
FILE *file = fopen("uncompressedFile", "r");
fseek(file, 0, SEEK_END);
long int fileSize = ftell(file);
return fileSize;
}
///--------------------------------------------------ENCODE----------------------------------------------------------------------//
///o arquivo do texto tem q ser colocado numa string text com cada caractere em uma posio
int encode(FILE* uncompressedFile){
long int fileSize = codeSize(uncompressedFile);
unsigned char *uncompressed_text = malloc(fileSize * sizeof(unsigned char));
uncompressed_text = ExtractFile(uncompressedFile);
Hashtable* hash; //hash ps arvore
Element* codeEntry = malloc(sizeof(Element));
Queue *toCompressQueue = createQueue(); ///fila composta de todos os bits ps compresso
unsigned char *uncompressed_byte;
unsigned char compressed_byte = 0;
int compressed_byte_length = 0;
int compressed_text_length = 0;
int uncompressed_text_index;
int trash_size = 0;
int code_index;
for(uncompressed_text_index = 0; uncompressed_text_index < sizeof(uncompressed_text); uncompressed_text_index++) {
uncompressed_byte = &uncompressed_text[uncompressed_text_index];
codeEntry = getHashElement(hash, uncompressed_byte); //hash
for(code_index = 0; code_index < codeEntry->char_huff_size; code_index++) {
if(codeEntry->char_huff[code_index] == 1) {
compressed_byte = (compressed_byte << 1) | 1;
}
else{
compressed_byte = (compressed_byte << 1);
}
compressed_byte_length++;
compressed_text_length++;
if(compressed_byte_length == 8) {
addToQueue(toCompressQueue, compressed_byte);
compressed_byte_length = 0;
}
}
}
if(compressed_byte_length != 0) {
trash_size = 8 - compressed_byte_length;
compressed_byte = compressed_byte << trash_size;
addToQueue(toCompressQueue, compressed_byte);
}
return 0;
}
void createHeader(int trash_size, unsigned int treeSizeEncode){
unsigned char byte1, byte2, aux;
byte1 = trash_size << 5;
aux = treeSizeEncode >>8;
byte1 = byte1 | aux;
treeSizeEncode = treeSizeEncode & 255;
byte2 = (unsigned char) treeSizeEncode;
///------------- sobrescrever --------------///
}
///--------------------------------------------------ENCODE----------------------------------------------------------------------//
|
C
|
#include<stdio.h>
unsigned long long int fact(int);
int main(){
int n;
scanf("%d", &n);
printf("%llu\n", fact(n));
}
unsigned long long int fact(int n){
unsigned long long int f=1;
if(n == 1)
return 1;
f=n*fact(n-1);
return f;
}
|
C
|
#include "stdin.h"
#include "system.h"
#include "walloc.h"
#include "palloc.h"
#include "kprint.h"
static FILE stdinstream;
static FILE *redirectstream = 0;
FILE *getstdinstream(void)
{
return redirectstream ? redirectstream : &stdinstream;
}
void redirect(FILE *newstream)
{
redirectstream = newstream;
++(redirectstream->currentreadoffset);
}
void removeredirect(void)
{
redirectstream = 0;
}
void setupstdin(void)
{
stdinstream.length = 0x00000FFF;
stdinstream.stream = (unsigned char*)palloc(stdinstream.length);
stdinstream.currentreadoffset = 0;
stdinstream.currentwriteoffset = 1;
memset(stdinstream.stream, 0, stdinstream.length);
}
void stdinputc(unsigned char c)
{
if(stdinstream.currentreadoffset == stdinstream.currentwriteoffset)
{
memset(stdinstream.stream, 0, (unsigned int)(((unsigned char*)(stdinstream.currentwriteoffset + stdinstream.stream)) + 1 - stdinstream.stream));
stdinstream.currentreadoffset = 0;
stdinstream.currentwriteoffset = 1;
}
if(c == 4 || ((c == '\r' || c == '\n') && *(unsigned char*)(stdinstream.currentwriteoffset + stdinstream.stream) != '\\'))
++stdinstream.currentreadoffset;
if(c == '\b')
--stdinstream.currentwriteoffset;
else
*(unsigned char*)(stdinstream.currentwriteoffset++ + stdinstream.stream) = c;
writec(c);
}
unsigned char stdingetc(void)
{
if(stdinstream.currentreadoffset == stdinstream.currentwriteoffset)
{
memset(stdinstream.stream, 0, (unsigned int)(((unsigned char*)(stdinstream.currentwriteoffset + stdinstream.stream)) + 1 - stdinstream.stream));
stdinstream.currentreadoffset = 0;
stdinstream.currentwriteoffset = 1;
}
if(*(unsigned char*)(stdinstream.currentreadoffset + stdinstream.stream) == 4 || stdinstream.currentreadoffset == stdinstream.length - 1)
return 0;
while(*((unsigned char*)(stdinstream.currentreadoffset + stdinstream.stream)) == 0);
return *((unsigned char*)(stdinstream.currentreadoffset++ + stdinstream.stream));
}
unsigned char stdingets(unsigned char* s, unsigned int length)
{
unsigned char cbuff;
while(--length > 0 && (cbuff = stdingetc()))
{
if(cbuff == 4 || ((cbuff == '\r' || cbuff == '\n') && *(unsigned char*)(stdinstream.currentwriteoffset + stdinstream.stream) != '\\'))
{
break;
}
*s++ = cbuff;
}
*s = 0;
if(cbuff == 4 || stdinstream.currentreadoffset == stdinstream.length - 1)
return 0;
return 1;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <conio.h>
int main(int argc, char const *argv[]) {
const unsigned char* fName = "file.map";
BOOL process;
STARTUPINFO cInf;
PROCESS_INFORMATION pInf;
HANDLE hFileMap;
HANDLE hFile;
ZeroMemory(&cInf, sizeof(STARTUPINFO));
const int lSize = 9;
unsigned char* pGet;
HANDLE MySemaphore;
HANDLE rSemaphore;
HANDLE wSemaphore;
rSemaphore = CreateSemaphoreA(NULL, 1, 1, "MessegeSemaphore1");
if (rSemaphore == NULL) {
fprintf(stdout,"Semaphore messege: Error %ld\n", GetLastError());
return 0;
}
WaitForSingleObject(rSemaphore, 0);
wSemaphore = CreateSemaphoreA(NULL, 1, 1, "MessegeSemaphore2");
if (wSemaphore == NULL) {
fprintf(stdout,"Semaphore messege: Error %ld\n", GetLastError());
return 0;
}
MySemaphore = CreateSemaphoreA(NULL, 1, 1, "MySemaphore");
if (MySemaphore == NULL) {
fprintf(stdout,"Semaphore: Error %ld\n", GetLastError());
return 0;
}
WaitForSingleObject(MySemaphore, 0);
WaitForSingleObject(wSemaphore, 0);
process = CreateProcess("serv.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &cInf, &pInf);
if (process == FALSE) {
fprintf(stdout,"CreateProcess: Error %ld\n", GetLastError());
return 0;
}
while (1) {
if (!WaitForSingleObject(MySemaphore, 0)) {
break;
}
}
hFileMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, fName);
if (hFileMap == NULL){
fprintf(stderr, "Can't open memory mapped file: %ld\n", GetLastError());
return 0;
}
while (1) {
printf("Enter expression> ");
int a, b;
char c;
scanf("%d", &a);
scanf(" %c", &c);
scanf("%d", &b);
unsigned char bytes[9];
bytes[0] = (int)((a >> 24) & 0xFF) ;
bytes[1] = (int)((a >> 16) & 0xFF) ;
bytes[2] = (int)((a >> 8) & 0XFF);
bytes[3] = (int)((a & 0XFF));
bytes[4] = c;
bytes[5] = (int)((b >> 24) & 0xFF) ;
bytes[6] = (int)((b >> 16) & 0xFF) ;
bytes[7] = (int)((b >> 8) & 0XFF);
bytes[8] = (int)((b & 0XFF));
unsigned char* dataPtr = (unsigned char*)MapViewOfFile(hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, lSize);
if (dataPtr == NULL) {
fprintf(stdout,"GetPointer1: Error %ld\n", GetLastError());
CloseHandle(hFileMap);
CloseHandle(hFile);
return 0;
}
for (int i = 0; i < 9; ++i) {
*((unsigned char*)dataPtr + i) = bytes[i];
}
ReleaseSemaphore(rSemaphore, 1, NULL);
while (1) {
if (!WaitForSingleObject(wSemaphore, 0)) {
break;
}
}
pGet = (unsigned char*) MapViewOfFile(hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, lSize);
if (pGet == NULL) {
fprintf(stderr, "Error reading from memory (MapViewOfFile): %ld\n", GetLastError());
return 0;
}
int ans = ((pGet[0] << 24) + (pGet[1] << 16) + (pGet[2] << 8) + (pGet[3] ));
printf("Result is : %d\n", ans);
}
CloseHandle(MySemaphore);
CloseHandle(wSemaphore);
CloseHandle(rSemaphore);
TerminateProcess(pInf.hProcess, NO_ERROR);
return 0;
}
|
C
|
#include <stdio.h>
#define return_exam(p) if(!(p)){printf("error:"#p"\tfile_name:%s\tfunction_nae:%s\tline:%d .\n",__FILE__, __func__, __LINE__); return 0;}
int print()
{
return_exam(0);
}
int main(int argc, char **argv)
{
print();
printf("hello world!!!\n");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.