language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "calculate.h"
void print_error_and_exit(int err)
{
if(err == FAILURE)
{
printf("The calculation failed. Please retry.\n");
}
else if(err == OUT_OF_BOUNDS)
{
printf("The calculation failed due to out of bounds output. Please retry.\n");
}
else if(err == INVALID_INPUT)
{
printf("The calculation failed due to invalid inputs. Please retry.\n");
}
else if(err == INVALID_NUM_1)
{
printf("The calculation failed due to invalid input 1. Please retry.\n");
}
else if(err == INVALID_NUM_2)
{
printf("The calculation failed due to invalid input 2. Please retry.\n");
}
_exit(EXIT_FAILURE);
}
int main(int argc, char * argv[])
{
int iRetVal = SUCCESS;
if(argc != 3)
{
printf("Incorrect number of arguments.\nFormat: ./main <Roman_string_1> <Romand_string_2>\nPlease retry.\n");
return 1;
}
char acSum[MAX_LEN] = {0};
char acDiff[MAX_LEN] = {0};
iRetVal = calculate_sum(argv[1], argv[2], (char *) &acSum);
if(iRetVal != SUCCESS)
{
print_error_and_exit(iRetVal);
}
if(iRetVal == SUCCESS)
{
strcmp(acSum, "") ? printf("The sum is: %s\n\n", acSum) :
printf("The sum is: -\n");
}
iRetVal = calculate_diff(argv[1], argv[2], (char *) &acDiff);
if(iRetVal != SUCCESS && iRetVal != NEGATIVE_DIFFERENCE)
{
print_error_and_exit(iRetVal);
}
if(iRetVal == SUCCESS)
{
strcmp(acDiff, "") ? printf("The difference is: %s\n\n", acDiff) :
printf("The difference is: -\n");
}
else if(iRetVal == NEGATIVE_DIFFERENCE)
{
printf("The difference is: Negative %s\n\n", acDiff);
}
return SUCCESS;
}
|
C | /*
Write a C program to calculate
factorial of a number.
*/
#include <stdio.h>
main()
{
int numberInput,i,result;
printf("C program to calculate factorial of a number\n");
printf("Enter a Number: ");
scanf("%d",&numberInput);
result = 1;
for(i = 1; numberInput >= i; i++){
result = result * i;
}
printf("Factorial of %d is: %d\n",numberInput,result);
}
|
C | /*
** get_size.c for get_size in /home/sachs_a/delivery/IA/dante/depth/src/depth
**
** Made by Alexandre Sachs
** Login <[email protected]>
**
** Started on Sun Apr 23 12:36:09 2017 Alexandre Sachs
** Last update Sun Apr 23 12:36:09 2017 Alexandre Sachs
*/
#include "get_next_line.h"
int get_size(int fd)
{
int pos;
char *str;
pos = 0;
while ((str = get_next_line(fd)))
{
pos++;
free(str);
}
return (pos);
}
|
C | /*
** EPITECH PROJECT, 2021
** libmy
** File description:
** Defines qsort_r_do_quick
*/
#pragma once
#include "my/stdlib.h"
#include "my/cpp-like/algorithm.h"
#include "my/string.h"
#include "my/features.h"
#include <stddef.h>
#include <stdbool.h>
struct qsort_state {
char *base;
char *p_median;
char *pa;
char *pb;
char *pc;
char *pd;
};
MY_ATTR_ACCESS((read_write, 1, 3)) MY_ATTR_ACCESS((read_write, 2, 3))
MY_ATTR_NONNULL((1, 2)) static void swap_elements(char *elem1, char *elem2,
size_t element_size)
{
char buffer[10000];
size_t copy_size;
while (element_size) {
copy_size = MY_MIN(sizeof(buffer), element_size);
my_memcpy(buffer, elem1, copy_size);
my_memcpy(elem1, elem2, copy_size);
my_memcpy(elem2, buffer, copy_size);
elem1 += copy_size;
elem2 += copy_size;
element_size -= copy_size;
}
}
static void finish_quick(struct qsort_state *state, size_t num_elements,
size_t element_size,
const struct my_qsort_r_internal_comparison_function_and_argument *cmp)
{
char *p_end = state->base + num_elements * element_size;
size_t distance = MY_MIN(state->pa - state->base, state->pb - state->pa);
if (distance)
swap_elements(state->base, state->pb - distance, distance);
distance = MY_MIN(state->pd - state->pc, p_end - state->pd - element_size);
if (distance)
swap_elements(state->pb, p_end - distance, distance);
distance = state->pb - state->pa;
if (distance > element_size)
my_internal_qsort_r(state->base, distance / element_size, element_size,
cmp);
distance = state->pd - state->pc;
if (distance > element_size)
my_internal_qsort_r(p_end - distance, distance / element_size,
element_size, cmp);
}
static bool do_below_iter(struct qsort_state *state, size_t element_size,
const struct my_qsort_r_internal_comparison_function_and_argument *cmp)
{
int r = cmp->func(state->pb, state->base, cmp->argument);
if (r > 0)
return (false);
if (r == 0) {
swap_elements(state->pa, state->pb, element_size);
state->pa += element_size;
}
state->pb += element_size;
return (true);
}
static bool do_above_iter(struct qsort_state *state, size_t element_size,
const struct my_qsort_r_internal_comparison_function_and_argument *cmp)
{
int r = cmp->func(state->pc, state->base, cmp->argument);
if (r < 0)
return (false);
if (r == 0) {
swap_elements(state->pc, state->pd, element_size);
state->pd -= element_size;
}
state->pc -= element_size;
return (true);
}
static void do_quick(struct qsort_state *state, size_t num_elements,
size_t element_size,
const struct my_qsort_r_internal_comparison_function_and_argument *cmp)
{
swap_elements(state->base, state->p_median, element_size);
while (true) {
while (state->pb <= state->pc)
if (!do_below_iter(state, element_size, cmp))
break;
while (state->pb <= state->pc)
if (!do_above_iter(state, element_size, cmp))
break;
if (state->pb > state->pc)
break;
swap_elements(state->pb, state->pc, element_size);
state->pb += element_size;
state->pc -= element_size;
}
finish_quick(state, num_elements, element_size, cmp);
}
|
C | //
// server.c
//
#include "server.h"
int numServers = 1;
int main(int argc,char** argv) {
int clientSock = 0, numReady,numClients,full,serverSock;
struct sockaddr_in client;
socklen_t clientLen = sizeof(client); //To pass &clientLen
struct in_addr statAddr;
long bytesRead = 0,bytesWritten = 0;
int fds[FD_SETSIZE]; //Set to 0 if fd closed
for(int i = 0; i < FD_SETSIZE; i++ ) fds[i] = 0;
numReady = numClients = full = 0;
serverSock = openPort(SERVER_PORT);
fd_set listenSet,activeSet;
int highSocket = serverSock;
FD_ZERO(&listenSet);
FD_SET(serverSock,&listenSet);
while(TRUE) {
activeSet = listenSet;
if((numReady = select(highSocket+1,&activeSet,NULL,NULL,NULL)) < 1) perror("Select");
if(FD_ISSET(serverSock,&activeSet)) { //New connection
numReady--;
FD_CLR(serverSock,&activeSet); //So we don't trigger below
if (numClients < POOL_SIZE && (clientSock = accept(serverSock,(struct sockaddr *)&client,&clientLen)) < 0) {
perror("Can't accept client");
} else if(numClients < POOL_SIZE && clientSock > 0) {
if(highSocket < clientSock) highSocket = clientSock;
FD_SET(clientSock,&listenSet);
fds[clientSock] = client.sin_addr.s_addr;
numClients++;
}
}
for(int i = 0; i < FD_SETSIZE && numReady > 0;i++) {
if(FD_ISSET(i,&activeSet)) {
numReady--;
bytesRead = bytesWritten = 0;
if(handleRequest(i,&bytesRead,&bytesWritten) < 0) { // We must quit.
FD_CLR(i,&listenSet);
numClients--;
fds[i] = 0;
} else {
statAddr.s_addr = fds[i];
}
}
}
} //end While
return EXIT_SUCCESS;
}
/* Handles request made by FD. Returns -1 if we closed connection,
and 1 otherwise */
int handleRequest(int fd,long* bytesRead,long* bytesWritten) {
char buffer[BUFLEN];
char* quitMessage = "BY";
char* invalidMessage = "NO";
long answer;
int numChars = (int)recv(fd,buffer,BUFLEN-1,0);
buffer[numChars] = 0; //Null terminate received string.
if(numChars <= 0) { //Close connection
printf("Client has closed connection\n");
shutdown(fd,SHUT_RDWR);
close(fd);
return -1;
} else if((answer = parseString(buffer,fd)) >= 0) {
*bytesWritten += answer;
} else {
if(answer == -1) {
printf("Client requested we close connection\n");
dprintf(fd,"%s",quitMessage);
}
if(answer == -2) {
printf("Received Invalid Command:%s\n",buffer);
dprintf(fd,"%s",invalidMessage);
*bytesWritten += answer;
}
shutdown(fd,SHUT_RDWR);
close(fd);
*bytesRead += numChars;
return -1;
}
*bytesRead += numChars;
return numChars;
}
|
C | #include "volume_base.h"
#include "volume.h"
#include "volume_dispatch.h"
static
STATUS
_VolInitialize(
IN PDEVICE_OBJECT Disk,
IN PPARTITION_INFORMATION PartitionInformation,
INOUT PDRIVER_OBJECT DriverObject
);
STATUS
(__cdecl VolDriverEntry)(
INOUT PDRIVER_OBJECT DriverObject
)
{
STATUS status;
PDEVICE_OBJECT* pDiskDevices;
DWORD noOfDisks;
DWORD i;
DWORD j;
PIRP pIrp;
DWORD structureSize;
PDISK_LAYOUT_INFORMATION pDiskLayout;
ASSERT(NULL != DriverObject);
status = STATUS_SUCCESS;
pDiskDevices = NULL;
noOfDisks = 0;
pIrp = NULL;
structureSize = 0;
pDiskLayout = NULL;
DriverObject->DispatchFunctions[IRP_MJ_READ] = VolDispatchReadWrite;
DriverObject->DispatchFunctions[IRP_MJ_WRITE] = VolDispatchReadWrite;
DriverObject->DispatchFunctions[IRP_MJ_DEVICE_CONTROL] = VolDispatchDeviceControl;
status = IoGetDevicesByType(DeviceTypeDisk, &pDiskDevices, &noOfDisks);
if (!SUCCEEDED(status))
{
LOG_FUNC_ERROR("IoGetDevicesByType\n", status);
return status;
}
__try
{
for (i = 0; i < noOfDisks; ++i)
{
PDEVICE_OBJECT pCurDisk = pDiskDevices[i];
do
{
if (NULL != pDiskLayout)
{
LOGL("Calling HeapFreePoolWithTag for pDiskLayout: 0x%X\n", pDiskLayout);
ExFreePoolWithTag(pDiskLayout, HEAP_TEMP_TAG);
pDiskLayout = NULL;
}
if (0 != structureSize)
{
pDiskLayout = ExAllocatePoolWithTag(PoolAllocateZeroMemory, structureSize, HEAP_TEMP_TAG, 0);
if (NULL == pDiskLayout)
{
status = STATUS_HEAP_NO_MORE_MEMORY;
LOG_FUNC_ERROR_ALLOC("HeapALllocatePoolWithTag", structureSize);
__leave;
}
LOGL("pDiskLayout has address: 0x%X\n", pDiskLayout);
}
if (NULL != pIrp)
{
IoFreeIrp(pIrp);
pIrp = NULL;
}
pIrp = IoBuildDeviceIoControlRequest(IOCTL_DISK_LAYOUT_INFO,
pCurDisk,
NULL,
0,
pDiskLayout,
structureSize
);
ASSERT(NULL != pIrp);
LOG_TRACE_IO("Successfully built IRP for device control\n");
status = IoCallDriver(pCurDisk, pIrp);
if (!SUCCEEDED(status))
{
LOG_FUNC_ERROR("IoCallDriver", status);
__leave;
}
status = pIrp->IoStatus.Status;
ASSERT(pIrp->IoStatus.Information <= MAX_DWORD);
structureSize = (DWORD)pIrp->IoStatus.Information;
} while (STATUS_BUFFER_TOO_SMALL == status);
if (!SUCCEEDED(status))
{
LOG_FUNC_ERROR("IoCallDriver", status);
__leave;
}
ASSERT(NULL != pDiskLayout);
for (j = 0; j < pDiskLayout->NumberOfPartitions; ++j)
{
status = _VolInitialize(pCurDisk,
&pDiskLayout->Partitions[j],
DriverObject
);
if (!SUCCEEDED(status))
{
LOG_FUNC_ERROR("VolInitialize", status);
__leave;
}
LOG("[%d][%d] Volume successfully initialized\n", i, j);
}
}
}
__finally
{
if (NULL != pDiskLayout)
{
LOGL("Calling HeapFreePoolWithTag for pDiskLayout: 0x%X\n", pDiskLayout);
ExFreePoolWithTag(pDiskLayout, HEAP_TEMP_TAG);
pDiskLayout = NULL;
}
if (NULL != pDiskDevices)
{
IoFreeTemporaryData(pDiskDevices);
pDiskDevices = NULL;
}
if (NULL != pIrp)
{
IoFreeIrp(pIrp);
pIrp = NULL;
}
LOG_FUNC_END;
}
return status;
}
STATUS
_VolInitialize(
IN PDEVICE_OBJECT Disk,
IN PPARTITION_INFORMATION PartitionInformation,
INOUT PDRIVER_OBJECT DriverObject
)
{
STATUS status;
PVOLUME pVolumeData;
PDEVICE_OBJECT pVolumeDevice;
if (NULL == Disk)
{
return STATUS_INVALID_PARAMETER1;
}
status = STATUS_SUCCESS;
pVolumeData = NULL;
pVolumeDevice = NULL;
__try
{
pVolumeDevice = IoCreateDevice(DriverObject, sizeof(VOLUME), DeviceTypeVolume);
if (NULL == pVolumeDevice)
{
LOG_FUNC_ERROR_ALLOC("IoCreateDevice", sizeof(VOLUME));
status = STATUS_DEVICE_COULD_NOT_BE_CREATED;
__leave;
}
pVolumeDevice->DeviceAlignment = Disk->DeviceAlignment;
// get volume object
pVolumeData = (PVOLUME)IoGetDeviceExtension(pVolumeDevice);
ASSERT(NULL != pVolumeData);
pVolumeData->DiskDevice = Disk;
memcpy(&pVolumeData->PartitionInformation, PartitionInformation, sizeof(PARTITION_INFORMATION));
// attach to disk
IoAttachDevice(pVolumeDevice, Disk);
}
__finally
{
if (!SUCCEEDED(status))
{
if (NULL != pVolumeDevice)
{
IoDeleteDevice(pVolumeDevice);
pVolumeDevice = NULL;
}
}
}
return status;
} |
C | /* Alexaner Simchuk, string_manip_tests.c
* Unit test infrastructure for testing the methods in string_manip.c
*/
#include "string_manip.h"
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
bool run_stringArrayLen = true;
bool run_removeBegArray = true;
bool run_stripNewline = true;
#define ASSERT_ISNULL(val) (!val) ? true : false
#define ASSERT_ISNOTNULL(val) (val) ? true : false
#define ASSERT_TRUE(val) (val) ? true : false
#define ASSERT_FALSE(val) (val) ? false : true
#define ASSERT_STR_EQUAL(str1,str2) (strcmp(str1,str2) == 0) ? true: false
#define ASSERT_STR_NEQUAL(str1,str2) (strcmp(str1,str2) != 0) ? true: false
#define PSUC() GRN "Success!" RESET
#define PFAIL() RED "Failed." RESET
#define PYEL(str) YEL str RESET
#define PMAG(str) MAG str RESET
#define PCYN(str) CYN str RESET
int main(int argc, char* argv[]) {
//Tests for string_manip.c::stringArrayLen()
if (run_stringArrayLen) {
printf(PYEL("TESTING STRINGARRAYLEN():\n"));
printf(PMAG("(all should pass)\n"));
char **test1 = NULL;
printf("%s is NULL input == -1... %s\n", PCYN("Testing stringArrayLen():"),
(-1 == stringArrayLen(test1)) ? PSUC() : PFAIL());
char *test2[] = { NULL };
printf("%s is {%s} == 0 ... %s\n", PCYN("Testing stringArrayLen():"),
test2[0],
(0 == stringArrayLen(test2)) ? PSUC() : PFAIL());
char *test3[] = { "string1", NULL };
printf("%s is {%s, %s} == 1 ... %s\n", PCYN("Testing stringArrayLen():"),
test3[0], test3[1],
(1 == stringArrayLen(test3)) ? PSUC() : PFAIL());
char *test4[] = { "string1", "string2", NULL };
printf("%s is {%s, %s, %s} == 2 ... %s\n", PCYN("Testing stringArrayLen():"),
test4[0], test4[1], test4[2],
(2 == stringArrayLen(test4)) ? PSUC() : PFAIL());
}
//Tests for string_manip.c::removeBegArray()
if (run_removeBegArray) {
printf(PYEL("TESTING REMOVEBEGARRAY():\n"));
printf(PMAG("(all should pass)\n"));
printf(PMAG("(tests for STRINGARRAYLEN() should pass first)\n"));
char str1[] = "str1";
char str2[] = "str2";
char str3[] = "str3";
char str4[] = "str4";
char str5[] = "str5";
char **rba_test = (char**)calloc(3, sizeof(char*));
rba_test[0] = str1;
rba_test[1] = str2;
rba_test[2] = NULL;
//check each index
char **result = removeBegArray(rba_test,1);
printf("%s using args {%s, %s, %s} and 1:\n", PCYN("Testing removeBegArray():"),
str1, str2, "NULL");
printf("Return value is not NULL ... %s\n",
(ASSERT_ISNOTNULL(result)) ? PSUC() : PFAIL());
printf("New array index 0 is %s ... %s\n", str2,
(strcmp(result[0], str2) == 0) ? PSUC() : PFAIL());
printf("New array index 1 is %s ... %s\n", "NULL",
(ASSERT_ISNULL(result[1])) ? PSUC() : PFAIL());
free(result);
free(rba_test);
rba_test = (char**)calloc(6, sizeof(char*));
rba_test[0] = str1;
rba_test[1] = str2;
rba_test[2] = str3;
rba_test[3] = str4;
rba_test[4] = str5;
rba_test[5] = NULL;
result = removeBegArray(rba_test,3);
printf("%s using args {%s, %s, %s, %s, %s, %s} and 3:\n",
PCYN("Testing removeBegArray():"),
str1, str2, str3, str4, str5, "NULL");
printf("Return value is not NULL ... %s\n",
(ASSERT_ISNOTNULL(result)) ? PSUC() : PFAIL());
printf("New array index 0 is %s ... %s\n", str4,
(strcmp(result[0], str4) == 0) ? PSUC() : PFAIL());
printf("New array index 1 is %s ... %s\n", str5,
(strcmp(result[1], str5) == 0) ? PSUC() : PFAIL());
printf("New array index 2 is %s ... %s\n", "NULL",
(ASSERT_ISNULL(result[2])) ? PSUC() : PFAIL());
free(result);
free(rba_test);
rba_test = NULL;
result = removeBegArray(rba_test,3);
printf("%s using args %s and 3:\n",
PCYN("Testing removeBegArray():"),
"NULL");
printf("Return value is NULL ... %s\n",
(ASSERT_ISNULL(result)) ? PSUC() : PFAIL());
rba_test = (char**)calloc(1,sizeof(char*));
rba_test[0] = NULL;
result = removeBegArray(rba_test,3);
printf("%s using args {%s} and 3:\n",
PCYN("Testing removeBegArray():"),
"NULL");
printf("Return value is NULL ... %s\n",
(ASSERT_ISNULL(result)) ? PSUC() : PFAIL());
if(result) free(result);
if(rba_test) free(rba_test);
rba_test = (char**)calloc(3, sizeof(char*));
rba_test[0] = str1;
rba_test[1] = str2;
rba_test[2] = NULL;
result = removeBegArray(rba_test,3);
printf("%s using args {%s, %s, %s} and 3:\n", PCYN("Testing removeBegArray():"),
str1, str2, "NULL");
printf("Return value is NULL ... %s\n",
(ASSERT_ISNULL(result)) ? PSUC() : PFAIL());
if(result) free(result);
if(rba_test) free(rba_test);
}
//Tests for string_manip.c::stripNewline()
if (run_stripNewline) {
printf(PYEL("TESTING STRIPNEWLINE():\n"));
printf(PMAG("(all should pass)\n"));
char str_newline1[] = "randomestrinmg\0";
char str_newline2[] = "buuuuuurp\n";
char str_newline3[] = "";
char *str_newline4 = NULL;
char *result = stripNewline(str_newline1);
printf("%s using arg \"%s\":\n", PCYN("Testing stripNewline():"),
str_newline1);
printf("Return val \"%s\" is \"%s\" ... %s\n",
result, str_newline1,
(strcmp(result, str_newline1) == 0) ? PSUC() : PFAIL());
result = stripNewline(str_newline2);
printf("%s using arg \"%s\":\n", PCYN("Testing stripNewline():"),
str_newline2);
printf("Return val \"%s\" is \"%s\" ... %s\n",
result, "buuuuuurp",
(strcmp(result, "buuuuuurp") == 0) ? PSUC() : PFAIL());
result = stripNewline(str_newline3);
printf("%s using arg \"%s\":\n", PCYN("Testing stripNewline():"),
str_newline3);
printf("Return val %s is (null) ... %s\n",
result,
(ASSERT_ISNULL(result)) ? PSUC() : PFAIL());
result = stripNewline(str_newline4);
printf("%s using arg %s:\n", PCYN("Testing stripNewline():"),
str_newline4);
printf("Return val %s is (null) ... %s\n",
result,
(ASSERT_ISNULL(result)) ? PSUC() : PFAIL());
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rotate_if.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fboggs <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/15 15:12:14 by fboggs #+# #+# */
/* Updated: 2020/03/15 15:13:34 by fboggs ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/push_swap.h"
void rotate_if_next(t_what **storage, t_num **tmp)
{
if ((*tmp)->index == (*storage)->next)
rotate_while_heada_next(&(*storage));
else
push('b', &(*storage));
}
void rotate_while_heada_next(t_what **storage)
{
r_rotate(&(*storage)->head_a, &(*storage)->tail_a, &(*storage));
(*storage)->tail_a->sort = 1;
(*storage)->next += 1;
}
void if_small_index_in_usual_alg_split(t_what **strg, t_num **tmp)
{
if ((*strg)->curr_stack == 'A')
push('b', &(*strg));
else
{
if ((*tmp)->index == (*strg)->next)
{
push('a', &(*strg));
rotate_while_heada_next(&(*strg));
}
else
r_rotate(&(*strg)->head_b, &(*strg)->tail_b, &(*strg));
}
}
void if_small_block_in_a(t_what **storage, int count, t_num *tmp)
{
while (count-- && tmp)
{
rotate_if_next(&(*storage), &(tmp));
tmp = ((*storage)->curr_stack == 'A') ? ((*storage)->head_a) :
((*storage)->head_b);
}
}
|
C | /*
** show_list.c for showlist in /home/peau_c/rendu/PSU/PSU_2015_tetris
**
** Made by Clement Peau
** Login <[email protected]>
**
** Started on Thu Mar 3 14:26:49 2016 Clement Peau
** Last update Thu Mar 3 15:46:11 2016 Clement Peau
*/
#include "linked_list.h"
void show_list(t_tetriminos *list)
{
t_tetriminos *tmp;
tmp = list->next;
while (tmp != NULL)
{
PUTSTR(tmp->name);
tmp = tmp->next;
}
}
|
C | /* test-expr.c -- Testing: filter expression parsing and processing.
Copyright (C) 2020, 2022 Genome Research Ltd.
Author: James Bonfield <[email protected]>
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 notices 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 <config.h>
#include <stdio.h>
#include <string.h>
#include "../htslib/hts_expr.h"
int lookup(void *data, char *str, char **end, hts_expr_val_t *res) {
int foo = 15551; // my favourite palindromic prime
int a = 1;
int b = 2;
int c = 3;
res->is_str = 0;
if (strncmp(str, "foo", 3) == 0) {
*end = str+3;
res->d = foo;
} else if (*str == 'a') {
*end = str+1;
res->d = a;
} else if (*str == 'b') {
*end = str+1;
res->d = b;
} else if (*str == 'c') {
*end = str+1;
res->d = c;
} else if (strncmp(str, "magic", 5) == 0) {
// non-empty string
*end = str+5;
res->is_str = 1;
kputs("plugh", ks_clear(&res->s));
} else if (strncmp(str, "empty-but-true", 14) == 0) {
// empty string
*end = str+14;
res->is_true = 1;
res->is_str = 1;
kputs("", ks_clear(&res->s));
} else if (strncmp(str, "empty", 5) == 0) {
// empty string
*end = str+5;
res->is_str = 1;
kputs("", ks_clear(&res->s));
} else if (strncmp(str, "zero-but-true", 13) == 0) {
*end = str+13;
res->d = 0;
res->is_true = 1;
} else if (strncmp(str, "null-but-true", 13) == 0) {
*end = str+13;
hts_expr_val_undef(res);
res->is_true = 1;
} else if (strncmp(str, "null", 4) == 0) {
// null string (eg aux:Z tag is absent)
*end = str+4;
hts_expr_val_undef(res);
} else if (strncmp(str, "nan", 3) == 0) {
// sqrt(-1), 0/0 and similar
// Semantically the same operations as null.
*end = str+3;
hts_expr_val_undef(res);
} else {
return -1;
}
return 0;
}
typedef struct {
int truth_val;
double dval;
char *sval;
char *str;
} test_ev;
static inline int strcmpnull(const char *a, const char *b) {
if (!a && !b) return 0;
if (!a && b) return -1;
if (a && !b) return 1;
return strcmp(a, b);
}
// Compare NAN as equal, for testing we returned the correct values
static inline int cmpfloat(double d1, double d2) {
// If needs be, can use DBL_EPSILON in comparisons here.
return d1 == d2 || (isnan(d1) && isnan(d2));
}
int test(void) {
// These are all valid expressions that should work
test_ev tests[] = {
{ 1, 1, NULL, "1"},
{ 1, 1, NULL, "+1"},
{ 1, -1, NULL, "-1"},
{ 0, 0, NULL, "!7"},
{ 1, 1, NULL, "!0"},
{ 1, 1, NULL, "!(!7)"},
{ 1, 1, NULL, "!!7"},
{ 1, 5, NULL, "2+3"},
{ 1, -1, NULL, "2+-3"},
{ 1, 6, NULL, "1+2+3"},
{ 1, 1, NULL, "-2+3"},
{ 0, NAN, NULL, "1+null" },
{ 0, NAN, NULL, "null-1" },
{ 0, NAN, NULL, "-null" },
{ 1, 6, NULL, "2*3"},
{ 1, 6, NULL, "1*2*3"},
{ 0, 0, NULL, "2*0"},
{ 1, 7, NULL, "(7)"},
{ 1, 7, NULL, "((7))"},
{ 1, 21, NULL, "(1+2)*(3+4)"},
{ 1, 14, NULL, "(4*5)-(-2*-3)"},
{ 0, NAN, NULL, "2*null"},
{ 0, NAN, NULL, "null/2"},
{ 0, NAN, NULL, "0/0"},
{ 1, 1, NULL, "(1+2)*3==9"},
{ 1, 1, NULL, "(1+2)*3!=8"},
{ 0, 0, NULL, "(1+2)*3!=9"},
{ 0, 0, NULL, "(1+2)*3==8"},
{ 0, 0, NULL, "1>2"},
{ 1, 1, NULL, "1<2"},
{ 0, 0, NULL, "3<3"},
{ 0, 0, NULL, "3>3"},
{ 1, 1, NULL, "9<=9"},
{ 1, 1, NULL, "9>=9"},
{ 1, 1, NULL, "2*4==8"},
{ 1, 1, NULL, "16==0x10"},
{ 1, 1, NULL, "15<0x10"},
{ 1, 1, NULL, "17>0x10"},
{ 0, 0, NULL, "2*4!=8"},
{ 1, 1, NULL, "4+2<3+4"},
{ 0, 0, NULL, "4*2<3+4"},
{ 1, 8, NULL, "4*(2<3)+4"}, // boolean; 4*(1)+4
{ 1, 1, NULL, "(1<2) == (3>2)"},
{ 1, 1, NULL, "1<2 == 3>2"},
{ 0, NAN, NULL, "null <= 0" },
{ 0, NAN, NULL, "null >= 0" },
{ 0, NAN, NULL, "null < 0" },
{ 0, NAN, NULL, "null > 0" },
{ 0, NAN, NULL, "null == null" },
{ 0, NAN, NULL, "null != null" },
{ 0, NAN, NULL, "null < 10" },
{ 0, NAN, NULL, "10 > null" },
{ 1, 1, NULL, "2 && 1"},
{ 0, 0, NULL, "2 && 0"},
{ 0, 0, NULL, "0 && 2"},
{ 1, 1, NULL, "2 || 1"},
{ 1, 1, NULL, "2 || 0"},
{ 1, 1, NULL, "0 || 2"},
{ 1, 1, NULL, "1 || 2 && 3"},
{ 1, 1, NULL, "2 && 3 || 1"},
{ 1, 1, NULL, "0 && 3 || 2"},
{ 0, 0, NULL, "0 && 3 || 0"},
{ 0, 0, NULL, " 5 - 5 && 1"},
{ 0, 0, NULL, "+5 - 5 && 1"},
{ 0, 0, NULL, "null && 1"}, // null && x == null
{ 0, 0, NULL, "1 && null"},
{ 1, 1, NULL, "!null && 1"},
{ 1, 1, NULL, "1 && !null"},
{ 1, 1, NULL, "1 && null-but-true"},
{ 0, 0, NULL, "null || 0"}, // null || 0 == null
{ 0, 0, NULL, "0 || null"},
{ 1, 1, NULL, "!null || 0"},
{ 1, 1, NULL, "0 || !null"},
{ 1, 1, NULL, "0 || null-but-true"},
{ 1, 1, NULL, "null || 1"}, // null || 1 == 1
{ 1, 1, NULL, "1 || null"},
{ 1, 1, NULL, "3 & 1"},
{ 1, 2, NULL, "3 & 2"},
{ 1, 3, NULL, "1 | 2"},
{ 1, 3, NULL, "1 | 3"},
{ 1, 7, NULL, "1 | 6"},
{ 1, 2, NULL, "1 ^ 3"},
{ 0, NAN, NULL, "1 | null"},
{ 0, NAN, NULL, "null | 1"},
{ 0, NAN, NULL, "1 & null"},
{ 0, NAN, NULL, "null & 1"},
{ 0, NAN, NULL, "0 ^ null"},
{ 0, NAN, NULL, "null ^ 0"},
{ 0, NAN, NULL, "1 ^ null"},
{ 0, NAN, NULL, "null ^ 1"},
{ 1, 1, NULL, "(1^0)&(4^3)"},
{ 1, 2, NULL, "1 ^(0&4)^ 3"},
{ 1, 2, NULL, "1 ^ 0&4 ^ 3"}, // precedence, & before ^
{ 1, 6, NULL, "(1|0)^(4|3)"},
{ 1, 7, NULL, "1 |(0^4)| 3"},
{ 1, 7, NULL, "1 | 0^4 | 3"}, // precedence, ^ before |
{ 1, 1, NULL, "4 & 2 || 1"},
{ 1, 1, NULL, "(4 & 2) || 1"},
{ 0, 0, NULL, "4 & (2 || 1)"},
{ 1, 1, NULL, "1 || 4 & 2"},
{ 1, 1, NULL, "1 || (4 & 2)"},
{ 0, 0, NULL, "(1 || 4) & 2"},
{ 1, 1, NULL, " (2*3)&7 > 4"},
{ 0, 0, NULL, " (2*3)&(7 > 4)"}, // C precedence equiv
{ 1, 1, NULL, "((2*3)&7) > 4"}, // Python precedence equiv
{ 1, 1, NULL, "((2*3)&7) > 4 && 2*2 <= 4"},
{ 1, 1, "plugh", "magic"},
{ 1, 1, "", "empty"},
{ 1, 1, NULL, "magic == \"plugh\""},
{ 1, 1, NULL, "magic != \"xyzzy\""},
{ 1, 1, NULL, "\"abc\" < \"def\""},
{ 1, 1, NULL, "\"abc\" <= \"abc\""},
{ 0, 0, NULL, "\"abc\" < \"ab\""},
{ 0, 0, NULL, "\"abc\" <= \"ab\""},
{ 0, 0, NULL, "\"abc\" > \"def\""},
{ 1, 1, NULL, "\"abc\" >= \"abc\""},
{ 1, 1, NULL, "\"abc\" > \"ab\""},
{ 1, 1, NULL, "\"abc\" >= \"ab\""},
{ 0, NAN, NULL, "null == \"x\"" },
{ 0, NAN, NULL, "null != \"x\"" },
{ 0, NAN, NULL, "null < \"x\"" },
{ 0, NAN, NULL, "null > \"x\"" },
{ 1, 1, NULL, "\"abbc\" =~ \"^a+b+c+$\""},
{ 0, 0, NULL, "\"aBBc\" =~ \"^a+b+c+$\""},
{ 1, 1, NULL, "\"aBBc\" !~ \"^a+b+c+$\""},
{ 1, 1, NULL, "\"xyzzy plugh abracadabra\" =~ magic"},
{ 1, 1, "", "empty-but-true" },
{ 0, 0, NULL, "!empty-but-true" },
{ 1, 1, NULL, "!!empty-but-true" },
{ 1, 1, NULL, "1 && empty-but-true && 1" },
{ 0, 0, NULL, "1 && empty-but-true && 0" },
{ 0, NAN, NULL, "null" },
{ 1, 1, NULL, "!null" },
{ 0, 0, NULL, "!!null", },
{ 0, 0, NULL, "!\"foo\"" },
{ 1, 1, NULL, "!!\"foo\"" },
{ 1, NAN, NULL, "null-but-true" },
{ 0, 0, NULL, "!null-but-true" },
{ 1, 1, NULL, "!!null-but-true" },
{ 1, 0, NULL, "zero-but-true" },
{ 0, 0, NULL, "!zero-but-true" },
{ 1, 1, NULL, "!!zero-but-true" },
{ 1, log(2), NULL, "log(2)"},
{ 1, exp(9), NULL, "exp(9)"},
{ 1, 9, NULL, "log(exp(9))"},
{ 1, 8, NULL, "pow(2,3)"},
{ 1, 3, NULL, "sqrt(9)"},
{ 0, NAN, NULL, "sqrt(-9)"},
{ 1, 2, NULL, "default(2,3)"},
{ 1, 3, NULL, "default(null,3)"},
{ 0, 0, NULL, "default(null,0)"},
{ 1, NAN, NULL, "default(null-but-true,0)"},
{ 1, NAN, NULL, "default(null-but-true,null)"},
{ 1, NAN, NULL, "default(null,null-but-true)"},
{ 1, 1, NULL, "exists(\"foo\")"},
{ 1, 1, NULL, "exists(12)"},
{ 1, 1, NULL, "exists(\"\")"},
{ 1, 1, NULL, "exists(0)"},
{ 0, 0, NULL, "exists(null)"},
{ 1, 1, NULL, "exists(null-but-true)"},
};
int i, res = 0;
hts_expr_val_t r = HTS_EXPR_VAL_INIT;
for (i = 0; i < sizeof(tests) / sizeof(*tests); i++) {
hts_filter_t *filt = hts_filter_init(tests[i].str);
if (!filt)
return 1;
if (hts_filter_eval2(filt, NULL, lookup, &r)) {
fprintf(stderr, "Failed to parse filter string %s\n",
tests[i].str);
res = 1;
hts_filter_free(filt);
continue;
}
if (!hts_expr_val_exists(&r)) {
if (r.is_true != tests[i].truth_val ||
!cmpfloat(r.d, tests[i].dval)) {
fprintf(stderr,
"Failed test: \"%s\" == \"%f\", got %s, \"%s\", %f\n",
tests[i].str, tests[i].dval,
r.is_true ? "true" : "false", r.s.s, r.d);
res = 1;
}
} else if (r.is_str && (strcmpnull(r.s.s, tests[i].sval) != 0
|| !cmpfloat(r.d, tests[i].dval)
|| r.is_true != tests[i].truth_val)) {
fprintf(stderr,
"Failed test: \"%s\" == \"%s\", got %s, \"%s\", %f\n",
tests[i].str, tests[i].sval,
r.is_true ? "true" : "false", r.s.s, r.d);
res = 1;
} else if (!r.is_str && (!cmpfloat(r.d, tests[i].dval)
|| r.is_true != tests[i].truth_val)) {
fprintf(stderr, "Failed test: %s == %f, got %s, %f\n",
tests[i].str, tests[i].dval,
r.is_true ? "true" : "false", r.d);
res = 1;
}
hts_expr_val_free(&r);
hts_filter_free(filt);
}
return res;
}
int main(int argc, char **argv) {
if (argc > 1) {
hts_expr_val_t v = HTS_EXPR_VAL_INIT;
hts_filter_t *filt = hts_filter_init(argv[1]);
if (hts_filter_eval2(filt, NULL, lookup, &v))
return 1;
printf("%s\t", v.is_true ? "true":"false");
if (v.is_str)
puts(v.s.s);
else
printf("%g\n", v.d);
hts_expr_val_free(&v);
hts_filter_free(filt);
return 0;
}
return test();
}
|
C | //
// server.c
// File Server
//
// Created by Alessio Giordano on 23/12/18.
//
// O46001858 - 23/12/18
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#define UTENTI 5
/*
Generale
*/
char homepath[4097] = "";
int LastIndexOf(char c, char *str) {
int index = -1; int max = strlen(str);
for(int i = 0; i < max; i++) {
if(c == str[i]) index = i;
};
return index;
}
/* ***************************************** */
/*
Gestione della lista dei path
*/
pthread_mutex_t locker;
typedef struct pathnode {
char path[4097];
struct pathnode *next;
} pathnode_t;
typedef pathnode_t* pathlist_t;
pathlist_t ind = NULL;
pathlist_t cur = NULL;
pthread_mutex_t lista;
void AddPathList(char *pat) {
pathlist_t temp_list;
temp_list = (pathlist_t)malloc(sizeof(pathnode_t));
strncpy(temp_list->path, pat, 4097);
temp_list->next = NULL;
if (cur == NULL) {
ind = temp_list;
cur = temp_list;
} else {
cur->next = temp_list;
cur = temp_list;
};
}
void ScanDir(char *pat) {
DIR *dir; struct dirent *dir_info;
if( (dir = opendir(pat)) != NULL) {
while ( (dir_info = readdir(dir)) != NULL) {
char abs_path[4097];
if ( ((dir_info->d_type == DT_DIR) || (dir_info->d_type == DT_REG)) &&
((strcmp(dir_info->d_name, ".") != 0) && (strcmp(dir_info->d_name, "..") != 0)) ) {
strcpy(abs_path, pat);
strcat(abs_path, dir_info->d_name);
if (dir_info->d_type == DT_DIR) {
abs_path[0] = 'd';
strcat(abs_path, "/");
};
AddPathList(abs_path);
};
};
closedir(dir);
};
}
int ScanList(char *dir) {
pathlist_t tem = ind; pathlist_t pre = NULL;
while (tem != NULL) {
if (tem->path[0] == 'd') {
strcpy(dir, tem->path);
dir[0] = '/';
if (tem == ind) {
if (ind->next == NULL) {
ind = NULL;
cur = NULL;
} else {
ind = tem->next;
};
} else if (tem->next == NULL) {
pre->next = NULL;
cur = pre;
} else {
pre->next = tem->next;
};
free(tem);
return 1;
};
pre = tem;
tem = tem->next;
};
return 0;
}
void *ListHandler(void *args) {
while(1) {
char pat[4097];
pthread_mutex_lock(&lista);
if ( ScanList(pat) ) {
ScanDir(pat);
} else {
int *retval = 0;
pthread_mutex_unlock(&lista);
pthread_exit( (void*)retval );
};
pthread_mutex_unlock(&lista);
}
}
pthread_t Scanner(char *dir) {
ScanDir(dir);
char messaggio[] = ""; pthread_t tid;
pthread_create(&tid, NULL, ListHandler, (void*)messaggio);
return tid;
}
/* ***************************************** */
/*
Sistema di Login
*/
typedef struct utente {
char nome[50];
char password[50];
char token[50];
} utente;
typedef char token[50];
utente clienti[UTENTI];
int Login(int login_to, char *nome, char *password, token tok) {
char login_buffer[50] = "";
for(int i = 0; i < UTENTI; i++) {
if( (strcmp(nome, clienti[i].nome) == 0) && (strcmp(password, clienti[i].password) == 0) && (strlen(nome) > 4) ) {
// Genero il token
sprintf(clienti[i].token, "%c%d%c%c", clienti[i].nome[0], (int)time(NULL), clienti[i].nome[3], clienti[i].nome[4]);
strcpy(tok, clienti[i].token);
strcpy(login_buffer, clienti[i].token);
send(login_to, (void*)login_buffer, sizeof(login_buffer), 0);
return 1;
};
};
strcpy(login_buffer, "ERR");
send(login_to, (void*)login_buffer, sizeof(login_buffer), 0);
return 0;
}
int IsLogged(token tok) {
for(int i = 0; i < UTENTI; i++) {
if( strcmp(tok, clienti[i].token) == 0 ) return 1;
};
return 0;
}
int PopulateClients(char *path) {
FILE *f;
f = fopen(path, "r");
if(f != NULL) {
for(int i = 0; i < UTENTI; i++) {
char temp_nome[50] = ""; char temp_password[50] = "";
int result = fscanf(f, "%s %s", temp_nome, temp_password);
if( (result == 2) && (strlen(temp_nome) > 4) ) {
strcpy(clienti[i].nome, temp_nome); strcpy(clienti[i].password, temp_password);
} else if (result == EOF) {
break;
} else {
i--;
};
};
return 1;
} else {
return 0;
};
}
/* ***************************************** */
/*
Listing dei File disponibili
*/
void Listing(int list_to) {
pathlist_t position = ind;
char buffer[4097] = "";
while (position != NULL) {
strncpy(buffer, "", sizeof(buffer));
strcpy(buffer, position->path);
send(list_to, (void*)buffer, sizeof(buffer), 0);
position = position->next;
};
strncpy(buffer, "", sizeof(buffer));
strcpy(buffer, "END");
send(list_to, (void*)buffer, sizeof(buffer), 0);
}
/* ***************************************** */
/*
Funzionalità di Download
*/
int Download(char *path, int download_to) {
int target = strlen(homepath);
if ( strncmp(path, homepath, target) == 0) {
int requested_file = open(path, O_RDONLY, NULL);
if (requested_file != -1) {
char buffer[200] = "";
while( read(requested_file, (void*)buffer, sizeof(buffer)) != 0) {
send(download_to, (void*)buffer, sizeof(buffer), 0);
strncpy(buffer, "", sizeof(buffer));
};
close(requested_file);
sprintf(buffer, "%d", EOF);
send(download_to, (void*)buffer, sizeof(buffer), 0);
return 1;
} else {
char buffer[200] = "ERR";
send(download_to, (void*)buffer, sizeof(buffer), 0);
return 0;
};
} else {
char buffer[200] = "ERR";
send(download_to, (void*)buffer, sizeof(buffer), 0);
return 0;
};
};
/* ***************************************** */
/*
Funzionalità di Upload
*/
int Upload(char *name, int upload_from) {
char recvdir[4097];
strcpy(recvdir, homepath); strcat(recvdir, "recvdir/");
mkdir(recvdir, S_IRUSR | S_IWUSR | S_IXUSR);
strcat(recvdir, name);
int uploaded_file = open(recvdir, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR);
if (uploaded_file != -1) {
char buffer[200] = ""; char EOFcond[200]; sprintf(EOFcond, "%d", EOF);
while( strcmp(buffer, EOFcond) != 0 ) {
strncpy(buffer, "", sizeof(buffer));
recv(upload_from, (void*)buffer, sizeof(buffer), 0);
if(strcmp(buffer, EOFcond) != 0) write(uploaded_file, buffer, sizeof(buffer));
};
close(uploaded_file);
return 1;
} else {
return 0;
};
};
/* ***************************************** */
/*
Gestione delle richieste TCP del client
*/
void *ClientHandler(void *args) {
int socket_client = (*(int *)args);
while(1) {
char buffer[4118] = "";
recv(socket_client, (void*)buffer, sizeof(buffer), 0);
char comando[20] = ""; token tok; char argomento1[4097]; char argomento2[50];
sscanf(buffer, "%s %s %s %s", comando, tok, argomento1, argomento2);
if(strcmp(comando, "LOGIN") == 0) {
// Verifica che l'utente in questione sia collegato
if(Login(socket_client, argomento1, argomento2, tok)) {
printf("Login Effettuato - Token: %s\n", tok);
} else {
printf("Login Fallito\n");
}
} else if(strcmp(comando, "LIST") == 0) {
// Invia al client la lista di file disponibili al Download
if(IsLogged(tok)) {
Listing(socket_client);
printf("Listing dei file disponibili a %s\n", tok);
} else {
printf("Tentativo di Listing non autorizzato\n");
};
} else if(strcmp(comando, "DOWNLOAD") == 0) {
// Incomincia la procedura di download
if(IsLogged(tok)) {
if(Download(argomento1, socket_client)) {
printf("%s ha scaricato il file %s\n", tok, argomento1);
} else {
printf("Fallito Download del file %s\n", argomento1);
};
} else {
printf("Tentativo di Download non autorizzato\n");
};
} else if(strcmp(comando, "UPLOAD") == 0) {
// Incomincia la procedura di upload
if(IsLogged(tok)) {
if(Upload(argomento1, socket_client)) {
printf("%s ha caricato il file %s\n", tok, argomento1);
} else {
printf("Fallito Upload del file %s\n", argomento1);
};
} else {
printf("Tentativo di Upload non autorizzato\n");
};
} else if(strcmp(comando, "ESCI") == 0) {
close(socket_client);
printf("Disconnesso\n");
pthread_exit(0);
};
strncpy(buffer, "", sizeof(buffer));
};
}
/* ***************************************** */
int main(int argc, const char *argv[]) {
printf("Attendi mentre indicizzo la cartella Home... ");
// Inizializzazione del Mutex e verifica dell'esito
if (pthread_mutex_init(&lista, NULL) != 0) exit(1);
// Creazione della lista a partire dalla home
pthread_t tid;
// La variabile Path è definita nell'header
strcpy(homepath, getenv("HOME")); strcat(homepath, "/");
// strcat(homepath, "Desktop/"); // Usato nella demo mostrata in README.md
tid = Scanner(homepath);
pthread_join(tid, NULL);
printf("Fatto\n");
// Popoliamo il vettore dei Client
if(!PopulateClients("clients.txt")) {
strcpy(clienti[0].nome, "default"); strcpy(clienti[0].password, "default");
};
// Preparazione al Socket TCP
int socket_id = socket(AF_INET, SOCK_STREAM, 0); // Creiamo un socket Internet
if(socket_id < 0) exit(1);
struct sockaddr_in bind_socket_id;
bind_socket_id.sin_family = AF_INET; // Siamo nel dominio di Internet
bind_socket_id.sin_addr.s_addr = INADDR_ANY; // Accettiamo da qualsiasi interfaccia
bind_socket_id.sin_port = htons(8960); // Porta 8960 senza problema di Big/Little End.
int bind_result = bind(socket_id, (struct sockaddr*)&bind_socket_id, sizeof(bind_socket_id)); // Infine facciamo la Bind
if(bind_result < 0) exit(1);
int listen_result = listen(socket_id, UTENTI); // Il numero massimo di client consentiti è definito nella costante UTENTI a inizio file...
if(listen_result < 0) exit(1);
// E 24/12/18 17:51
// TCP stuff
while (1) {
printf("Attendo il client... ");
fflush(stdout);
pthread_t tid;
int accept_result = accept(socket_id, NULL, NULL);
printf("Connesso\n");
pthread_create(&tid, NULL, ClientHandler, (void *)&accept_result);
};
}
|
C | #include <stdio.h>
int main(void) {
char c;
int counter = 0;
while((c = getchar()) != '\n') {
if(c == ' ' && counter == 0) {
printf("\n");
}
else {
printf("%c", c);
counter = 0;
}
}
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
void memdump(char * p , int len) {
// Add your code here.
int i;
unsigned char buff[17];
unsigned char *pc = (unsigned char*)p;
for (i = 0; i < len; i++){
if ((i % 16) == 0){
if (i != 0){
printf(" %s\n", buff);
}
printf(" %04x ", i);
}
printf(" %02x", pc[i]);
if((pc[i] < 0x20) || (pc[i] > 0x7e)){
buff[i % 16] = '.';
} else {
buff[i % 16] = pc[i];
}
buff[(i%16)+1] = '\0';
}
while ((i % 16) != 0) {
printf(" ");
i++;
}
printf(" %s\n", buff);
}
struct X{
char a;
int i;
char b;
int *p;
};
struct List {
char * str;
struct List * next;
};
int main() {
double y = 14;
char str[20];
int a = 66;
int b = -77;
struct X x;
struct List * head;
x.a = 'G';
x.i = 42;
x.b = '0';
x.p = &x.i;
strcpy(str, "Hello world\n");
printf("&x=0x%x\n", &x.a);
printf("&y=0x%x\n", &y);
memdump((char *) &x.a, 64);
head = (struct List *) malloc(sizeof(struct List));
head->str=strdup("Greetings ");
head->next = (struct List *) malloc(sizeof(struct List));
head->next->str = strdup("from ");
head->next->next = (struct List *) malloc(sizeof(struct List));
head->next->next->str = strdup("CS250");
head->next->next->next = NULL;
printf("head=0x%x\n", head);
memdump((char*) head, 128);
}
|
C | #include"List.h"
int main()
{
List s;
ListInit(&s);
ListPushBack(&s, 1);
ListPushBack(&s, 2);
ListPushBack(&s, 3);
ListPushBack(&s, 4);
ListPushBack(&s, 5);
ListPrint(&s);
ListPushFront(&s, 10);
ListPushFront(&s, 20);
ListPushFront(&s, 30);
ListPushFront(&s, 40);
ListPushFront(&s, 50);
ListPrint(&s);
ListPopFront(&s);
ListPopFront(&s);
ListPrint(&s);
ListPopBack(&s);
ListPopBack(&s);
ListPrint(&s);
ListDestroy(&s);
} |
C | #include "../src/internal.h"
#include "../src/types.h"
#include "test.h"
#include <assert.h>
#include <passwand/passwand.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
TEST("pack: basic functionality") {
char _pt[] = "hello world";
const pt_t p = {
.data = (uint8_t *)_pt,
.length = sizeof(_pt),
};
const iv_t iv = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
ppt_t pp;
int r = pack_data(&p, iv, &pp);
ASSERT_EQ(r, PW_OK);
ASSERT_GT(pp.length, 0ul);
passwand_secure_free(pp.data, pp.length);
}
TEST("pack: is aligned") {
char _pt[] = "Deliberately not 16-byte aligned text";
assert(sizeof(_pt) % 16 != 0);
pt_t p = {
.data = (uint8_t *)_pt,
.length = sizeof(_pt),
};
const iv_t iv = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
ppt_t pp;
int r = pack_data(&p, iv, &pp);
ASSERT_EQ(r, PW_OK);
ASSERT_GT(pp.length, 0ul);
ASSERT_EQ(pp.length % 16, 0ul);
passwand_secure_free(pp.data, pp.length);
}
|
C | #include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
void write_fifo(int descriptor)
{
char *message = "Kolokwium na 30 pkt";
if(write(descriptor,message,strlen(message))<0)
perror("write");
}
int main(void)
{
int descriptor = open("fifo",O_WRONLY);
if(descriptor < 0)
perror("open");
write_fifo(descriptor);
if(close(descriptor)<0)
perror("close");
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int x;
int y;
for (x = 1; x<=10; x++){
printf("Tabla del %d\n", x);
for (y = 1; y <= 10; y++){
printf("%d x %d = %d\n", x, y, x*y);
}
y = 1;
printf("\n");
}
return (0);
}
|
C | /*
** EPITECH PROJECT, 2019
** game loop
** File description:
** yeh yeh yeh
*/
#include "navy.h"
int client_server_loop(snavy_t *navy, int current_hit,
int current_string)
{
if (connection.is_server) {
attack_s(navy, current_hit);
if ((navy->game_status = check_win(navy)) != 0)
return 1;
defend_s(navy, current_string);
print_maps(navy->s_map2d, navy->c_map2d);
} else {
defend_c(navy, current_string);
if ((navy->game_status = check_win(navy)) != 0)
return 1;
attack_c(navy, current_hit);
print_maps(navy->c_map2d, navy->s_map2d);
}
return 0;
}
void game_loop(snavy_t *navy)
{
int current_hit = 0;
int current_string = 0;
while ((navy->game_status = check_win(navy)) == 0) {
current_string++;
current_hit++;
client_server_loop(navy, current_hit, current_string);
}
end_print(navy);
} |
C | #include <stdio.h>
int queuearr[];
int N,s=0,front=0,rear=0;
int size(){
return s;
}
int dispFront(){
return(queuearr[front]);
}
int isEmpty(){
return (size()==0);
}
void enqueue(int el){
if(size()==N){
printf("\nQueue is full\n");
}
else{
s++;
queuearr[rear]=el;
rear=(rear+1)%N;
}
}
int dequeue(){
if(isEmpty()){
printf("\nEmpty queue\n");
}
else{
s--;
int el=queuearr[front];
front=(front+1)%N;
return el;
}
}
void displayQueue(){
printf("\n[");
if(rear>front){
for(int i=front;i<rear;i++){
printf("%d, ",queuearr[i]);
}
}
else{
for(int i=front;i<N && size()!=0;i++){
printf("%d, ",queuearr[i]);
}
for(int i=0;i<rear && size()!=0;i++){
printf("%d, ",queuearr[i]);
}
}
printf("]\n");
}
void main(){
N=3;
int queuearr[N];
enqueue(1);
enqueue(2);
enqueue(3);
dequeue();
enqueue(4);
displayQueue();
printf("\n Front element: %d",dispFront());
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* swap_funcs.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: syamada <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/07 16:29:01 by syamada #+# #+# */
/* Updated: 2018/08/11 11:57:17 by syamada ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void swap_a(t_stack **a, t_stack **b, t_oplist **oplist)
{
int tmp;
if (!a || !b || !*a)
return ;
if (!(*a)->next)
return ;
tmp = (*a)->data;
(*a)->data = (*a)->next->data;
(*a)->next->data = tmp;
add_oplist(oplist, SA);
}
void swap_b(t_stack **a, t_stack **b, t_oplist **oplist)
{
int tmp;
if (!a || !b || !*b)
return ;
if (!(*b)->next)
return ;
tmp = (*b)->data;
(*b)->data = (*b)->next->data;
(*b)->next->data = tmp;
add_oplist(oplist, SB);
}
void swap_ab(t_stack **a, t_stack **b, t_oplist **oplist)
{
swap_a(a, b, NULL);
swap_b(a, b, NULL);
add_oplist(oplist, SS);
}
|
C | #include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"
void loop(int p){
double i, j;
for(i = 0; i < 10000; i++)
for(j=0; j < 100000; j++);
printf(1, "Terminou %d\n", p);
}
int main(void){
int p[10];
p[0] = fork(10);
printf(1,"%d tickets\n", 10);
if(p[0] == 0){
//sleep(100);
loop(0);
exit();
}
p[1] = fork(5);
printf(1,"%d tickets\n", 5);
if(p[1] == 0){
//sleep(100);
loop(1);
exit();
}
p[2] = fork(25);
printf(1,"%d tickets\n", 25);
if(p[2] == 0){
loop(2);
exit();
}
wait();
wait();
wait();
exit();
return 0;
}
|
C | // 2
/*
BIJ
ָһ¼key, valueļֵԡBѴҪļֵԣ
Ҫvalue滻ɵvalueBkey,һҶӽнв
1ҪkeyֵҵҶӽ㲢롣
2жϵǰkeyĸǷСڵm-1е3
3ԽмkeyΪķѳ֣Ȼмkey뵽УkeyָѺ벿֣
keyָ֧ѺҰ벿֣Ȼǰָ㣬е3
*/
#include "pch.h"
extern struct config_information config_inf; //configϢб b+tree.c
extern struct disk_file_information disk_file[FILE_AMOUNT]; //ÿļϢ b+tree.c
extern struct save_content s_c[content_num]; //Ŀ¼
extern int btree_block_apply();
void btree_insert_data(int table_num, int key, int index_num, int data_num) {
//ؼ
bnode node;
int unit;
int block_index0, block_index1;
long position;
int i, middle_count; //ؼ
printf("==============\n");
position = index_num * config_inf.block_size * 1024;
fseek(disk_file[0].file_point, position + sizeof(int), 0); //λļʼ
fread(&node, sizeof(bnode), 1, disk_file[0].file_point);
//ؼ
//printf("ؼ\n");
for (i = 0; i < node.keynum; i++)
{
if (key <= node.key[i])
{
middle_count = node.key[i];
node.key[i] = key;
key = middle_count;
}
printf(" node.key[%d] = %d\n", i, node.key[i]);
}
node.key[node.keynum] = key; //node.keynumkey //keyСkeyֵ䣬
printf(" node.key[%d] = %d\n", node.keynum, node.key[node.keynum]);
node.keynum++;
printf("==============\n");
//дԱ½ڵʱȡȷ
fseek(disk_file[0].file_point, position + sizeof(int), 0); //λļʼ
fwrite(&node, sizeof(bnode), 1, disk_file[0].file_point);
if (node.keynum == m)
{
printf(" node.keynum = %d,", m);
//int middle_num = m / 2 + 1; //мؼ ʡռ
if (index_num != s_c[table_num].index_block)
{
//disk_file[0].file_block_amount
//飬"һ"п
printf(" Ǹڵ\n");
//տ,дһؼ֣m / 2 + 1ʼΪмֵһڵ
//block_index1 = btree_insert_node(node.key[m / 2 + 1], node.parent_block_num, node.key_block[m / 2 + 1]);
block_index1 = btree_insert_node(0, 1, node.parent_block_num, node.key, node.key_block, node.child_block_num);
//0ƣ1ϴؼָ֣һд
/*
for (i = m / 2 + 1 + 1; i <= m; i++)
{
btree_insert_data(table_num, node.key[i], block_index1, node.key_block[i]);
}*/
////[m / 2]Ϊm / 2 + 1ݣΪмֵһڵ룬0ţ
btree_insert_data(table_num, node.key[m / 2], node.parent_block_num, node.key_block[m / 2]); //ϴ
//0
for (i = m / 2; i < m; i++)
{
node.key[i] = 0;
node.key_block[i] = 0;
node.child_block_num[i] = 0;
}
node.child_block_num[m] = 0;
node.keynum = m / 2;
}
else
{
//ţ""п죬飬ݷֵӿ飬ʹһ
printf(" ڵ\n");
//node.leaf = 0; //Ϊ֧ڵ
//տ
//
//block_index0 = btree_insert_node(node.key[0], index_num, node.key_block[0]);
block_index0 = btree_insert_node(1, 0, index_num, node.key, node.key_block, node.child_block_num);
/*for (i = 1; i < m / 2; i++)
{
btree_insert_data(table_num, node.key[i], block_index0, node.key_block[i]);
}*/
// Һ
//printf(" node.key[m / 2 + 1] = %d\n", node.key[m / 2 + 1]);
//block_index1 = btree_insert_node(node.key[m / 2 + 1], index_num, node.key_block[m / 2 + 1]);
block_index1 = btree_insert_node(0, 0, index_num, node.key, node.key_block, node.child_block_num);
/*for (i = m / 2 + 2 + 1; i <= m; i++)
{
btree_insert_data(table_num, node.key[i], block_index1, node.key_block[i]);
}*/
//ؼֵ
node.key[0] = node.key[m / 2];
node.key_block[0] = node.key_block[m / 2];
node.keynum = 1;
//0
for ( i = 1; i < m; i++)
{
node.key[i] = 0;
node.key_block[i] = 0;
}
//ָ
node.child_block_num[0] = block_index0;
node.child_block_num[1] = block_index1;
//0
for (i = 2; i <= m; i++)
{
node.child_block_num[i] = 0;
}
}
}
/*
else
{
//ָ
node.child_block_num[0] = block_index0;
node.child_block_num[1] = block_index1;
node.child_block_num[2] = 0;
}*/
//д
fseek(disk_file[0].file_point, position + sizeof(int), 0); //λļʼ
fwrite(&node, sizeof(bnode), 1, disk_file[0].file_point);
}
//int btree_insert_node(int key, int prior_block_index, int block_data) {
int btree_insert_node(int left, int up_data, int parent_block_num, int key[], int key_block[], int child_block_num[]) {
bnode node, parent_node, child_node;
int child_node_key[m + 1] = { 0 }, middle_count, middle_index; //ؼ
int block_index, position;
int i; //ѭ
printf(" ڵ\n");
//ڵʼ
if (left) //
{
for (i = 0; i < m; i++)
{
if (i < m / 2)
{
node.key[i] = key[i];
node.key_block[i] = key_block[i];
node.child_block_num[i] = child_block_num[i];
}
else {
node.key[i] = 0;
node.key_block[i] = 0;
if (i == m / 2)
{
node.child_block_num[i] = child_block_num[i]; //βָ븴
}
else
{
node.child_block_num[i] = 0;
}
}
}
}
else //
{
for (i = 0; i < m; i++)
{
if (i + m / 2 + 1 < m)
{
node.key[i] = key[m / 2 + 1 + i];
node.key_block[i] = key_block[m / 2 + 1 + i];
node.child_block_num[i] = child_block_num[m / 2 + 1 + i];
}
else {
node.key[i] = 0;
node.key_block[i] = 0;
if (i + m / 2 + 1 == m)
{
node.child_block_num[i] = child_block_num[m / 2 + 1 + i]; //βָ븴
}
else
{
node.child_block_num[i] = 0;
}
}
}
}
node.child_block_num[m] = 0; //0ʼơ0mΪm+1
node.keynum = m - m / 2 - 1;
//node.leaf = 1; //Ҷӽڵ㣿
node.parent_block_num = parent_block_num;
//½ڵ
block_index = btree_block_apply();
//
position = block_index * config_inf.block_size * 1024;
fseek(disk_file[0].file_point, position + sizeof(int), 0); //λļʼ
fwrite(&node, sizeof(bnode), 1, disk_file[0].file_point);
//ڵ
for ( i = 0; i < node.keynum; i++)
{
printf(" node.key[%d] = %d ", i, node.key[i]);
printf(" node.key_block[%d] = %d ", i, node.key_block[i]);
printf(" node.child_block_num[%d] = %d \n", i, node.child_block_num[i]);
}
printf(" node.child_block_num[%d] = %d \n", node.keynum, node.child_block_num[node.keynum]);
printf(" keynum = %d, node.parent_block_num = %d\n", node.keynum, node.parent_block_num);
//˫дӽڵ㣬
//˫ڵ
position = parent_block_num * config_inf.block_size * 1024;
fseek(disk_file[0].file_point, position + sizeof(int), 0); //λļʼ
fread(&parent_node, sizeof(bnode), 1, disk_file[0].file_point);
//ÿָеһؼ
for (i = 0; i < parent_node.keynum; i++)
{
if (parent_node.child_block_num[i] != 0)
{
position = parent_node.child_block_num[i] * config_inf.block_size * 1024;
fseek(disk_file[0].file_point, position + sizeof(int), 0); //λļʼ
fread(&child_node, sizeof(bnode), 1, disk_file[0].file_point);
child_node_key[i] = child_node.key[0];
}
else
{
child_node_key[i] = 0;
}
}
//ݹؼָֽ
middle_index = block_index;
for (int i = 0; i < parent_node.keynum; i++)
{
if (key <= child_node_key[i])
{
//ؼ
middle_count = child_node_key[i];
child_node_key[i] = key;
key = middle_count;
//˫еĺָ
middle_count = parent_node.child_block_num[i];
parent_node.child_block_num[i] = middle_index;
middle_index = middle_count;
}
else if (child_node_key[i] == 0)
{
//ؼ
middle_count = child_node_key[i];
child_node_key[i] = key;
key = middle_count;
//˫еĺָ
middle_count = parent_node.child_block_num[i];
parent_node.child_block_num[i] = middle_index;
middle_index = middle_count;
break;
}
}
//node.keynumnum //middle_indexСmiddle_indexֵ䣬
if (up_data) {
parent_node.child_block_num[parent_node.keynum + 1] = middle_index;
}
else
{
parent_node.child_block_num[parent_node.keynum] = middle_index;
}
//ڵ
printf(" ˫ڵ㣡\n");
for (i = 0; i < parent_node.keynum; i++)
{
printf(" node.key[%d] = %d ", i, parent_node.key[i]);
printf(" node.key_block[%d] = %d ", i, parent_node.key_block[i]);
printf(" node.child_block_num[%d] = %d \n", i, parent_node.child_block_num[i]);
}
printf(" node.child_block_num[%d] = %d \n", parent_node.keynum, parent_node.child_block_num[parent_node.keynum]);
printf(" keynum = %d, node.parent_block_num = %d\n", parent_node.keynum, parent_node.parent_block_num);
//д˫ڵ
position = parent_block_num * config_inf.block_size * 1024;
fseek(disk_file[0].file_point, position + sizeof(int), 0); //λļʼ
fwrite(&parent_node, sizeof(bnode), 1, disk_file[0].file_point);
printf(" \n");
printf("==============\n");
return block_index;
}
|
C | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define MABANGJIN_SIZE 3
int main()
{
int k, l;
int mabangjin[MABANGJIN_SIZE][MABANGJIN_SIZE];
char answer;
for (k = 0; k < MABANGJIN_SIZE; k++)
{
for (l = 0; l < MABANGJIN_SIZE; l++)
scanf("%d", &mabangjin[k][l]);
}
int i=0, result1 = 0, result2 = 0, result3 = 0, result4 = 0, result5 = 0, result6=0, result7=0, result8=0;
for(i=0; i<3; i++){
result1 +=mabangjin[0][i];
}
for(i=0; i<3; i++){
result2 +=mabangjin[1][i];
}
for(i=0; i<3; i++){
result3 +=mabangjin[2][i];
}
for(i=0; i<3; i++){
result4 +=mabangjin[i][0];
}
for(i=0; i<3; i++){
result5 += mabangjin[i][1];
}
for(i=0; i<3; i++){
result6 += mabangjin[i][2];
}
result7 = mabangjin[0][0] + mabangjin[1][1] + mabangjin[2][2];
result8 = mabangjin[0][2] + mabangjin[1][1] + mabangjin[2][0];
int j=0;
int arr[7] = {result1, result2, result3, result4, result5, result6, result7, result8};
if(arr[i++] == arr[0]) printf("O\n");
else printf("X\n");
return 0;
}
|
C | /*
* (C) Copyright 2012
* Joe Hershberger, National Instruments, [email protected]
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef __ENV_ATTR_H__
#define __ENV_ATTR_H__
#define ENV_ATTR_LIST_DELIM ','
#define ENV_ATTR_SEP ':'
/*
* env_attr_walk takes as input an "attr_list" that takes the form:
* attributes = [^,:\s]*
* entry = name[:attributes]
* list = entry[,list]
* It will call the "callback" function with the "name" and attribute as "value"
* The callback may return a non-0 to abort the list walk.
* This return value will be passed through to the caller.
* 0 is returned on success.
*/
extern int env_attr_walk(const char *attr_list,
int (*callback)(const char *name, const char *value));
/*
* env_attr_lookup takes as input an "attr_list" with the same form as above.
* It also takes as input a "name" to look for.
* If the name is found in the list, it's value is copied into "attributes".
* There is no protection on attributes being too small for the value.
* It returns -1 if attributes is NULL, 1 if "name" is not found, 2 if
* "attr_list" is NULL.
* Returns 0 on success.
*/
extern int env_attr_lookup(const char *attr_list, const char *name,
char *attributes);
#endif /* __ENV_ATTR_H__ */
|
C | /* call tagFile to tag a file. Call getFileTag to read the tag of that file. */
#include "types.h"
#include "user.h"
#define O_RDONLY 0x000
#define O_WRONLY 0x001
#define O_RDWR 0x002
#define O_CREATE 0x200
#undef NULL
#define NULL ((void*)0)
int ppid;
volatile int global = 1;
#define assert(x) if (x) {} else { \
printf(1, "%s: %d ", __FILE__, __LINE__); \
printf(1, "assert failed (%s)\n", # x); \
printf(1, "TEST FAILED\n"); \
kill(ppid); \
exit(); \
}
int
main(int argc, char *argv[])
{
ppid = getpid();
int fd = open("ls", O_RDWR);
printf(1, "fd of ls: %d\n", fd);
char* key = "type";
char* val = "utility";
int len = 7;
int res = tagFile(fd, key, val, len);
tagFile(fd, "bbyy", "12345", 5);
assert(res > 0);
char buf[7];
int valueLength = getFileTag(fd, key, buf, 7);
assert(valueLength == len);
struct Key keys[16];
int numTags = getAllTags(fd, keys, 16);
//close(fd);
int i;
for(i = 0; i < len; i++){
char v_actual = buf[i];
char v_expected = val[i];
assert(v_actual == v_expected);
}
printf(1, "%s%d\n", "the return value of getAllTags is: ", numTags);
printf(1, "TEST PASSED\n");
//exit();
//----------------------------------------------------------------------
ppid = getpid();
//int fd1 = open("ls", O_RDWR);
printf(1, "%s%d\n", "the value of fd1: ", fd);
// char* key1 = "type";
// char* val1 = "utility";
// int len1 = 7;
// int res1 = tagFile(fd1, key1, val1, len1);
// printf(1, "%s%d\n", "the return value of tagFile is: ", res1);
//close(fd1);
//懂了,open的时候,O_RDWR和这个O_RDONLY打开的不是一个文件.....
//int fd = open("ls", O_RDONLY);
//printf(1, "%s%d\n", "the value of fd: ", fd);
struct Key keys1[16];
int numTags1 = getAllTags(fd, keys1, 16);
printf(1, "%s%d\n", "the return value of getAllTags is: ", numTags1);
if(numTags1 < 0){
exit();
}
if(numTags1 > 16){
numTags1 = 16;
}
char buffer[18];
printf(1, "Here is a list of this file's tags:\n");
for(i = 0; i < numTags1; i++){
//printf(1,"%s\n" ,"进入了numTags这个大的循环中, 开始去找对应的值, 然后,从buffer中读取的");
int res = getFileTag(fd, keys1[i].key, buffer, 18);
if(res > 0){
printf(1, "%s: %s\n", keys1[i].key, buffer);
}
}
//printf(1,"%s\n" ,"出了循环");
close(fd);
//printf(1,"%s\n" ,"也就是关闭文件成功");
exit();
}
|
C | #include <stdio.h>
int main() {
int x[5], cont[4]={0}, i;
for(i=0; i<5; i++){
scanf("%d", &x[i]);
if(x[i] < 0)
cont[0]++;
if(x[i] > 0)
cont[1]++;
if(x[i]%2 == 0)
cont[2]++;
if(x[i]%2 != 0)
cont[3]++;
}
printf("%d valor(es) par(es)\n", cont[2]);
printf("%d valor(es) impar(es)\n", cont[3]);
printf("%d valor(es) positivo(s)\n", cont[1]);
printf("%d valor(es) negativo(s)\n", cont[0]);
return 0;
}
|
C | #include<stdlib.h>
#include<stdio.h>
#define ElementType int
#define ERROR -1
struct Node{
ElementType Data;
struct Node* Next;
};
struct QNode{
struct Node* rear;
struct Node* front;
};
typedef struct QNode* Queue;
/*出队*/
ElementType DeleteQ(Queue PtrQ){
struct Node* FrontCell;
ElementType FrontElem;
if(PtrQ->front==NULL){
printf("Queue is empty\n");
return ERROR;
}
FrontCell=PtrQ->front;
if(PtrQ->front==PtrQ->rear)
PtrQ->front=PtrQ->rear=NULL;
else
PtrQ->front=PtrQ->front->Next;
FrontElem=FrontCell->Data;
free(FrontCell);
return FrontElem;
} |
C | #include<stdio.h>
int main()
{
int i=4,z;
int *p=&i;
z=100;
z=z/(*p);
printf("%d%d",*p,z);
return 0;
}
|
C | /* stringlib: split implementation */
#ifndef STRINGLIB_FASTSEARCH_H
#error must include "stringlib/fastsearch.h" before including this module
#endif
/* Overallocate the initial list to reduce the number of reallocs for small
split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three
resizes, to sizes 4, 8, then 16. Most observed string splits are for human
text (roughly 11 words per line) and field delimited data (usually 1-10
fields). For large strings the split algorithms are bandwidth limited
so increasing the preallocation likely will not improve things.*/
#define MAX_PREALLOC 12
/* 5 splits gives 6 elements */
#define PREALLOC_SIZE(maxsplit) \
(maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
#define SPLIT_APPEND(data, left, right) \
sub = STRINGLIB_NEW((data) + (left), \
(right) - (left)); \
if (sub == NULL) \
goto onError; \
if (PyList_Append(list, sub)) { \
Py_DECREF(sub); \
goto onError; \
} \
else \
Py_DECREF(sub);
#define SPLIT_ADD(data, left, right) { \
sub = STRINGLIB_NEW((data) + (left), \
(right) - (left)); \
if (sub == NULL) \
goto onError; \
if (count < MAX_PREALLOC) { \
PyList_SET_ITEM(list, count, sub); \
} else { \
if (PyList_Append(list, sub)) { \
Py_DECREF(sub); \
goto onError; \
} \
else \
Py_DECREF(sub); \
} \
count++; }
/* Always force the list to the expected size. */
#define FIX_PREALLOC_SIZE(list) Py_SET_SIZE(list, count)
Py_LOCAL_INLINE(PyObject *)
STRINGLIB(split_whitespace)(PyObject* str_obj,
const STRINGLIB_CHAR* str, Py_ssize_t str_len,
Py_ssize_t maxcount)
{
Py_ssize_t i, j, count=0;
PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
PyObject *sub;
if (list == NULL)
return NULL;
i = j = 0;
while (maxcount-- > 0) {
while (i < str_len && STRINGLIB_ISSPACE(str[i]))
i++;
if (i == str_len) break;
j = i; i++;
while (i < str_len && !STRINGLIB_ISSPACE(str[i]))
i++;
#if !STRINGLIB_MUTABLE
if (j == 0 && i == str_len && STRINGLIB_CHECK_EXACT(str_obj)) {
/* No whitespace in str_obj, so just use it as list[0] */
Py_INCREF(str_obj);
PyList_SET_ITEM(list, 0, (PyObject *)str_obj);
count++;
break;
}
#endif
SPLIT_ADD(str, j, i);
}
if (i < str_len) {
/* Only occurs when maxcount was reached */
/* Skip any remaining whitespace and copy to end of string */
while (i < str_len && STRINGLIB_ISSPACE(str[i]))
i++;
if (i != str_len)
SPLIT_ADD(str, i, str_len);
}
FIX_PREALLOC_SIZE(list);
return list;
onError:
Py_DECREF(list);
return NULL;
}
Py_LOCAL_INLINE(PyObject *)
STRINGLIB(split_char)(PyObject* str_obj,
const STRINGLIB_CHAR* str, Py_ssize_t str_len,
const STRINGLIB_CHAR ch,
Py_ssize_t maxcount)
{
Py_ssize_t i, j, count=0;
PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
PyObject *sub;
if (list == NULL)
return NULL;
i = j = 0;
while ((j < str_len) && (maxcount-- > 0)) {
for(; j < str_len; j++) {
/* I found that using memchr makes no difference */
if (str[j] == ch) {
SPLIT_ADD(str, i, j);
i = j = j + 1;
break;
}
}
}
#if !STRINGLIB_MUTABLE
if (count == 0 && STRINGLIB_CHECK_EXACT(str_obj)) {
/* ch not in str_obj, so just use str_obj as list[0] */
Py_INCREF(str_obj);
PyList_SET_ITEM(list, 0, (PyObject *)str_obj);
count++;
} else
#endif
if (i <= str_len) {
SPLIT_ADD(str, i, str_len);
}
FIX_PREALLOC_SIZE(list);
return list;
onError:
Py_DECREF(list);
return NULL;
}
Py_LOCAL_INLINE(PyObject *)
STRINGLIB(split)(PyObject* str_obj,
const STRINGLIB_CHAR* str, Py_ssize_t str_len,
const STRINGLIB_CHAR* sep, Py_ssize_t sep_len,
Py_ssize_t maxcount)
{
Py_ssize_t i, j, pos, count=0;
PyObject *list, *sub;
if (sep_len == 0) {
PyErr_SetString(PyExc_ValueError, "empty separator");
return NULL;
}
else if (sep_len == 1)
return STRINGLIB(split_char)(str_obj, str, str_len, sep[0], maxcount);
list = PyList_New(PREALLOC_SIZE(maxcount));
if (list == NULL)
return NULL;
i = j = 0;
while (maxcount-- > 0) {
pos = FASTSEARCH(str+i, str_len-i, sep, sep_len, -1, FAST_SEARCH);
if (pos < 0)
break;
j = i + pos;
SPLIT_ADD(str, i, j);
i = j + sep_len;
}
#if !STRINGLIB_MUTABLE
if (count == 0 && STRINGLIB_CHECK_EXACT(str_obj)) {
/* No match in str_obj, so just use it as list[0] */
Py_INCREF(str_obj);
PyList_SET_ITEM(list, 0, (PyObject *)str_obj);
count++;
} else
#endif
{
SPLIT_ADD(str, i, str_len);
}
FIX_PREALLOC_SIZE(list);
return list;
onError:
Py_DECREF(list);
return NULL;
}
Py_LOCAL_INLINE(PyObject *)
STRINGLIB(rsplit_whitespace)(PyObject* str_obj,
const STRINGLIB_CHAR* str, Py_ssize_t str_len,
Py_ssize_t maxcount)
{
Py_ssize_t i, j, count=0;
PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
PyObject *sub;
if (list == NULL)
return NULL;
i = j = str_len - 1;
while (maxcount-- > 0) {
while (i >= 0 && STRINGLIB_ISSPACE(str[i]))
i--;
if (i < 0) break;
j = i; i--;
while (i >= 0 && !STRINGLIB_ISSPACE(str[i]))
i--;
#if !STRINGLIB_MUTABLE
if (j == str_len - 1 && i < 0 && STRINGLIB_CHECK_EXACT(str_obj)) {
/* No whitespace in str_obj, so just use it as list[0] */
Py_INCREF(str_obj);
PyList_SET_ITEM(list, 0, (PyObject *)str_obj);
count++;
break;
}
#endif
SPLIT_ADD(str, i + 1, j + 1);
}
if (i >= 0) {
/* Only occurs when maxcount was reached */
/* Skip any remaining whitespace and copy to beginning of string */
while (i >= 0 && STRINGLIB_ISSPACE(str[i]))
i--;
if (i >= 0)
SPLIT_ADD(str, 0, i + 1);
}
FIX_PREALLOC_SIZE(list);
if (PyList_Reverse(list) < 0)
goto onError;
return list;
onError:
Py_DECREF(list);
return NULL;
}
Py_LOCAL_INLINE(PyObject *)
STRINGLIB(rsplit_char)(PyObject* str_obj,
const STRINGLIB_CHAR* str, Py_ssize_t str_len,
const STRINGLIB_CHAR ch,
Py_ssize_t maxcount)
{
Py_ssize_t i, j, count=0;
PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
PyObject *sub;
if (list == NULL)
return NULL;
i = j = str_len - 1;
while ((i >= 0) && (maxcount-- > 0)) {
for(; i >= 0; i--) {
if (str[i] == ch) {
SPLIT_ADD(str, i + 1, j + 1);
j = i = i - 1;
break;
}
}
}
#if !STRINGLIB_MUTABLE
if (count == 0 && STRINGLIB_CHECK_EXACT(str_obj)) {
/* ch not in str_obj, so just use str_obj as list[0] */
Py_INCREF(str_obj);
PyList_SET_ITEM(list, 0, (PyObject *)str_obj);
count++;
} else
#endif
if (j >= -1) {
SPLIT_ADD(str, 0, j + 1);
}
FIX_PREALLOC_SIZE(list);
if (PyList_Reverse(list) < 0)
goto onError;
return list;
onError:
Py_DECREF(list);
return NULL;
}
Py_LOCAL_INLINE(PyObject *)
STRINGLIB(rsplit)(PyObject* str_obj,
const STRINGLIB_CHAR* str, Py_ssize_t str_len,
const STRINGLIB_CHAR* sep, Py_ssize_t sep_len,
Py_ssize_t maxcount)
{
Py_ssize_t j, pos, count=0;
PyObject *list, *sub;
if (sep_len == 0) {
PyErr_SetString(PyExc_ValueError, "empty separator");
return NULL;
}
else if (sep_len == 1)
return STRINGLIB(rsplit_char)(str_obj, str, str_len, sep[0], maxcount);
list = PyList_New(PREALLOC_SIZE(maxcount));
if (list == NULL)
return NULL;
j = str_len;
while (maxcount-- > 0) {
pos = FASTSEARCH(str, j, sep, sep_len, -1, FAST_RSEARCH);
if (pos < 0)
break;
SPLIT_ADD(str, pos + sep_len, j);
j = pos;
}
#if !STRINGLIB_MUTABLE
if (count == 0 && STRINGLIB_CHECK_EXACT(str_obj)) {
/* No match in str_obj, so just use it as list[0] */
Py_INCREF(str_obj);
PyList_SET_ITEM(list, 0, (PyObject *)str_obj);
count++;
} else
#endif
{
SPLIT_ADD(str, 0, j);
}
FIX_PREALLOC_SIZE(list);
if (PyList_Reverse(list) < 0)
goto onError;
return list;
onError:
Py_DECREF(list);
return NULL;
}
Py_LOCAL_INLINE(PyObject *)
STRINGLIB(splitlines)(PyObject* str_obj,
const STRINGLIB_CHAR* str, Py_ssize_t str_len,
int keepends)
{
/* This does not use the preallocated list because splitlines is
usually run with hundreds of newlines. The overhead of
switching between PyList_SET_ITEM and append causes about a
2-3% slowdown for that common case. A smarter implementation
could move the if check out, so the SET_ITEMs are done first
and the appends only done when the prealloc buffer is full.
That's too much work for little gain.*/
Py_ssize_t i;
Py_ssize_t j;
PyObject *list = PyList_New(0);
PyObject *sub;
if (list == NULL)
return NULL;
for (i = j = 0; i < str_len; ) {
Py_ssize_t eol;
/* Find a line and append it */
while (i < str_len && !STRINGLIB_ISLINEBREAK(str[i]))
i++;
/* Skip the line break reading CRLF as one line break */
eol = i;
if (i < str_len) {
if (str[i] == '\r' && i + 1 < str_len && str[i+1] == '\n')
i += 2;
else
i++;
if (keepends)
eol = i;
}
#if !STRINGLIB_MUTABLE
if (j == 0 && eol == str_len && STRINGLIB_CHECK_EXACT(str_obj)) {
/* No linebreak in str_obj, so just use it as list[0] */
if (PyList_Append(list, str_obj))
goto onError;
break;
}
#endif
SPLIT_APPEND(str, j, eol);
j = i;
}
return list;
onError:
Py_DECREF(list);
return NULL;
}
|
C | //
// Created by sayan on 11/21/18.
// Adapted from http://moodycamel.com/blog/2013/a-fast-lock-free-queue-for-c++
//
#include "hclasses.h"
#define MEMORY_ORDER_RELAXED 0
#define MEMORY_ORDER_ACQUIRE GASNETT_ATOMIC_ACQ
#define MEMORY_ORDER_RELEASE GASNETT_ATOMIC_REL
const char* HQUEUE_TAGSTR = "QIEU";
struct _hqueue_t
{
gasnett_atomic_t head;
size_t local_tail;
char cachelinefiller0[GASNETI_CACHE_LINE_BYTES - sizeof(gasnett_atomic_t) - sizeof(size_t)];
gasnett_atomic_t tail;
size_t local_head;
char cachelinefiller1[GASNETI_CACHE_LINE_BYTES - sizeof(gasnett_atomic_t) - sizeof(size_t)];
char *data;
size_t size_mask;
char *raw_self;
uint32_t tag;
};
typedef void* item_t;
hqueue_t *hqueue_new(size_t capacity)
{
/// Round off capacity to nearest power of 2 (round up)
--capacity;
capacity |= capacity >> 1;
capacity |= capacity >> 2;
capacity |= capacity >> 4;
for (size_t i = 1; i < sizeof(size_t); i <<= 1) {
capacity |= capacity >> (i << 3);
}
++capacity;
/// find alignments
size_t alignof_hq = __alignof__(hqueue_t);
size_t alignof_it = __alignof__(item_t);
size_t size = sizeof(hqueue_t) + alignof_hq - 1;
size += sizeof(item_t) * capacity + alignof_it - 1;
/// allocate memory
char *new_hq_raw = hmalloc(char, size);
char *hq_ptr_aligned =
new_hq_raw + (alignof_hq - ((uintptr_t)new_hq_raw % alignof_hq)) % alignof_hq;
char *data_ptr = hq_ptr_aligned + sizeof(hqueue_t);
char *data_ptr_aligned =
data_ptr + (alignof_it - ((uintptr_t)data_ptr % alignof_it)) % alignof_it;
/// fix references
hqueue_t *self = (hqueue_t *)hq_ptr_aligned;
self->tag = *((uint32_t *)HQUEUE_TAGSTR);
self->data = data_ptr_aligned;
self->raw_self = new_hq_raw;
self->local_tail = 0;
self->local_head = 0;
self->size_mask = capacity - 1;
/// perform a full fence (seq_cst)
gasnett_atomic_set(&self->head, 0, GASNETT_ATOMIC_MB_PRE); // NOLINT
gasnett_atomic_set(&self->tail, 0, GASNETT_ATOMIC_MB_POST); // NOLINT
return self;
}
void hqueue_destroy(hqueue_t **self_p)
{
if (self_p)
{
hqueue_t *self = *self_p;
if (self)
{
self->tag = 0xdeadbeef;
hfree(self->raw_self);
*self_p = NULL;
}
}
}
bool hqueue_is(void *self)
{
assert(self);
return ((hqueue_t *)self)->tag == *((uint32_t *)HQUEUE_TAGSTR);
}
bool hqueue_try_push(hqueue_t *self, item_t item)
{
assert(hqueue_is(self));
size_t head = self->local_head;
size_t tail = gasnett_atomic_read(&self->tail, MEMORY_ORDER_RELAXED);
size_t next = (tail + 1) & self->size_mask;
if (next != head || next != (self->local_head = gasnett_atomic_read(&self->head, MEMORY_ORDER_ACQUIRE)))
{
/// there is room for at least one more element
char *location = self->data + tail * sizeof(item_t);
memcpy(location, (char *)&item, sizeof(item_t));
gasnett_atomic_set(&self->tail, next, MEMORY_ORDER_RELEASE);
return true;
}
return false;
}
bool hqueue_try_pop(hqueue_t *self, item_t *item_p)
{
assert(hqueue_is(self));
assert(item_p);
size_t tail = self->local_tail;
size_t head = gasnett_atomic_read(&self->head, MEMORY_ORDER_RELAXED);
if (head != tail || head != (self->local_tail = gasnett_atomic_read(&self->tail, MEMORY_ORDER_ACQUIRE)))
{
char *location = self->data + head * sizeof(item_t);
memcpy((char *)item_p, location, sizeof(item_t));
head = (head + 1) & self->size_mask;
gasnett_atomic_set(&self->head, head, MEMORY_ORDER_RELEASE);
return true;
}
return false;
} |
C | #include <string.h>
#include <stdio.h>
int main(int argc, char* argv[]){
double num = 11.0111111111;
char arr[200];
sprintf(arr, "%2.13f", num);
int end=1;
int i=0;
while(end!=0x00){
printf("%c\n and size of arr %lu",arr[i],sizeof(arr));
i++;
end=arr[i];
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
main(){
int array[10];
int file;
char *filename = "./ehaasch_foo.txt";
char buffer[20];
printf("Enter 10 integers: \n");
file = open(filename, O_WRONLY | O_CREAT, 0644);
if (file == -1) {
fprintf(stderr, "File %s could not be opened\n", filename);
exit(1);
}
int i;
for (i=0;i<10;i++){
scanf("%d", &array[i]);
}
for (i=9;i>=0;i--){
printf("%d ", array[i]);
sprintf(buffer, "%d ", array[i]);
write(file, buffer, strlen(buffer));
}
close(file);
return 0;
}
|
C | #pragma once
static const char *ALPHA_BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/*
* ַתΪBase64
*/
void char2base64(const char *buf, const long size, char *base64Char) {
int a = 0;
int i = 0;
while (i < size) {
char b0 = buf[i++];
char b1 = (i < size) ? buf[i++] : 0;
char b2 = (i < size) ? buf[i++] : 0;
int int63 = 0x3F; // 00111111
int int255 = 0xFF; // 11111111
base64Char[a++] = ALPHA_BASE[(b0 >> 2) & int63];
base64Char[a++] = ALPHA_BASE[((b0 << 4) | ((b1 & int255) >> 4)) & int63];
base64Char[a++] = ALPHA_BASE[((b1 << 2) | ((b2 & int255) >> 6)) & int63];
base64Char[a++] = ALPHA_BASE[b2 & int63];
}
int temp = a;
switch (size % 3) {
case 1:
base64Char[--temp] = '=';
case 2:
base64Char[--temp] = '=';
}
base64Char[a] = '\0';
}
/*
* Base64תΪַʽ
*/
void base642char(const char *base64Char, const long base64CharSize, char *originChar, long originCharSize) {
int toInt[128] = { -1 };
for (int i = 0; i < 64; i++) {
toInt[ALPHA_BASE[i]] = i;
}
int int255 = 0xFF;
int index = 0;
for (int i = 0; i < base64CharSize; i += 4) {
int c0 = toInt[base64Char[i]];
int c1 = toInt[base64Char[i + 1]];
originChar[index++] = (((c0 << 2) | (c1 >> 4)) & int255);
if (index >= originCharSize) {
return;
}
int c2 = toInt[base64Char[i + 2]];
originChar[index++] = (((c1 << 4) | (c2 >> 2)) & int255);
if (index >= originCharSize) {
return;
}
int c3 = toInt[base64Char[i + 3]];
originChar[index++] = (((c2 << 6) | c3) & int255);
}
}
/*
* charתΪƣÿַ8λ
*/
void char2Bits(const char* buf, int size, int* bits)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < 8; j++)
bits[i * 8 + 7 - j] = ((buf[i] >> j) & 1);
}
/*
* תΪchar
*/
void bits2char(const int* bits, int size, char* buf)
{
int sum = 0, count = 0;
for (int i = 0; i < size; i++) {
sum = sum * 2 + bits[i];
if (i % 8 == 7) {
buf[count++] = sum;
sum = 0;
}
}
}
/*
* 鿽
*/
void copyArray(int* dest, int* src, int size)
{
for (int i = 0; i < size; i++)
dest[i] = src[i];
} |
C | /* Build an (unbalanced) binary search tree of words in input. */
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void * xrealloc(void *buf, size_t num, size_t siz, void *end);
FILE * xfopen(const char *path, const char *mode);
typedef struct string{ char *start, *end; size_t cap; } string;
typedef struct int_buffer { int *start, *end; size_t cap; } int_buffer;
struct entry {
char *word;
int count; /* Number of times this word appears */
struct int_buffer lines; /* Lines in which the word appears */
struct entry *node[2];
};
#define expand(T) static void \
push_##T(int c, T *b) \
{ \
if( b->start == NULL || b->end >= b->start + b->cap ) { \
b->start = xrealloc(b->start, b->cap += 128, \
sizeof *b->start, &b->end); \
} \
*b->end++ = c; \
}
expand(int_buffer)
expand(string)
#undef expand
#define push(c, X) _Generic((X), \
struct int_buffer *: push_int_buffer, \
struct string *: push_string \
)(c, X)
static int
index_s(struct string *s, int i)
{
if( i >= 0 ) {
return s->start + i < s->end ? s->start[i] : EOF;
} else {
return s->start <= s->end + i ? s->end[i] : EOF;
}
}
static struct entry *
new_node(const char *word)
{
struct entry *e = calloc(1, sizeof *e);
if( e == NULL ){
perror("calloc");
exit(EXIT_FAILURE);
}
if( (e->word = strdup(word)) == NULL ){
perror("out of memory");
exit(EXIT_FAILURE);
}
return e;
}
/* Find an entry in the table, or insert if not present. */
static struct entry *
lookup(struct entry **table, const char *word)
{
struct entry *t = *table;
if( t ) {
int cmp = strcasecmp(word, t->word);
if( cmp != 0 ) {
t = lookup(&t->node[cmp > 0], word);
}
} else {
t = *table = new_node(word);
}
return t;
}
static void
process_word(struct entry **table, int line, const struct string *w)
{
struct entry *e = lookup(table, w->start);
assert( e != NULL );
e->count += 1;
push(line, &e->lines);
}
/* In-order descent of the tree, printing one line per entry */
static void
print_table(const struct entry *t)
{
if( t ) {
print_table(t->node[0]);
printf("%s: {%d:", t->word, t->count);
for( int i = 0; i < t->count - 1; i++ ) {
printf("%d,", t->lines.start[i]);
}
printf("%d}\n", t->lines.start[t->count - 1]);
print_table(t->node[1]);
}
}
static void
free_table(struct entry *t)
{
if( t ) {
free_table(t->node[0]);
free_table(t->node[1]);
free(t->lines.start);
free(t->word);
free(t);
}
}
static void *
xrealloc(void *buf, size_t num, size_t siz, void *endvp)
{
char **e = endvp, *s = buf;
ptrdiff_t offset = s && e && *e ? *e - s : 0;
/* Without this printf, getting segfaults with -O2. TODO */
/* printf(stderr, "num = %zd\n", num); */
s = realloc(s, num * siz);
if( s == NULL ){
perror("realloc");
exit(EXIT_FAILURE);
}
if( e != NULL ){
*e = s + offset;
}
return s;
}
int (*is_word)(int) = isalnum;
static int
get_word(struct string *w, FILE *ifp)
{
int b, c;
int rv = 0;
while( (b = c = fgetc(ifp)) != EOF && is_word(c)){
push(tolower(c), w);
rv = 1;
}
/* Handle some edge cases. */
if( strchr("-,'", b) ) {
c = fgetc(ifp);
if( b == '-' && c == '\n' ) {
/* hyphen at end of word */
return get_word(w, ifp);
} else if(
(b == '-' && is_word(c)) /* embedded hyphen in a word */
|| (b == ',' && isdigit(index_s(w, -1)) && isdigit(c) )
|| (b == '\'' && isalpha(c))
){
push(b, w);
ungetc(c, ifp);
return get_word(w, ifp);
}
}
push('\0', w);
if( c != EOF ){
ungetc(c, ifp);
}
return rv;
}
/* Discard all input that is not a word. */
static int
skip_non(int *line, FILE *ifp)
{
int c;
while( (c = fgetc(ifp)) != EOF && !is_word(c) ){
if( c == '\n' ) {
*line += 1;
}
}
if( c != EOF ){
ungetc(c, ifp);
}
return c != EOF;
}
int
main(int argc, char **argv)
{
FILE *ifp = argc > 1 ? xfopen(argv[1], "r") : stdin;
struct string word = {0};
struct entry *table = NULL;
int line = 1;
while( skip_non(&line, ifp) && get_word(&word, ifp) ){
process_word(&table, line, &word);
word.end = word.start;
}
print_table(table);
free_table(table);
free(word.start);
}
FILE *
xfopen(const char *path, const char *mode)
{
FILE *fp = path[0] != '-' || path[1] != '\0' ? fopen(path, mode) :
*mode == 'r' ? stdin : stdout;
if( fp == NULL ){
perror(path);
exit(EXIT_FAILURE);
}
return fp;
}
|
C | #include <errno.h>
//#include <pthread.h>
//#include <semaphore.h>
#include <signal.h>
//#include "buffer.h"
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
pthread_t thid1,thid2,thid3,thid4,thid5;
/*****************************************************************/
void *dispaly5(void *arg)
{
printf("START thread 5\n");
//sleep(2);
while(1){
printf("Hey I am thread 5\n");
//sleep(2);
}
pthread_exit(NULL);
}
/******************#include <pthread.h>***********************************************/
void *dispaly4(void *arg)
{
printf("START thread 4\n");
//sleep(2);
while(1){
printf("Hey I am thread 4\n");
//sleep(2);
}
pthread_exit(NULL);
}
/*****************************************************************/
void *dispaly3(void *arg){
printf("START thread 3\n");
//sleep(2);
while(1){
printf("Hey I am thread 3\n");
//sleep(2);
}
pthread_exit(NULL);
}
/*****************************************************************/
void *dispaly2(void *arg)
{
printf("START thread 2\n");
//sleep(2);
while(1){
printf("Hey I am thread 2\n");
//sleep(2);
}
pthread_pthread_exitexit(NULL);
}
/*****************************************************************/
void *dispaly1(void *arg)
{
printf("START thread 1\n");
//sleep(2);
while(1){
printf("Hey I am thread 1\n");
//sleep(2);
}
pthread_exit(NULL);
}
/*****************************************************************/
int main(){
int ret;
ret = pthread_create(&thid5,NULL,dispaly5,NULL);
if(ret>0) { printf("error in thread creation 5\n");
exit(4); }
ret = pthread_create(&thid4,NULL,dispaly4,NULL);
if(ret>0) { printf("error in thread creation 4\n");
exit(4); }
ret = pthread_create(&thid3,NULL,dispaly3,NULL);
if(ret>0) { printf("error in thread creation 3\n");
exit(4); }
ret = pthread_create(&thid2,NULL,dispaly2,NULL);
if(ret>0) { printf("error in thread creation 2\n");
exit(4); }
ret = pthread_create(&thid1,NULL,dispaly1,NULL);
if(ret>0) { printf("error in thread creation 1\n");
exit(4); }
pthread_join(thid1,NULL);
pthread_join(thid2,NULL);
pthread_join(thid3,NULL);
pthread_join(thid4,NULL);
pthread_join(thid5,NULL);
exit(0);
}
|
C | /**
* Quadrofly Software (http://quadrofly.ni-c.de)
*
* @file controller/lib/pid.c
* @brief PID controller
* @ingroup controller
* @author Willi Thiel ([email protected])
* @date Apr 29, 2012
*/
#include "main.h"
#include "pid.h"
#include <stdlib.h>
#include <inttypes.h>
#ifdef EEPROM_AVAILABLE
#include <avr/eeprom.h>
#endif /* EEPROM_AVAILABLE */
static float pid_e_sum[4] = { 0, 0, 0, 0 }; /*!< Sum of last errors */
static float pid_e_old[4] = { 0, 0, 0, 0 }; /*!< Last error */
/* PID values */
float pid_p = PID_KP; /*!< Factor P */
float pid_i = PID_KI; /*!< Factor I */
float pid_d = PID_KD; /*!< Factor D */
float pid_max_error_sum = PID_MAX_ERROR_SUM; /*!< Max errors we sum, more errors will be ignored */
float pid_error_cap = PID_ERROR_CAP; /*!< An error below this cap invalidates all errors and starts from scratch */
#ifdef EEPROM_AVAILABLE
static float EEMEM ee_pid_p = PID_KP; /*!< EEMEM var for pid_p */
static float EEMEM ee_pid_i = PID_KI; /*!< EEMEM var for pid_i */
static float EEMEM ee_pid_d = PID_KD; /*!< EEMEM var for pid_d */
static float EEMEM ee_pid_max_error_sum = PID_MAX_ERROR_SUM; /*!< EEMEM var for max_error_sum */
static float EEMEM ee_pid_error_cap = PID_ERROR_CAP; /*!< EEMEM var for error_cap */
#endif /* EEPROM_AVAILABLE */
/**
* Initialize PID controller and read settings from EEPROM
*/
void pid_init(void) {
#ifdef EEPROM_AVAILABLE
/* Read vars from EEPROM */
pid_p = eeprom_read_float(&ee_pid_p);
pid_i = eeprom_read_float(&ee_pid_i);
pid_d = eeprom_read_float(&ee_pid_d);
pid_max_error_sum = eeprom_read_float(&ee_pid_max_error_sum);
pid_error_cap = eeprom_read_float(&ee_pid_error_cap);
#endif /* EEPROM_AVAILABLE */
}
/**
* Writes the PID variables to the EEPROM
*/
void pid_eeprom_write(void) {
#ifdef EEPROM_AVAILABLE
eeprom_update_float(&ee_pid_p, pid_p);
eeprom_update_float(&ee_pid_i, pid_i);
eeprom_update_float(&ee_pid_d, pid_d);
eeprom_update_float(&ee_pid_max_error_sum, pid_max_error_sum);
eeprom_update_float(&ee_pid_error_cap, pid_error_cap);
#endif /* EEPROM_AVAILABLE */
}
/**
* PID controller
*
* @param target The target value to reach
* @param actual The actual value
* @param key A unique key to identify the pid filter (0..3)
* @return The calculated PID control value
*/
float pid_calculate(float target, float actual, uint8_t key) {
float e; /*!< Error */
float Ki; /*!< Temporary Factor I */
float u_p; /*!< P value */
float u_i; /*!< I value */
float u_d; /*!< D value */
float result; /*!< The result */
/* Error */
e = (target - actual);
/* I part extensions */
pid_e_sum[key] += e;
if (abs(e) <= pid_error_cap) {
Ki = 0;
pid_e_sum[key] = 0;
} else {
Ki = pid_i;
if (pid_e_sum[key] >= pid_max_error_sum) {
pid_e_sum[key] = pid_max_error_sum;
} else if (pid_e_sum[key] <= -pid_max_error_sum) {
pid_e_sum[key] = -pid_max_error_sum;
}
}
/* P */
u_p = e * pid_p;
/* I */
u_i = pid_e_sum[key] * Ki;
/* D */
u_d = (e - pid_e_old[key]) * pid_d;
pid_e_old[key] = e;
result = 1.0 + ((u_p + u_i + u_d) / PID_SENSITIVITY);
if (result > 2.0) {
result = 2.0;
} else if (result < 0.0) {
result = 0.0;
}
return result;
}
|
C | #include <stdio.h>
int isEven(int num){
if(num%2==0){
return 1; // if even
}
return 0; // if not even
}
int main(){
printf("1: %d\n",isEven(1));
printf("2: %d\n",isEven(2));
return 0;
}
|
C | // finding the nth number in the series.
#include<stdio.h>
#include<math.h>
int main()
{
int i;
printf("input");
scanf("%d",&i);
int a[8] = {1,5,13,25,41,61,85,113};
printf("Output : %d",a[i-1]);
return 0;
}
|
C |
// print pyramid by abc
#include <stdio.h>
char abcArray[26] = {'A','B','C','D','E','F','G','H','I','J','K','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
void printabcArray();
void printPyramid();
int sizeofarray = sizeof(abcArray) / sizeof(abcArray[0]); // to count how many elements in array
int row;
int main() {
printf("Enter a number of row? ");
scanf("%d", &row);
printf("%d\n", row);
// printabcArray();
printPyramid();
}
void printabcArray() { // remember the last elements of array is '/0'
for (int i=0; i<sizeofarray; i++) {
printf("%c, ", abcArray[i]);
}
}
void printPyramid() { // only allow for 26 due to the number of alphabets
for (int i=0; i<row; ++i) {
int positions = i;
for (int j=0; j<=i; ++j) {
if(positions > 25) {
positions = positions - 26;
}
printf("%c", abcArray[positions]);
}
printf("\n");
}
}
|
C | #include "smp_calendar.h"
#include "smp_spin.h"
#include "smp.h"
#include "i18n.h"
//supported year֧һ
#define SMP_CALENDAR_YEAR_MIN 1900
#define SMP_CALENDAR_YEAR_MAX 2100
//supported month֧
#define SMP_CALENDAR_MONTH_MIN 1
#define SMP_CALENDAR_MONTH_MAX 12
#define SMP_CALENDAR_SPIN_YEAR 1 //year spin widŮ뷢չ
#define SMP_CALENDAR_SPIN_YEAR_X SMP_ITEM_SPACE //year spin leftת
#define SMP_CALENDAR_SPIN_YEAR_WIDTH 90 //year spin width
#define SMP_CALENDAR_STR_YEAR_X (SMP_CALENDAR_SPIN_YEAR_X + SMP_CALENDAR_SPIN_YEAR_WIDTH + SMP_ITEM_SPACE) //year string left
#define SMP_CALENDAR_SPIN_MONTH 2 //month spin widŮ뷢չ
#define SMP_CALENDAR_SPIN_MONTH_X (SMP_CALENDAR_SPIN_YEAR_WIDTH + SMP_ITEM_HEIGHT + 3*SMP_ITEM_SPACE) //month spin left
#define SMP_CALENDAR_SPIN_MONTH_WIDTH 70 //month spin width
#define SMP_CALENDAR_STR_MONTH_X (SMP_CALENDAR_SPIN_MONTH_X + SMP_CALENDAR_SPIN_MONTH_WIDTH + SMP_ITEM_SPACE) //month string left
#define SMP_CALENDAR_WEEKDAY_TITLE_X SMP_ITEM_SPACE //weekday bar left spaceƽռ
//calendar data
typedef struct SMP_CalendarData
{
int year; //current yearǰ
int month; //current monthǰ
int day; //current dayǰ
int32 dayw, dayh; //temp information for the controlΪ¶Ϣ
}CALDATA, *PCALDATA;
////////////////////////////////////////////////////////////////
const char sStrDays[32][3] =
{
" 0", " 1", " 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
"30", "31"
};
//ڼ
static int CaculateWeekDay(int year, int month, int day)
{
int weekday;
//һºͶ±ǰһ
if((month==1) || (month==2))
{
month += 12;
year--;
}
weekday = (day + 2*month + 3*(month+1)/5 + year + year/4 - year/100 + year/400)%7 + 1;
if(weekday==7) weekday=0;
return weekday;
}
//ڣijж
static int DaysOfMonth(int year, int month)
{
static const char sDays[2][12] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
if(month < 1){
month += 12;
year--;
}
else if(month > 12){
month -= 12;
year++;
}
return sDays[(year%100!=0 && year%4==0) || year%400==0][month-1];
}
static VOID SMP_Calendar_HighLightDate(HWND hWnd, int DayOld, int DayNew)
{
PCALDATA pData = _GET_WINDATA(hWnd, PCALDATA);
int weekday = CaculateWeekDay(pData->year, pData->month, 1);
int step, x = SMP_CALENDAR_WEEKDAY_TITLE_X, y = 2*SMP_ITEM_HEIGHT + 2;
SGL_WindowToScreen(hWnd, &x, &y);
step = (_WIDTH(hWnd) - 2*SMP_CALENDAR_WEEKDAY_TITLE_X) /7;
DayOld += weekday - 1;
GAL_Rectangle(PHYSICALGC, x + step * MOD(DayOld, 7), y + pData->dayh * DIV(DayOld, 7), step, pData->dayh, COLOR_lightwhite);
GAL_FlushRegion(PHYSICALGC, x + step * MOD(DayOld, 7), y + pData->dayh * DIV(DayOld, 7), step, pData->dayh);
DayNew += weekday - 1;
GAL_Rectangle(PHYSICALGC, x + step * MOD(DayNew, 7), y + pData->dayh * DIV(DayNew, 7), step, pData->dayh, COLOR_red);
GAL_FlushRegion(PHYSICALGC, x + step * MOD(DayNew, 7), y + pData->dayh * DIV(DayNew, 7), step, pData->dayh);
}
static VOID SMP_Calendar_UpdateValuesToSpins(HWND hWnd)
{
HWND hControl;
PCALDATA pData = _GET_WINDATA(hWnd, PCALDATA);
hControl = SGL_FindChildWindow(hWnd, SMP_CALENDAR_SPIN_YEAR);
SMP_Spin_SetValue(hControl, pData->year, FALSE, FALSE);
hControl = SGL_FindChildWindow(hWnd, SMP_CALENDAR_SPIN_MONTH);
SMP_Spin_SetValue(hControl, pData->month, FALSE, FALSE);
}
static VOID SMP_Calendar_MoveByStep(HWND hWnd, int step)
{
PCALDATA pData = _GET_WINDATA(hWnd, PCALDATA);
int year = pData->year;
int month = pData->month;
int day = pData->day;
day += step;
if(day < 1)
{
--month;
day = DaysOfMonth(pData->year, month);
}else if(day > DaysOfMonth(pData->year, pData->month)){
++month;
day = 1;
}
if(month < 1)
{
month = 12;
--year;
}else if(month > 12){
month = 1;
++year;
}
if(year < SMP_CALENDAR_YEAR_MIN || year > SMP_CALENDAR_YEAR_MAX)
return;
if(year == pData->year && month == pData->month)
{
SMP_Calendar_HighLightDate(hWnd, pData->day, day);
pData->day = day;
}else{
pData->year = year;
pData->month = month;
pData->day = day;
SMP_Calendar_UpdateValuesToSpins(hWnd);
SGL_UpdateWindow(hWnd);
}
}
VOID SMP_Calendar_GetDate(HWND hWnd, int * year, int * month, int * day)
{
PCALDATA pData = _GET_WINDATA(hWnd, PCALDATA);
if(year) *year = pData->year;
if(month) *month = pData->month;
if(day) *day = pData->day;
}
VOID SMP_Calendar_SetDate(HWND hWnd, int year, int month, int day)
{
PCALDATA pData = _GET_WINDATA(hWnd, PCALDATA);
if(year < SMP_CALENDAR_YEAR_MIN || year > SMP_CALENDAR_YEAR_MAX
|| month < SMP_CALENDAR_MONTH_MIN || month > SMP_CALENDAR_MONTH_MAX
|| day < 1 || day > DaysOfMonth(year, month))
return;
pData->year = year;
pData->month = month;
pData->day = day;
}
LRESULT SMP_Calendar_WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
PCALDATA pData = _GET_WINDATA(hWnd, PCALDATA);
switch(Msg)
{
case WM_CREATE:
{
HWND hControl;
//malloc the data
pData = (PCALDATA)SGL_MALLOC(sizeof(CALDATA));
if(NULL == pData){
SGL_TRACE("%s, %d: memory out\n", __FILE__, __LINE__);
return 1;
}
SGL_MEMSET(pData, 0, sizeof(CALDATA));
_SET_WINDATA(hWnd, pData);
//create the children windowsڵĶͯ
//spin of year
hControl = SGL_CreateWindow(SMP_Spin_WndProc,
SMP_CALENDAR_SPIN_YEAR_X, 1, SMP_CALENDAR_SPIN_YEAR_WIDTH, SMP_ITEM_HEIGHT - 1,
SMP_CALENDAR_SPIN_YEAR, 0, 0);
SMP_Spin_SetRange(hControl, SMP_CALENDAR_YEAR_MIN, SMP_CALENDAR_YEAR_MAX, 1);
SGL_AddChildWindow(hWnd, hControl);
_BGCOLOR(hControl) = COLOR_controlbg;
//spin of month
hControl = SGL_CreateWindow(SMP_Spin_WndProc,
SMP_CALENDAR_SPIN_MONTH_X, 1, SMP_CALENDAR_SPIN_MONTH_WIDTH, SMP_ITEM_HEIGHT - 1,
SMP_CALENDAR_SPIN_MONTH, 0, 0);
SMP_Spin_SetRange(hControl, SMP_CALENDAR_MONTH_MIN, SMP_CALENDAR_MONTH_MAX, 1);
SGL_AddChildWindow(hWnd, hControl);
_BGCOLOR(hControl) = COLOR_controlbg;
break;
}
case WM_DESTROY:
{
if(pData) SGL_FREE(pData);
break;
}
case WM_SHOW:
{
if(pData->year == 0 ||pData->month == 0 || pData->day == 0 )
{
mr_datetime date;
mrc_getDatetime(&date);
pData->year = date.year;
pData->month = date.month;
pData->day = date.day;
}
SMP_Calendar_UpdateValuesToSpins(hWnd);
mrc_textWidthHeight((PSTR)sStrDays[31], FALSE, (uint16)SGL_GetSystemFont(), &pData->dayw, &pData->dayh);
pData->dayh += 2;
break;
}
case WM_PAINT:
{
int i, j, step, x = 0, y = 0;
int days, weekday;
int32 wt, ht;
HFONT font = SGL_GetSystemFont();
SGL_WindowToScreen(hWnd, &x, &y);
//draw the title barƱ
mrc_textWidthHeight((PSTR)SGL_LoadString(STR_YEAR), TRUE, (uint16)font, &wt, &ht);
if(_IS_SET_ANY(hWnd, WS_BORDER))
{
GAL_Rectangle(PHYSICALGC, x, y, _WIDTH(hWnd), _HEIGHT(hWnd), COLOR_lightgray);
GAL_FillBox(PHYSICALGC, x + 1, y + 1, _WIDTH(hWnd) - 2, SMP_ITEM_HEIGHT - 1, COLOR_controlbg);
}else{
GAL_FillBox(PHYSICALGC, x, y, _WIDTH(hWnd), SMP_ITEM_HEIGHT, COLOR_controlbg);
}
mrc_drawText((PSTR)SGL_LoadString(STR_YEAR), (int16)SMP_CALENDAR_STR_YEAR_X, (int16)(y + DIV(SMP_ITEM_HEIGHT-ht, 2)), 0, 0, 0, TRUE, (uint16)font);
mrc_drawText((PSTR)SGL_LoadString(STR_MONTH), (int16)SMP_CALENDAR_STR_MONTH_X, (int16)(y + DIV(SMP_ITEM_HEIGHT-ht, 2)), 0, 0, 0, TRUE, (uint16)font);
//draw the weekday title barƱƽ
step = (_WIDTH(hWnd) - 2*SMP_CALENDAR_WEEKDAY_TITLE_X) /7;
y += SMP_ITEM_HEIGHT;
for(i = 0; i < 7; i++)
mrc_drawText((PSTR)SGL_LoadString(STR_SUNDAY + i), (int16)(x+SMP_CALENDAR_WEEKDAY_TITLE_X + i*step), (int16)(y + DIV(SMP_ITEM_HEIGHT - ht, 2)), 0, 0, 0, TRUE, (uint16)font);
y+= SMP_ITEM_HEIGHT;
GAL_Rectangle(PHYSICALGC, x+1, y, _WIDTH(hWnd)-2, 6*pData->dayh + 4, COLOR_lightgray);
weekday = CaculateWeekDay(pData->year, pData->month, 1);
days = DaysOfMonth(pData->year, pData->month);
y += 2; x += SMP_CALENDAR_WEEKDAY_TITLE_X;
for(i = 1; i <= days; i++)
{
j = MOD(weekday + i - 1, 7);
mrc_drawText((PSTR)sStrDays[i], (int16)(x + j*step), (int16)y, 0, 0, 0, FALSE, (uint16)font);
if(i == pData->day)
GAL_Rectangle(PHYSICALGC, x + j*step, y, step, pData->dayh, COLOR_red);
if(j == 6) y+=pData->dayh;
}
break;
}
case WM_KEYDOWN:
case WM_KEYDOWNREPEAT:
{
switch(wParam)
{
case MR_KEY_UP:
SMP_Calendar_MoveByStep(hWnd, -7);
return 1;
case MR_KEY_DOWN:
SMP_Calendar_MoveByStep(hWnd, 7);
return 1;
case MR_KEY_RIGHT:
SMP_Calendar_MoveByStep(hWnd, 1);
return 1;
case MR_KEY_LEFT:
SMP_Calendar_MoveByStep(hWnd, -1);
return 1;
}
break;
}
case WM_KEYUP:
{
switch(wParam)
{
case MR_KEY_SELECT:
SGL_NotifyParent(hWnd, SMP_CALENDARN_SELECTED, hWnd);
return 1;
}
break;
}
case WM_MOUSEDOWN:
case WM_MOUSEUP:
{
if((int)wParam >= SMP_CALENDAR_WEEKDAY_TITLE_X && (int)wParam < _WIDTH(hWnd) - SMP_CALENDAR_WEEKDAY_TITLE_X
&& (int)lParam >= 2*SMP_ITEM_HEIGHT + 2 && (int)lParam < _HEIGHT(hWnd) - 2)
{
int step = (_WIDTH(hWnd) - 2*SMP_CALENDAR_WEEKDAY_TITLE_X) /7;
int day = (wParam - SMP_CALENDAR_WEEKDAY_TITLE_X)/step + (lParam -2*SMP_ITEM_HEIGHT - 2) / pData->dayh * 7;
day -= CaculateWeekDay(pData->year, pData->month, 1) - 1;
if(Msg == WM_MOUSEDOWN){
if(day != pData->day && day > 0 && day <= DaysOfMonth(pData->year, pData->month)){
SMP_Calendar_HighLightDate(hWnd, pData->day, day);
pData->day = day;
}
}
else{
if(day == pData->day)
SGL_NotifyParent(hWnd, SMP_CALENDARN_SELECTED, hWnd);
}
}
break;
}
case WM_COMMAND:
{
WID id = LOWORD(wParam);
//WORD code = HIWORD(wParam); //just one kind notify eventWord= HIWORDwParam; / /ֻһ֪ͨ¼
RECT clip;
if(id == SMP_CALENDAR_SPIN_YEAR)
pData->year = (Sint32)lParam;
else
pData->month = (Sint32)lParam;
if(pData->day > DaysOfMonth(pData->year, pData->month))
pData->day = DaysOfMonth(pData->year, pData->month);
clip.left = 0; clip.top = 2*SMP_ITEM_HEIGHT; clip.width = _WIDTH(hWnd); clip.height = _HEIGHT(hWnd) - clip.top;
SGL_UpdateWindowEx(hWnd, &clip);
break;
}
}
return 0;
}
|
C | #include "main.h"
#define STEPS 100
#define BUDGET 9
int main(int argc, char **argv) {
if (argc < 3) {
printf("Not enough arguments. Must supply and input and output file for evaluation.\n");
return 0;
}
// Buffers for reading inputs
char *inputs_path = argv[1];
char *output_path = argv[2];
FILE *inputs_file = fopen(inputs_path, "r");
FILE *output_file = fopen(output_path, "r");
int buffer_size = NUM_INPUT_FEATURES * SEQ_LENGTH * 6;
char buffer[buffer_size];
uint16_t outputBufferSize = 10;
char outputBuffer[outputBufferSize];
// Initialize an buffer for states
matrix states[SEQ_LENGTH];
int16_t stateData[SEQ_LENGTH * STATE_SIZE * VECTOR_COLS] = {0};
for (uint16_t i = 0; i < SEQ_LENGTH; i++) {
states[i].numRows = STATE_SIZE;
states[i].numCols = VECTOR_COLS;
states[i].data = &stateData[i * STATE_SIZE * VECTOR_COLS];
}
// Initialize a buffer for the logits
matrix logits[NUM_OUTPUTS];
int16_t logitsData[NUM_OUTPUTS * NUM_OUTPUT_FEATURES * VECTOR_COLS] = {0};
for (uint16_t i = 0; i < NUM_OUTPUTS; i++) {
logits[i].numRows = NUM_OUTPUT_FEATURES;
logits[i].numCols = VECTOR_COLS;
logits[i].data = &logitsData[i * NUM_OUTPUT_FEATURES * VECTOR_COLS];
}
// Initialize an input buffer
int16_t data[NUM_INPUT_FEATURES * VECTOR_COLS];
matrix input;
input.numRows = NUM_INPUT_FEATURES;
input.numCols = VECTOR_COLS;
input.data = data;
int16_t output_buffer_size = 5;
char output_buffer[output_buffer_size];
int time = 0;
ExecutionState execState;
// Track test statistics (useful for debugging)
uint16_t numCorrect = 0;
uint16_t numLevels = 0;
int16_t label;
uint16_t levelCounts[NUM_OUTPUTS];
for (uint16_t i = 0; i < NUM_OUTPUTS; i++) {
levelCounts[i] = 0;
}
int32_t energyBudget = int_to_fp32(BUDGET * STEPS, FIXED_POINT_PRECISION);
int16_t thresholds[NUM_OUTPUTS] = { 0 };
// Create the budget distribution
#ifdef IS_BUDGET_RNN
// Load the initial class counts
int16_t budget = int_to_fp(BUDGET, FIXED_POINT_PRECISION);
int32_t classCounts[NUM_OUTPUT_FEATURES][NUM_OUTPUTS];
interpolate_counts(classCounts, budget, FIXED_POINT_PRECISION);
BudgetDistribution distribution;
init_distribution(&distribution, classCounts, STEPS, FIXED_POINT_PRECISION);
// Create the PID controller
PidController controller;
init_pid_controller(&controller, FIXED_POINT_PRECISION);
// Initialize the offset to the budget and get the initial thresholds
int16_t budgetOffset = 0;
interpolate_thresholds(thresholds, fp_add(budget, budgetOffset), FIXED_POINT_PRECISION);
ConfidenceBound bound;
bound.lower = 0;
bound.upper = 0;
#endif
int16_t avgEnergy;
int32_t totalEnergy = 0;
int16_t stepEnergy = 0;
uint8_t updateCounter = UPDATE_WINDOW;
while (fgets(buffer, buffer_size, inputs_file) != NULL) {
// Get the label
fgets(outputBuffer, outputBufferSize, output_file);
label = (int16_t) (outputBuffer[0] - '0');
char *token = strtok(buffer, " ");
// Initialize the execution state
execState.levelsToExecute = 0;
execState.isStopped = 0;
execState.isCompleted = 0;
execState.prediction = -1;
execState.cumulativeUpdateProb = int_to_fp(1, FIXED_POINT_PRECISION);
#ifdef IS_RNN
execState.levelsToExecute = 7;
execState.isStopped = 1;
#endif
// Iterate through the sequence elements
uint16_t i;
for (i = 0; i < SEQ_LENGTH; i++) {
// Fetch features for the i-th element
uint16_t j;
for (j = 0; j < NUM_INPUT_FEATURES; j++) {
input.data[j * VECTOR_COLS] = atoi(token);
token = strtok(NULL, " ");
}
if (should_process(i, &execState)) {
process_input(&input, states, logits, i, thresholds, &execState);
} else {
if (i > 0) {
matrix_replace(states + i, states + (i - 1));
} else {
matrix_set(states + i, 0);
}
}
#ifdef IS_SKIP_RNN
// Update the state update probability
int16_t nextUpdateProb = get_state_update_prob(states + i, execState.cumulativeUpdateProb, FIXED_POINT_PRECISION);
execState.cumulativeUpdateProb = nextUpdateProb;
#endif
}
time += 1;
updateCounter -= 1;
totalEnergy = fp32_add(totalEnergy, ENERGY_ESTIMATES[execState.levelsToExecute]);
// printf("Prediction: %d\n", execState.prediction);
numCorrect += (uint16_t) (execState.prediction == label);
numLevels += execState.levelsToExecute + 1;
#ifdef IS_BUDGET_RNN
levelCounts[execState.levelsToExecute] += 1;
if (updateCounter == 0) {
bound = get_budget(energyBudget, time, STEPS, ENERGY_ESTIMATES, &distribution, FIXED_POINT_PRECISION);
}
avgEnergy = (int16_t) fp32_div(totalEnergy, int_to_fp32(time, FIXED_POINT_PRECISION), FIXED_POINT_PRECISION);
budgetOffset = control_step(bound.lower, bound.upper, avgEnergy, &controller);
// Update the distribution
// stepEnergy = ENERGY_ESTIMATES[execState.levelsToExecute];
// update_distribution(execState.prediction, execState.levelsToExecute, stepEnergy, &distribution, FIXED_POINT_PRECISION);
// prevEnergy = ENERGY_ESTIMATES[execState.levelsToExecute];
if (updateCounter == 0) {
interpolate_thresholds(thresholds, fp_add(budget, budgetOffset), FIXED_POINT_PRECISION);
updateCounter = UPDATE_WINDOW;
}
#endif
if (time % 1000 == 0) {
printf("Finished %d samples\n", time);
}
}
printf("Accuracy for model: %d / %d\n", numCorrect, time);
printf("Average number of levels: %d / %d\n", numLevels, time);
float energyPerStep = ((float) totalEnergy) / ((1 << FIXED_POINT_PRECISION) * STEPS);
printf("Average Energy per Step: %f\n", energyPerStep);
printf("{ ");
for (uint16_t i = 0; i < NUM_OUTPUTS; i++) {
printf("%d ", levelCounts[i]);
}
printf("}\n");
fclose(inputs_file);
fclose(output_file);
return 0;
}
|
C | #include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int hello(int argc, char** argv) {
printf("hello, word!\n");
printf("%s\n", "hello, word!");
printf("%s %s\n", "hello,","1234");
}
int main()
{
int num1; //
int num2;
int num3;
num1 = 10;
num2 = 20;
num3 = 30;
printf("%d %d %d\n", num1, num2, num3); // 10 20 30: %d
return 0;
}
int main2()
{
int num1, num2, num3; // Ͽ
num1 = 10;
num2 = 20;
num3 = 30;
printf("%d %d %d\n", num1, num2, num3); // 10 20 30: %d
return 0;
}
int main3()
{
int num1 = 10;
int num2 = 20, num3 = 30;
printf("%d %d %d\n", num1, num2, num3); // 10 20 30: %d
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include "SL_list.h"
int is_empty(SL_list *LL) {
if(LL == 0) return 1; else return 0;
}
int get_first(SL_list *LL) {
return LL->content;
}
SL_list *get_next(SL_list *LL) {
if(is_empty(LL)) {
printf("ERROR: trying to get_next "
"from NULL pointer\n");
return 0;
}
return LL->next;
}
SL_list *set_next(SL_list *LL, SL_list *new_next) {
LL->next = new_next;
return LL;
}
SL_list *insert_last_2(int val, SL_list *LL) {
if(is_empty(LL))
return insert_first(val, LL);
return set_next(LL, insert_last_2(val, get_next(LL)));
}
SL_list *insert_last(int val, SL_list *LL) {
SL_list *link;
if(is_empty(LL))
return insert_first(val, LL);
link = LL;
while(!is_empty(get_next(link)))
link = get_next(link);
link->next = insert_first(val, 0);
return LL;
}
SL_list *insert_first(int val, SL_list *LL) {
SL_list *res = (SL_list *)malloc(sizeof(SL_list));
res->content = val;
res->next = LL;
return res;
}
SL_list *insert_sorted(int val, SL_list *LL) {
if(is_empty(LL))
return insert_first(val, LL);
if(get_first(LL) < val)
return insert_first(val, LL);
if(is_empty(get_next(LL))) {
LL->next = insert_first(val, EMPTY_LIST);
return LL;
}
if(get_first(get_next(LL)) >= val) {
LL->next = insert_first(val, get_next(LL));
return LL;
}
LL->next = insert_sorted(val, LL->next);
return LL;
}
SL_list *copy_node(SL_list *pLL, SL_list *revLL) {
return insert_first(get_first(pLL), revLL);
}
SL_list *reverse(SL_list *LL) {
SL_list *pLL = LL, *revLL = EMPTY_LIST;
while(!is_empty(pLL)) {
revLL = copy_node(pLL, revLL);
pLL = pLL->next;
}
return revLL;
} |
C | #include <gtk/gtk.h>
int main( int argc,char *argv[] )
{
// 1.gtk初始化工作
gtk_init(&argc, &argv);
// 2.创建一个顶层窗口
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
// 3.1 创建一个table
GtkWidget *table = gtk_table_new(5,4,TRUE);
// 3.2 将table加入到window中
gtk_container_add(GTK_CONTAINER(window),table);
// 4.创建一个行编辑
GtkWidget *entry = gtk_entry_new();
// 设置行编辑的内容
gtk_entry_set_text(GTK_ENTRY(entry), "3+2=4");
// 设置行编辑不允许编辑,只能显示用
gtk_editable_set_editable(GTK_EDITABLE(entry), FALSE);
//5 创建多个按钮
GtkWidget *button0 = gtk_button_new_with_label("0");
GtkWidget *button1 = gtk_button_new_with_label("1");
GtkWidget *button2 = gtk_button_new_with_label("2");
GtkWidget *button3 = gtk_button_new_with_label("3");
GtkWidget *button4 = gtk_button_new_with_label("4");
GtkWidget *button5 = gtk_button_new_with_label("5");
GtkWidget *button6 = gtk_button_new_with_label("6");
GtkWidget *button7 = gtk_button_new_with_label("7");
GtkWidget *button8 = gtk_button_new_with_label("8");
GtkWidget *button9 = gtk_button_new_with_label("9");
GtkWidget *button_add = gtk_button_new_with_label("+");
GtkWidget *button_minus = gtk_button_new_with_label("-");
GtkWidget *button_mul = gtk_button_new_with_label("*");
GtkWidget *button_div = gtk_button_new_with_label("/");
GtkWidget *button_equal = gtk_button_new_with_label("=");
GtkWidget *button_delete = gtk_button_new_with_label("c");
// 6.将上面的按钮放入到table容器中
gtk_table_attach_defaults(GTK_TABLE(table), entry, 0,4,0,1);
gtk_table_attach_defaults(GTK_TABLE(table), button0, 0,1,4,5);
gtk_table_attach_defaults(GTK_TABLE(table), button1, 0,1,3,4);
gtk_table_attach_defaults(GTK_TABLE(table), button2, 1,2,3,4);
gtk_table_attach_defaults(GTK_TABLE(table), button3, 2,3,3,4);
gtk_table_attach_defaults(GTK_TABLE(table), button4, 0,1,2,3);
gtk_table_attach_defaults(GTK_TABLE(table), button5, 1,2,2,3);
gtk_table_attach_defaults(GTK_TABLE(table), button6, 2,3,2,3);
gtk_table_attach_defaults(GTK_TABLE(table), button7, 0,1,1,2);
gtk_table_attach_defaults(GTK_TABLE(table), button8, 1,2,1,2);
gtk_table_attach_defaults(GTK_TABLE(table), button9, 2,3,1,2);
gtk_table_attach_defaults(GTK_TABLE(table), button_add, 1,2,4,5);
gtk_table_attach_defaults(GTK_TABLE(table), button_minus, 2,3,4,5);
gtk_table_attach_defaults(GTK_TABLE(table), button_mul, 3,4,2,3);
gtk_table_attach_defaults(GTK_TABLE(table), button_div, 3,4,3,4);
gtk_table_attach_defaults(GTK_TABLE(table), button_equal, 3,4,4,5);
gtk_table_attach_defaults(GTK_TABLE(table), button_delete, 3,4,1,2);
// 7.显示所有文件
gtk_widget_show_all(window);
// 8.主事件循环
gtk_main();
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <btn/cstr.h>
#include <btn/print.h>
#include <btn/vector.h>
#include "print.h"
#include "option.h"
void print_option(const option * opt)
{
#define INDENT 2
#define DETAIL_INDENT 25
static const char * detail_indent = " ";
size_t opt_len = 0;
fputs(" ", stdout);
if (opt->s_arg) {
fputs(opt->s_arg, stdout);
opt_len += strlen(opt->s_arg);
// print opt-arg if there
if (opt->p_str) {
printf(" %s", opt->p_str);
opt_len += strlen(opt->p_str) + 1;
}
if (opt->l_arg) {
fputs(", ", stdout);
opt_len += 2;
}
}
if (opt->l_arg) {
fputs(opt->l_arg, stdout);
opt_len += strlen(opt->l_arg);
// print out the opt-arg with =
if (opt->p_str) {
printf("=%s", opt->p_str);
opt_len += strlen(opt->p_str) + 1;
}
}
// print out the default
if (opt->pd_str) {
printf(" (default '%s')", opt->pd_str);
opt_len += strlen(opt->pd_str) + 13;
}
// fill out spaces until the details
for (size_t i = opt_len; i < DETAIL_INDENT; ++i) {
fputs(" ", stdout);
}
// print out details string
if (opt_len >= DETAIL_INDENT) {
fputs("\n", stdout);
fputs(detail_indent, stdout);
}
size_t i = 0;
char c;
while ((c = opt->d_str[i]) != '\0') {
if (c == '\n') {
puts(""); // sys independent newline
fputs(detail_indent, stdout);
} else {
fputc(c, stdout);
}
++i;
}
puts("");
}
void print_options(const option * options, size_t num_options)
{
bool section = false;
for (size_t i = 0; i < num_options; ++i) {
const option * opt = &options[i];
if (opt->func == NULL) {
if (opt->assign) {
if (section) {
// already in section: end section
puts("");
section = false;
} else {
// not section: start a new section
puts("");
puts(opt->d_str);
section = true;
}
} else {
puts(opt->d_str);
}
continue;
}
print_option(opt);
}
}
static inline
bool check_option(const option * opt, int * parg_i, const char * arg,
void * aux, vector * non_options, int argc, char ** argv)
{
bool match = false;
// typical case: match against the short arg or long arg
if (!opt->assign) {
if ((opt->s_arg && strcmp(opt->s_arg, arg) == 0) ||
(opt->l_arg && strcmp(opt->l_arg, arg) == 0)) {
int ret = opt->func(aux, arg, NULL);
if (ret != 0)
exit(ret);
match = true;
}
} else {
const char * assign = NULL;
if (opt->s_arg != NULL && arg[1] == opt->s_arg[1]) {
match = true;
// for short args
// opt-arg can either come from arg itself or next arg
if (arg[2] != '\0') {
assign = &arg[2];
} else {
// next arg
(*parg_i) += 1;
if (*parg_i < argc)
assign = argv[*parg_i];
}
} else if (opt->l_arg != NULL) {
// long args are a bit more complicated: can use = or space
size_t equal_idx = strcfind(arg, '=', 0);
if (equal_idx != SIZE_MAX) {
// found an equal: need to use strncmp
if (strncmp(opt->l_arg, arg, equal_idx) == 0) {
match = true;
assign = &arg[equal_idx + 1];
}
} else {
// no equal: try straight strcmp
if (strcmp(opt->l_arg, arg) == 0) {
match = true;
// next arg
(*parg_i) += 1;
if (*parg_i < argc)
assign = argv[*parg_i];
}
}
}
if (match) {
if (assign != NULL && assign[0] == '\0')
assign = NULL;
int ret = opt->func(aux, arg, assign);
if (ret != 0)
exit(ret);
}
}
return match;
}
void parse_options(const char * src, const option * options, size_t num_options,
void * aux, vector * non_options, int argc, char ** argv)
{
for (int arg_i = 1; arg_i < argc; ++arg_i) {
const char * arg = argv[arg_i];
bool is_opt = false;
bool check_opts = true;
// check against the options if arg starts with a dash
if (check_opts && arg[0] == '-') {
// "--" will turn off future opt checking
if (strcmp("--", arg) == 0) {
check_opts = false;
continue;
}
for (size_t opt_i = 0; !is_opt && opt_i < num_options; ++opt_i) {
const option * opt = &options[opt_i];
if (opt->func == NULL) // is printing metadata
continue;
is_opt = check_option(opt, &arg_i, arg, aux, non_options, argc, argv);
}
if (!is_opt) {
msg(src, M_ERROR,
"Unrecognized command line option " ANSI_F_BWHT "'%s'",
arg);
}
} else {
// interpret this as a non-option
vector_push_back(non_options, &arg);
}
}
}
|
C | /***************************************************************************//**
@file mapa.c
@brief Creacion y actualizacion constante del mapa de juego, de los troncos
y de los vehiculos
@author Grupo 1: Cristian Meichtry, Juan Martin Rodriguez
******************************************************************************/
/*****************************************************************************/
// Header Files //
/*****************************************************************************/
#include "mapa.h"
/*****************************************************************************/
// definicion de variables locales //
/*****************************************************************************/
static mapa_t mapa; //declaracion del mapa de juego
//definicion e inicializacion de las estructuras de cada carril (no se inicializaron todos los campos)
static carril_t tronco2 = {0, 0, 1, 1, 2, LOG};
static carril_t tronco3 = {0, 0, 1, 1, 3, LOG};
static carril_t tronco4 = {0, 0, 1, 1, 4, LOG};
static carril_t tronco5 = {0, 0, 1, 1, 5, LOG};
static carril_t tronco6 = {0, 0, 1, 1, 6, LOG};
static carril_t tronco7 = {0, 0, 1, 1, 7, LOG};
static carril_t vehiculo9 = {0, 1, 1, 2, 9, TRUCK}; //en los ultimos dos carriles de los vehiculos solo hay camiones
static carril_t vehiculo10 = {0, 1, 1, 2, 10, TRUCK};
static carril_t vehiculo11 = {0, 1, 1, 1, 11, CAR};
static carril_t vehiculo12 = {0, 1, 1, 1, 12, CAR};
static carril_t vehiculo13 = {0, 1, 1, 1, 13, CAR};
static carril_t vehiculo14 = {0, 1, 1, 1, 14, CAR};
/*****************************************************************************/
// prototipos de funciones locales //
/*****************************************************************************/
/*****************************************************************************
* @brief creacion_de_objetos: actualiza el mapa linea por linea constantemente
* @param arr_troncos: arreglo de estructuras de troncos
* @param arr_vehiculos: arreglo de estructuras de vehiculos
* @param nivel: nivel de juego actual
**/
static void creacion_de_objetos(carril_t* arr_troncos[6], carril_t* arr_vehiculos[6], u_int8_t nivel);
/*****************************************************************************
* @brief convertir_velocidad: actualiza el mapa linea por linea constantemente
* @param arr: arreglo de estructuras de troncos o de vehiculos
**/
static void convertir_velocidad(carril_t* arr[6]);
/*****************************************************************************
* @brief crear_vehiculos: actualiza el mapa linea por linea constantemente
* @param arr_vehiculos: arreglo de estructuras de vehiculos
* @param cant_vel: cantidad de velocidades que va a haber en ese nivel
**/
static void crear_vehiculos(carril_t* arr_vehiculos[6], int cant_vel);
/*****************************************************************************
* @brief crear_troncos: actualiza el mapa linea por linea constantemente
* @param arr_troncos: arreglo de estructuras de troncos
* @param cant_vel: cantidad de velocidades que va a haber en ese nivel
**/
static void crear_troncos(carril_t* arr_troncos[6], int cant_vel);
/*****************************************************************************
* @brief actualiza_linea: actualiza el mapa linea por linea constantemente
* @param carril: carril que se quiere actualizar
**/
static void actualiza_linea(carril_t* carril);
/*****************************************************************************
* @brief carga_mapa: actualiza el mapa linea por linea constantemente
* @param linea: carril que se quiere cargar
**/
static void carga_mapa(carril_t* linea);
/*****************************************************************************/
// definicion de funciones globales //
/*****************************************************************************/
void creacion_mapa(void){ //crea el mapa pero sin ningun vehiculo, mapa base
int i, j; //variables para contadores
for(i = 0; i < SIZE; i++){
mapa[0][i] = DEAD;
mapa[1][i] = DEAD;
}
for(i = 2; i <= 14; i= i+3){
mapa[1][i] = WIN;
}
for(i = 2; i <= 7; i++){
for(j = 0; j < SIZE; j++){
mapa[i][j] = WATER;
}
}
for(i = 9; i <= 14; i++){
for(j = 0; j < SIZE; j++){
mapa[i][j] = STREET;
}
}
for(i = 0; i < SIZE; i++){
mapa[8][i] = SAFE;
mapa[15][i] = SAFE;
}
}
void inicia_mapa(u_int8_t nivel){ //se crean todos los objetos de un nivel, se mantienen a lo largo del nivel
int i;
carril_t* arr_troncos[6] = {&tronco2, &tronco3, &tronco4, &tronco5, &tronco6, &tronco7};
carril_t* arr_vehiculos[6] = {&vehiculo9, &vehiculo10, &vehiculo11, &vehiculo12, &vehiculo13, &vehiculo14};
creacion_de_objetos(arr_troncos, arr_vehiculos, nivel);
//Limpia celda donde llega la rana, si se pasa de nivel pasa de OCUPADO a WIN
for(i = 2; i <= 14; i= i+3){
mapa[1][i] = WIN;
}
//Carga al mapa los nuevos objetos del nivel
for(i = 0; i < 6; i++){
carga_mapa(arr_troncos[i]);
carga_mapa(arr_vehiculos[i]);
}
}
carril_t * get_carril(uint8_t linea){
carril_t* carriles[12] = {
&tronco2, &tronco3, &tronco4, &tronco5, &tronco6, &tronco7,
&vehiculo9, &vehiculo10, &vehiculo11, &vehiculo12, &vehiculo13, &vehiculo14
};
return carriles[linea];
}
mapa_t * get_mapa(void){
return &mapa;
}
mapa_t* actualiza_mundo(void){ //actualiza el mapa constantemente
int i;
carril_t* carriles[12] = {
&tronco2, &tronco3, &tronco4, &tronco5, &tronco6, &tronco7,
&vehiculo9, &vehiculo10, &vehiculo11, &vehiculo12, &vehiculo13, &vehiculo14
};
for(i = 0; i < 12; i++){
actualiza_linea(carriles[i]); //actualiza linea por linea
}
return &mapa;
}
/*****************************************************************************/
// definicion de funciones locales //
/*****************************************************************************/
static void creacion_de_objetos(carril_t* arr_troncos[6], carril_t* arr_vehiculos[6], u_int8_t nivel){ //se crea cada objeto con sus atributos correspondientes
int i;
srand(time(NULL));
switch(nivel){
case 1:
crear_vehiculos(arr_vehiculos, 2); //en nivel 1 solo hay dos velocidades posibles (velocidad 1 y 2)
crear_troncos(arr_troncos, 2);
break;
case 2:
crear_vehiculos(arr_vehiculos, 3); //en nivel 2 hay tres velocidades posibles (velocidad 1, 2 y 3)
crear_troncos(arr_troncos, 3);
break;
case 3:
crear_vehiculos(arr_vehiculos, 3); //en nivel 3 hay tres velocidades posibles (velocidad 2, 3 y 4)
crear_troncos(arr_troncos, 3);
for(i = 0; i < 6; i++){
(arr_vehiculos[i] -> velocidad)++;
(arr_troncos[i] -> velocidad)++;
}
break;
case 4:
crear_vehiculos(arr_vehiculos, 2); //en nivel 4 solo hay dos velocidades posibles (3 y 4)
crear_troncos(arr_troncos, 2);
for(i = 0; i < 6; i++){
(arr_vehiculos[i] -> velocidad) += 2;
(arr_troncos[i] -> velocidad) +=2;
}
break;
case 5:
crear_vehiculos(arr_vehiculos, 2); //en nivel 5 solo hay dos velocidades posibles (4 y 5)
crear_troncos(arr_troncos, 2);
for(i = 0; i < 6; i++){
(arr_vehiculos[i] -> velocidad) += 3;
(arr_troncos[i] -> velocidad) += 3;
}
break;
}
for(i = 0; i < 6; i++){
(arr_vehiculos[i] -> tiempo_previo) = clock();
(arr_troncos[i] -> tiempo_previo) = clock();
}
convertir_velocidad(arr_vehiculos); //se convierte las velocidades 1, 2, 3, 4, 5
convertir_velocidad(arr_troncos); //a los valores constantes definidos
}
static void convertir_velocidad(carril_t* arr[6]){ //"traduce" los valores enteros que se asignaron aleatoriamente a los valores constates definidos
int i;
for(i = 0; i < 6; i++){
switch(arr[i] -> velocidad){
case 0:
case 1:
arr[i] -> tm_cell = MUY_LENTO;
break;
case 2:
arr[i] -> tm_cell = LENTO;
break;
case 3:
arr[i] -> tm_cell = NORMAL;
break;
case 4:
arr[i] -> tm_cell = RAPIDO;
break;
case 5:
arr[i] -> tm_cell = MUY_RAPIDO;
break;
}
}
}
static void crear_vehiculos(carril_t* arr_vehiculos[6], int cant_vel){ //recibe la cantidad de velocidades a la que se mueven los vehiculos dependiendo del nivel y el arreglo de vehiculos
int i, j;
int espacio_libre = 0;
for(i = 0; i < 6; i++){
arr_vehiculos[i] -> direccion = rand() % 2; //la direccion es 0 o 1
arr_vehiculos[i] -> velocidad = rand() % cant_vel + 1; //asigna velocidades random dependiendo de la cantidad que correspondan para el nivel
arr_vehiculos[i] -> cant_obj = (arr_vehiculos[i] -> size_obj == 1) ? rand() % 3 + 2: rand() % 3 + 1; //asigna la cantidad de elementos que pueden aparecer
//depende del tamaño del vehiculo (auto/camion)
espacio_libre = (arr_vehiculos[i] -> size_obj == 1) ? rand() % 3 + 1 : rand() % 3 + 3; //define el espacio libre que puede haber entre los vehiculos
if(arr_vehiculos[i] -> direccion == IZQ_A_DER){ //se crean los vehiculos dependiendo del sentido, cantidad y tamaño asignados para cada carril
arr_vehiculos[i] -> pos_inic_objetos[0] = espacio_libre - 1;
for(j = 1; j < arr_vehiculos[i] -> cant_obj; j++){
arr_vehiculos[i] -> pos_inic_objetos[j] = arr_vehiculos[i] -> pos_inic_objetos[j-1] - espacio_libre - 1 - rand() % 2;
}
}
else{
arr_vehiculos[i] -> pos_inic_objetos[0] = (SIZE - 1) - (espacio_libre - 1);
for(j = 1; j < arr_vehiculos[i] -> cant_obj; j++){
arr_vehiculos[i] -> pos_inic_objetos[j] = arr_vehiculos[i] -> pos_inic_objetos[j-1] + espacio_libre + 1 + rand() % 2;
}
}
}
}
static void crear_troncos(carril_t* arr_troncos[6], int cant_vel){ //recibe la cantidad de velocidades a la que se mueven los troncos dependiendo del nivel y el arreglo de troncos
int i,j;
int espacio_libre = 0;
for(i = 0; i < 6; i++){
arr_troncos[i] -> direccion = rand() % 2; //la direccion es 0 o 1
arr_troncos[i] -> size_obj = rand() % 3 + 2; //los troncos pueden ser de 2, 3 o 4 cuadritos
arr_troncos[i] -> velocidad = rand() % cant_vel + 1;
switch(arr_troncos[i] -> size_obj){ //define el espacio libre que puede haber entre los troncos dependiendo del size de los mismos
case 4:
arr_troncos[i] -> cant_obj = rand() % 2 + 2;
espacio_libre = (arr_troncos[i] -> cant_obj == 3) ? 2 : 3;
break;
case 3:
arr_troncos[i] -> cant_obj = rand() % 3 + 2;
espacio_libre = (arr_troncos[i] -> cant_obj == 4) ? 1 : ((arr_troncos[i] -> cant_obj == 3 ) ? 2 : 4);
break;
case 2:
arr_troncos[i] -> cant_obj = rand() % 3 + 3;
espacio_libre = (arr_troncos[i] -> cant_obj == 5) ? 1 : ((arr_troncos[i] -> cant_obj == 4 ) ? 2 : 4);
break;
}
if(arr_troncos[i] -> direccion == IZQ_A_DER){ //funcionamiento analogo a crear_vehiculos
arr_troncos[i] -> pos_inic_objetos[0] = espacio_libre - 1;
for(j = 1; j < arr_troncos[i] -> cant_obj; j++){
arr_troncos[i] -> pos_inic_objetos[j] = arr_troncos[i] -> pos_inic_objetos[j-1] - espacio_libre - arr_troncos[i] -> size_obj;
}
}
else{
arr_troncos[i] -> pos_inic_objetos[0] = (SIZE - 1) - (espacio_libre - 1);
for(j = 1; j < arr_troncos[i] -> cant_obj; j++){
arr_troncos[i] -> pos_inic_objetos[j] = arr_troncos[i] -> pos_inic_objetos[j-1] + espacio_libre + arr_troncos[i] -> size_obj;
}
}
}
}
static void actualiza_linea(carril_t* linea){ //actualiza cada carril por saparado segun la velocidad de los objetos
int i;
if(((clock() - (linea -> tiempo_previo))/(double)CLOCKS_PER_SEC) >= linea -> tm_cell){
linea -> tiempo_previo = clock();
linea -> act_prev = 1;
for(i = 0; i < linea -> cant_obj; i++){
linea -> pos_inic_objetos[i] += (linea -> direccion == IZQ_A_DER) ? 1 : -1;
}
carga_mapa(linea); //carga el mapa actualizado
}
else{
linea -> act_prev = 0;
}
}
static void carga_mapa(carril_t* linea){ //carga el mapa despues de cada actualizacion
int i, j;
u_int8_t columna;
if(linea -> direccion == IZQ_A_DER){ //chequeo sentido y le asigno posicion por posicion el valor que corresponda
for(i = 0; i < linea -> cant_obj; i++){
if(linea -> pos_inic_objetos[i] >= 0 && linea -> pos_inic_objetos[i] < SIZE){
for(j = 0; j < linea -> size_obj; j++){
columna = linea -> pos_inic_objetos[i] - j;
if(columna >= 0){
mapa[linea -> carril][columna] = linea -> objeto;
}
}
}
else if(linea -> pos_inic_objetos[i] >= SIZE){
if(linea -> pos_inic_objetos[i] - linea -> size_obj + 1 < SIZE){
for(j = 1; j < linea -> size_obj; j++){
columna = linea -> pos_inic_objetos[i] - j;
if(columna < SIZE){
mapa[linea -> carril][columna] = linea -> objeto;
}
}
}
else{
mapa[linea -> carril][SIZE - 1] = (linea -> objeto == LOG) ? WATER : STREET;
linea -> pos_inic_objetos[i] = -2;
}
}
if(linea -> pos_inic_objetos[i] - linea -> size_obj >= 0){
mapa[linea -> carril][linea -> pos_inic_objetos[i] - linea -> size_obj] = (linea -> objeto == LOG) ? WATER : STREET;
}
}
}
else{
for(i = 0; i < linea -> cant_obj; i++){
if(linea -> pos_inic_objetos[i] >= 0 && linea -> pos_inic_objetos[i] < SIZE){
for(j = 0; j < linea -> size_obj; j++){
columna = linea -> pos_inic_objetos[i] + j;
if(columna < SIZE){
mapa[linea -> carril][columna] = linea -> objeto;
}
}
}
else if(linea -> pos_inic_objetos[i] < 0){
if(linea -> pos_inic_objetos[i] + linea -> size_obj - 1 >= 0){
for(j = 1; j < linea -> size_obj; j++){
columna = linea -> pos_inic_objetos[i] + j;
if(columna >= 0){
mapa[linea -> carril][columna] = linea -> objeto;
}
}
}
else{
mapa[linea -> carril][0] = (linea -> objeto == LOG) ? WATER : STREET;
linea -> pos_inic_objetos[i] = SIZE;
}
}
if(linea -> pos_inic_objetos[i] + linea -> size_obj < SIZE){
mapa[linea -> carril][linea -> pos_inic_objetos[i] + linea -> size_obj] = (linea -> objeto == LOG) ? WATER : STREET;
}
}
}
}
|
C | //
// Created by mkg on 10/7/2016.
//
/* json.c parses json files for view objects */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include "../include/json.h"
/* global variables */
int line = 1; // global var for line numbers as we parse
object objects[MAX_OBJECTS]; // allocate space for all objects in json file
Light lights[MAX_OBJECTS]; // allocate space for lights
int nlights;
int nobjects;
/* helper functions */
// next_c wraps the getc function that provides error checking and line #
// Problem: if we do ungetc, it could screw us up on the line #
int next_c(FILE* json) {
int c = fgetc(json);
#ifdef DEBUG
printf("next_c: '%c'\n", c);
#endif
if (c == '\n') {
line++;;
}
if (c == EOF) {
fprintf(stderr, "Error: next_c: Unexpected EOF: %d\n", line);
exit(1);
}
return c;
}
/* skips any white space from current position to next character*/
void skip_ws(FILE *json) {
int c = next_c(json);
while (isspace(c)) {
c = next_c(json);
}
if (c == '\n')
line--; // we backed up to the previous line
ungetc(c, json); // move back one character (instead of fseek)
}
/* checks that the next character is d */
void expect_c(FILE* json, int d) {
int c = next_c(json);
if (c == d) return;
fprintf(stderr, "Error: Expected '%c': %d\n", d, line);
exit(1);
}
/* gets the next value from a file - This is *expected* to be a number */
double next_number(FILE* json) {
double val;
int res = fscanf(json, "%lf", &val);
if (res == EOF) {
fprintf(stderr, "Error: Expected a number but found EOF: %d\n", line);
exit(1);
}
return val;
}
/* since we could use 0-255 or 0-1 or whatever, this function checks bounds */
int check_color_val(double v) {
if (v < 0.0 || v > 1.0)
return 0;
return 1;
}
/* check bounds for colors in json light objects. These can be anything >= 0 */
int check_light_color_val(double v) {
if (v < 0.0)
return 0;
return 1;
}
/* gets the next 3 values from FILE as vector coordinates */
double* next_vector(FILE* json) {
double* v = malloc(sizeof(double)*3);
skip_ws(json);
expect_c(json, '[');
skip_ws(json);
v[0] = next_number(json);
skip_ws(json);
expect_c(json, ',');
skip_ws(json);
v[1] = next_number(json);
skip_ws(json);
expect_c(json, ',');
skip_ws(json);
v[2] = next_number(json);
skip_ws(json);
expect_c(json, ']');
return v;
}
/* Checks that the next 3 values in the FILE are valid rgb numbers */
double* next_color(FILE* json, boolean is_rgb) {
double* v = malloc(sizeof(double)*3);
skip_ws(json);
expect_c(json, '[');
skip_ws(json);
v[0] = next_number(json);
skip_ws(json);
expect_c(json, ',');
skip_ws(json);
v[1] = next_number(json);
skip_ws(json);
expect_c(json, ',');
skip_ws(json);
v[2] = next_number(json);
skip_ws(json);
expect_c(json, ']');
// check that all values are valid
if (is_rgb) {
if (!check_color_val(v[0]) ||
!check_color_val(v[1]) ||
!check_color_val(v[2])) {
fprintf(stderr, "Error: next_color: rgb value out of range: %d\n", line);
exit(1);
}
}
else {
if (!check_light_color_val(v[0]) ||
!check_light_color_val(v[1]) ||
!check_light_color_val(v[2])) {
fprintf(stderr, "Error: next_color: light value out of range: %d\n", line);
exit(1);
}
}
return v;
}
/* grabs a string wrapped in quotes from FILE */
char* parse_string(FILE *json) {
skip_ws(json);
int c = next_c(json);
if (c != '"') {
fprintf(stderr, "Error: Expected beginning of string but found '%c': %d\n", c, line);
exit(1); // not a string
}
c = next_c(json); // should be first char in the string
char buffer[128]; // strings are gauranteed to be 128 or less
int i = 0;
while (c != '"') {
if (isspace(c)) {
continue;
}
buffer[i] = c;
i++;
c = next_c(json);
}
buffer[i] = 0;
return strdup(buffer); // returns a malloc'd version of buffer
}
/**
* Reads all scene info from a json file and stores it in the global object
* array. This does a lot of work...It checks for specific values and keys in
* the file and places the values into the appropriate portion of the current
* object.
* @param json file handler with ASCII json data
*/
void read_json(FILE *json) {
//read in data from file
// expecting square bracket but we need to get rid of whitespace
skip_ws(json);
// find beginning of the list
int c = next_c(json);
if (c != '[') {
fprintf(stderr, "Error: read_json: JSON file must begin with [\n");
exit(1);
}
skip_ws(json);
c = next_c(json);
// check if file empty
if (c == ']' || c == EOF) {
fprintf(stderr, "Error: read_json: Empty json file\n");
exit(1);
}
skip_ws(json);
int obj_counter = 0;
int light_counter = 0;
int obj_type;
boolean not_done = true;
// flags for testing whether or not objects have these elements
boolean has_ior = false;
boolean has_reflect = false;
boolean has_refract = false;
// find the objects
while (not_done) {
//c = next_c(json);
if (obj_counter > MAX_OBJECTS) {
fprintf(stderr, "Error: read_json: Number of objects is too large: %d\n", line);
exit(1);
}
if (c == ']') {
fprintf(stderr, "Error: read_json: Unexpected ']': %d\n", line);
fclose(json);
exit(1);
}
if (c == '{') { // found an object
skip_ws(json);
char *key = parse_string(json);
if (strcmp(key, "type") != 0) {
fprintf(stderr, "Error: read_json: First key of an object must be 'type': %d\n", line);
exit(1);
}
skip_ws(json);
// get the colon
expect_c(json, ':');
skip_ws(json);
char *type = parse_string(json);
if (strcmp(type, "camera") == 0) {
obj_type = CAMERA;
objects[obj_counter].type = CAMERA;
}
else if (strcmp(type, "sphere") == 0) {
obj_type = SPHERE;
objects[obj_counter].type = SPHERE;
}
else if (strcmp(type, "plane") == 0) {
obj_type = PLANE;
objects[obj_counter].type = PLANE;
}
else if (strcmp(type, "light") == 0) {
obj_type = LIGHT;
}
else {
exit(1);
}
skip_ws(json);
while (true) {
// , }
c = next_c(json);
if (c == '}') {
// stop parsing this object
break;
}
else if (c == ',') {
// read another field
skip_ws(json);
char* key = parse_string(json);
skip_ws(json);
expect_c(json, ':');
skip_ws(json);
if (strcmp(key, "width") == 0) {
if (obj_type != CAMERA) {
fprintf(stderr, "Error: read_json: Width cannot be set on this type: %d\n", line);
exit(1);
}
double temp = next_number(json);
if (temp <= 0) {
fprintf(stderr, "Error: read_json: width must be positive: %d\n", line);
exit(1);
}
objects[obj_counter].camera.width = temp;
}
else if (strcmp(key, "height") == 0) {
if (obj_type != CAMERA) {
fprintf(stderr, "Error: read_json: Height cannot be set on this type: %d\n", line);
exit(1);
}
double temp = next_number(json);
if (temp <= 0) {
fprintf(stderr, "Error: read_json: height must be positive: %d\n", line);
exit(1);
}
objects[obj_counter].camera.height = temp;
}
else if (strcmp(key, "radius") == 0) {
if (obj_type != SPHERE) {
fprintf(stderr, "Error: read_json: Radius cannot be set on this type: %d\n", line);
exit(1);
}
double temp = next_number(json);
if (temp <= 0) {
fprintf(stderr, "Error: read_json: radius must be positive: %d\n", line);
exit(1);
}
objects[obj_counter].sphere.radius = temp;
}
else if (strcmp(key, "theta") == 0) {
if (obj_type != LIGHT) {
fprintf(stderr, "Error: read_json: Theta cannot be set on this type: %d\n", line);
exit(1);
}
double theta = next_number(json);
if (theta > 0.0) {
lights[light_counter].type = SPOTLIGHT;
}
else if (theta < 0.0) {
fprintf(stderr, "Error: read_json: theta must be >= 0: %d\n", line);
exit(1);
}
lights[light_counter].theta_deg = theta;
}
else if (strcmp(key, "radial-a0") == 0) {
if (obj_type != LIGHT) {
fprintf(stderr, "Error: read_json: Radial-a0 cannot be set on this type: %d\n", line);
exit(1);
}
double rad_a = next_number(json);
if (rad_a < 0) {
fprintf(stderr, "Error: read_json: radial-a0 must be positive: %d\n", line);
exit(1);
}
lights[light_counter].rad_att0 = rad_a;
}
else if (strcmp(key, "radial-a1") == 0) {
if (obj_type != LIGHT) {
fprintf(stderr, "Error: read_json: Radial-a1 cannot be set on this type: %d\n", line);
exit(1);
}
double rad_a = next_number(json);
if (rad_a < 0) {
fprintf(stderr, "Error: read_json: radial-a1 must be positive: %d\n", line);
exit(1);
}
lights[light_counter].rad_att1 = rad_a;
}
else if (strcmp(key, "radial-a2") == 0) {
if (obj_type != LIGHT) {
fprintf(stderr, "Error: read_json: Radial-a2 cannot be set on this type: %d\n", line);
exit(1);
}
double rad_a = next_number(json);
if (rad_a < 0) {
fprintf(stderr, "Error: read_json: radial-a2 must be positive: %d\n", line);
exit(1);
}
lights[light_counter].rad_att2 = rad_a;
}
else if (strcmp(key, "angular-a0") == 0) {
if (obj_type != LIGHT) {
fprintf(stderr, "Error: read_json: Angular-a0 cannot be set on this type: %d\n", line);
exit(1);
}
double ang_a = next_number(json);
if (ang_a < 0) {
fprintf(stderr, "Error: read_json: angular-a0 must be positive: %d\n", line);
exit(1);
}
lights[light_counter].ang_att0 = ang_a;
}
else if (strcmp(key, "color") == 0) {
if (obj_type != LIGHT) {
fprintf(stderr, "Error: Just plain 'color' vector can only be applied to a light object\n");
exit(1);
}
lights[light_counter].color = next_color(json, false);
}
else if (strcmp(key, "direction") == 0) {
if (obj_type != LIGHT) {
fprintf(stderr, "Error: Direction vector can only be applied to a light object\n");
exit(1);
}
lights[light_counter].type = SPOTLIGHT;
lights[light_counter].direction = next_vector(json);
}
else if (strcmp(key, "specular_color") == 0) {
if (obj_type == SPHERE)
objects[obj_counter].sphere.spec_color = next_color(json, true);
else if (obj_type == PLANE)
objects[obj_counter].plane.spec_color = next_color(json, true);
else {
fprintf(stderr, "Error: read_json: speculaor_color vector can't be applied here: %d\n", line);
exit(1);
}
}
else if (strcmp(key, "diffuse_color") == 0) {
if (obj_type == SPHERE)
objects[obj_counter].sphere.diff_color = next_color(json, true);
else if (obj_type == PLANE)
objects[obj_counter].plane.diff_color = next_color(json, true);
else {
fprintf(stderr, "Error: read_json: diffuse_color vector can't be applied here: %d\n", line);
exit(1);
}
}
else if (strcmp(key, "position") == 0) {
if (obj_type == SPHERE)
objects[obj_counter].sphere.position = next_vector(json);
else if (obj_type == PLANE)
objects[obj_counter].plane.position = next_vector(json);
else if (obj_type == LIGHT)
lights[light_counter].position = next_vector(json);
else {
fprintf(stderr, "Error: read_json: Position vector can't be applied here: %d\n", line);
exit(1);
}
}
else if (strcmp(key, "reflectivity") == 0) {
has_reflect = true;
if (obj_type == SPHERE)
objects[obj_counter].sphere.reflect = next_number(json);
else if (obj_type == PLANE)
objects[obj_counter].plane.reflect = next_number(json);
else {
fprintf(stderr, "Error: read_json: Reflectivity can't be applied here: %d\n", line);
exit(1);
}
}
else if (strcmp(key, "refractivity") == 0) {
has_refract = true;
if (obj_type == SPHERE)
objects[obj_counter].sphere.refract = next_number(json);
else if (obj_type == PLANE)
objects[obj_counter].plane.refract = next_number(json);
else {
fprintf(stderr, "Error: read_json: Refractivity can't be applied here: %d\n", line);
exit(1);
}
}
else if (strcmp(key, "ior") == 0) {
has_ior = true;
if (obj_type == SPHERE)
objects[obj_counter].sphere.ior = next_number(json);
else if (obj_type == PLANE)
objects[obj_counter].plane.ior = next_number(json);
else {
fprintf(stderr, "Error: read_json: ior can't be applied here: %d\n", line);
exit(1);
}
}
else if (strcmp(key, "normal") == 0) {
if (obj_type != PLANE) {
fprintf(stderr, "Error: read_json: Normal vector can't be applied here: %d\n", line);
exit(1);
}
else
objects[obj_counter].plane.normal = next_vector(json);
}
else {
fprintf(stderr, "Error: read_json: '%s' not a valid object: %d\n", key, line);
exit(1);
}
skip_ws(json);
}
else {
fprintf(stderr, "Error: read_json: Unexpected value '%c': %d\n", c, line);
exit(1);
}
}
skip_ws(json);
c = next_c(json);
if (c == ',') {
// noop
skip_ws(json);
}
else if (c == ']') {
not_done = false;
}
else {
fprintf(stderr, "Error: read_json: Expecting comma or ]: %d\n", line);
exit(1);
}
}
if (obj_type == LIGHT) {
if (lights[light_counter].type == SPOTLIGHT) {
if (lights[light_counter].direction == NULL) {
fprintf(stderr, "Error: read_json: 'spotlight' light type must have a direction: %d\n", line);
exit(1);
}
if (lights[light_counter].theta_deg == 0.0) {
fprintf(stderr, "Error: read_json: 'spotlight' light type must have a theta value: %d\n", line);
exit(1);
}
}
light_counter++;
}
else {
if (obj_type == SPHERE || obj_type == PLANE) {
if (objects[obj_counter].sphere.spec_color == NULL) {
fprintf(stderr, "Error: read_json: object must have a specular color: %d\n", line);
exit(1);
}
if (objects[obj_counter].sphere.diff_color == NULL) {
fprintf(stderr, "Error: read_json: object must have a diffuse color: %d\n", line);
exit(1);
}
if (obj_type == SPHERE) {
Sphere *sphere = &objects[obj_counter].sphere;
if (!has_refract) {
sphere->refract = 0.0;
}
if (!has_reflect) {
sphere->reflect = 0.0;
}
if (!has_ior) {
sphere->ior = 1.0;
}
if (sphere->refract + sphere->reflect > 1.0) {
fprintf(stderr, "Error: read_json: The sum of reflectivity and refractivity cannot be greater than 1: %d\n", line);
exit(1);
}
}
else if (obj_type == PLANE) {
Plane *plane = &objects[obj_counter].plane;
if (!has_refract) {
plane->refract = 0.0;
}
if (!has_reflect) {
plane->reflect = 0.0;
}
if (!has_ior) {
plane->ior = 1.0;
}
if (plane->refract + plane->reflect > 1.0) {
fprintf(stderr, "Error: read_json: The sum of reflectivity and refractivity cannot be greater than 1: %d\n", line);
exit(1);
}
}
}
if (obj_type == CAMERA) {
if (objects[obj_counter].camera.width == 0) {
fprintf(stderr, "Error: read_json: camera must have a width: %d\n", line);
exit(1);
}
if (objects[obj_counter].camera.height == 0) {
fprintf(stderr, "Error: read_json: camera must have a height: %d\n", line);
exit(1);
}
}
obj_counter++;
}
if (not_done)
c = next_c(json);
}
fclose(json);
nlights = light_counter;
nobjects = obj_counter;
}
/**
* initializes list of objects to be empty for each element
*/
void init_objects() {
memset(objects, '\0', sizeof(objects));
}
/**
* initializes list of lights to be empty for each element
*/
void init_lights() {
memset(lights, '\0', sizeof(lights));
}
/* testing/debug functions */
void print_objects(object *obj) {
int i = 0;
while (i < MAX_OBJECTS && obj[i].type > 0) {
printf("object type: %d\n", obj[i].type);
if (obj[i].type == CAMERA) {
printf("height: %lf\n", obj[i].camera.height);
printf("width: %lf\n", obj[i].camera.width);
}
// TODO: add printing of diffuse colors as well
else if (obj[i].type == SPHERE) {
printf("color: %lf %lf %lf\n", obj[i].sphere.spec_color[0],
obj[i].sphere.spec_color[1],
obj[i].sphere.spec_color[2]);
printf("position: %lf %lf %lf\n", obj[i].sphere.position[0],
obj[i].sphere.position[1],
obj[i].sphere.position[2]);
printf("radius: %lf\n", obj[i].sphere.radius);
}
else if (obj[i].type == PLANE) {
printf("color: %lf %lf %lf\n", obj[i].plane.spec_color[0],
obj[i].plane.spec_color[1],
obj[i].plane.spec_color[2]);
printf("position: %lf %lf %lf\n", obj[i].plane.position[0],
obj[i].plane.position[1],
obj[i].plane.position[2]);
printf("normal: %lf %lf %lf\n", obj[i].plane.normal[0],
obj[i].plane.normal[1],
obj[i].plane.normal[2]);
}
else {
printf("unsupported value\n");
}
i++;
}
printf("end at i=%d\n", i);
}
|
C | #include <stdio.h>
#include <stdlib.h>
int mark[1000];
void markfunc(int x,int n)
{
for(int j=2*x;j<=n;j+=x)
mark[j]=1;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=2;i<n;i++)
if(mark[i]==0)
markfunc(i,n);
for(int i=1;i<=n;i++)
if(mark[i]==0)
printf("%d ",i);
return 0;
}
|
C | /* LuaBER utilities */
#include <ctype.h> /* isdigit */
#include <string.h> /* memmove */
#include <lauxlib.h>
#define atod(cp, num) \
while (isdigit (*(cp))) \
(num) = ((num) << 3) + ((num) << 1) + (*((cp)++) & ~'0');
#define bytes_count(x) \
!(x) ? 0 : ((x) & 0xFF000000) ? 4 : ((x) & 0xFF0000) ? 3 \
: ((x) & 0xFF00) ? 2 : 1
static unsigned int
reverse (register unsigned int x)
{
x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
return x;
}
static int
dtoa (char *s, int len, int num)
{
if (!len) return 0;
if (!num) {
*s = '0';
len = 1;
} else {
int i = len;
do {
s[--i] = (num % 10) | '0';
num /= 10;
} while (num && i > 0);
len -= i;
memmove (s, &s[i], len);
}
return len;
}
/*
* Arguments: string
* Returns: string
*/
int
oid2str (lua_State *L)
{
#define OID_STRSIZE 32
char oid[OID_STRSIZE];
unsigned int num;
unsigned char sub, oidi = 0;
size_t len = 0;
const char *oidp = lua_tolstring (L, -1, &len);
if (!oidp) return 0;
num = *oidp++;
sub = num / 40;
if (sub > 2) sub = 2;
num = num - sub * 40;
oidi += dtoa (&oid[oidi], OID_STRSIZE - oidi, sub);
for (; ; ) {
oid[oidi++] = '.';
oidi += dtoa (&oid[oidi], OID_STRSIZE - oidi, num);
if (!--len || oidi >= OID_STRSIZE) break;
for (num = 0; *oidp & 0x80; --len, ++oidp, num <<= 7)
num |= *oidp & 0x7F;
num |= *oidp++;
}
lua_pushlstring (L, oid, oidi > OID_STRSIZE ? OID_STRSIZE : oidi);
return 1;
}
/*
* Arguments: string
* Returns: string
*/
int
str2oid (lua_State *L)
{
#define OID_SIZE 24
unsigned int num = 0, number;
unsigned char sub = 0, oid[OID_SIZE], *oidp = oid;
const char *strp = lua_tostring (L, -1);
if (!strp) return 0;
atod (strp, sub);
if ((sub > 2) || (*strp++ != '.')) return 0;
atod (strp, num);
*oidp++ = sub * 40 + num;
num = 0;
while (*strp == '.') {
++strp;
atod (strp, num);
number = num & 0x7F;
num >>= 7;
for (sub = 1; num; ++sub) {
number <<= 8;
number |= (unsigned char) num | 0x80;
num >>= 7;
}
/* buffer overflow? */
if (oidp > oid + OID_SIZE - sub) return 0;
for (; sub; --sub, number >>= 8)
*oidp++ = (unsigned char) number;
}
lua_pushlstring (L, (char *) oid, oidp - oid);
return 1;
}
/*
* Arguments: string
* Returns: number
*/
int
bitstr2num (lua_State *L)
{
lua_pushnumber (L,
(lua_Number) reverse (*((unsigned int *) luaL_checkstring (L, 1))));
return 1;
}
/*
* Arguments: number
* Returns: string
*/
int
num2bitstr (lua_State *L)
{
unsigned int num = reverse ((int) lua_tonumber (L, 1));
lua_pushlstring (L, (char *) &num, bytes_count(num));
return 1;
}
|
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#define MAXBIN 32
#define MAXHEX 8
#define MAXDBL 100
/*
Author: Genaro Martínez S.
id: A01566055
date: 13/03/2020
use the routines to display several types of data from strings.
*/
unsigned int hexToInt(const char *hex)
{
unsigned int result = 0;
while (*hex)
{
if (*hex > 47 && *hex < 58)
result += (*hex - 48);
else if (*hex > 64 && *hex < 71)
result += (*hex - 55);
else if (*hex > 96 && *hex < 103)
result += (*hex - 87);
else
{
printf("wrong character detected");
break;
}
if (*++hex)
result <<= 4;
}
return result;
}
int stringBinToInt(const char *str)
{
// initialize result.
unsigned int result = 0;
for (int i = strlen(str) - 1, j = 0; i >= 0; i--, j++)
{
char k = str[i] - '0'; // assuming ASCII
// pointer operator to assign new position.
k <<= j;
result += k;
}
return result;
}
double pointerToDouble(const char *str) {
double a = atof(str);
return a;
}
unsigned int hexToInt(const char *hex);
int stringBinToInt(const char *str);
int main(int argc, char const *argv[])
{
char hex[MAXBIN];
char bin[MAXHEX];
char dbl[MAXDBL];
double a, b;
// 0101010101
// FFFFF
printf("bin: \n");
scanf("%s", &bin);
printf("hex: \n");
scanf("%s", &hex);
printf("dbl: \n");
scanf("%s", &dbl);
printf("Binary value in int = %d \n", stringBinToInt(bin));
printf("\n");
printf("Hexadecimal value in decimal = %lu\n", hexToInt(hex));
printf("\n");
printf ("double point number in dbl = %f\n" ,pointerToDouble(dbl));
return 0;
}
|
C | #include<stdio.h>
int main(void) {
short int i = 0;
printf("%ld", sizeof(i));
for(i<=5 && i>=-1; ++i; i>0) {
printf("%u,", i);
}
return 0;
}
|
C | /* day_mon2.c -- 让编译器计算元素个数 p247 */
#include <stdio.h>
int main (void)
{
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31};
int index;
for (index = 0; index < sizeof days /sizeof days[0] ; index++)
printf ("Month %d has %2d days.\n", index + 1,
days[index]);
return 0;
}
|
C | #define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <sched.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <sys/mount.h>
#include "util.h"
struct ancestor_args {
/* Two pipes for setup_userns communication */
int pipefd_pid[2];
int pipefd_done[2];
/* Pipe to report last ancestor pid */
int pipefd_last[2];
int level;
};
struct message {
int pid;
};
static int ancestor(void *args);
#define CLONE_STACK_SIZE 4096
#define __stack_aligned__ __attribute__((aligned(16)))
/*
* Clone process with new pid and user namespace, passing "proc"-level pid over
* pipes from child to parent, so that we can setup userns for this process
* right.
*/
static int clone_ns_ancestor(struct ancestor_args *aa)
{
char stack[CLONE_STACK_SIZE] __stack_aligned__;
struct message msg = {};
int flags = CLONE_NEWUSER | CLONE_NEWPID | SIGCHLD;
int status;
int len;
int pid;
if (pipe(aa->pipefd_pid) == -1) {
perror("pipe");
return -1;
}
if (pipe(aa->pipefd_done) == -1) {
perror("pipe");
goto err_close;
}
/* For last ancestor we only create userns */
if (aa->level == 1)
flags &= ~CLONE_NEWPID;
pid = clone(ancestor, &stack[CLONE_STACK_SIZE],
flags | SIGCHLD, aa);
if (pid == -1) {
printf("Fail to clone ancestor %d: %m\n", aa->level);
goto err_close;
}
close_safe(&aa->pipefd_pid[1]);
close_safe(&aa->pipefd_done[0]);
len = read(aa->pipefd_pid[0], &msg, sizeof(msg));
if (len != sizeof(msg)) {
perror("read pid");
goto err;
}
close_safe(&aa->pipefd_pid[0]);
if (setup_userns(msg.pid))
goto err;
len = write(aa->pipefd_done[1], &msg, sizeof(msg));
if (len != sizeof(msg)) {
perror("write done");
goto err;
}
close_safe(&aa->pipefd_done[1]);
return pid;
err:
kill(pid, SIGKILL);
waitpid(pid, &status, 0);
err_close:
close_safe(&aa->pipefd_pid[1]);
close_safe(&aa->pipefd_done[0]);
close_safe(&aa->pipefd_pid[0]);
close_safe(&aa->pipefd_done[1]);
return -1;
}
/*
* Send "proc"-level pid to parent, so that it can setup userns for us.
*/
static int ancestor_prepare(struct ancestor_args *aa)
{
struct message msg = {};
close_safe(&aa->pipefd_pid[0]);
close_safe(&aa->pipefd_done[1]);
msg.pid = get_proc_pid();
if (msg.pid == -1)
goto err;
if (write(aa->pipefd_pid[1], &msg, sizeof(msg)) != sizeof(msg)) {
perror("write");
goto err;
}
close_safe(&aa->pipefd_pid[1]);
if (read(aa->pipefd_done[0], &msg, sizeof(msg)) != sizeof(msg)) {
perror("read");
goto err;
}
close_safe(&aa->pipefd_done[0]);
return 0;
err:
close_safe(&aa->pipefd_pid[1]);
close_safe(&aa->pipefd_done[0]);
return -1;
}
/*
* Recursively clone needed amount of ancestors. In last ancestor pass
* "proc"-level pid to ns_main and hang in sleep loop.
*/
static int ancestor(void *args)
{
struct ancestor_args *aa = (struct ancestor_args *)args;
int status;
int pid;
close_safe(&aa->pipefd_last[0]);
if (ancestor_prepare(aa)) {
printf("Failed to prepare ancestor %d\n", aa->level);
goto err;
}
aa->level--;
if (aa->level) {
pid = clone_ns_ancestor(aa);
if (pid == -1) {
printf("Failed to clone ns_ancestor %d\n", aa->level);
goto err;
}
close_safe(&aa->pipefd_last[1]);
waitpid(pid, &status, 0);
} else {
struct message msg = {};
msg.pid = get_proc_pid();
if (msg.pid == -1)
goto err;
if (write(aa->pipefd_last[1], &msg, sizeof(msg)) != sizeof(msg)) {
perror("write");
goto err;
}
while (1)
sleep(1);
}
return 0;
err:
close_safe(&aa->pipefd_last[1]);
return 1;
}
#define ptr_to_u64(ptr) ((__u64)((uintptr_t)(ptr)))
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
static int last_pidns_helper(int last_pid)
{
int userns_fd = -1, userns_kid;
pid_t set_tid[] = {1, 10, 10, 10, 10, 10};
struct _clone_args ca = {
.exit_signal = SIGCHLD,
.set_tid = ptr_to_u64(set_tid),
.set_tid_size = ARRAY_SIZE(set_tid),
.flags = CLONE_OWNER_NS | CLONE_NEWPID,
};
int cpid;
int status = 0;
userns_fd = open_ns_fd(last_pid, "user");
if (userns_fd == -1) {
printf("Can't open userns_fd of %d\n", last_pid);
return 1;
}
if (get_ns_kid(userns_fd, &userns_kid)) {
printf("Can't get userns kid of %d\n", last_pid);
close_safe(&userns_fd);
return 1;
}
printf("Last ancestor userns %u\n", userns_kid);
ca.userns_fd = userns_fd;
cpid = clone3(&ca);
if (cpid == -1) {
perror("clone3");
close_safe(&userns_fd);
return 1;
} else if (cpid == 0) {
int proc_pid;
int pidns_fd = -1;
int ownerns_fd = -1, ownerns_kid;
char comm[4096];
close_safe(&userns_fd);
proc_pid = get_proc_pid();
if (proc_pid == -1)
exit(1);
pidns_fd = open_ns_fd(proc_pid, "pid");
if (pidns_fd == -1) {
printf("Can't open pidns_fd of %d\n", last_pid);
exit(1);
}
ownerns_fd = ioctl(pidns_fd, NS_GET_USERNS);
if (ownerns_fd < 0) {
perror("ioctl NS_GET_USERNS");
close_safe(&pidns_fd);
exit(1);
}
close_safe(&pidns_fd);
if (get_ns_kid(ownerns_fd, &ownerns_kid)) {
printf("Can't get userns kid of %d\n", proc_pid);
close_safe(&ownerns_fd);
exit(1);
}
close_safe(&ownerns_fd);
printf("New init pidns owner userns %u\n", ownerns_kid);
if (snprintf(comm, sizeof(comm), "grep NSpid /proc/%d/status",
proc_pid) >= sizeof(comm)) {
perror("snprintf comm truncated");
return -1;
}
system(comm);
exit(0);
}
close_safe(&userns_fd);
if ((waitpid(cpid, &status, 0) < 0) || status) {
printf("Child cpid has bad exit status %d: %m\n", status);
return 1;
}
return 0;
}
#define NUM_ANCESTORS 5
static int ns_main(void *unused)
{
int exit_code = 1;
struct ancestor_args aa = {
.pipefd_pid = {-1, -1},
.pipefd_done = {-1, -1},
.pipefd_last = {-1, -1},
.level = NUM_ANCESTORS,
};
struct message msg = {};
int status = 0;
int pid;
int last_pid = 0;
int pidns_fd = -1;
int helper_pid;
if (prepare_mntns())
return 1;
/* Pipe to get pid in current pidns of the last ancestor */
if (pipe(aa.pipefd_last) == -1) {
perror("pipe");
return 1;
}
pid = clone_ns_ancestor(&aa);
if (pid == -1) {
printf("Failed to clone ns_ancestor %d\n", aa.level);
goto err_close;
}
close_safe(&aa.pipefd_last[1]);
if (read(aa.pipefd_last[0], &msg, sizeof(msg)) != sizeof(msg)) {
perror("read");
goto err;
}
close_safe(&aa.pipefd_last[0]);
last_pid = msg.pid;
/*
* Preparation stage finished: Now we have NUM_ANCESTORS ancestors
* hanging, each ancestor created one more nested level of
* userns+pidns except last one which only has new nested userns. And
* last_pid is a pid of this last ancestor (e.g. 6).
*
* ┌−−−−−−−−−−−−┐ ┌−−−−−−−−−−−−┐ ┌−−−−−−−−−−−−−−┐
* ╎ usernses ╎ ╎ pidnses ╎ ╎ processes ╎
* ╎ ╎ ╎ ╎ ╎ ╎
* ╎ ┌────────┐ ╎ ╎ ┌────────┐ ╎ ╎ ┌──────────┐ ╎
* ╎ │ usr_1 │ ╎─▶╎ │ pid_1 │ ╎─▶╎ │ns_main(1)│ ╎
* ╎ └────────┘ ╎ ╎ └────────┘ ╎ ╎ └──────────┘ ╎
* ╎ │ ╎ ╎ │ ╎ ╎ │ ╎
* ╎ ▼ ╎ ╎ ▼ ╎ ╎ ▼ ╎
* ╎ ┌────────┐ ╎ ╎ ┌────────┐ ╎ ╎ ┌─────────┐ ╎
* ╎ │ usr_2 │ ╎─▶╎ │ pid_2 │ ╎─▶╎ │ anc(2) │ ╎
* ╎ └────────┘ ╎ ╎ └────────┘ ╎ ╎ └─────────┘ ╎
* ╎ │ ╎ ╎ │ ╎ ╎ │ ╎
* ╎ ▼ ╎ ╎ ▼ ╎ ╎ ▼ ╎
* ╎ ┌────────┐ ╎ ╎ ┌────────┐ ╎ ╎ ┌─────────┐ ╎
* ╎ │ usr_3 │ ╎─▶╎ │ pid_3 │ ╎─▶╎ │ anc(3) │ ╎
* ╎ └────────┘ ╎ ╎ └────────┘ ╎ ╎ └─────────┘ ╎
* ╎ │ ╎ ╎ │ ╎ ╎ │ ╎
* ╎ ▼ ╎ ╎ ▼ ╎ ╎ ▼ ╎
* ╎ ┌────────┐ ╎ ╎ ┌────────┐ ╎ ╎ ┌─────────┐ ╎
* ╎ │ usr_4 │ ╎─▶╎ │ pid_4 │ ╎─▶╎ │ anc(4) │ ╎
* ╎ └────────┘ ╎ ╎ └────────┘ ╎ ╎ └─────────┘ ╎
* ╎ │ ╎ ╎ │ ╎ ╎ │ ╎
* ╎ ▼ ╎ ╎ ▼ ╎ ╎ ▼ ╎
* ╎ ┌────────┐ ╎ ╎ ┌────────┐ ╎ ╎ ┌─────────┐ ╎
* ╎ │ usr_5 │ ╎─▶╎ │ pid_5 │ ╎─▶╎ │ anc(5) │ ╎
* ╎ └────────┘ ╎ ╎ └────────┘ ╎ ╎ └─────────┘ ╎
* ╎ │ ╎ └−−−−−−−−−−−−┘ ╎ │ ╎
* ╎ ▼ ╎ ╎ ▼ ╎
* ╎ ┌────────┐ ╎ ╎ ┌─────────┐ ╎
* ╎ │ usr_6 │ ╎─────────────────▶╎ │ anc(6) │ ╎
* ╎ └────────┘ ╎ ╎ └─────────┘ ╎
* └−−−−−−−−−−−−┘ └−−−−−−−−−−−−−−┘
*
* Imagine now that we want to create one more process which would be
* an init/reaper of one more new pidns (pid_6), like this:
*
* ┌−−−−−−−−−−−−┐ ┌−−−−−−−−−−−−┐ ┌−−−−−−−−−−−−−−┐
* ╎ ┌────────┐ ╎ ╎ ┌────────┐ ╎ ╎ ┌─────────┐ ╎
* ╎ │ usr_5 │ ╎─▶╎ │ pid_5 │ ╎─▶╎ │ anc(5) │ ╎
* ╎ └────────┘ ╎ ╎ └────────┘ ╎ ╎ └─────────┘ ╎
* ╎ │ ╎ ╎ │ ╎ ╎ ╎
* ╎ ▼ ╎ ╎ ▼ ╎ ╎ ╎
* ╎ ┌────────┐ ╎ ╎ ┌────────┐ ╎ ╎ ┌─────────┐ ╎
* ╎ │ usr_6 │ ╎─▶╎ │ pid_6 │ ╎─▶╎ │ init │ ╎
* ╎ └────────┘ ╎ ╎ └────────┘ ╎ ╎ └─────────┘ ╎
* └−−−−−−−−−−−−┘ └−−−−−−−−−−−−┘ └−−−−−−−−−−−−−−┘
*
* But we also want to set proper pid numbers in each of pid_1..pid_6,
* e.g. {10,10,10,10,10,1}.
*
* We can't do it with clone3 with clone_args.set_tid set for all the
* levels without new CLONE_OWNER_NS. Because if we want new pidns
* pid_6 to be owned by userns usr_6 without CLONE_OWNER_NS we should
* be in usr_6 at the time of clone, and we would not have permissions
* to set tid in pidnses pid_5..pid_1 because we are in relatively
* unprivileged usens, relative to usr_5..usr_1.
*
* With setting /proc/sys/kernel/ns_last_pid on each pidns level we can
* do it. But we should also be able to do it with less racy new
* set_tid interface too. And with CLONE_OWNER_NS we can:
*/
pidns_fd = open_ns_fd(last_pid, "pid");
if (pidns_fd == -1) {
printf("Can't open pidns_fd of %d\n", last_pid);
goto err;
}
if (setns(pidns_fd, CLONE_NEWPID)) {
perror("setns");
close_safe(&pidns_fd);
goto err;
}
close_safe(&pidns_fd);
helper_pid = fork();
if (helper_pid == -1) {
perror("fork");
goto err;
} else if (helper_pid == 0) {
exit(last_pidns_helper(last_pid));
}
if ((waitpid(helper_pid, &status, 0) < 0) || status) {
printf("Child helper_pid has bad exit status %d: %m\n", status);
goto err;
}
exit_code = 0;
err:
if (last_pid)
kill(last_pid, SIGKILL);
else
kill(pid, SIGKILL);
waitpid(pid, &status, 0);
err_close:
close_safe(&aa.pipefd_last[0]);
close_safe(&aa.pipefd_last[1]);
return exit_code;
}
int main()
{
char stack[CLONE_STACK_SIZE] __stack_aligned__;
int status = 0;
int pid;
pid = clone(ns_main, &stack[CLONE_STACK_SIZE],
CLONE_NEWNS | CLONE_NEWPID | SIGCHLD, NULL);
if (pid == -1) {
perror("clone ns_main");
return 1;
}
if (waitpid(pid, &status, 0) < 0 || status) {
printf("Child ns_main has bad exit status %d: %m\n", status);
return 1;
}
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include "stack.h"
Stack* CreateStack() //ջ,һλô0ʼ
{
Stack* p = (Stack*)malloc(sizeof(Stack));
p->array = (ElementType*)malloc(MAXSIZE*sizeof(ElementType));
for (int i = 0; i < MAXSIZE; i++)
{
p->array[i] = 0;
}
p->Top = -1;
p->len = MAXSIZE;
return p;
}
void Push(Stack* PtrS, ElementType item)
{
//assert(PtrS->Top <= MAXSIZE - 1,"The stack is full");
if(PtrS->Top >= PtrS->len)
{
ElementType *array = (ElementType*)malloc((PtrS->Top + 1 + MAXSIZE)*sizeof(ElementType));
//printf("array size = %lx\n", sizeof(array)/sizeof(array[0]));
//int top = PtrS->Top;
int L = PtrS->len;
memcpy(array, PtrS->array, L * sizeof(ElementType));
free(PtrS->array);
PtrS->array = array;
//PtrS->Top = top;
PtrS->len = L + MAXSIZE;
}
PtrS->array[PtrS->Top++] = item;
printf("%d Push success!\n", PtrS->array[PtrS->Top - 1]);
}
ElementType Pop(Stack * PtrS) //ջ
{
if(PtrS->Top == 0)
{
printf("This is a empty stack!");
return 0;
}
int data = PtrS->array[PtrS->Top - 1];
PtrS->Top = PtrS->Top - 1;
return data;
}
int IsEmpty(Stack* S) //жջǷΪգ
{
if (S->Top == -1)
{
printf("This is a empty stack!\n");
return 1;
}
else
{
printf("This is not a empty stack!\n");
return 0;
}
}
void ClearStack(Stack* PtrS)
{
free(PtrS);
printf("ClearStack success!\n");
}
|
C | /*
域名解析,获取指定域名对应的别名和地址。
*/
#include <stdio.h>
#include<netdb.h>
#include<unistd.h>
int main()
{
struct hostent *ent = NULL;
ent = gethostbyname("www.baidu.com");
printf("%s\n",ent->h_aliases[0]);
printf("%hhu.%hhu.%hhu.%hhu\n",ent->h_addr_list[1][0],ent->h_addr_list[1][1],ent->h_addr_list[1][2],ent->h_addr_list[1][3]);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_errors_otool.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gperroch <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/09 09:50:06 by gperroch #+# #+# */
/* Updated: 2018/03/19 18:21:01 by gperroch ### ########.fr */
/* */
/* ************************************************************************** */
#include "nm_otool.h"
void ft_errors(int type, char *file_name)
{
if (type == ARGS_NUMBER)
{
ft_printf("error: ft_otool: at least one file must be specified\n");
exit(EXIT_FAILURE);
}
if (type == INVALID_FILE)
ft_printf("%s: is not an object file\n", file_name);
if (type == MAPPING_ERROR)
ft_printf("ERROR in ft_mapping_file() for %s.\n", file_name);
if (type == NOT_EXISTING)
ft_printf("ft_otool: %s: %s\n", file_name, "No such file or directory");
if (type == NO_PERM)
ft_printf("ft_otool: %s: %s\n", file_name, "Permission denied.");
if (type == CORRUPTED)
{
ft_printf("ft_otool: %s truncated or malformed object\n\n", file_name);
exit(1);
}
}
|
C | /* monitor.c -- This file is part of ctools
*
* Copyright (C) 2015 - David Oberhollenzer
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#define TL_OS_EXPORT
#include "tl_thread.h"
#include "os.h"
int tl_monitor_init(tl_monitor *this)
{
assert(this);
this->notify_event = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!this->notify_event)
return 0;
this->notify_all_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!this->notify_all_event) {
CloseHandle(this->notify_event);
return 0;
}
InitializeCriticalSection(&this->mutex);
InitializeCriticalSection(&this->waiter_mutex);
this->wait_count = 0;
return 1;
}
void tl_monitor_cleanup(tl_monitor *this)
{
assert(this);
CloseHandle(this->notify_event);
CloseHandle(this->notify_all_event);
DeleteCriticalSection(&this->mutex);
DeleteCriticalSection(&this->waiter_mutex);
}
tl_monitor *tl_monitor_create(void)
{
tl_monitor *this = calloc(1, sizeof(*this));
if (!tl_monitor_init(this)) {
free(this);
this = NULL;
}
return this;
}
void tl_monitor_destroy(tl_monitor *this)
{
assert(this);
tl_monitor_cleanup(this);
free(this);
}
int tl_monitor_lock(tl_monitor *this, unsigned long timeout)
{
assert(this);
return tl_mutex_lock((tl_mutex *)&this->mutex, timeout);
}
void tl_monitor_unlock(tl_monitor *this)
{
assert(this);
tl_mutex_unlock((tl_mutex *)&this->mutex);
}
int tl_monitor_wait(tl_monitor *this, unsigned long timeout)
{
DWORD status = WAIT_FAILED, waittime = timeout ? timeout : INFINITE;
HANDLE events[2];
assert(this);
/* increment wait count */
EnterCriticalSection(&this->waiter_mutex);
++(this->wait_count);
LeaveCriticalSection(&this->waiter_mutex);
/* wait for event */
LeaveCriticalSection(&this->mutex);
events[0] = this->notify_event;
events[1] = this->notify_all_event;
status = WaitForMultipleObjects(2, events, FALSE, waittime);
/* decrement wait count */
EnterCriticalSection(&this->waiter_mutex);
--(this->wait_count);
if (this->wait_count == 0 && status == (WAIT_OBJECT_0 + 1))
ResetEvent(this->notify_all_event);
LeaveCriticalSection(&this->waiter_mutex);
/* restore state */
EnterCriticalSection(&this->mutex);
return status != WAIT_TIMEOUT && status != WAIT_FAILED;
}
void tl_monitor_notify(tl_monitor *this)
{
assert(this);
EnterCriticalSection(&this->waiter_mutex);
if (this->wait_count > 0)
SetEvent(this->notify_event);
LeaveCriticalSection(&this->waiter_mutex);
}
void tl_monitor_notify_all(tl_monitor *this)
{
assert(this);
EnterCriticalSection(&this->waiter_mutex);
if (this->wait_count > 0)
SetEvent(this->notify_all_event);
LeaveCriticalSection(&this->waiter_mutex);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* writting_helper.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vomelchu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/03 17:46:35 by vomelchu #+# #+# */
/* Updated: 2019/01/02 13:25:09 by vomelchu ### ########.fr */
/* */
/* ************************************************************************** */
#include "doom_nukem.h"
int num_ele(t_data *data, int x, int y)
{
t_vertex *vert;
int q;
q = 0;
vert = &data->vertex;
while (vert->next != NULL)
{
if (vert->x_vert == x && vert->y_vert == y)
return (q);
q++;
vert = vert->next;
}
if (vert->x_vert == x && vert->y_vert == y)
return (q);
return (0);
}
t_vector last_vect(t_data *data, int q)
{
t_sector *sect;
t_vector dot_1;
sect = &data->sectors[q];
while (sect->next->next != NULL)
sect = sect->next;
dot_1.x = (double)sect->x0;
dot_1.y = (double)sect->y0;
return (dot_1);
}
int find_wall(t_data *data, t_vector dot_1, t_vector dot_2, int check)
{
t_sector *sector;
int q;
q = -1;
while (++q <= data->current_sector)
{
sector = &data->sectors[q];
while (sector->next != NULL && q != check)
{
if (((int)dot_1.x == sector->x0 && (int)dot_1.y == sector->y0 &&
DT2X && (int)dot_2.y == sector->next->y0)
|| ((int)dot_2.x == sector->x0 && DT2Y &&
DT1X && (int)dot_1.y == sector->next->y0))
return (q);
if (sector->next->next == NULL)
if ((DTX && (int)dot_1.y == sector->y0 &&
DTY && (int)dot_2.y == data->sectors[q].y0)
|| ((int)dot_2.x == sector->x0 && (int)dot_2.y == sector->y0 &&
DT && (int)dot_1.y == data->sectors[q].y0))
return (q);
sector = sector->next;
}
}
return (-1);
}
void writte_walls(t_data *data, FILE *fp, int q)
{
t_sector *sector;
t_vector dot_1;
t_vector dot_2;
char *wall;
sector = &data->sectors[q];
dot_1 = last_vect(data, q);
dot_2.x = (double)sector->x0;
dot_2.y = (double)sector->y0;
wall = ft_itoa(find_wall(data, dot_1, dot_2, q));
fwrite(wall, ft_strlen(wall), 1, fp);
fwrite(" ", 1, 1, fp);
free(wall);
while (sector->next->next != NULL)
{
dot_1.x = (double)sector->x0;
dot_1.y = (double)sector->y0;
dot_2.x = (double)sector->next->x0;
dot_2.y = (double)sector->next->y0;
wall = ft_itoa(find_wall(data, dot_1, dot_2, q));
fwrite(wall, ft_strlen(wall), 1, fp);
fwrite(" ", 1, 1, fp);
free(wall);
sector = sector->next;
}
}
void make_vertex_list(t_data *data)
{
int q;
t_sector *sector;
t_vertex *vert;
q = -1;
vert = &data->vertex;
vert->next = NULL;
while (++q <= data->current_sector)
{
sector = &data->sectors[q];
while (sector->next != NULL)
{
vert->x_vert = sector->x0;
vert->y_vert = sector->y0;
if (sector->next != NULL)
{
if (!(vert->next = (t_vertex *)malloc(sizeof(t_vertex))))
ft_error("Bad malloc in vertex");
vert = vert->next;
}
sector = sector->next;
}
}
vert->next = NULL;
}
|
C | #include <stdio.h>//preprocessor directive to include standard input output function headerfile
int main()
{
int i,num,n,large=0;// integer variables declaration
printf("How many numbers: ");//Ask user to input how many numbers
scanf("%d",&n);//scanf function for taking the input values from user
for(i=0; i<n; i++)// for loop from i=0 and i<n and incriment in i
{
printf("\nEnter number %d: ",i+1);
scanf("%d",&num);//scanf function for taking the input values from user
if(num>large) // if statement for checking the num is greater then large
large=num; // the value of num is assigned to large
}
printf("\n\nThe Largest Number is %d",large);//printf function for printing the largest number
return 0;
} |
C | #include <stdio.h>
int main()
{
int array[10] = {1, 2, 3, 4, 2, 3, 5, 2, 1, 1};
/*int buffArray[2];
memset(array, 2, 10);*/
int indexFirst = 0;
int indexLast = 0;
int count = 1;
for (int i = 9; i >= 0; i--)
{
for (int j = i - 1; j >= 0; j--)
{
if (array[i] == array[j])
{
indexLast = i;
indexFirst = j;
count++;
}
else
{
break;
}
}
if (count >= i / 2)
{
i = i - count;
}
}
printf("%i\n", indexFirst);
printf("%i\n", indexLast);
printf("%i\n", count);
}
|
C | /*
Sistema de una empresa de alquiler de equipos que tiene clientes que pueden alquilar equipos
para uno o varios proyectos. Permite ingresar/modificar/eliminar clientes, proyectos, equipos,
los procesos de: conteo, despacho, devolucin, generacin de facturas, cuenta del cliente y
cobros al cliente.
Autor: Naoki Nakao
Fecha: en curso
*/
#include "utils.h"
#include <conio.c>
/*
Funcin : seleccionarOpcion
Argumentos: char menu[][MAXOPC]: contiene las opciones del men
int n: cantidad de opciones del men
int px: posicin a desplegar en x
int py: posicin a desplegar en y
int pos: posicin inicial
Objetivo : controlar el movimiento del cursor al mostrar el men
Retorno : (int) pos: opcin que se seleccion al presionar [ENTER]
*/
int seleccionarOpcion(char menu[][MAXOPC], int n, int px, int py, int pos)
{
char tecla;
_setcursortype(FALSE);
do {
mostrarMenu(menu, n, px, py, pos);
do {
tecla = getch();
} while (tecla != ARRIBA && tecla != ABAJO && tecla != ENTER && tecla != ESC);
if (tecla != ESC)
{
if (tecla == ARRIBA)
{
if (pos != 0)
pos--;
else
pos = n-1;
}
else if (tecla == ABAJO)
{
if (pos < n-1)
pos++;
else
pos = 0;
}
}
else pos = EXIT;
} while (tecla != ENTER && tecla != ESC);
_setcursortype(100);
return pos;
}
/*
Funcin : mostrarMenu
Argumentos: char menu[][MAXOPC]: contiene las opciones del men
int n: cantidad de opciones del men
int px: posicin a desplegar en x
int py: posicin a desplegar en y
int actual: posicin actual del cursor
Objetivo : mostrar el men
Retorno : ---
*/
void mostrarMenu(char menu[][MAXOPC], int n, int px, int py, int actual)
{
int index;
for (index = 0; index < n; index++)
{
setColor(BLUE, LIGHTGRAY);
if (index == actual)
setColor(YELLOW, BLUE);
gotoxy(px, py+index);
printf("%s", menu[index]);
}
defaultColor();
return;
}
/*
Funcin : setColor
Argumentos: int colortexto: color a cambiar del texto
int colorfondo: color a cambiar del fondo
Objetivo : cambiar el color del texto y el fondo
Retorno : ---
*/
void setColor(int colortexto, int colorfondo)
{
textcolor(colortexto);
textbackground(colorfondo);
}
/*
Funcin : defaultColor
Argumentos: ---
Objetivo : reestablecer los colores predeterminados de la consola
Retorno : ---
*/
void defaultColor()
{
setColor(WHITE, BLACK);
}
/*
Funcin : randomString
Argumentos: char *destino: cadena de destino
char *aux: cadena auxiliar con espacios en blanco
int inf: valor mnimo para el caracter
int sup: valor mximo para el caracter
Objetivo : agregar caracteres aleatorios a "destino"
Retorno : ---
*/
void randomString(char *destino, char *aux, int inf, int sup)
{
int index;
strcpy(destino, aux);
for (index = 0; *(destino+index) != NULL; index++)
destino[index] = (rand() % (sup-inf+1)) + inf;
return;
}
/*
Funcin : fsize
Argumentos: FILE *pf: referencia del archivo
Objetivo : calcular la longitud en bytes de "pf"
Retorno : (long) cantbytes
*/
long fsize(FILE *pf)
{
long posarch = ftell(pf), cantbytes;
fseek(pf,0L,SEEK_END);
cantbytes = ftell(pf);
fseek(pf,posarch,SEEK_SET);
return cantbytes;
}
/*
Funcin : opcionesCliente
Argumentos: int opcion: indica la accin a realizar
char *archivo: nombre del archivo donde se encuentran los datos
Objetivo : agregar, leer, modificar o borrar datos de los clientes
Retorno : ---
*/
void opcionesCliente(int opcion, char *archivo)
{
FILE *pf;
NODOCLIENTE *cabeza = NULL, *temp;
CLIENTE *cliente;
long cantidad;
int seleccionar, index;
char tecla;
// abriendo el archivo
if ((pf = fopen(archivo, "rb")) != NULL)
{
cantidad = fsize(pf)/sizeof(CLIENTE);
cliente = (CLIENTE*)malloc(sizeof(CLIENTE));
for (index = 0; index < cantidad; index++)
{
fread(cliente, sizeof(CLIENTE), 1, pf);
insertarFrenteCliente(&cabeza, *cliente);
}
free(cliente);
fclose(pf);
}
else if (opcion != AGREGAR)
{
puts("No hay clientes agregados.");
Sleep(DELAY);
clrscr();
return;
}
if (opcion == AGREGAR)
{
do {
cliente = (CLIENTE*)calloc(1, sizeof(CLIENTE));
printf("Digite los datos del cliente: \n\n");
capturarDatosCliente(cliente);
insertarFrenteCliente(&cabeza, *cliente);
free(cliente);
printf("\n\n%cDesea agregar otro cliente? S(i) o N(o): ", 168);
do {
tecla = toupper(getch());
} while (tecla != 'S' && tecla != 'N');
clrscr();
} while (tecla != 'N');
}
else if (opcion == LEER)
{
seleccionar = listarClientes(cabeza, cantidad, INIX, INIY, RANGO);
clrscr();
}
else if (opcion == MODIFICAR)
{
seleccionar = listarClientes(cabeza, cantidad, INIX, INIY, RANGO);
clrscr();
temp = cabeza;
for (index = 0; index < seleccionar; index++)
temp = temp->siguiente;
if (seleccionar != EXIT)
{
char campos[][MAXOPC] = {"ID cliente ",
"Primer nombre ",
"Segundo nombre ",
"Primer apellido ",
"Segundo apellido",
"ID documento ",
"Direccion "};
int camposel;
do {
gotoxy(INIX, INIY);
printf("Seleccione un campo");
gotoxy(INIX, INIY+10);
printf("Presione [ESC] para salir");
camposel = seleccionarOpcion(campos, 7, INIX, INIY+2, 0);
modificarDatosCliente(temp, camposel);
clrscr();
} while (camposel != EXIT);
}
else clrscr();
}
else if (opcion == BORRAR)
{
seleccionar = listarClientes(cabeza, cantidad, INIX, INIY, RANGO);
gotoxy(INIX, INIY+9);
printf("%cSeguro que desea eliminar este cliente? S(i) o N(o): ");
do {
tecla = toupper(getch());
} while (tecla != 'S' && tecla != 'N');
if (tecla == 'S')
{
temp = cabeza;
for (index = 0; index < seleccionar; index++)
temp = temp->siguiente;
eliminarCliente(&cabeza, temp);
gotoxy(INIX, INIY+10);
printf("Cliente eliminado.");
Sleep(DELAY);
}
clrscr();
}
// sobreescribiendo el archivo si la opcin seleccionada fue
// para agregar, modificar o borrar clientes
if (opcion != LEER)
{
if ((pf = fopen(archivo, "wb")) != NULL)
{
cliente = (CLIENTE*)malloc(sizeof(CLIENTE));
for (temp = cabeza, index = 0; temp != NULL; temp = temp->siguiente, index++)
{
(*cliente) = temp->datos;
fwrite(cliente, sizeof(CLIENTE), 1, pf);
}
free(cliente);
fclose(pf);
}
}
return;
}
/*
Funcin : capturarDatosCliente
Arrgumentos : CLIENTE *cliente: referencia donde se almacenarn los datos
Objetivo : capturar los datos de un cliente
Retorno : ---
*/
void capturarDatosCliente(CLIENTE *cliente)
{
printf("Primer nombre: ");
captureTextField(cliente->primernomb, LENPRINOMBRE, 15, 3, FALSE, FALSE);
printf("Segundo nombre: ");
captureTextField(cliente->segnomb, LENSEGNOMBRE, 16, 4, FALSE, FALSE);
printf("Primer apellido: ");
captureTextField(cliente->primerapel, LENPRIAPEL, 17, 5, FALSE, FALSE);
printf("Segundo apellido: ");
captureTextField(cliente->segapel, LENSEGAPEL, 18, 6, FALSE, FALSE);
printf("ID documento: ");
captureTextField(cliente->docid, MAXID, 14, 7, TRUE, TRUE);
printf("Direcci%cn: ", 162);
captureTextField(cliente->direccion, LENDIR, 11, 8, FALSE, FALSE);
// generando un id para el cliente
randomString(cliente->idcliente, RANDSTR15, INFNUM, SUPNUM);
return;
}
/*
Funcin : insertarFrenteCliente
Arrgumentos : NODOCLIENTE **cabeza: cabeza de la lista
CLIENTE info: nueva infromacin
Objetivo : insertar informacin de clientes al inicio de la lista
Retorno : ---
*/
void insertarFrenteCliente(NODOCLIENTE **cabeza, CLIENTE info)
{
NODOCLIENTE *nuevo = (NODOCLIENTE*)malloc(sizeof(NODOCLIENTE));
nuevo->datos = info;
nuevo->siguiente = (*cabeza);
nuevo->anterior = NULL;
if ((*cabeza) != NULL)
(*cabeza)->anterior = nuevo;
(*cabeza) = nuevo;
return;
}
/*
Funcin : listarClientes
Arrgumentos : NODOCLIENTE *clientes: lista donde estn almacenados los clientes
int n: cantidad de clientes
int px: poscin en x
int py: posicin en y
int rango: cantidad de clientes mostrados en el men de scroll
Objetivo : desplegar un men con cursor para seleccionar un cliente
Retorno : (int) pos: cliente seleccionado
*/
int listarClientes(NODOCLIENTE *clientes, int n, int px, int py, int rango)
{
char tecla;
int pos = 0, inf = 0, sup = rango;
_setcursortype(FALSE);
do {
mostrarClientes(clientes, n, px, py, pos, inf, sup);
do {
tecla = getch();
} while (tecla != ARRIBA && tecla != ABAJO && tecla != ENTER && tecla != ESC);
if (tecla != ESC)
{
if (tecla == ARRIBA)
{
if (pos != 0)
{
pos--;
if (pos < inf)
{
inf--;
sup--;
}
}
else
{
pos = n-1;
sup = n-1;
inf = sup-rango;
}
}
else if (tecla == ABAJO)
{
if (pos < n-1)
{
pos++;
if (pos > sup)
{
sup++;
inf++;
}
}
else
{
pos = 0;
inf = 0;
sup = rango;
}
}
}
else pos = EXIT;
} while (tecla != ENTER && tecla != ESC);
_setcursortype(100);
return pos;
}
/*
Funcin : mostrarClientes
Arrgumentos : NODOCLIENTE *clientes: lista donde estn almacenados los clientes
int n: cantidad de clientes
int px: poscin en x
int py: posicin en y
int inf: indica el primer cliente mostrado en la salida
int sup: indica el ltimo cliente mostrado en la salida
Objetivo : mostrar los clientes
Retorno : ---
*/
void mostrarClientes(NODOCLIENTE *clientes, int n, int px, int py, int actual, int inf, int sup)
{
NODOCLIENTE *index = clientes;
int cont, renglon;
// se recorre la lista hasta el primer cliente que
// se mostrar en el men de scroll
for (cont = 0; cont != inf; cont++)
index = index->siguiente;
gotoxy(px, py);
setColor(WHITE, GREEN);
printf(" ID Nombre completo ");
char espacio[] = " ";
for (index, cont = inf, renglon = 0; cont <= sup && index != NULL; index = index->siguiente, cont++, renglon++)
{
gotoxy(px, py+renglon+2);
setColor(BLUE, LIGHTGRAY);
if (cont == actual)
setColor(YELLOW, BLUE);
printf("%s", espacio);
gotoxy(px+1, py+renglon+2);
printf("%s", index->datos.idcliente);
gotoxy(px+19, py+renglon+2);
printf("%s", index->datos.primernomb);
if (index->datos.segnomb[0] != NULL)
printf(" %c.", index->datos.segnomb[0]);
printf(" %s", index->datos.primerapel);
printf(" %s", index->datos.segapel);
}
defaultColor();
return;
}
/*
Funcin : modificarDatosCliente
Arrgumentos : NODOCLIENTE *cliente: regerencia del cliente
int campo: indica el campo que se va a modificar
Objetivo : modificar un campo en la informacin del cliente
Retorno : ---
*/
void modificarDatosCliente(NODOCLIENTE *cliente, int campo)
{
int px = INIX+17, py = INIY+2+campo;
if (campo == 0)
{
captureTextField(cliente->datos.idcliente, MAXIDCLIENTE, px, py, FALSE, TRUE);
}
else if (campo == 1)
{
captureTextField(cliente->datos.primernomb, LENPRINOMBRE, px, py, FALSE, FALSE);
}
else if (campo == 2)
{
captureTextField(cliente->datos.segnomb, LENSEGNOMBRE, px, py, FALSE, FALSE);
}
else if (campo == 3)
{
captureTextField(cliente->datos.primerapel, LENPRIAPEL, px, py, FALSE, FALSE);
}
else if (campo == 4)
{
captureTextField(cliente->datos.segapel, LENSEGAPEL, px, py, FALSE, FALSE);
}
else if (campo == 5)
{
captureTextField(cliente->datos.docid, MAXID, px, py, FALSE, TRUE);
}
else if (campo == 6)
{
captureTextField(cliente->datos.direccion, LENDIR, px, py, FALSE, FALSE);
}
return;
}
/*
Funcin : eliminarCliente
Arrgumentos : NODOCLIENTE **cabeza: referencia a la cabeza de la lista
NODOCLIENTE *elim: nodo de la lista a eliminar
Objetivo : eliminar un cliente
Retorno : ---
*/
void eliminarCliente(NODOCLIENTE **cabeza, NODOCLIENTE *elim)
{
if ((*cabeza) == NULL || elim == NULL)
return;
if ((*cabeza) == elim)
(*cabeza) = elim->siguiente;
if (elim->siguiente != NULL)
elim->siguiente->anterior = elim->anterior;
if (elim->anterior != NULL)
elim->anterior->siguiente = elim->siguiente;
free(elim);
return;
}
/*
Funcin : opcionesEquipos
Argumentos: int opcion: indica la accin a realizar
char *archivo: nombre del archivo donde se encuentran los datos
Objetivo : agregar, leer, modificar o borrar datos de los equipos
Retorno : ---
*/
void opcionesEquipos(int opcion, char *archivo)
{
FILE *pf;
NODOEQUIPO *cabeza = NULL, *temp;
EQUIPO *equipo;
long cantidad;
int seleccionar, index;
char tecla;
// abriendo el archivo
if ((pf = fopen(archivo, "rb")) != NULL)
{
cantidad = fsize(pf)/sizeof(EQUIPO);
equipo = (EQUIPO*)malloc(sizeof(EQUIPO));
while (!feof(pf))
{
fread(equipo, sizeof(EQUIPO), 1, pf);
insertarFrenteEquipo(&cabeza, *equipo);
}
free(equipo);
fclose(pf);
}
else if (opcion != AGREGAR)
{
puts("No hay equipos agregados.");
Sleep(DELAY);
clrscr();
return;
}
if (opcion == AGREGAR)
{
do {
equipo = (EQUIPO*)calloc(1, sizeof(EQUIPO));
printf("Digite los datos del equipo:\n\n");
capturarDatosEquipo(equipo);
insertarFrenteEquipo(&cabeza, *equipo);
free(equipo);
printf("\n\n%cDesea agregar otro equipo? S(i) o N(o): ", 168);
do {
tecla = toupper(getch());
} while (tecla != 'S' && tecla != 'N');
clrscr();
} while (tecla != 'N');
}
else if (opcion == LEER)
{
seleccionar = listarEquipos(cabeza, cantidad, INIX, INIY, RANGO);
clrscr();
}
else if (opcion == MODIFICAR)
{
seleccionar = listarEquipos(cabeza, cantidad, INIX, INIY, RANGO);
clrscr();
if (seleccionar != EXIT)
{
temp = cabeza;
for (index = 0; index < seleccionar; index++)
temp = temp->siguiente;
char campos[][MAXOPC] = {"ID del equipo ",
"Nombre ",
"Cantidad en inventario",
"Precio de alquiler ",
"Costo de venta ",};
int camposel;
do {
gotoxy(INIX, INIY);
printf("Seleccione un campo");
gotoxy(INIX, INIY+10);
printf("Presione [ESC] para salir");
camposel = seleccionarOpcion(campos, 5, INIX, INIY+2, 0);
modificarInfoEquipos(temp, camposel);
clrscr();
} while (camposel != EXIT);
}
else clrscr();
}
else if (opcion == BORRAR)
{
seleccionar = listarEquipos(cabeza, cantidad, INIX, INIY, RANGO);
gotoxy(INIX, INIY+9);
printf("%cSeguro que desea eliminar este equipo? S(i) o N(o): ", 168);
do {
tecla = toupper(getch());
} while (tecla != 'S' && tecla != 'N');
if (tecla == 'S')
{
temp = cabeza;
for (index = 0; index < seleccionar; index++)
temp = temp->siguiente;
eliminarEquipo(&cabeza, temp);
gotoxy(INIX, INIY+10);
printf("Equipo eliminado.");
Sleep(DELAY);
}
clrscr();
}
// sobreescribiendo el archivo si la opcin seleccionada fue
// para agregar, modificar o borrar clientes
if (opcion != LEER)
{
if ((pf = fopen(archivo, "wb")) != NULL)
{
equipo = (EQUIPO*)malloc(sizeof(EQUIPO));
for (temp = cabeza, index = 0; temp != NULL; temp = temp->siguiente, index++)
{
fseek(pf, index*sizeof(EQUIPO), SEEK_SET);
(*equipo) = temp->datos;
fwrite(equipo, sizeof(EQUIPO), 1, pf);
}
free(equipo);
fclose(pf);
}
}
return;
}
/*
Funcin : capturarDatosEquipo
Arrgumentos : EQUIPO *equipo: referencia donde se almacenarn los datos
Objetivo : capturar los datos de un equipo
Retorno : ---
*/
void capturarDatosEquipo(EQUIPO *equipo)
{
printf("Nombre del equipo: ");
captureTextField(equipo->descripcion, LENDESC, 19, 3, FALSE, FALSE);
printf("Cantidad en inventario: ");
captureIntegerField(&equipo->cantinventario, 10, 24, 4);
printf("Precio de pr%cstamo: ", 130);
captureNumericField(&equipo->precioprestamo, 10, 2, 20, 5);
printf("Precio de venta: ");
captureNumericField(&equipo->costoequipo, 10, 2, 17, 6);
// la cantidad de equipos prestados inicia en 0
equipo->cantprestados = 0;
// generando un ID para el equipo
randomString(equipo->idequipo, RANDSTR5, INFNUM, SUPNUM);
return;
}
/*
Funcin : insertarFrenteEquipo
Arrgumentos : NODOEQUIPO **cabeza: cabeza de la lista
EQUIPO info: nueva infromacin
Objetivo : insertar informacin de equipos al inicio de la lista
Retorno : ---
*/
void insertarFrenteEquipo(NODOEQUIPO **cabeza, EQUIPO info)
{
NODOEQUIPO *nuevo = (NODOEQUIPO*)malloc(sizeof(NODOEQUIPO));
nuevo->datos = info;
nuevo->siguiente = (*cabeza);
nuevo->anterior = NULL;
if ((*cabeza) != NULL)
(*cabeza)->anterior = nuevo;
(*cabeza) = nuevo;
return;
}
/*
Funcin : listarEquipos
Arrgumentos : NODOEQUIPO *equipos: lista donde estn almacenados los equipos
int n: cantidad de clientes
int px: poscin en x
int py: posicin en y
int rango: cantidad de equipos mostrados en el men de scroll
Objetivo : desplegar un men con cursor para seleccionar un equipo
Retorno : (int) pos: equipo seleccionado
*/
int listarEquipos(NODOEQUIPO *equipos, int n, int px, int py, int rango)
{
char tecla;
int pos = 0, inf = 0, sup = rango;
_setcursortype(FALSE);
do {
mostrarEquipos(equipos, n, px, py, pos, inf, sup);
do {
tecla = getch();
} while (tecla != ARRIBA && tecla != ABAJO && tecla != ENTER && tecla != ESC);
if (tecla != ESC)
{
if (tecla == ARRIBA)
{
if (pos != 0)
{
pos--;
if (pos < inf)
{
inf--;
sup--;
}
}
else
{
pos = n-1;
sup = n-1;
inf = sup-rango;
}
}
else if (tecla == ABAJO)
{
if (pos < n-1)
{
pos++;
if (pos > sup)
{
sup++;
inf++;
}
}
else
{
pos = 0;
inf = 0;
sup = rango;
}
}
}
else pos = EXIT;
} while (tecla != ENTER && tecla != ESC);
_setcursortype(100);
return pos;
}
/*
Funcin : mostrarEquipos
Arrgumentos : NODOEQUIPO *equipos: lista donde estn almacenados los equipos
int n: cantidad de clientes
int px: poscin en x
int py: posicin en y
int inf: indica el primer equipo mostrado en la salida
int sup: indica el ltimo equipo mostrado en la salida
Objetivo : mostrar los equipos
Retorno : ---
*/
void mostrarEquipos(NODOEQUIPO *equipos, int n, int px, int py, int actual, int inf, int sup)
{
NODOEQUIPO *index = equipos;
int cont, renglon;
// se recorre la lista hasta el primer cliente que
// se mostrar en el men de scroll
for (cont = 0; cont != inf; cont++)
index = index->siguiente;
gotoxy(px, py);
setColor(WHITE, GREEN);
printf(" ID Descripci%cn Inventario Alquilados Pr%cstamo Costo ", 162, 130);
char espacio[] = " ";
for (index, cont = inf, renglon = 0; cont <= sup && index != NULL; index = index->siguiente, cont++, renglon++)
{
gotoxy(px, py+renglon+2);
setColor(BLUE, LIGHTGRAY);
if (cont == actual)
setColor(YELLOW, BLUE);
printf("%s", espacio);
gotoxy(px+1, py+renglon+2);
printf("%s", index->datos.idequipo);
gotoxy(px+9, py+renglon+2);
printf("%s", index->datos.descripcion);
gotoxy(px+32, py+renglon+2);
printf("%d", index->datos.cantinventario);
gotoxy(px+45, py+renglon+2);
printf("%d", index->datos.cantprestados);
gotoxy(px+58, py+renglon+2);
printf("%.2f", index->datos.precioprestamo);
gotoxy(px+69, py+renglon+2);
printf("%.2f", index->datos.costoequipo);
}
defaultColor();
return;
}
/*
Funcin : modificarInfoEquipos
Arrgumentos : NODOCLIENTE *equipo: regerencia del equipo
int campo: indica el campo que se va a modificar
Objetivo : modificar un campo en la informacin del equipo
Retorno : ---
*/
void modificarInfoEquipos(NODOEQUIPO *equipos, int campo)
{
int px = INIX+23, py = INIY+2+campo;
if (campo == 0)
{
captureTextField(equipos->datos.idequipo, MAXIDEQUIPO-1, px, py, FALSE, TRUE);
}
if (campo == 1)
{
captureTextField(equipos->datos.descripcion, LENDESC-1, px, py, FALSE, FALSE);
}
if (campo == 2)
{
captureIntegerField(&equipos->datos.cantinventario, 10, px, py);
}
if (campo == 3)
{
captureNumericField(&equipos->datos.precioprestamo, 10, 2, px, py);
}
if (campo == 4)
{
captureNumericField(&equipos->datos.costoequipo, 10, 2, px, py);
}
}
/*
Funcin : eliminarEquipo
Arrgumentos : NODOEQUIPO **cabeza: referencia a la cabeza de la lista
NODOEQUIPO *elim: nodo de la lista a eliminar
Objetivo : eliminar un equipo
Retorno : ---
*/
void eliminarEquipo(NODOEQUIPO **cabeza, NODOEQUIPO *elim)
{
if ((*cabeza) == NULL || elim == NULL)
return;
if ((*cabeza) == elim)
(*cabeza) = elim->siguiente;
if (elim->siguiente != NULL)
elim->siguiente->anterior = elim->anterior;
if (elim->anterior != NULL)
elim->anterior->siguiente = elim->siguiente;
free(elim);
return;
}
/*
Funcin : insertarFrenteProyecto
Arrgumentos : NODOPROYECTO **cabeza: cabeza de la lista
PROYECTO info: nueva infromacin
Objetivo : insertar informacin de proyectos al inicio de la lista
Retorno : ---
*/
void insertarFrenteProyecto(NODOPROYECTO **cabeza, PROYECTO info)
{
NODOPROYECTO *nuevo = (NODOPROYECTO*)malloc(sizeof(NODOPROYECTO));
nuevo->datos = info;
nuevo->siguiente = (*cabeza);
nuevo->anterior = NULL;
if ((*cabeza) != NULL)
(*cabeza)->anterior = nuevo;
(*cabeza) = nuevo;
return;
}
void insertarFrentePropcontracto(NODOPROPCONTRACTO **cabeza, PROPCONTRACTO info)
{
NODOPROPCONTRACTO *nuevo = (NODOPROPCONTRACTO*)malloc(sizeof(NODOPROPCONTRACTO));
nuevo->datos = info;
nuevo->siguiente = (*cabeza);
nuevo->anterior = NULL;
if ((*cabeza) != NULL)
(*cabeza)->anterior = nuevo;
(*cabeza) = nuevo;
return;
}
/*
Funcin : nuevoProyecto
Arrgumentos : NODOPROYECTO *cabproyectos: lsita de los proyectos
char *fclientes: nombre del archivo con la informacin de los clientes
Objetivo : iniciar un nuevo proyecto
Retorno : (PROYECTO) proyecto: informacin de un nuevo proyecto
*/
PROYECTO nuevoProyecto(NODOPROYECTO *cabproyectos, char *fclientes)
{
PROYECTO *proyecto = (PROYECTO*)calloc(1, sizeof(PROYECTO));
NODOCLIENTE *cabclientes = NULL, *temp;
CLIENTE cliente;
FILE *pf;
int index, seleccionar, cantclientes;
printf("Digite la informaci%cn del proyecto:\n\n", 162);
printf("Descripci%cn: ", 162);
captureTextField(proyecto->descripcion, LENDESC-1, 13, 3, FALSE, FALSE);
// seleccionando el cliente dueo del proyecto
if ((pf = fopen(fclientes, "rb")) != NULL)
{
cantclientes = fsize(pf)/sizeof(CLIENTE);
while (!feof(pf))
{
fread(&cliente, sizeof(CLIENTE), 1, pf);
insertarFrenteCliente(&cabclientes, cliente);
}
fclose(pf);
}
else
{
printf("\nNo hay clientes agregados.");
Sleep(DELAY);
return;
}
printf("\nDue%co del proyecto:", 164);
seleccionar = listarClientes(cabclientes, cantclientes, INIX, INIY+5, RANGO);
temp = cabclientes;
for (index = 0; index < seleccionar; index++)
temp = temp->siguiente;
strcpy(proyecto->idcliente, &temp->datos.idcliente);
// generando un id aleatorio para el proyecto
randomString(proyecto->idproyecto, RANDSTR5, INFNUM, SUPNUM);
return (*proyecto);
}
/*
Funcin : captureTextField
Arrgumentos : char* str : cadena de texto a capturar
int n : longitud de "str"
char* tipo : indica el mensaje segn el tipo de dato
int pos_x : posicin en las columnas
int pos_y : posicin en las filas
int flag : indica si se restringe el espacio
int alfanumeric: indica si el campo ser alfa-numrico
Objetivo : capturar campo de tipo texto
Retorno : ---
*/
void captureTextField(char* str, int n, int pos_x, int pos_y, int flag, int alfanumeric)
{
int index, last;
char key, temp[n];
for (index = 0; *(str+index) != NULL; index++);
last = index;
do {
showField(str, index, n, pos_x, pos_y);
do {
key = getch();
} while (!(key >= 33 && key <= 126) && key != IZQUIERDA && key != DERECHA &&
key != BARRA && key != BKSP && key != ESC && key != ENTER);
if (alfanumeric && !(key >= INFNUM && key <= SUPNUM) && key != BKSP && key != ESC && key != ENTER)
continue;
if (key == DERECHA)
{
if (index < n-1 && index < last)
{
index++;
}
}
else if (key == IZQUIERDA)
{
if (index > 0)
index--;
}
else if (key == BARRA)
{
if (!flag)
{
// se verifica que los caracteres no se salgan del margen
// permitido al presionar la barra espaciadora
if (index < n-1 && strEnd(str) < n)
{
strcpy(temp, str+index);
strcpy(str+index, " ");
strcpy(str+index+1, temp);
index++;
last++;
}
}
}
else
{
if (key != ENTER && key != ESC)
{
if (key == BKSP)
{
if (index)
{
strcpy(temp, str+index);
index--;
strcpy(str+index, temp);
last--;
}
}
else if (index < n)
{
*(str+index) = key;
index++;
if (index > last)
last = index;
}
}
}
*(str+last) = NULL;
} while (key != ENTER && key != ESC);
clearLine(pos_x, pos_y);
gotoxy(pos_x, pos_y);
printf(" %s", str);
printf("\n");
return;
}
/*
Funcin : strEnd
Arrgumentos : char* str : cadena de texto
Objetivo : encontrar la posicin del caracter NULL
Retorno : (int) count : posicin del caracter NULL
*/
int strEnd(char* str)
{
int count = 0;
while (*(str+count))
count++;
return count;
}
/*
Funcin : captureDateField
Arrgumentos : char* str : cadena de texto a capturar
int n : longitud de "str"
int pos_x : columnas
int pos_y : filas
Objetivo : capturar campo de tipo fecha
Retorno : ---
*/
void captureDateField(char* str, int n, int pos_x, int pos_y)
{
int index = 0, last = index;
char key;
do {
showField(str, index, n, pos_x, pos_y);
do {
key = getch();
} while (!(key >= INFNUM && key <= SUPNUM) && key != SLASH && key != ENTER && key != ESC
&& key != DERECHA && key != IZQUIERDA && key != BKSP);
if (key == DERECHA)
{
if (index < n-1 && index < last)
index++;
}
else if (key == IZQUIERDA)
{
if (index > 0)
index--;
}
else
{
if (key != ENTER && key != ESC)
{
if (key == BKSP)
{
if (index)
{
index--;
*(str+index) = NULL;
last--;
}
}
else if (index < n)
{
*(str+index) = key;
index++;
if (index > last)
last = index;
}
}
}
*(str+last) = NULL;
} while (key != ENTER && key != ESC);
return;
}
/*
Funcin : validDate
Arrgumentos : char* date : fecha en cadena de texto
int* day : almacena el da en "date"
int* month : almacena el mes en "date"
int* year : almacena el ao en "date"
Objetivo : validar que la fecha y su formato sean correctos
Retorno : (int) 1 si la fecha es correcta; (int) 0 en caso contrario
*/
int validDate(char* date, int* day, int* month, int* year)
{
int index, count;
// validando la posicin de los slash
if (*(date+2) != SLASH && *(date+5) != SLASH)
return FALSE;
// validando la cantidad de nmeros
for (index = 0, count = 0; index < MAXDATE; index++)
{
if (*(date+index) >= '0' && *(date+index) <= '9')
count++;
}
if (count != 8) return FALSE;
char temp[MAXDATE-6];
int d_months[] = {DM31, DM30-2, DM31, DM30, DM31, DM30, DM31, DM31, DM30, DM31, DM30, DM31};
strncpy(temp, date, 2);
*day = strtol(temp, NULL, 10);
strncpy(temp, date+3, 2);
*month = strtol(temp, NULL, 10);
strncpy(temp, date+6, 4);
*year = strtol(temp, NULL, 10);
// validando la cantidad de das en los meses
if (*month <= 12 && *month > 0 && *day > 0)
{
if (*month == FEB)
{
// validando ao bisiesto
if ( *day == DM30-1 && !(*year % 4) )
return TRUE;
}
if (*day > d_months[*month-1])
return FALSE;
}
else
return FALSE;
return TRUE;
}
/*
Funcin : captureIntegerField
Arrgumentos : int* num : nmero a capturar
int digits : cantidad de dgitos permitidos en "str"
int pos_x : posicin en las columnas
int pos_y : posicin en las filas
Objetivo : capturar campo de tipo numrico
Retorno : ---
*/
void captureIntegerField(int* num, int digits, int pos_x, int pos_y)
{
int index = 0, n = digits, last = index;
char key, *str;
str = (char*)calloc(digits, sizeof(char));
do {
showField(str, index, n, pos_x, pos_y);
do {
key = getch();
} while (!(key >= '0' && key <= '9') && key != ENTER && key != ESC &&
key != DERECHA && key != IZQUIERDA && key != BKSP);
if (key == DERECHA)
{
if (index < n-1 && index < last)
index++;
}
else if (key == IZQUIERDA)
{
if (index > 0)
index--;
}
else
{
if (key != ENTER && key != ESC)
{
if (key == BKSP)
{
if (index)
{
index--;
*(str+index) = NULL;
last--;
}
}
else if (index < n)
{
*(str+index) = key;
index++;
if (index > last)
last = index;
}
}
}
*(str+last) = NULL;
} while (key != ENTER && key != ESC);
*num = strtol(str, NULL, 10);
clearLine(pos_x, pos_y);
gotoxy(pos_x, pos_y);
printf(" %d", *num);
printf("\n");
return;
}
/*
Funcin : captureNumericField
Arrgumentos : int* num : nmero a capturar
int digits : cantidad de dgitos permitidos en "str"
int precision : cantidad de nmeros despus del punto
int pos_x : posicin en las columnas
int pos_y : posicin en las filas
Objetivo : capturar campo de tipo numrico
Retorno : ---
*/
void captureNumericField(float* num, int digits, int precision, int pos_x, int pos_y)
{
int index = 0, n = digits, last = index, flag = FALSE;
char key, *str;
str = (char*)calloc(digits, sizeof(char));
do {
showField(str, index, n, pos_x, pos_y);
do {
key = getch();
} while (!(key >= '0' && key <= '9') && (key != DOT && !flag) && key != ENTER
&& key != ESC && key != DERECHA && key != IZQUIERDA && key != BKSP);
if (key == DERECHA)
{
if (index < n-1 && index < last)
index++;
}
else if (key == IZQUIERDA)
{
if (index > 0)
index--;
}
else if (key == DOT)
{
if (!flag)
{
*(str+index) = key;
index++;
if (index > last)
last = index;
}
}
else
{
if (key != ENTER && key != ESC)
{
if (key == BKSP)
{
if (index)
{
index--;
*(str+index) = NULL;
last--;
}
}
else if (index < n)
{
*(str+index) = key;
index++;
if (index > last)
last = index;
}
}
}
flag = FALSE;
for (int count = 0; *(str+count); count++)
{
if (*(str+count) == DOT)
{
flag = TRUE;
if ( (n - (count+1)) > precision )
{
n = count+precision+1;
clearLine(pos_x, pos_y);
}
break;
}
}
*(str+last) = NULL;
if (flag)
continue;
else
n = digits;
} while (key != ENTER && key != ESC);
*num = strtof(str, NULL);
clearLine(pos_x, pos_y);
gotoxy(pos_x, pos_y);
printf(" %.2f", *num);
printf("\n");
return;
}
/*
Funcin : showField
Arrgumentos : char* str : cadena de texto
int pos : posicin del cursor
int n : longitud de "str"
int x : posicin en x (columnas)
int y : posicin en y (filas)
Objetivo : mostrar el campo de texto
Retorno : ---
*/
void showField(char* str, int pos, int n, int x, int y)
{
int index;
setColor(BLUE, LIGHTGRAY);
for (index = 0; index < n; index++)
{
gotoxy(x+index+1, y);
if (*(str+index))
printf("%c", *(str+index));
else
printf(" ");
}
defaultColor();
gotoxy(x+pos+1, y);
return;
}
/*
Funcin : clearLine
Arrgumentos : int pos_x: columnas
int pos_y: filas
Objetivo : borrar la lnea "line"
Retorno : ---
*/
void clearLine(int pos_x, int pos_y)
{
for (pos_x; pos_x <= MAXLINE; pos_x++)
{
gotoxy(pos_x, pos_y);
printf(" ");
}
return;
}
|
C | #include <stdio.h>
#define D_S 1
#if D_S
#include <conio.h>
#endif
char* expand(char const * const, char *);
char* expand(char const * const s1, char * s2){
static char oc = '\0';
char *psrc = s1, *ptar = s2;
while(*psrc != '\0'){
switch(*psrc){
case '-':
if(oc && oc < psrc[1]){
++psrc;
while(*psrc > oc)
*ptar++ = ++oc;
}else
*ptar++ = *psrc;
break;
default:
*ptar++ = *psrc;
break;
}
oc = *psrc++;
}
*ptar = '\0';
return s2;
}
#if D_S
int main(){
char a[] = {"-a-g-pGoodhp-aHello-zWorld0-5W-Z-----"},
b[125];
clrscr();
printf("Original=%s\n", a);
printf("First =%s\n", expand(a, b));
return 0;
}
#endif |
C | #include "file.h"
int main(int argc, char *argv[]) {
char *name_source, *name_result;
char step_to_step_mode = 0; //0 pour directe, 1 pour pas à pas
char error_check = 0;
program prog;
char input = '\0';
printf(" ----------MIPS EMULATOR---------- \n");
if (argc > 3) printf("ERROR : Unvalid numbers of arguments => Please specify the source file and the mode (if needed)\n");
else if (argc >= 2) {
data_counter = 0;
name_source = *(argv+1);
name_result = *(argv+1);
if (argc == 3){
if (strcmp(argv[2],"-pas")) {
printf("Unknown mode : please mark '-pas' if you want the step_to_step mode\n\nQuitting program");
error_check = 1;
}
else step_to_step_mode = 1;
}
if (!error_check){
test_and_hexified(&name_source, &name_result);
prog = init_program();
init_label_list();
printf("\nSource file : %s\nThe output will be written in : %s\n\n",name_source, name_result);
if (step_to_step_mode) printf("--- Please note that instructions with labels will have their correct hexadecimal traduction after the program is fully read.\n");
read_file(name_source, prog, step_to_step_mode);
translate_to_hexa(prog);
write_file(name_result, prog);
init_registers();
init_data_memory();
print_prog(prog);
printf("**** Press [enter] to start execute ****\n");
scanf("%c",&input);
execution(prog, step_to_step_mode);
printf("\n Final processor state :\n\n");
print_registers();
print_memory();
printf("\nProgram finished.\n\n");
free_memory();
free_label();
free_prog(prog);
}
}
else {
printf("\n---- You are in the interactive mode of the MIPS emulator.");
printf("\n---- If you want to use a program file, please exit and use './emul-mips your_file -pas (optionnal)'");
printf("\n---- Please note that your file should be in the 'tests' directory.\n");
init_registers();
init_data_memory();
interactive_mode();
free_memory();
}
printf("--------- Quitting emulator ---------\n");
return 0;
}
|
C | int gotoxy(int y, int x){
printf("\033[%d;%dH",y,x);
}
char buttonLabel[8][60]={
{"1. Add student"},
{"2. Search Student"},
{"3. Modify Student Record"},
{"4. Generate Marksheet"},
{"5. Delete Student Record"},
{"6. Change Password"},
{"7. Exit"},
{"What do you want:"}
};
int mapButton[8][2]={ // [0] is y and [1] is x
{3,4}, //1. Add Student
{3,35},//2. Search Student
{6,4}, //3. Modify Student Record
{6,35},//4. Generate Marksheet
{9,4}, //5. Delete Student Record
{9,35},//6. Change Student Record
{12,4},// 7. Exit
{12,4}
};
int drawColumn(){
int count;
for (count = 1; count < 13; count++) printf("|\033[D\033[B");
}
int drawRow(int n){
int count;
for (count = 0; count < n; count++) printf("%c",((count==28&&n!=59)||(n==58&&count == 57))?'|':'_');
}
int drawWindowFrame(){
gotoxy(1,1);
int count;
drawRow(59);// Top Edge
gotoxy(2,1);
drawColumn();
gotoxy(2,59);
drawColumn();
gotoxy(2,30);
drawColumn();
gotoxy(13,2);
drawRow(58);// Bottom Edge
gotoxy(4,2);
drawRow(57);// Normal Edge
gotoxy(20,20);
gotoxy(7,2);
drawRow(57);// Normal Edge
gotoxy(10,2);
drawRow(57);// Normal Edge
gotoxy(12,22);
}
int mainWindow(){
int count;
for (count = 0; count<8; count++){
gotoxy(mapButton[count][0],mapButton[count][1]);
printf("%s",buttonLabel[count]);
}
}
|
C | // ex8
// Typedef
// Named structures
// Anon. structures, typedef is declared just after the struct
// Plain typedef
struct a{
int fa;
};
typedef struct {
int fb;
};
typedef int myint;
typedef myint myint2;
typedef struct a sa;
typedef sa tsa;
typedef struct {
int fb;
}sb, sb2;
typedef sb tsb;
typedef int a1[3];
typedef a1 *a2;
typedef a2 a3[5];
a3 va3;
typedef int *(*( *(a4[5])));
int f1(){
myint vv1;
myint2 vv2;
tsa vv3;
sb vv4;
a1 vv5;
a3 vv6;
vv1 = 1;
vv2 = 2;
vv3.fa = 3;
vv4.fb = 4;
vv5[2] = 5;
vv6[4] = &vv5;
a3[4] = &vv5;
return 0;
} |
C | #include <stdio.h>
int main()
{
char a[100];
int i,uper,lower,marks,num;
i=0;
uper=0;
lower=0;
marks=0;
num=0;
printf("please input a string:\n") ;
scanf("%s",a);
i=0;
while(a[i]!=NULL)
{
if(a[i]<=57&&a[i]>=48)
{
num++;
}
else
{
if(a[i]<=90&&a[i]>=65)
{
uper++;
}
else
{
if(a[i]<=122&&a[i]>=97)
{
lower++;
}
else
{
marks++;
}
}
}
i++;
}
printf("total chars: %d \n",i) ;
printf("uper chars: %d \n",uper) ;
printf("lower chars: %d \n",lower) ;
printf("number chars: %d \n",num) ;
printf("other chars: %d \n",marks) ;
}
|
C | #define _CRT_SECURE_NO_WARNINGS
#include"LinkStack.h"
int IsNumber(char c)
{
return c >= '0' && c <= '9';
}
void NumberOperate(char* p)
{
printf("%c", *p);
}
int IsLeft(char c)
{
return c == '(';
}
int IsRight(char c)
{
return c == ')';
}
int IsOperator( char c)
{
return c == '+' || c == '-' || c == '*' || c == '/';
}
int GetPriority(char c)
{
if (c == '*' || c == '/')
{
return 2;
}
if (c == '+' || c == '-')
{
return 1;
}
return 0;
}
typedef struct MYCHAR
{
LinkNode node;
char* p;
}MyChar;
MyChar* CreateMychar(char* p)
{
MyChar* mychar = (MyChar*)malloc(sizeof(MyChar));
mychar->p = p;
return mychar;
}
void LeftOperate(LinkStack* stack, char* p)
{
Push_LinkStack(stack, (LinkNode*)CreateMychar(p));
}
void RightOperate(LinkStack* stack)
{
while (Size_LinkStack(stack) > 0)
{
MyChar* mychar = (MyChar*)Top_LinkStack(stack);
if (IsLeft(*(mychar->p)))
{
Pop_LinkStack(stack);
break;
}
printf("%c", *(mychar->p));
Pop_LinkStack(stack);
free(mychar);
}
}
void OperatorOperate(LinkStack* stack, char* p)
{
MyChar* mychar = (MyChar*)Top_LinkStack(stack);
if (mychar == NULL)
{
Push_LinkStack(stack, (LinkNode*)CreateMychar(p));
return;
}
if (GetPriority(*(mychar->p)) < GetPriority(*p))
{
Push_LinkStack(stack, (LinkNode*)CreateMychar(p));
return;
}
else
{
while (Size_LinkStack(stack) > 0)
{
MyChar* mychar2 = (MyChar*)Top_LinkStack(stack);
if (GetPriority(*(mychar2->p)) < GetPriority(*p))
{
Push_LinkStack(stack, (LinkNode*)CreateMychar(p));
break;
}
printf("%c", *(mychar2->p));
Pop_LinkStack(stack);
free(mychar2);
}
}
}
int main()
{
char* str = "8+(3-1)*5";
char* p = str;
LinkStack* stack = Init_LinkStack();
while (*p != '\0')
{
if (IsNumber(*p))
{
NumberOperate(p);
}
if (IsLeft(*p))
{
LeftOperate(stack, p);
}
if (IsRight(*p))
{
RightOperate(stack);
}
if (IsOperator(*p))
{
OperatorOperate(stack, p);
}
p++;
}
while (Size_LinkStack(stack) > 0)
{
MyChar* mychar = (MyChar*)Top_LinkStack(stack);
printf("%c", *(mychar->p));
Pop_LinkStack(stack);
free(mychar);
}
printf("\n");
return 0;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tzerates <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/07 14:06:24 by tzerates #+# #+# */
/* Updated: 2020/01/16 15:58:44 by tzerates ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_free(char **index, int count)
{
while (count > -1)
{
free(index[count]);
count--;
}
free(index);
return (NULL);
}
static void ft_strcpy(char *dest, char *src, unsigned int n)
{
unsigned int i;
i = 0;
while (src[i] && i < n)
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
static unsigned int count_words(const char *str, char c)
{
unsigned int i;
unsigned int nb_words;
unsigned int word_len;
nb_words = 0;
i = 0;
while (str[i])
{
while (str[i] && str[i] == c)
i++;
word_len = 0;
while (str[i + word_len] && str[i + word_len] != c)
word_len++;
if (word_len)
nb_words++;
i += word_len;
}
return (nb_words);
}
static char **fill_words(char **index, const char *str,
char c, unsigned int nb_words)
{
unsigned int word_len;
unsigned int i;
unsigned int j;
i = -1;
j = 0;
while (++i < nb_words)
{
while (str[j] && str[j] == c)
j++;
word_len = 0;
while (str[j + word_len] && str[j + word_len] != c)
word_len++;
index[i] = (char*)malloc(sizeof(char) * (word_len + 1));
if (!index[i])
return (ft_free(index, i));
ft_strcpy(index[i], (char*)&str[j], word_len);
j += word_len;
}
return (index);
}
char **ft_split(const char *str, char c)
{
char **index;
unsigned int nb_words;
if (!str)
return (NULL);
nb_words = count_words((char*)str, c);
index = (char**)malloc(sizeof(char*) * (nb_words + 1));
if (!index)
return (NULL);
index = fill_words(index, (char*)str, c, nb_words);
index[nb_words] = 0;
return (index);
}
|
C | #include <stdio.h>
int main(void)
{
int n,i;
int v[10]={0};
printf("请输入一个正整数:");
scanf("%d",&n);
while(n>0){
switch(n%10)
{
case 0:v[0]=v[0]+1;break;
case 1:v[1]=v[1]+1;break;
case 2:v[2]=v[2]+1;break;
case 3:v[3]=v[3]+1;break;
case 4:v[4]=v[4]+1;break;
case 5:v[5]=v[5]+1;break;
case 6:v[6]=v[6]+1;break;
case 7:v[7]=v[7]+1;break;
case 8:v[8]=v[8]+1;break;
case 9:v[9]=v[9]+1;break;
}
n=n/10;
}
for(i=0;i<10;i++)
if(v[i]>0)
printf("%d出现次数:%d\n",i,v[i]);
return 0;
} |
C | /*
A01 Fraction Program
Program Structure:
- This file:
Runs fnctions from various header files.
- IO.h
Header file containing IO functions,
Interface between User and Program
- Operations.h
Header file containing all functions created for specific operations,
Including Addition, Subtraction, Multiplication, and so on...
All those functions are abstracted away.
The only visible functions are decideWhatToDo, and doWhatIsToBeDone.
decideWhatToDo will return a function pointer that doWhatIsToBeDone runs.
- DataBase.h
Contains MultiDimensional Arrays that can be used to store data.
Syntax Sugar: Just include this header file to access these arrays instead
of passing them by reference each time.
@author Abdul Mannan Syed, [email protected]
@author Collin McMcormack, [email protected]
@date 10/26/2021
*/
// Header files
#include "IO.h"
#include "Operations.h"
#include "DataBase.h"
// Entry Point of Program
int main() {
ClearConsole();
//
while(DataBase_ProgramCanRun()) {
// Holds User Choice
int UserChoice;
// Showing Option Menu, and getting user response
showMenu(&UserChoice);
// Deciding what function to run, based on user choice
getFunctionToRun(UserChoice)();
return 0;
}
} |
C | /******************************************************************************
filename RoomExit.h
author Matthew Picioccio
DP email [email protected]
course GAM100 ** Do not use this code in your team project
Brief Description:
This file declares the RoomExit interface, which is used to manage room exits
in the game.
******************************************************************************/
#pragma once
#include "stdafx.h" /* bool */
/* Forward declaration for the RoomExit type */
typedef struct RoomExit RoomExit;
/* Adds an exit to a given list, which might be NULL (an empty list). Returns the new head of the list */
RoomExit* RoomExit_Add(RoomExit* existingList, const char* direction, int nextRoomIndex, bool showInHelp);
/* Free the memory associated with a linked list of RoomExits */
void RoomExit_Free(RoomExit** roomExitListPtr);
/* Find the next room index associated with a given direction */
bool RoomExit_Find(RoomExit* roomExitList, const char* direction, int* outNextRoomIndex);
/* Print the list of exits to standard output */
void RoomExit_Print(RoomExit* roomExitList); |
C | #include "pthreads.h"
int count = 0;
int capacity = INIT_CAPACITY;
// int numberArray[INIT_CAPACITY];
int *numberArray;
int finalArray[INIT_CAPACITY];
int main(int argc, char *argv[])
{
pthread_t tid_s1; /* The thread identifier */
pthread_t tid_s2; /* The thread identifier */
pthread_t tid_m; /* The thread identifier */
pthread_attr_t attr_s1; /* The set of thread attributes */
pthread_attr_t attr_s2; /* The set of thread attributes */
pthread_attr_t attr_m; /* The set of thread attributes */
if (argc == 2)
{
numberArray = malloc(INIT_CAPACITY * sizeof(numberArray));
FILE *myFile;
myFile = fopen(argv[1], "r");
//read file into array
int i, num, ch;
if (myFile == NULL)
{
printf("Error Reading File\n");
exit (0);
}
ch = fscanf(myFile, "%d,", &num);
while (ch != EOF)
{
if (count >= capacity)
{
capacity *= 2;
numberArray = realloc(numberArray, capacity * sizeof(*numberArray));
}
numberArray[count] = num;
ch = fscanf(myFile, "%d,", &num);
count++;
}
fclose(myFile);
printArray(count, 1);
/* Create parameter structs */
parameters *p1 = param_left_create(count);
parameters *p2 = param_right_create(count);
parameters *p3 = param_merge_create(count);
/* Get the default attributes */
pthread_attr_init(&attr_s1);
pthread_attr_init(&attr_s2);
pthread_attr_init(&attr_m);
/* Create the thread */
pthread_create(&tid_s1, &attr_s1, sort, (void *) p1);
pthread_create(&tid_s2, &attr_s2, sort, (void *) p2);
/* Wait for the thread to exit */
pthread_join(tid_s1, NULL);
pthread_join(tid_s2, NULL);
pthread_create(&tid_m, &attr_m, sort, (void *) p3);
pthread_join(tid_m, NULL);
printArray(count, 0);
free(p1);
free(p2);
free(p3);
free(numberArray);
}
else
{
printf("Please provide the filename.\n");
exit (0);
}
return 0;
}
parameters *param_merge_create(int length)
{
parameters *temp = (parameters *) malloc(sizeof(parameters));
temp->start = 0;
temp->end = length - 1;
return temp;
}
parameters *param_left_create(int length)
{
parameters *temp = (parameters *) malloc(sizeof(parameters));
temp->start = 0;
temp->end = length / 2 - 1;
return temp;
}
parameters *param_right_create(int length)
{
parameters *temp = (parameters *) malloc(sizeof(parameters));
temp->start = length / 2;
temp->end = length - 1;
return temp;
}
void *sort(void *param)
{
parameters *data = (parameters *) param;
quicksort(data->start, data->end);
pthread_exit(0);
}
void quicksort(int l, int r)
{
int j;
if( l < r )
{
// divide and conquer
j = partition(l, r);
quicksort(l, j-1);
quicksort(j+1, r);
}
}
int partition(int l, int r)
{
int pivot, i, j, t;
pivot = numberArray[l];
i = l;
j = r+1;
while(1)
{
do ++i;
while(numberArray[i] <= pivot && i <= r);
do --j;
while(numberArray[j] > pivot);
if(i >= j)
{
break;
}
t = numberArray[i];
numberArray[i] = numberArray[j];
numberArray[j] = t;
}
t = numberArray[l];
numberArray[l] = numberArray[j];
numberArray[j] = t;
return j;
}
void printArray(int count, int initial)
{
if (initial)
{
printf("Initial: [%d", numberArray[0]);
}
else
{
printf("Sorted: [%d", numberArray[0]);
}
int i;
for (i = 1; i < count; i++)
{
printf(", %d", numberArray[i]);
}
printf("]\n");
} |
C | //
// Created by win10 on 2021/6/19.
//
#include "Student.h"
struct StudentTable init_student_table() {
struct StudentTable table;
strcpy(table.type, "S");
// Fill the table with 1000 demo entries
for (int i = 1; i <= 1000; ++i) {
// Init student
struct Student *demo_student = malloc(sizeof(struct Student));
memset(demo_student, 0, sizeof(struct Student)); // Clean up the memory.
demo_student->student_number = i;
strcpy(demo_student->student_name, "ChopperCP");
strcpy(demo_student->gender, "Male");
demo_student->age = 21;
strcpy(demo_student->school, "School of Intelligence Engineering Science");
// Fill the table
table.data[i - 1] = demo_student;
table.last_available = i;
}
return table;
}
int compare_student(const void *lhs, const void *rhs) {
unsigned int lhs_student_number = (*((struct Student **) lhs))->student_number;
unsigned int rhs_student_number = (*((struct Student **) rhs))->student_number;
return lhs_student_number - rhs_student_number;
}
int compare_student_student_course(const void *lhs, const void *rhs) {
unsigned int lhs_student_number = (*((struct Student **) lhs))->student_number;
unsigned int rhs_student_number = (*((struct StudentCourse **) rhs))->student_number;
return lhs_student_number - rhs_student_number;
}
int add_student(struct StudentTable *table, struct Student *student) {
if (table->last_available >= MAX_STUDENT_TABLE_ENT_CNT) {
printf("[!] Not enough space in the table.");
return -1;
}
// Insert the student to the last place.
table->data[table->last_available++] = student;
// Sort the table.
qsort(table->data, table->last_available, sizeof(struct Student *), compare_student);
return 0;
}
void _clean_Student_from_StudentTable(struct Student **result_student, struct StudentTable *student_table) {
struct Student **start = result_student;
struct Student **end = result_student;
struct Student **last_table_entry = &(student_table->data[student_table->last_available - 1]);
while ((*end)->student_number == (*result_student)->student_number) {
printf("[*] Entry found, student number: %u\n",(*end)->student_number);
++end;
}
// From start-end is the memory which will be cleaned.
// Move the rest forward.
while (end <= last_table_entry) {
memcpy(start++, end++, sizeof(struct Student *));
}
student_table->last_available -= end - start;
}
void _clean_Student_from_StudentCourseTable(struct StudentCourse **result_student_course,
struct StudentCourseTable *student_course_table) {
struct StudentCourse **start = result_student_course;
struct StudentCourse **end = result_student_course;
struct StudentCourse **last_table_entry = &(student_course_table->data[student_course_table->last_available - 1]);
while ((*end)->student_number == (*result_student_course)->student_number) {
printf("[*] Entry found, student number: %u, course number: %u\n",(*end)->student_number,(*end)->course_number);
++end;
}
// From start-end is the memory which will be cleaned.
// Move the rest forward.
while (end <= last_table_entry) {
memcpy(start++, end++, sizeof(struct StudentCourse *));
}
student_course_table->last_available -= end - start;
}
int remove_student(struct StudentTable *student_table, struct StudentCourseTable *student_course_table,
struct Student *target_student) {
// Only student_number in target_student is searched, other elements in target_student are ignored.
struct Student **result_student = bsearch(&target_student, student_table->data, student_table->last_available,
sizeof(struct Student *), compare_student);
if (result_student == NULL) {
printf("[!] Student with the number %u not found!\n", target_student->student_number);
return -1;
} else {
printf("[*] Student with the number %u found, name: %s.\n", target_student->student_number,
(*result_student)->student_name);
}
// Remove student from student_table
_clean_Student_from_StudentTable(result_student, student_table);
// Can't use binary search in SC because there are more than 1 entry which has the same student_number.
struct StudentCourse **result_student_course = &student_course_table->data[0];
struct StudentCourse **last_table_entry = &(student_course_table->data[student_course_table->last_available - 1]);
while ((result_student_course <= last_table_entry) &&
((*result_student_course)->student_number != target_student->student_number)) {
++result_student_course;
}
// struct StudentCourse** result_student_course=bsearch(&target_student,student_course_table->data,student_course_table->last_available,sizeof(struct StudentCourse*),compare_student_student_course);
if (result_student_course > last_table_entry) {
// Result not found
result_student_course = NULL;
}
if (result_student_course == NULL) {
printf("[*] Student with the number %u not found in SC\n", target_student->student_number);
return -1;
} else {
printf("[*] Student with the number %u found in SC, course number: %u.\n", target_student->student_number,
(*result_student_course)->course_number);
// Remove student from student_course table.
_clean_Student_from_StudentCourseTable(result_student_course, student_course_table);
}
return 0;
}
int update_student_name(struct StudentTable *student_table, struct Student *target_student) {
// Only student_number in target_student is searched, other elements in target_student are ignored.
// From student_table
struct Student **result_student = bsearch(&target_student, student_table->data, student_table->last_available,
sizeof(struct Student *), compare_student);
if (result_student == NULL) {
printf("[!] Student with the number %u not found!\n", target_student->student_number);
return -1;
} else {
printf("[*] Student with the number %u found, name: %s.\n", target_student->student_number,
(*result_student)->student_name);
}
// Operations
strcpy((*result_student)->student_name, target_student->student_name);
return 0;
}
int update_student_gender(struct StudentTable *student_table, struct Student *target_student) {
// Only student_number in target_student is searched, other elements in target_student are ignored.
// From student_table
struct Student **result_student = bsearch(&target_student, student_table->data, student_table->last_available,
sizeof(struct Student *), compare_student);
if (result_student == NULL) {
printf("[!] Student with the number %u not found!\n", target_student->student_number);
return -1;
} else {
printf("[*] Student with the number %u found, name: %s.\n", target_student->student_number,
(*result_student)->student_name);
}
// Operations
strcpy((*result_student)->gender, target_student->gender);
return 0;
}
int update_student_age(struct StudentTable *student_table, struct Student *target_student) {
// Only student_number in target_student is searched, other elements in target_student are ignored.
// From student_table
struct Student **result_student = bsearch(&target_student, student_table->data, student_table->last_available,
sizeof(struct Student *), compare_student);
if (result_student == NULL) {
printf("[!] Student with the number %u not found!\n", target_student->student_number);
return -1;
} else {
printf("[*] Student with the number %u found, name: %s.\n", target_student->student_number,
(*result_student)->student_name);
}
// Operations
(*result_student)->age = target_student->age;
return 0;
}
int update_student_school(struct StudentTable *student_table, struct Student *target_student) {
// Only student_number in target_student is searched, other elements in target_student are ignored.
// From student_table
struct Student **result_student = bsearch(&target_student, student_table->data, student_table->last_available,
sizeof(struct Student *), compare_student);
if (result_student == NULL) {
printf("[!] Student with the number %u not found!\n", target_student->student_number);
return -1;
} else {
printf("[*] Student with the number %u found, name: %s.\n", target_student->student_number,
(*result_student)->student_name);
}
// Operations
strcpy((*result_student)->school, target_student->school);
return 0;
}
int select_student_number(struct StudentTable *student_table, struct Student *target_student) {
struct Student **result_student = bsearch(&target_student, student_table->data, student_table->last_available,
sizeof(struct Student *), compare_student);
if (result_student == NULL) {
printf("[!] Student with the number %u not found!\n", target_student->student_number);
return -1;
} else {
printf("[*] Student with the number %u found, name: %s.\n", target_student->student_number,
(*result_student)->student_name);
}
return 0;
}
int select_student_name(struct StudentTable *student_table, struct Student *target_student) {
struct Student **result_student = &student_table->data[0];
struct Student **last_table_entry = &(student_table->data[student_table->last_available - 1]);
int found = 0;
while (result_student <= last_table_entry) {
if (strcmp((*result_student)->student_name,target_student->student_name)==0) {
printf("[*] Student with the name %s found, student number: %u.\n", target_student->student_name,
(*result_student)->student_number);
found = 1;
}
++result_student;
}
if (found == 0) {
printf("[*] Student with the name %s not found.\n", target_student->student_name);
return -1;
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#define SIZE 3
int main()
{
int i;
int *ptr;
int *temp;
ptr = (int *)malloc(sizeof(int)*SIZE);
temp = ptr;
for(i=0;i<SIZE;i++)
{
scanf("%d",ptr++);
}
ptr = temp;
for(i=0;i<SIZE;i++)
{
printf("\n%d",*ptr++);
}
return 0;
}
|
C | #include <stdio.h>
#include "holberton.h"
/**
* sqrt_ - fun
* @x: var
* @y: var
*
* Return: 0
*/
int sqrt_(int x, int y)
{
if (x > y)
return (-1);
if ((x * x) == y)
return (x);
else
return (sqrt_(++x, y));
}
/**
* _sqrt_recursion - fun
* @n:var
*
* Return: 0
*/
int _sqrt_recursion(int n)
{
if (n == 0)
return (-1);
return (sqrt_(1, n));
}
|
C | /* Fast Fourier Transform
* Cooley-Tukey algorithm with 2-radix DFT
*/
#include <complex.h>
#define PI 3.14159265358979323846
void fft_slow(int* x, double complex* X, unsigned int N) {
unsigned int n, k;
// Iterate through, allowing X_K = sum_N of the complex frequencies.
for (k = 0; k < N; k++) {
for (n = 0; n < N; n++) {
X[k] += x[n] * cexp(-2 * PI * I * n * k / N);
}
}
}
void fft_radix2(int* x, double complex* X, unsigned int N, unsigned int s) {
unsigned int k;
double complex t;
// At the lowest level pass through (delta T=0 means no phase).
if (N == 1) {
X[0] = x[0];
return;
}
// Cooley-Tukey: recursively split in two, then combine beneath.
fft_radix2(x, X, N/2, 2*s);
fft_radix2(x+s, X + N/2, N/2, 2*s);
for (k = 0; k < N/2; k++) {
t = X[k];
X[k] = t + cexp(-2 * PI * I * k / N) * X[k + N/2];
X[k + N/2] = t - cexp(-2 * PI * I * k / N) * X[k + N/2];
}
}
void fft(int* x, double complex* X, unsigned int N) {
fft_radix2(x, X, N, 1);
}
|
C | #include <stdint.h>
#include <stdbool.h>
// includes da biblioteca driverlib
#include "inc/hw_memmap.h"
#include "driverlib/gpio.h"
#include "driverlib/sysctl.h"
#include "driverlib/systick.h"
#include "grlib/grlib.h"
#include "cfaf128x128x16.h" // Projects/drivers
uint8_t LED_D1 = 0;
tContext sContext;
void DisplayInit(){
cfaf128x128x16Init();
cfaf128x128x16Clear();
GrContextInit(&sContext, &g_sCfaf128x128x16);
GrFlush(&sContext);
GrContextFontSet(&sContext, g_psFontFixed6x8);
GrContextForegroundSet(&sContext, ClrWhite);
GrContextBackgroundSet(&sContext, ClrBlack);
} // DisplayInit
void ContextInit(){
GrStringDraw(&sContext, "Sistemas Embarcados", -1, 6, 60, true);
GrStringDraw(&sContext, "2019/2", -1, 42, 70, true);
} // ContextInit
void SysTick_Handler(void){
GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_1, LED_D1); // Acende ou apaga LED D1
LED_D1 ^= GPIO_PIN_1; // Troca estado do LED D1
} // SysTick_Handler
void main(void){
DisplayInit();
ContextInit();
SysTickPeriodSet(12000000); // f = 1Hz para clock = 24MHz
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPION); // Habilita GPIO N (LED D1 = PN1, LED D2 = PN0)
while(!SysCtlPeripheralReady(SYSCTL_PERIPH_GPION)); // Aguarda final da habilitao
GPIOPinTypeGPIOOutput(GPIO_PORTN_BASE, GPIO_PIN_0 | GPIO_PIN_1); // LEDs D1 e D2 como sada
GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_0 | GPIO_PIN_1, 0); // LEDs D1 e D2 apagados
GPIOPadConfigSet(GPIO_PORTN_BASE, GPIO_PIN_0 | GPIO_PIN_1, GPIO_STRENGTH_12MA, GPIO_PIN_TYPE_STD);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); // Habilita GPIO F (LED D3 = PF4, LED D4 = PF0)
while(!SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOF)); // Aguarda final da habilitao
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_0 | GPIO_PIN_4); // LEDs D3 e D4 como sada
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_0 | GPIO_PIN_4, 0); // LEDs D3 e D4 apagados
GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_0 | GPIO_PIN_4, GPIO_STRENGTH_12MA, GPIO_PIN_TYPE_STD);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOJ); // Habilita GPIO J (push-button SW1 = PJ0, push-button SW2 = PJ1)
while(!SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOJ)); // Aguarda final da habilitao
GPIOPinTypeGPIOInput(GPIO_PORTJ_BASE, GPIO_PIN_0 | GPIO_PIN_1); // push-buttons SW1 e SW2 como entrada
GPIOPadConfigSet(GPIO_PORTJ_BASE, GPIO_PIN_0 | GPIO_PIN_1, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
SysTickIntEnable();
SysTickEnable();
while(1){
if(GPIOPinRead(GPIO_PORTJ_BASE, GPIO_PIN_0) == GPIO_PIN_0) // Testa estado do push-button SW1
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_4, 0); // Apaga LED D3
else
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_4, GPIO_PIN_4); // Acende LED D3
if(GPIOPinRead(GPIO_PORTJ_BASE, GPIO_PIN_1) == GPIO_PIN_1) // Testa estado do push-button SW2
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_0, 0); // Apaga LED D4
else
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_0, GPIO_PIN_0); // Acende LED D4
} // while
} // main |
C | #include <stdio.h>
int pow4(int x) {
return x * x * x * x;
}
int main(void)
{
int x;
printf("请输入整数:");
scanf("%d", &x);
printf("%d 的4次幂是: %d", x, pow4(x));
return 0;
} |
C | #include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main()
{
int a,i,j,b,d,c;
scanf("%d", &i);
for (a=0; a<i; a++)
{
for (b=(i-1-a); b>0; b--)
printf(" ");
for (j=0; j<=a; j++)
printf("#");
printf("\n");
}
return 0;
}
|
C | //
// Created by seanchen on 2020-02-15.
//
#include <stdio.h>
#include "utils.h"
#include <include/shared.h>
#include <string.h>
#include <fcntl.h>
#include <zconf.h>
#include <sys/mman.h>
#include <elf.h>
#include <errno.h>
#define __arm__
#ifdef __arm__
#define Elf_Ehdr Elf32_Ehdr
#define Elf_Shdr Elf32_Shdr
#define Elf_Sym Elf32_Sym
#elif defined(__aarch64__)
#define Elf_Ehdr Elf64_Ehdr
#define Elf_Shdr Elf64_Shdr
#define Elf_Sym Elf64_Sym
#else
#error "Arch is unknown"
#endif
typedef struct ctxInfo {
void *execAddr; //可执行段的地址
void *dynstr; //动态字串表
void *dynsym; //动态符号表
int symsNum; //符号个数
//off_t off; //VA与文件中位置的差
} CTXINFO;
void *my_dlopen(char *libPath) {
FILE *maps;
char buf[0x100];
char *libName = strrchr(libPath, '/')+1;
uint32_t addr;
off_t size;
int fd;
Elf32_Ehdr *elf = MAP_FAILED;
CTXINFO *ctx = 0;
void *shtoff; //节头表地址
void *shtAddr;
uint32_t shtNum; //节数量
uint32_t shtSize; //每个节大小
//找到so模块
if ((maps = fopen("/proc/self/maps", "r")) == NULL) {
LOGI("open maps error");
return NULL;
}
//获取so执行段地址
while (fgets(buf, sizeof(buf), maps)) {
if (strstr(buf, "r-xp") && strstr(buf, libName))
break;
}
if (sscanf(buf, "%x", &addr) != 1) {
LOGI("get addr error");
return NULL;
}
fclose(maps);
//打开so文件
if ((fd = open(libPath, O_RDONLY) )== -1) {
LOGI("open so error :%s", strerror(errno));
return NULL;
}
//获得文件大小
size = lseek(fd, 0, SEEK_END);
//在内存映射该文件,类型为elf
if ((elf = (Elf32_Ehdr *) mmap(0, size, PROT_READ, MAP_SHARED, fd, 0) )== MAP_FAILED) {
LOGI("mmap so failed");
close(fd);
return NULL;
}
//关闭so文件
close(fd);
ctx = (CTXINFO *) calloc(1, sizeof(CTXINFO));
ctx->execAddr = addr; //so执行段地址
shtoff = elf->e_shoff; //节头表偏移
shtNum = elf->e_shnum; //节头表表项数量
shtSize = elf->e_shentsize; //节头表每个表项的大小
shtAddr = ((void *) elf) + elf->e_shoff; //节头表逻辑地址
for (uint32_t i = 0; i < shtNum; i++, shtAddr += shtSize) {
Elf_Shdr *sh = (Elf_Shdr *)shtAddr;
switch (sh->sh_type) {
case SHT_DYNSYM://11
ctx->dynsym = calloc(1, sh->sh_size);
memcpy(ctx->dynsym, ((void *) elf + sh->sh_offset), sh->sh_size);
ctx->symsNum = sh->sh_size / sizeof(Elf_Sym);
break;
case SHT_STRTAB://3
ctx->dynstr = calloc(1, sh->sh_size);
memcpy(ctx->dynstr, (void *) elf + sh->sh_offset, sh->sh_size);
break;
//当前节区为程序定义节区:program defined information
// case SHT_PROGBITS:
// if(!ctx->dynstr || !ctx->dynsym) break;
// //获得偏移,在动态链接库文件中 sh->sh_addr = sh->sh_offset
// ctx->off = sh->sh_addr - sh->sh_offset;
// break;
//在动态链接库文件中 sh->sh_addr = sh->sh_offset
}
if (ctx->dynstr && ctx->dynsym) {
break;
}
}
//关闭内存映射
munmap(elf,size);
return ctx;
}
void *my_dlsym(void *ctxStruct,char *symName){
if(ctxStruct==NULL){
return NULL;
}
CTXINFO *ctx = (CTXINFO*)ctxStruct;
Elf_Sym *sym =(Elf_Sym*) ctx->dynsym;
char *dynstrAddr = ctx->dynstr;
int i;
for(i=0;i<ctx->symsNum;i++,sym++){
char *name = dynstrAddr+sym->st_name;
if(strcmp(name,symName)==0){
// void *res = ctx->execAddr+sym->st_value-ctx->off;
void *res = ctx->execAddr + sym->st_value;
return res;
}
}
return NULL;
} |
C | Write a C program to find the maximum and minimum from the 3 user inputted numbers.
#include <stdio.h>
int main()
{
int num1, num2, num3, min,max;
scanf("%d%d%d",&num1,&num2,&num3);
if(num1>num2)
{
if(num1>num3)
{
max=num1;
}
else
{
max=num3;
}
}
else
{
if(num2>num3)
{
max=num2;
}
else
{
max=num3;
}
}
printf("%d\n",max);
if(num1<num2)
{
if(num1<num3)
{
min=num1;
}
else
{
min=num3;
}
}
else
{
if(num2<num3)
{
min= num2;
}
else
{
min=num3;
}
}
printf("%d", min);
return 0;
}
|
C | #include<stdio.h>
void reverse(char *str);
int main() {
char str[] = "abcdef";
printf("%s\n", str);
reverse(str);
printf("%s\n", str);
return 0;
}
void reverse(char *str) {
char *incr_idx, *decr_idx;
char tmp;
incr_idx = str;
for(decr_idx = str; *(decr_idx+1) != '\0'; decr_idx++);
for(; incr_idx < decr_idx; incr_idx++, decr_idx--) {
tmp = (*incr_idx);
(*incr_idx) = (*decr_idx);
(*decr_idx) = tmp;
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* create_bmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rgilles <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/07 16:06:17 by rgilles #+# #+# */
/* Updated: 2020/11/07 16:06:18 by rgilles ### ########.fr */
/* */
/* ************************************************************************** */
#include <cub3d.h>
int file_header(int nblines, int lineweight, int fd)
{
unsigned char header[14];
int size;
ft_bzero(&header, 14);
size = 14 + 40 + lineweight * nblines;
header[0] = (unsigned char)('B');
header[1] = (unsigned char)('M');
header[2] = (unsigned char)(size);
header[3] = (unsigned char)(size >> 8);
header[4] = (unsigned char)(size >> 16);
header[5] = (unsigned char)(size >> 24);
header[10] = (unsigned char)(14 + 40);
return (write(fd, header, 14));
}
int info_header(int height, int width, int fd)
{
unsigned char header[40];
ft_bzero(&header, 40);
header[0] = (unsigned char)(40);
header[4] = (unsigned char)(width);
header[5] = (unsigned char)(width >> 8);
header[6] = (unsigned char)(width >> 16);
header[7] = (unsigned char)(width >> 24);
header[8] = (unsigned char)(height);
header[9] = (unsigned char)(height >> 8);
header[10] = (unsigned char)(height >> 16);
header[11] = (unsigned char)(height >> 24);
header[12] = (unsigned char)(1);
header[14] = (unsigned char)(4 * 8);
return (write(fd, header, 40));
}
int mk_bmp(char *image, int height, int width)
{
int fd;
int i;
int ret;
fd = open("image.bmp", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1)
return (-1);
ret = file_header(height, width * 4, fd);
if (ret == -1)
return (-1);
ret = info_header(height, width, fd);
if (ret == -1)
return (-1);
i = height;
while (i-- >= 0)
{
ret = write(fd, image + (i * width * 4), width * 4);
if (ret == -1)
return (ret);
}
close(fd);
return (0);
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<MATH.H>
// Matteo Raccichini, 3 INA, 14/11/2016
// Scambio di valori tra due variabili
main()
{
int A; //variabile che contiene A
int B; //variabile che contiene B
int TEMP; //variabile che contiene la variabile temporanea
printf("\n Inserire A "); //chiedi al video la misura di A
scanf("%d",&A); //indica indirizzo iniziale di A
printf("\n Inserire B "); //chiedi al video la misura di B
scanf("%d",&B); //indica indirizzo iniziale di B
TEMP=A;
A=B;
B=TEMP;
printf("\n A= %d",A);
printf("\n B= %d",B);
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include "preset.h"
void preset_menu_print()
{
system("clear");
printf("1. Gliger\n");
printf("2. Gosper's gliger gun\n");
printf("3. Pulsar\n");
printf("4. Lightweight spaceship\n");
printf("5. Pentadecathlon\n");
}
int preset_menu_check_input(char input[2])
{
return !(input[1] == '\0' && (input[0] >= '1' && input[0] <= '5'));
}
void preset_menu(char field[FIELD_HEIGHT][FIELD_WIDTH])
{
preset_menu_print();
char chose;
while (1) {
char temp[2];
scanf("%s", temp);
if (!preset_menu_check_input(temp)) {
chose = temp[0];
break;
} else {
printf("Wrong input, please input 1-5\n");
}
}
switch (chose) {
case '1':
glider(field);
break;
case '2':
glider_gun(field);
break;
case '3':
pulsar(field);
break;
case '4':
spaceship(field);
break;
case '5':
pentadecathlon(field);
break;
}
}
void glider(char field[FIELD_HEIGHT][FIELD_WIDTH])
{
field[9][51] = '*';
field[10][51] = '*';
field[11][51] = '*';
field[11][50] = '*';
field[10][49] = '*';
}
void glider_gun(char field[FIELD_HEIGHT][FIELD_WIDTH])
{
field[6][2] = '*';
field[6][3] = '*';
field[7][2] = '*';
field[7][3] = '*';
field[6][12] = '*';
field[7][12] = '*';
field[8][12] = '*';
field[5][13] = '*';
field[9][13] = '*';
field[4][14] = '*';
field[10][14] = '*';
field[4][15] = '*';
field[10][15] = '*';
field[7][16] = '*';
field[5][17] = '*';
field[9][17] = '*';
field[6][18] = '*';
field[7][18] = '*';
field[8][18] = '*';
field[7][19] = '*';
field[4][22] = '*';
field[5][22] = '*';
field[6][22] = '*';
field[4][23] = '*';
field[5][23] = '*';
field[6][23] = '*';
field[3][24] = '*';
field[7][24] = '*';
field[2][26] = '*';
field[3][26] = '*';
field[7][26] = '*';
field[8][26] = '*';
field[4][36] = '*';
field[5][36] = '*';
field[4][37] = '*';
field[5][37] = '*';
}
void pulsar(char field[FIELD_HEIGHT][FIELD_WIDTH])
{
field[6][44] = '*';
field[7][44] = '*';
field[8][44] = '*';
field[12][44] = '*';
field[13][44] = '*';
field[14][44] = '*';
field[4][46] = '*';
field[4][47] = '*';
field[4][48] = '*';
field[9][46] = '*';
field[9][47] = '*';
field[9][48] = '*';
field[11][46] = '*';
field[11][47] = '*';
field[11][48] = '*';
field[16][46] = '*';
field[16][47] = '*';
field[16][48] = '*';
field[6][49] = '*';
field[7][49] = '*';
field[8][49] = '*';
field[12][49] = '*';
field[13][49] = '*';
field[14][49] = '*';
field[6][51] = '*';
field[7][51] = '*';
field[8][51] = '*';
field[12][51] = '*';
field[13][51] = '*';
field[14][51] = '*';
field[4][52] = '*';
field[4][53] = '*';
field[4][54] = '*';
field[9][52] = '*';
field[9][53] = '*';
field[9][54] = '*';
field[11][52] = '*';
field[11][53] = '*';
field[11][54] = '*';
field[16][52] = '*';
field[16][53] = '*';
field[16][54] = '*';
field[6][56] = '*';
field[7][56] = '*';
field[8][56] = '*';
field[12][56] = '*';
field[13][56] = '*';
field[14][56] = '*';
}
void spaceship(char field[FIELD_HEIGHT][FIELD_WIDTH])
{
field[8][48] = '*';
field[8][51] = '*';
field[9][52] = '*';
field[10][48] = '*';
field[10][52] = '*';
field[11][49] = '*';
field[11][50] = '*';
field[11][51] = '*';
field[11][52] = '*';
}
void pentadecathlon(char field[FIELD_HEIGHT][FIELD_WIDTH])
{
field[10][46] = '*';
field[10][47] = '*';
field[10][49] = '*';
field[10][50] = '*';
field[10][51] = '*';
field[10][52] = '*';
field[10][54] = '*';
field[10][55] = '*';
field[9][48] = '*';
field[11][48] = '*';
field[9][53] = '*';
field[11][53] = '*';
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* new_elem.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: drecours <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/06/20 16:00:32 by drecours #+# #+# */
/* Updated: 2017/09/27 13:20:28 by drecours ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
static void double_joinfree(char *path, char *name, t_content *new)
{
new->path = ft_joinfree(path, "/", 0);
new->path = ft_joinfree(new->path, name, 1);
}
t_content *new_elem(t_content *content, char *name, char *path)
{
t_content *new;
if (!(new = ft_memalloc(sizeof(t_content))))
exit(-1);
if (ft_strcmp(name, "/") == 0 || path == NULL)
new->path = ft_strdup(name);
else if (ft_strcmp(path, "/") == 0 && !(ft_strcmp(name, "/") == 0))
new->path = ft_joinfree("/", name, 0);
else
double_joinfree(path, name, new);
if (!(new->buff = (struct stat*)ft_memalloc(sizeof(struct stat))))
exit(-1);
if (lstat(new->path, new->buff) == -1)
{
write(2, "ls: ", 4);
perror(new->path);
}
new->next = content;
if (content)
content->prev = new;
new->prev = NULL;
return (new);
}
|
C | #include <stdio.h>
#include "typs.h"
#include "sources.h"
int main() {
DblLinkedList* list = createDblLinkedList();
int keyW = 1;
int keyB = 2;
int a = 1;
int b = 1;
int c = 2;
int d = 1;
int e = 2;
int f = 2;
int g = 1;
pushFront(list, &a);
pushFront(list, &b);
pushFront(list, &c);
pushBack(list, &d);
pushBack(list, &e);
pushBack(list, &f);
pushBack(list, &g);
printDblLinkedList(list, printInt);
int i = 0;
int len = list->size;
int k = 1;
Node* temporaryWhite = NULL;
Node* temporaryBlack = NULL;
Node* tmp1 = list->head;
Node* tmp2 = list->tail;
while (tmp1 != tmp2) {
if (*(tmp1->value) == 2)
temporaryWhite = getNthq(list, i);
if (*(tmp2->value) == 1)
temporaryBlack = getNthq(list, len - k);
if ((temporaryBlack != NULL) && (temporaryWhite != NULL)) {
tmp1 = tmp1->next;
tmp2 = tmp2->prev;
deleteNth(list, i);
deleteNth(list, len - k - 1);
//printDblLinkedList(list, printInt);
insert(list, i, &keyW);
insert(list, len - k - 1, &keyB);
//printDblLinkedList(list, printInt);
temporaryWhite = NULL;
temporaryBlack = NULL;
i++;
k++;
}
else {
if ((temporaryBlack == NULL) && (temporaryWhite != NULL)) {
k++;
tmp2 = tmp2->prev;
}
if ((temporaryWhite == NULL) && (temporaryBlack != NULL)) {
tmp1 = tmp1->next;
i++;
}
if ((temporaryBlack == NULL) && (temporaryWhite == NULL)) {
tmp1 = tmp1->next;
tmp2 = tmp2->prev;
k++;
i++;
}
}
}
printDblLinkedList(list, printInt);
deleteDblLinkedList(&list);
return 0;
} |
C | //
// OneWire interface
//
// Implements Maxim OneWire device interface
//
#include "OneWire.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include "util/delay.h"
#define OW_DEVICE_PIN PA6
#define OW_DEVICE_OUTPORT PORTA
#define OW_DEVICE_INPORT PINA
#define OW_DEVICE_DIR DDRA
// set pin to output
#define OW_SET_OUTPUT() (OW_DEVICE_DIR |= (1<<OW_DEVICE_PIN))
// set pin to input
#define OW_SET_INPUT() (OW_DEVICE_DIR &= ~(1<<OW_DEVICE_PIN))
// write high to pin
#define OW_WRITE_HIGH() (OW_DEVICE_OUTPORT |= (1<<OW_DEVICE_PIN))
// write low to pin
#define OW_WRITE_LOW() (OW_DEVICE_OUTPORT &= ~(1<<OW_DEVICE_PIN))
// read pin
#define OW_READ() ((OW_DEVICE_INPORT & (1<<OW_DEVICE_PIN)) != 0)
bool OneWire_reset (void)
{
bool successful = false;
cli();
OW_WRITE_LOW();
OW_SET_OUTPUT();
_delay_us(500);
OW_SET_INPUT();
OW_WRITE_HIGH(); // enable pull-up
_delay_us(64);
successful = !OW_READ();
_delay_us(416);
successful = successful && OW_READ();
sei();
return successful;
}
static void write_0 (void)
{
cli();
OW_WRITE_LOW();
OW_SET_OUTPUT();
_delay_us(63);
OW_SET_INPUT();
OW_WRITE_HIGH(); // enable pull-up
_delay_us(2); // TREC
sei();
}
static void write_1 (void)
{
cli();
OW_WRITE_LOW();
OW_SET_OUTPUT();
_delay_us(3);
OW_SET_INPUT();
OW_WRITE_HIGH(); // enable pull-up
_delay_us(62);
sei();
}
void OneWire_writeBit (
const bool bit)
{
if (bit) {
write_1();
} else {
write_0();
}
}
void OneWire_writeByte (
const uint8_t byte)
{
uint8_t residual = byte;
for (int b = 0; b < 8; ++b) {
OneWire_writeBit(residual & 1);
residual >>= 1;
}
}
bool OneWire_readBit (void)
{
bool bit = false;
cli();
OW_WRITE_LOW();
OW_SET_OUTPUT();
_delay_us(2);
OW_SET_INPUT();
OW_WRITE_HIGH(); // enable pull-up
_delay_us(11);
bit = OW_READ();
_delay_us(54);
sei();
return bit;
}
uint8_t OneWire_readByte (void)
{
uint8_t byte = 0;
for (int b = 0; b < 8; ++b) {
byte >>= 1;
if (OneWire_readBit()) {
byte |= 0x80;
}
}
return byte;
}
|
C | #include <stdio.h>
#include <stdbool.h>
bool perfect(int n)
{ int s=0; int i;
for(i=1;i<n;i++)
{ if(n%i==0)
{
s=s+i;
}
}
if(n==s)
return true;
else
return false;
}
int main()
{
int n;
printf("Enter the number: ");
scanf("%d",&n);
bool t;
t=perfect(n);
if(t==true)
printf("Perfect number\n");
else
printf("Not a perfect number\n");
return 0;
}
|
C | /*
* string - string list routines
*
* Copyright (C) 1999-2004 David I. Bell and Ernest Bowen
*
* Primary author: David I. Bell
*
* Calc is open software; you can redistribute it and/or modify it under
* the terms of the version 2.1 of the GNU Lesser General Public License
* as published by the Free Software Foundation.
*
* Calc 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 Lesser General
* Public License for more details.
*
* A copy of version 2.1 of the GNU Lesser General Public License is
* distributed with calc under the filename COPYING-LGPL. You should have
* received a copy with calc; if not, write to Free Software Foundation, Inc.
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* @(#) $Revision: 29.4 $
* @(#) $Id: string.c,v 29.4 2004/02/23 14:04:01 chongo Exp $
* @(#) $Source: /usr/local/src/cmd/calc/RCS/string.c,v $
*
* Under source code control: 1990/02/15 01:48:10
* File existed as early as: before 1990
*
* Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/
*/
#include <stdio.h>
#include "calc.h"
#include "string.h"
#define STR_TABLECHUNK 100 /* how often to reallocate string table */
#define STR_CHUNK 2000 /* size of string storage allocation */
#define STR_UNIQUE 100 /* size of string to allocate separately */
STRING _nullstring_ = {"", 0, 1, NULL};
static char *chartable; /* single character string table */
static struct {
long l_count; /* count of strings in table */
long l_maxcount; /* maximum strings storable in table */
long l_avail; /* characters available in current string */
char *l_alloc; /* next available string storage */
char **l_table; /* current string table */
} literals;
/*
* Initialize or reinitialize a string header for use.
*
* given:
* hp structure to be inited
*/
void
initstr(STRINGHEAD *hp)
{
if (hp->h_list == NULL) {
hp->h_list = (char *)malloc(2000);
hp->h_avail = 2000;
hp->h_used = 0;
}
hp->h_avail += hp->h_used;
hp->h_used = 0;
hp->h_count = 0;
hp->h_list[0] = '\0';
hp->h_list[1] = '\0';
}
/*
* Copy a string to the end of a list of strings, and return the address
* of the copied string. Returns NULL if the string could not be copied.
* No checks are made to see if the string is already in the list.
* The string cannot be null or have imbedded nulls.
*
* given:
* hp header of string storage
* str string to be added
*/
char *
addstr(STRINGHEAD *hp, char *str)
{
char *retstr; /* returned string pointer */
char *list; /* string list */
long newsize; /* new size of string list */
long len; /* length of current string */
if ((str == NULL) || (*str == '\0'))
return NULL;
len = (long)strlen(str) + 1;
if (hp->h_avail <= len) {
newsize = len + 2000 + hp->h_used + hp->h_avail;
list = (char *)realloc(hp->h_list, newsize);
if (list == NULL)
return NULL;
hp->h_list = list;
hp->h_avail = newsize - hp->h_used;
}
retstr = hp->h_list + hp->h_used;
hp->h_used += len;
hp->h_avail -= len;
hp->h_count++;
strcpy(retstr, str);
retstr[len] = '\0';
return retstr;
}
/*
* Return a null-terminated string which consists of a single character.
* The table is initialized on the first call.
*/
char *
charstr(int ch)
{
char *cp;
int i;
if (chartable == NULL) {
cp = (char *)malloc(512);
if (cp == NULL) {
math_error("Cannot allocate character table");
/*NOTREACHED*/
}
for (i = 0; i < 256; i++) {
*cp++ = (char)i;
*cp++ = '\0';
}
chartable = cp - 512;
}
return &chartable[(ch & 0xff) * 2];
}
/*
* Find a string with the specified name and return its number in the
* string list. The first string is numbered zero. Minus one is returned
* if the string is not found.
*
* given:
* hp header of string storage
* str string to be added
*/
int
findstr(STRINGHEAD *hp, char *str)
{
register char *test; /* string being tested */
long len; /* length of string being found */
long testlen; /* length of test string */
int index; /* index of string */
if ((hp->h_count <= 0) || (str == NULL))
return -1;
len = (long)strlen(str);
test = hp->h_list;
index = 0;
while (*test) {
testlen = (long)strlen(test);
if ((testlen == len) && (*test == *str) && (strcmp(test, str) == 0))
return index;
test += (testlen + 1);
index++;
}
return -1;
}
/*
* Return the name of a string with the given index.
* If the index is illegal, a pointer to an empty string is returned.
*
* given:
* hp header of string storage
* n
*/
char *
namestr(STRINGHEAD *hp, long n)
{
register char *str; /* current string */
if (n >= hp->h_count)
return "";
str = hp->h_list;
while (*str) {
if (--n < 0)
return str;
str += (strlen(str) + 1);
}
return "";
}
/*
* Useful routine to return the index of one string within another one
* which has the format: "str1\000str2\000str3\000...strn\0\0". Index starts
* at one for the first string. Returns zero if the string being checked
* is not contained in the formatted string.
*
* Be sure to use \000 instead of \0. ANSI-C compilers interpret "foo\0foo..."
* as "foo\017oo...".
*
* given:
* format string formatted into substrings
* test string to be found in formatted string
*/
long
stringindex(char *format, char *test)
{
long index; /* found index */
long len; /* length of current piece of string */
long testlen; /* length of test string */
testlen = (long)strlen(test);
index = 1;
while (*format) {
len = (long)strlen(format);
if ((len == testlen) && (*format == *test) &&
(strcmp(format, test) == 0))
return index;
format += (len + 1);
index++;
}
return 0;
}
/*
* Add a possibly new literal string to the literal string pool.
* Returns the new string address which is guaranteed to be always valid.
* Duplicate strings will repeatedly return the same address.
*/
char *
addliteral(char *str)
{
register char **table; /* table of strings */
char *newstr; /* newly allocated string */
long count; /* number of strings */
long len; /* length of string to allocate */
len = (long)strlen(str);
if (len <= 1)
return charstr(*str);
/*
* See if the string is already in the table.
*/
table = literals.l_table;
count = literals.l_count;
while (count-- > 0) {
if ((str[0] == table[0][0]) && (str[1] == table[0][1]) &&
(strcmp(str, table[0]) == 0))
return table[0];
table++;
}
/*
* Make the table of string pointers larger if necessary.
*/
if (literals.l_count >= literals.l_maxcount) {
count = literals.l_maxcount + STR_TABLECHUNK;
if (literals.l_maxcount)
table = (char **) realloc(literals.l_table, count * sizeof(char *));
else
table = (char **) malloc(count * sizeof(char *));
if (table == NULL) {
math_error("Cannot allocate string literal table");
/*NOTREACHED*/
}
literals.l_table = table;
literals.l_maxcount = count;
}
table = literals.l_table;
/*
* If the new string is very long, allocate it manually.
*/
len = (len + 2) & ~1; /* add room for null and round up to word */
if (len >= STR_UNIQUE) {
newstr = (char *)malloc(len);
if (newstr == NULL) {
math_error("Cannot allocate large literal string");
/*NOTREACHED*/
}
strcpy(newstr, str);
table[literals.l_count++] = newstr;
return newstr;
}
/*
* If the remaining space in the allocate string is too small,
* then allocate a new one.
*/
if (literals.l_avail < len) {
newstr = (char *)malloc(STR_CHUNK);
if (newstr == NULL) {
math_error("Cannot allocate new literal string");
/*NOTREACHED*/
}
literals.l_alloc = newstr;
literals.l_avail = STR_CHUNK;
}
/*
* Allocate the new string from the allocate string.
*/
newstr = literals.l_alloc;
literals.l_avail -= len;
literals.l_alloc += len;
table[literals.l_count++] = newstr;
strcpy(newstr, str);
return newstr;
}
STRING *
stringadd(STRING *s1, STRING *s2)
{
STRING *s;
char *cfrom, *c;
long len;
if (s1->s_len == 0)
return slink(s2);
if (s2->s_len == 0)
return slink(s1);
len = s1->s_len + s2->s_len;
s = stralloc();
s->s_len = len;
s->s_str = (char *) malloc(len + 1);
if (s->s_str == NULL)
return NULL;
len = s1->s_len;
cfrom = s1->s_str;
c = s->s_str;
while (len-- > 0)
*c++ = *cfrom++;
len = s2->s_len;
cfrom = s2->s_str;
while (len-- > 0)
*c++ = *cfrom++;
*c = '\0';
return s;
}
/*
* stringneg reverses the characters in a string, returns null if malloc fails
*/
STRING *
stringneg(STRING *str)
{
long len;
STRING *s;
char *c, *cfrom;
len = str->s_len;
if (len <= 1)
return slink(str);
c = (char *) malloc(len + 1);
if (c == NULL)
return NULL;
s = stralloc();
s->s_len = len;
s->s_str = c;
cfrom = str->s_str + len;
while (len-- > 0)
*c++ = *--cfrom;
*c = '\0';
return s;
}
STRING *
stringsub(STRING *s1, STRING *s2)
{
STRING *tmp, *s;
tmp = stringneg(s2);
if (tmp == NULL)
return NULL;
s = stringadd(s1, tmp);
if (s != NULL)
sfree(tmp);
return s;
}
/*
* stringmul: repeated concatenation, reverse if negative multiplier
* returns null if malloc fails
*/
STRING *
stringmul(NUMBER *q, STRING *str)
{
long len;
long j;
NUMBER *tmp1, *tmp2;
char *c, *c1;
STRING *s;
BOOL neg;
if (str->s_len == 0)
return slink(str);
neg = qisneg(q);
q = neg ? qneg(q): qlink(q);
tmp1 = itoq(str->s_len);
tmp2 = qmul(q, tmp1);
qfree(tmp1);
tmp1 = qint(tmp2);
qfree(tmp2);
if (zge31b(tmp1->num)) {
qfree(q);
qfree(tmp1);
return NULL;
}
len = qtoi(tmp1);
qfree(tmp1);
qfree(q);
if (len == 0) {
s = stralloc();
s->s_len = 0;
s->s_str = charstr('\0');
return s;
}
c = (char *) malloc(len + 1);
if (c == NULL)
return NULL;
str = neg ? stringneg(str) : slink(str);
s = stralloc();
s->s_str = c;
s->s_len = len;
j = 0;
c1 = str->s_str;
while (len-- > 0) {
*c++ = *c1++;
if (++j == str->s_len) {
j = 0;
c1 = str->s_str;
}
}
*c = '\0';
sfree(str);
return s;
}
STRING *
stringand(STRING *s1, STRING *s2)
{
STRING *s;
long len;
char *c1, *c2, *c;
if (s1->s_len == 0 || s2->s_len == 0)
return slink(&_nullstring_);
len = s1->s_len;
if (s2->s_len < len)
len = s2->s_len;
s = stralloc();
s->s_len = len;
c = malloc(len + 1);
if (c == NULL)
return NULL;
s->s_str = c;
c1 = s1->s_str;
c2 = s2->s_str;
while (len-- > 0)
*c++ = *c1++ & *c2++;
return s;
}
STRING *
stringor(STRING *s1, STRING *s2)
{
STRING *s;
long len, i, j;
char *c1, *c2, *c;
if (s1->s_len < s2->s_len) {
s = s1;
s1 = s2;
s2 = s;
} /* Now len(s1) >= len(s2) */
if (s2->s_len == 0)
return slink(s1);
i = s1->s_len;
if (i == 0)
return slink(&_nullstring_);
len = s1->s_len;
s = stralloc();
s->s_len = len;
c = malloc(len + 1);
if (c == NULL)
return NULL;
s->s_str = c;
c1 = s1->s_str;
c2 = s2->s_str;
i = s2->s_len;
j = s1->s_len - i;
while (i-- > 0)
*c++ = *c1++ | *c2++;
while (j-- > 0)
*c++ = *c1++;
return s;
}
STRING *
stringxor(STRING *s1, STRING *s2)
{
STRING *s;
long len, i, j;
char *c1, *c2, *c;
if (s1->s_len < s2->s_len) {
s = s1;
s1 = s2;
s2 = s;
} /* Now len(s1) >= len(s2) */
if (s2->s_len == 0)
return slink(s1);
i = s1->s_len;
if (i == 0)
return slink(&_nullstring_);
len = s1->s_len;
s = stralloc();
s->s_len = len;
c = malloc(len + 1);
if (c == NULL)
return NULL;
s->s_str = c;
c1 = s1->s_str;
c2 = s2->s_str;
i = s2->s_len;
j = s1->s_len - i;
while (i-- > 0)
*c++ = *c1++ ^ *c2++;
while (j-- > 0)
*c++ = *c1++;
return s;
}
STRING *
stringdiff(STRING *s1, STRING *s2)
{
STRING *s;
long i;
char *c2, *c;
i = s1->s_len;
if (i == 0)
return slink(s1);
s = stringcopy(s1);
if (i > s2->s_len)
i = s2->s_len;
c = s->s_str;
c2 = s2->s_str;
while (i-- > 0)
*c++ &= ~*c2++;
return s;
}
STRING *
stringcomp(STRING *s1)
{
long len;
STRING *s;
char *c1, *c;
len = s1->s_len;
if (len == 0)
return slink(&_nullstring_);
c = malloc(len + 1);
if (c == NULL)
return NULL;
s = stralloc();
s->s_len = len;
s->s_str = c;
c1 = s1->s_str;
while (len-- > 0)
*c++ = ~*c1++;
*c = '\0';
return s;
}
STRING *
stringsegment(STRING *s1, long n1, long n2)
{
STRING *s;
char *c, *c1;
long len;
if ((n1 < 0 && n2 < 0) || (n1 >= s1->s_len && n2 >= s1->s_len))
return slink(&_nullstring_);
if (n1 < 0)
n1 = 0;
if (n2 < 0)
n2 = 0;
if (n1 >= s1->s_len)
n1 = s1->s_len - 1;
if (n2 >= s1->s_len)
n2 = s1->s_len - 1;
len = (n1 >= n2) ? n1 - n2 + 1 : n2 - n1 + 1;
s = stralloc();
c = malloc(len + 1);
if (c == NULL)
return NULL;
s->s_len = len;
s->s_str = c;
c1 = s1->s_str + n1;
if (n1 >= n2) {
/*
* We prevent the c1 pointer from walking behind s1_s_str
* by stopping one short of the end and running the loop one
* more time.
*
* We could stop the loop with just len-- > 0, but stopping
* short and running the loop one last time manually helps make
* code checkers such as insure happy.
*/
while (len-- > 1) {
*c++ = *c1--;
}
/* run the loop manually one last time */
*c++ = *c1;
} else {
while (len-- > 0)
*c++ = *c1++;
}
*c = '\0';
return s;
}
/*
* stringshift shifts s1 n bits to left if n > 0, -n to the right if n < 0;
* octets in string considered to be in decreasing order of index, as in
* ... a_3 a_2 a_1 a_0. Returned string has same length as s1.
* Vacated bits are filled with '\0'; bits shifted off end are lost
*/
STRING *
stringshift(STRING *s1, long n)
{
char *c1, *c;
STRING *s;
long len, i, j, k;
BOOL right;
char ch;
len = s1->s_len;
if (len == 0 || n == 0)
return slink(s1);
right = (n < 0);
if (right) n = -n;
j = n & 7;
k = 8 - j;
n >>= 3;
c = malloc(len + 1);
if (c == NULL)
return NULL;
s = stralloc();
s->s_len = len;
s->s_str = c;
c[len] = '\0';
if (n > len)
n = len;
ch = '\0';
c1 = s1->s_str;
i = n;
if (right) {
c += len;
c1 += len;
while (i-- > 0)
*--c = '\0';
i = len - n;
while (i-- > 0) {
*--c = ((unsigned char) *--c1 >> j) | ch;
ch = (unsigned char) *c1 << k;
}
} else {
while (i-- > 0)
*c++ = '\0';
i = len - n;
while (i-- > 0) {
*c++ = ((unsigned char) *c1 << j) | ch;
ch = (unsigned char) *c1++ >> k;
}
}
return s;
}
/*
* stringcpy copies as many characters as possible up to and including
* the first '\0' from s2 to s1 and returns s1
*/
STRING *
stringcpy(STRING *s1, STRING *s2)
{
char *c1, *c2;
long len;
c1 = s1->s_str;
c2 = s2->s_str;
len = s1->s_len;
while (len-- > 0 && *c2 != 0)
*c1++ = *c2++;
*c1 = '\0';
return slink(s1);
}
/*
* stringncpy copies up to n characters from s2 to s1 and returns s1
*/
STRING *
stringncpy(STRING *s1, STRING *s2, long num)
{
char *c1, *c2;
if (num > s1->s_len)
num = s1->s_len;
c1 = s1->s_str;
c2 = s2->s_str;
while (num-- > 0 && *c2 != 0)
*c1++ = *c2++;
while (num-- > 0)
*c1++ = '\0';
*c1 = '\0';
return slink(s1);
}
/*
* stringcontent counts the number of set bits in s
*/
long
stringcontent(STRING *s)
{
char *c;
unsigned char ch;
long count;
long len;
len = s->s_len;
count = 0;
c = s->s_str;
while (len-- > 0) {
ch = *c++;
while (ch) {
count += (ch & 1);
ch >>= 1;
}
}
return count;
}
long
stringhighbit(STRING *s)
{
char *c;
unsigned char ch;
long i;
i = s->s_len;
c = s->s_str + i;
while (--i >= 0 && *--c == '\0');
if (i < 0)
return -1;
i <<= 3;
for (ch = *c; ch >>= 1; i++);
return i;
}
long
stringlowbit(STRING *s)
{
char *c;
unsigned char ch;
long i;
for (i = s->s_len, c = s->s_str; i > 0 && *c == '\0'; i--, c++);
if (i == 0)
return -1;
i = (s->s_len - i) << 3;
for (ch = *c; !(ch & 1); ch >>= 1, i++);
return i;
}
/*
* stringcompare compares first len characters of strings starting at c1, c2
* Returns TRUE if and only if a difference is encountered.
* Essentially a local version of memcmp.
*/
static BOOL
stringcompare(char *c1, char *c2, long len)
{
while (len-- > 0) {
if (*c1++ != *c2++)
return TRUE;
}
return FALSE;
}
/*
* stringcmp returns TRUE if strings differ, FALSE if strings equal
*/
BOOL
stringcmp(STRING *s1, STRING *s2)
{
if (s1->s_len != s2->s_len)
return TRUE;
return stringcompare(s1->s_str, s2->s_str, s1->s_len);
}
/*
* stringrel returns 0 if strings are equal; otherwise 1 or -1 according
* as the greater of the first unequal characters are in the first or
* second string, or in the case of unequal-length strings when the compared
* characters are all equal, 1 or -1 according as the first or second string
* is longer.
*/
FLAG
stringrel(STRING *s1, STRING *s2)
{
char *c1, *c2;
long i1, i2;
i1 = s1->s_len;
i2 = s2->s_len;
if (i1 == 0)
return (i2 > 0);
if (i2 == 0)
return -1;
c1 = s1->s_str;
c2 = s2->s_str;
while (i1 > 0 && i2 > 0 && *c1 == *c2) {
i1--;
i2--;
c1++;
c2++;
}
if ((unsigned char) *c1 > (unsigned char) *c2) return 1;
if ((unsigned char) *c1 < (unsigned char) *c2) return -1;
if (i1 < i2) return -1;
return (i1 > i2);
}
/*
* str with characters c0, c1, ... is considered as a bitstream, 8 bits
* per character; within a character the bits ordered from low order to
* high order. For 0 <= i < 8 * length of str, stringbit returns 1 or 0
* according as the bit with index i is set or not set; other values of i
* return -1.
*/
int
stringbit(STRING *s, long index)
{
unsigned int ch;
int res;
if (index < 0)
return -1;
res = index & 7;
index >>= 3;
if (index >= s->s_len)
return -1;
ch = s->s_str[index];
return (ch >> res) & 1;
}
BOOL
stringtest(STRING *s)
{
long i;
char *c;
i = s->s_len;
c = s->s_str;
while (i-- > 0) {
if (*c++)
return TRUE;
}
return FALSE;
}
/*
* If index is in acceptable range, stringsetbit sets or resets specified
* bit in string s according as val is TRUE or FALSE, and returns 0.
* Returns 1 if index < 0; 2 if index too large.
*/
int
stringsetbit(STRING *s, long index, BOOL val)
{
char *c;
int bit;
if (index < 0)
return 1;
bit = 1 << (index & 7);
index >>= 3;
if (index >= s->s_len)
return 2;
c = &s->s_str[index];
*c &= ~bit;
if (val)
*c |= bit;
return 0;
}
/*
* stringsearch returns 0 and sets index = i if the first occurrence
* of s2 in s1 for start <= i < end is at index i. If no such occurrence
* is found, -1 is returned.
*/
int
stringsearch(STRING *s1, STRING *s2, long start, long end, ZVALUE *index)
{
long len2, i, j;
char *c1, *c2, *c;
char ch;
len2 = s2->s_len;
if (start < 0)
start = 0;
if (end < start + len2)
return -1;
if (len2 == 0) {
itoz(start, index);
return 0;
}
i = end - start - len2;
c1 = s1->s_str + start;
ch = *s2->s_str;
while (i-- >= 0) {
if (*c1++ == ch) {
c = c1;
c2 = s2->s_str;
j = len2;
while (--j > 0 && *c++ == *++c2);
if (j == 0) {
itoz(end - len2 - i - 1, index);
return 0;
}
}
}
return -1;
}
int
stringrsearch(STRING *s1, STRING *s2, long start, long end, ZVALUE *index)
{
long len1, len2, i, j;
char *c1, *c2, *c, *c2top;
char ch;
len1 = s1->s_len;
len2 = s2->s_len;
if (start < 0)
start = 0;
if (end > len1)
end = len1;
if (end < start + len2)
return -1;
if (len2 == 0) {
itoz(start, index);
return 0;
}
i = end - start - len2 + 1;
c1 = s1->s_str + end - 1;
c2top = s2->s_str + len2 - 1;
ch = *c2top;
while (--i >= 0) {
if (*c1-- == ch) {
c = c1;
j = len2;
c2 = c2top;
while (--j > 0 && *c-- == *--c2);
if (j == 0) {
itoz(start + i, index);
return 0;
}
}
}
return -1;
}
/*
* String allocation routines
*/
#define STRALLOC 100
static STRING *freeStr = NULL;
static STRING **firstStrs = NULL;
static long blockcount = 0;
STRING *
stralloc(void)
{
STRING *temp;
STRING **newfn;
if (freeStr == NULL) {
freeStr = (STRING *) malloc(sizeof (STRING) * STRALLOC);
if (freeStr == NULL) {
math_error("Unable to allocate memory for stralloc");
/*NOTREACHED*/
}
freeStr[STRALLOC - 1].s_next = NULL;
freeStr[STRALLOC - 1].s_links = 0;
/*
* We prevent the temp pointer from walking behind freeStr
* by stopping one short of the end and running the loop one
* more time.
*
* We would stop the loop with just temp >= freeStr, but
* doing this helps make code checkers such as insure happy.
*/
for (temp = freeStr + STRALLOC - 2; temp > freeStr; --temp) {
temp->s_next = temp + 1;
temp->s_links = 0;
}
/* run the loop manually one last time */
temp->s_next = temp + 1;
temp->s_links = 0;
blockcount++;
if (firstStrs == NULL) {
newfn = (STRING **) malloc( blockcount * sizeof(STRING *));
} else {
newfn = (STRING **)
realloc(firstStrs, blockcount * sizeof(STRING *));
}
if (newfn == NULL) {
math_error("Cannot allocate new string block");
/*NOTREACHED*/
}
firstStrs = newfn;
firstStrs[blockcount - 1] = freeStr;
}
temp = freeStr;
freeStr = temp->s_next;
temp->s_links = 1;
temp->s_str = NULL;
return temp;
}
/*
* makestring to be called only when str is the result of a malloc
*/
STRING *
makestring(char *str)
{
STRING *s;
long len;
len = (long)strlen(str);
s = stralloc();
s->s_str = str;
s->s_len = len;
return s;
}
STRING *
charstring(int ch)
{
STRING *s;
char *c;
c = (char *) malloc(2);
if (c == NULL) {
math_error("Allocation failure for charstring");
/*NOTREACHED*/
}
s = stralloc();
s->s_len = 1;
s->s_str = c;
*c++ = (char) ch;
*c = '\0';
return s;
}
/*
* makenewstring creates a new string by copying null-terminated str;
* str is not freed
*/
STRING *
makenewstring(char *str)
{
STRING *s;
char *c;
long len;
len = (long)strlen(str);
if (len == 0)
return slink(&_nullstring_);
c = (char *) malloc(len + 1);
if (c == NULL) {
math_error("malloc for makenewstring failed");
/*NOTREACHED*/
}
s = stralloc();
s->s_str = c;
s->s_len = len;
memcpy(c, str, len);
c[len] = '\0';
return s;
}
STRING *
stringcopy (STRING *s1)
{
STRING *s;
char *c;
long len;
len = s1->s_len;
if (len == 0)
return slink(s1);
c = malloc(len + 1);
if (c == NULL) {
math_error("Malloc failed for stringcopy");
/*NOTREACHED*/
}
s = stralloc();
s->s_len = len;
s->s_str = c;
memcpy(c, s1->s_str, len);
c[len] = '\0';
return s;
}
STRING *
slink(STRING *s)
{
if (s->s_links <= 0) {
math_error("Argument for slink has nonpositive links!!!");
/*NOTREACHED*/
}
++s->s_links;
return s;
}
void
sfree(STRING *s)
{
if (s->s_links <= 0) {
math_error("Argument for sfree has nonpositive links!!!");
/*NOTREACHED*/
}
if (--s->s_links > 0 || s->s_len == 0)
return;
free(s->s_str);
s->s_next = freeStr;
freeStr = s;
}
static long stringconstcount = 0;
static long stringconstavail = 0;
static STRING **stringconsttable;
#define STRCONSTALLOC 100
void
initstrings(void)
{
stringconsttable = (STRING **) malloc(sizeof(STRING *) * STRCONSTALLOC);
if (stringconsttable == NULL) {
math_error("Unable to allocate constant table");
/*NOTREACHED*/
}
stringconsttable[0] = &_nullstring_;
stringconstcount = 1;
stringconstavail = STRCONSTALLOC - 1;
}
/*
* addstring is called only from token.c
* When called, len is length of string including '\0'
*/
long
addstring(char *str, long len)
{
STRING **sp;
STRING *s;
char *c;
long index; /* index into constant table */
long first; /* first non-null position found */
BOOL havefirst;
if (stringconstavail <= 0) {
if (stringconsttable == NULL) {
initstrings();
} else {
sp = (STRING **) realloc((char *) stringconsttable,
sizeof(STRING *) * (stringconstcount + STRCONSTALLOC));
if (sp == NULL) {
math_error("Unable to reallocate string const table");
/*NOTREACHED*/
}
stringconsttable = sp;
stringconstavail = STRCONSTALLOC;
}
}
len--;
first = 0;
havefirst = FALSE;
sp = stringconsttable;
for (index = 0; index < stringconstcount; index++, sp++) {
s = *sp;
if (s->s_links == 0) {
if (!havefirst) {
havefirst = TRUE;
first = index;
}
continue;
}
if (s->s_len == len && stringcompare(s->s_str, str, len) == 0) {
s->s_links++;
return index;
}
}
s = stralloc();
c = (char *) malloc(len + 1);
if (c == NULL) {
math_error("Unable to allocate string constant memory");
/*NOTREACHED*/
}
s->s_str = c;
s->s_len = len;
memcpy(s->s_str, str, len+1);
if (havefirst) {
stringconsttable[first] = s;
return first;
}
stringconstavail--;
stringconsttable[stringconstcount++] = s;
return index;
}
STRING *
findstring(long index)
{
if (index < 0 || index >= stringconstcount) {
math_error("Bad index for findstring");
/*NOTREACHED*/
}
return stringconsttable[index];
}
void
freestringconstant(long index)
{
STRING *s;
STRING **sp;
if (index >= 0) {
s = findstring(index);
sfree(s);
if (index == stringconstcount - 1) {
sp = &stringconsttable[index];
while (stringconstcount > 0 && (*sp)->s_links == 0) {
stringconstcount--;
stringconstavail++;
sp--;
}
}
}
}
long
printechar(char *c)
{
long n;
unsigned char ch;
unsigned char ech; /* for escape sequence */
unsigned char nch; /* for next character */
BOOL three;
ch = *c;
if (ch >= ' ' && ch < 127 && ch != '\\' && ch != '\"') {
putchar(ch);
return 1;
}
putchar('\\');
ech = 0;
switch (ch) {
case '\n': ech = 'n'; break;
case '\r': ech = 'r'; break;
case '\t': ech = 't'; break;
case '\b': ech = 'b'; break;
case '\f': ech = 'f'; break;
case '\v': ech = 'v'; break;
case '\\': ech = '\\'; break;
case '\"': ech = '\"'; break;
case 7: ech = 'a'; break;
case 27: ech = 'e'; break;
}
if (ech) {
putchar(ech);
return 2;
}
nch = *(c + 1);
three = (nch >= '0' && nch < '8');
n = 2;
if (three || ch >= 64) {
putchar('0' + ch/64);
n++;
}
ch %= 64;
if (three || ch >= 8) {
putchar('0' + ch/8);
n++;
}
ch %= 8;
putchar('0' + ch);
return n;
}
void
fitstring(char *str, long len, long width)
{
long i, j, n, max;
char *c;
unsigned char ch, nch;
max = (width - 3)/2;
if (len == 0)
return;
c = str;
for (i = 0, n = 0; i < len && n < max; i++) {
n += printechar(c++);
}
if (i >= len)
return;
c = str + len;
nch = '\0';
for (n = 0, j = len ; j > i && n < max ; --j, nch = ch) {
ch = *--c;
n++;
if (ch >= ' ' && ch <= 127 && ch != '\\' && ch != '\"')
continue;
n++;
switch (ch) {
case '\n': case '\r': case '\t': case '\b': case '\f':
case '\v': case '\\': case '\"': case 7: case 27:
continue;
}
if (ch >= 64 || (nch >= '0' && nch <= '7')) {
n += 2;
continue;
}
if (ch >= 8)
n++;
}
if (j > i)
printf("...");
while (j++ < len)
(void) printechar(c++);
}
void
showstrings(void)
{
STRING *sp;
long i, j, k;
long count;
printf("Index Links Length String\n");
printf("----- ----- ------ ------\n");
sp = &_nullstring_;
printf(" 0 %5ld 0 \"\"\n", sp->s_links);
for (i = 0, k = 1, count = 1; i < blockcount; i++) {
sp = firstStrs[i];
for (j = 0; j < STRALLOC; j++, k++, sp++) {
if (sp->s_links > 0) {
++count;
printf("%5ld %5ld %6ld \"",
k, sp->s_links, sp->s_len);
fitstring(sp->s_str, sp->s_len, 50);
printf("\"\n");
}
}
}
printf("\nNumber: %ld\n", count);
}
void
showliterals(void)
{
STRING *sp;
long i;
long count = 0;
printf("Index Links Length String\n");
printf("----- ----- ------ ------\n");
for (i = 0; i < stringconstcount; i++) {
sp = stringconsttable[i];
if (sp->s_links > 0) {
++count;
printf("%5ld %5ld %6ld \"",
i, sp->s_links, sp->s_len);
fitstring(sp->s_str, sp->s_len, 50);
printf("\"\n");
}
}
printf("\nNumber: %ld\n", count);
}
|
C |
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct BST
{
int data;
struct BST *lchild;
struct BST *rchild;
}node;
node *create( node *root, int key)
{
node *temp;
if(root==NULL)
{
temp=(node *)malloc(sizeof(node));
temp->data=key;
temp->lchild=NULL;
temp->rchild=NULL;
root=temp;
}
else
{
if(key<root->data)
{
root->lchild=create(root->lchild, key);
}
else
{
root->rchild=create(root->rchild, key);
}
}
return root;
}
node * search(node *root, int key)
{
if(root==NULL)
return NULL;
else
{
if(root->data==key)
return root;
else if(root->data>key)
return search(root->lchild,key);
else
return search(root->rchild,key);
}
}
node * min(node *root)
{
if(root==NULL)
return NULL;
else
{
if(root->lchild==NULL)
return root;
else
return min(root->lchild);
}
}
node * max(node *root)
{
if(root==NULL)
return NULL;
else
{
if(root->rchild==NULL)
return root;
else
return max(root->rchild);
}
}
void displayBST(node *root)
{
if(root!=NULL)
{
displayBST(root->lchild);
printf("%d ", root->data);
displayBST(root->rchild);
}
}
void main()
{
int x, ch, ans=1;
node *root, *temp;
clrscr();
do
{
printf("\n1.Create\n2.Search\n3.Min Node\n4.Max Node\n5.Display\n\nEnter choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
{
printf("\nEnter Data: ");
scanf("%d", &x);
root=create(root,x);
break;
}
case 2:
{
printf("\nEnter the data to search: ");
scanf("%d", &x);
temp= search(root,x);
if(temp==NULL)
printf("\nData NOT found!");
else
printf("\nData FOUND");
break;
}
case 3:
{
temp=min(root);
printf("\n\nTHE MIN ELEMENT IS: %d", temp->data);
break;
}
case 4:
{
temp=max(root);
printf("\n\nTHE MAX ELEMENT IS: %d", temp->data);
break;
}
case 5:
{
printf("\n\nTHE DATA IS: ");
displayBST(root);
break;
}
default: printf("\n\n**WRONG CHOICE**");
}
printf("\nWant to enter more (0/1) : ");
scanf("%d", &ans);
}while(ans==1);
getch();
}
|
C | #include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
void listdirint(const char *name, int indent);
void handle_dir(char* name, char* filename, int indent){
char path[1024];
int space = 0;
snprintf(path, sizeof(path), "%s/%s", name, filename);
space = 40 - indent -strlen(filename);
if(space <= 0){
space = 1;
}
printf("%*s[%s]%*s%s\n", indent, "", filename, space, "", path);
listdirint(path, indent + 2);
}
void handle_file(char* name, char* filename, int indent){
char path[1024];
int space = 0;
snprintf(path, sizeof(path), "%s/%s", name, filename);
space = 40 - indent -strlen(filename);
if(space <= 0){
space = 1;
}
printf("%*s- %s%*s%s\n", indent, "", filename, space, "", path);
}
void listdirint(const char *name, int indent) {
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(name)))
return;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
handle_dir(name, entry->d_name, indent);
} else {
handle_file(name, entry->d_name, indent);
}
}
closedir(dir);
}
void listdir(const char* name){
listdirint(name, 0);
}
void main(int argc, char* argv[]){
char* path = ".";
if(argc >= 2){
path = argv[1];
}
listdir(path);
}
|
C | #include "lists.h"
/**
* add_nodeint_end - entry point.
* @head: double pointer to struct.
* @n: contains the numbers to list.
* Return: address of memory of new element.
*/
listint_t *add_nodeint_end(listint_t **head, const int n)
{
listint_t *node;
listint_t *new;
node = malloc(sizeof(listint_t));
if (node == NULL)
{
return (NULL);
free(node);
}
node->n = n;
node->next = NULL;
if (*head == NULL)
{
*head = node;
}
else
{
new = *head;
while (new->next != NULL)
{
new = new->next;
}
new->next = node;
}
return (*head);
}
|
C | /**************************
Exercice 44 : Ecrire un programme qui demande en boucle dentrer un nombre positif
jusqu obtenir satisfaction.
**************************/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N;
do
{
printf("\n Entrez le nombre positif n :");
scanf("%d", &N);
}
while (N <= 0);
{
printf("Bravo!! : \n");
}
return 0;
}
|
C | #include<stdio.h>
double mean(double x[],int n){
double sum=00.0;int i;
for(i=0;i<n;i++)sum+=x[i];
sum/=n;
return sum;}
int main(){
int i,n;double a[20];
printf("please input n as length:");
scanf("%d",&n);
printf("please input %d numbers:",n);
for(i=0;i<n;i++)scanf("%f",&a[i]);
for(i=0;i<n;i++)printf("%4.1f\n",a[i]);
printf("Average = %f",mean(a,n));
return 0;} |
C | #include <stdint.h>
#include <string.h>
#define MBEDTLS_XTEA_ENCRYPT 1
#define MBEDTLS_XTEA_DECRYPT 0
#define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH -0x0028
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT32_BE
#define GET_UINT32_BE(n,b,i) \
{ \
(n) = ( (uint32_t) (b)[(i) ] << 24 ) \
| ( (uint32_t) (b)[(i) + 1] << 16 ) \
| ( (uint32_t) (b)[(i) + 2] << 8 ) \
| ( (uint32_t) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_UINT32_BE
#define PUT_UINT32_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
typedef struct
{
uint32_t k[4];
}
mbedtls_xtea_context;
void mbedtls_xtea_init( mbedtls_xtea_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_xtea_context ) );
}
/*
* XTEA key schedule
*/
void mbedtls_xtea_setup( mbedtls_xtea_context *ctx, const unsigned char key[16] )
{
int i;
memset( ctx, 0, sizeof(mbedtls_xtea_context) );
for( i = 0; i < 4; i++ )
{
GET_UINT32_BE( ctx->k[i], key, i << 2 );
}
}
int mbedtls_xtea_crypt_ecb( mbedtls_xtea_context *ctx, int mode,
const unsigned char input[8], unsigned char output[8])
{
uint32_t *k, v0, v1, i;
k = ctx->k;
GET_UINT32_BE( v0, input, 0 );
GET_UINT32_BE( v1, input, 4 );
if( mode == MBEDTLS_XTEA_ENCRYPT )
{
uint32_t sum = 0, delta = 0x9E3779B9;
for( i = 0; i < 32; i++ )
{
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
}
}
else /* MBEDTLS_XTEA_DECRYPT */
{
uint32_t delta = 0x9E3779B9, sum = delta * 32;
for( i = 0; i < 32; i++ )
{
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
sum -= delta;
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
}
}
PUT_UINT32_BE( v0, output, 0 );
PUT_UINT32_BE( v1, output, 4 );
return( 0 );
}
/*
* XTEA-CBC buffer encryption/decryption
*/
int mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx, int mode, size_t length,
unsigned char iv[8], const unsigned char *input,
unsigned char *output)
{
int i;
unsigned char temp[8];
if( length % 8 )
return( MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH );
if( mode == MBEDTLS_XTEA_DECRYPT )
{
while( length > 0 )
{
memcpy( temp, input, 8 );
mbedtls_xtea_crypt_ecb( ctx, mode, input, output );
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 8 );
input += 8;
output += 8;
length -= 8;
}
}
else
{
while( length > 0 )
{
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_xtea_crypt_ecb( ctx, mode, output, output );
memcpy( iv, output, 8 );
input += 8;
output += 8;
length -= 8;
}
}
return( 0 );
}
int main(int argc, char *argv[])
{
mbedtls_xtea_context ctx;
uint8_t key[16] = {0};
uint8_t iv[8] = {0};
read(0, key, 16);
read(0, iv, 8);
int size = atoi(argv[1]);
uint8_t* buf = malloc(size);
uint8_t* buf2 = malloc(size);
memset(buf, 0, size);
memset(buf2, 0, size);
read(0, buf, size);
mbedtls_xtea_init( &ctx );
mbedtls_xtea_setup( &ctx, key );
mbedtls_xtea_crypt_cbc( &ctx, 0, size, iv, buf, buf2 );
for ( int i = 0; i < size; ++i )
printf("%02x", buf2[i]);
printf("\n");
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char input[30];
int n;
int j = 0;
int cntr = 1;
scanf("%s", &input);
while (input[j]) {
input[j] = tolower(input[j]);
j++;
}
int lgth = strlen(input);
int k;
int bool = 0;
int maximumCntr = 1;
for (k = 0; k < lgth-1; k++) {
if (input[k+1] == input[k]+1) {
while ((k < lgth-1) && input[k+1] == input[k]+1) {
cntr += 1;
k++;
}
if(cntr > maximumCntr) {
maximumCntr = cntr;
}
cntr = 1;
k--;
}
}
printf("%d\n", maximumCntr);
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "code.h"
#include "ast.h"
#include "parser.h"
int regist=0;
char* create_register(){
char* var = (char*) malloc(sizeof(char));
sprintf(var,"%s%d","t",regist);
regist++;
return var;
}
List_Instr* compile_cmdlist(CmdList* cmd_list,char* r);
List_Instr* compile_BoolExpr(BoolExpr* boolexpr, char* r, Label* labelTrue, Label* labelFalse);
List_Instr* compile_Cmd(Cmd* cmd,char* r);
List_Instr* compile_Expr(Expr* expr,char* r);
Atom* mkAtomInt(int n) {
Atom* node = (Atom*) malloc(sizeof(Atom));
node->kind = A_INT;
node->num = n;
return node;
}
Atom* mkAtomChar(char* c) {
Atom* node = (Atom*) malloc(sizeof(Atom));
node->kind = A_VAR;
node->var = strdup(c);
return node;
}
Instr* mkInstrOneAtom(iKind kind, char* var, Atom* atom) {
Instr* node = (Instr*) malloc(sizeof(Instr));
node->kind = kind;
node->args._one_var.var = strdup(var);
node->args._one_var.atom = atom;
return node;
}
Instr* mkInstrTwoAtom(iKind kind, char* var, Atom* atom1, Atom* atom2) {
Instr* node = (Instr*) malloc(sizeof(Instr));
node->kind = kind;
node->args._two_var.var = strdup(var);
node->args._two_var.atom1 = atom1;
node->args._two_var.atom2 = atom2;
return node;
}
Instr* mkInstrGoto(iKind kind, Label* label) {
Instr* node = (Instr*) malloc(sizeof(Instr));
node->kind = kind;
node->args._goto.label = label;
return node;
}
Instr* mkInstrIfElse(iKind kind, char* var, Atom* atom, Label* label1, Label* label2) {
Instr* node = (Instr*) malloc(sizeof(Instr));
node->kind = kind;
node->args._if_else.var = strdup(var);
node->args._if_else.atom = atom;
node->args._if_else.label1 = label1;
node->args._if_else.label2 = label2;
return node;
}
Instr* mkInstrTrueFalse(iKind kind, char* var, char* TorF, Label* label1, Label* label2) {
Instr* node = (Instr*) malloc(sizeof(Instr));
node->kind = kind;
node->args._if_else.var = strdup(var);
node->args._if_else.TorF = strdup(TorF);
node->args._if_else.label1 = label1;
node->args._if_else.label2 = label2;
return node;
}
Label* mkLab(char* var, List_Instr* list) {
Label* node = (Label*) malloc(sizeof(Label));
node->var = var;
node->list_instr = list;
return node;
}
Instr* head(List_Instr* list) {
return list->head;
}
List_Instr* tail(List_Instr* l) {
return l->tail;
}
List_Instr* mkList(Instr* code, List_Instr* l) {
List_Instr* node = (List_Instr*) malloc(sizeof(List_Instr));
node->head = code;
node->tail = l;
return node;
}
List_Instr* append(List_Instr* l1, List_Instr* l2) {
if(l1 == NULL)
return l2;
return mkList(head(l1), append(tail(l1), l2));
}
List_Instr* compile_cmdlist(CmdList* cmd_list,char* r) {
List_Instr* node = (List_Instr*) malloc(sizeof(List_Instr));
node = compile_Cmd(cmd_list->cmd,r);
while(cmd_list->cmd_list!=NULL){
cmd_list = cmd_list->cmd_list;
char* r1 = create_register();
node = append(node, compile_Cmd(cmd_list->cmd,r1));
}
return node;
}
List_Instr* compile_BoolExpr(BoolExpr* boolexpr, char* r, Label* labelTrue, Label* labelFalse) {
List_Instr* node = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp1 = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp2 = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp3 = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp4 = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp5 = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp6 = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp7 = (List_Instr*) malloc(sizeof(List_Instr));
char* r1;
char* r2;
switch(boolexpr->kind){
case E_TRUEORFALSE:
switch (boolexpr->attr.bool_value) {
case 1:
node = mkList(mkInstrOneAtom(TRU,r,mkAtomInt(boolexpr->attr.bool_value)), NULL);
break;
case 0:
node = mkList(mkInstrOneAtom(FALS,r,mkAtomInt(boolexpr->attr.bool_value)), NULL);
break;
}
case E_BOOL_OPERATION:
r1 = create_register();
temp1 = compile_Expr(boolexpr->attr.op.left,r1);
r2 = create_register();
temp2 = compile_Expr(boolexpr->attr.op.right,r2);
temp3 = append(temp1,temp2);
r1 = temp1->head->args._one_var.var;
r2 = temp2->head->args._one_var.var;
switch (boolexpr->attr.op.boolOp) {
case EQUAL:
temp4 = append(temp3, mkList(mkInstrTwoAtom(EQU,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
case NOT_EQUAL:
temp4 = append(temp3, mkList(mkInstrTwoAtom(N_EQU,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
case LESSER:
temp4 = append(temp3, mkList(mkInstrTwoAtom(LES,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
case BIGGER:
temp4 = append(temp3, mkList(mkInstrTwoAtom(BIG,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
case LESSER_EQUAL:
temp4 = append(temp3, mkList(mkInstrTwoAtom(LEQ,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
case BIGGER_EQUAL:
temp4 = append(temp3, mkList(mkInstrTwoAtom(BEQ,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
}
}
temp5=NULL;
temp6=NULL;
temp7=NULL;
if(labelTrue!=NULL)
temp5 = mkList(mkInstrGoto(LAB,labelTrue),NULL);
if(labelFalse!=NULL)
temp6 = mkList(mkInstrGoto(GOTO,labelFalse),NULL);
temp7 = append(temp5,temp6);
node = append(temp4,temp7);
return node;
}
int flag; // 0 for if, 1 for while
List_Instr* compile_Cmd(Cmd* cmd,char* r) {
List_Instr* node = (List_Instr*) malloc(sizeof(List_Instr));
char* r1;
char* r2;
char* r3;
char* r4;
switch(cmd->kind){
case E_ATRIB:
return compile_Expr(cmd->attr.atrib.value,r);
case E_IF:
r1 = create_register();
r2 = create_register();
flag=0;
return compile_BoolExpr(cmd->attr._if.boolExpr,r,mkLab(r1,compile_cmdlist(cmd->attr._if.cmd_list,r2)),NULL);
case E_IFELSE:
r1 = create_register();
r2 = create_register();
r3 = create_register();
r4 = create_register();
flag=0;
return compile_BoolExpr(cmd->attr._ifelse.boolExpr,r,mkLab(r1,compile_cmdlist(cmd->attr._ifelse.cmd_list1,r3)),mkLab(r2,compile_cmdlist(cmd->attr._ifelse.cmd_list2,r4)));
case E_WHILE:
r1 = create_register();
r2 = create_register();
flag=1;
return compile_BoolExpr(cmd->attr._while.boolExpr,r,mkLab(r1,compile_cmdlist(cmd->attr._while.cmd_list,r2)),NULL);
case E_PRINT:
break;
case E_PRINTVAR:
break;
case E_READ:
break;
default:
yyerror("Unknown command!\n");
}
return node;
}
List_Instr* compile_Expr(Expr* expr, char* r) {
List_Instr* node = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp1 = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp2 = (List_Instr*) malloc(sizeof(List_Instr));
List_Instr* temp3 = (List_Instr*) malloc(sizeof(List_Instr));
char* r1;
char* r2;
switch(expr->kind){
case E_INTEGER:
node = mkList(mkInstrOneAtom(NUM,r,mkAtomInt(expr->attr.value)),NULL);
break;
case E_VAR:
node = mkList(mkInstrOneAtom(VARIAB,r,mkAtomChar(expr->attr.var)),NULL);
break;
case E_OPERATION:
r1 = create_register();
temp1 = compile_Expr(expr->attr.op.left,r1);
r2 = create_register();
temp2 = compile_Expr(expr->attr.op.right,r2);
temp3 = append(temp1,temp2);
switch(expr->attr.op.operator){
case PLUS:
node = append(temp3, mkList(mkInstrTwoAtom(ADI,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
case MINUS:
node = append(temp3, mkList(mkInstrTwoAtom(SUB,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
case MULT:
node = append(temp3, mkList(mkInstrTwoAtom(MUL,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
case DIV:
node = append(temp3, mkList(mkInstrTwoAtom(DIVI,r,mkAtomChar(r1),mkAtomChar(r2)), NULL));
break;
}
}
return node;
}
void printInstr(Instr* inst){
switch(inst->kind){
case NUM:
printf("%s",inst->args._one_var.var);
printf(" := %d\n", inst->args._one_var.atom->num);
break;
case VARIAB:
printf("%s", inst->args._one_var.var);
printf(" := %s\n", inst->args._one_var.atom->var);
break;
case ADI:
printf("%s",inst->args._two_var.var);
printf(" := %s + %s\n", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case SUB:
printf("%s",inst->args._two_var.var);
printf(" := %s - %s\n", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case MUL:
printf("%s",inst->args._two_var.var);
printf(" := %s * %s\n", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case DIVI:
printf("%s",inst->args._two_var.var);
printf(" := %s / %s\n", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case LAB:
printf("\n");
printListInstr(inst->args._goto.label->list_instr);
break;
case GOTO:
printf("Label %s:\n",inst->args._goto.label->var);
printListInstr(inst->args._goto.label->list_instr);
break;
case TRU:
printf("TRU\n");
break;
case FALS:
printf("FALS\n");
break;
case EQU:
if(flag==1)
printf("loop %s == %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
if(flag==0)
printf("if %s == %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case N_EQU:
if(flag==1)
printf("loop %s != %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
if(flag==0)
printf("if %s != %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case LES:
if(flag==1)
printf("loop %s < %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
if(flag==0)
printf("if %s < %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case BIG:
if(flag==1)
printf("loop %s > %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
if(flag==0)
printf("if %s > %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case LEQ:
if(flag==1)
printf("loop %s <= %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
if(flag==0)
printf("if %s <= %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
case BEQ:
if(flag==1)
printf("loop %s >= %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
if(flag==0)
printf("if %s >= %s ", inst->args._two_var.atom1->var, inst->args._two_var.atom2->var);
break;
default: printf("Não existe\n");
}
}
void printListInstr(List_Instr* list){
if(list == NULL)
return;
if(list->tail == NULL){
printInstr(list->head);
return;
}
printInstr(list->head);
printListInstr(list->tail);
return;
}
int main(int argc, char** argv) {
argc--;
argv++;
if(argc!=0) {
yyin=fopen(*argv,"r");
if(!yyin) {
printf("'%s':could not open file\n", *argv);
return 1;
}
}
if(yyparse()==0) {
char* r = create_register();
List_Instr* list = compile_cmdlist(root,r);
printf("SYSCALL\n");
printListInstr(list);
}
return 0;
}
/*
int main() {
Expr* expr1 = ast_integer(2);
Expr* expr2 = ast_integer(5);
Expr* expr3 = ast_operation(MULT,expr1,expr2);
char* var = (char*) malloc(sizeof(char));
var = "x";
Expr* expr4 = ast_var(var);
Expr* res = ast_operation(MINUS,expr4,expr3);
BoolExpr* be = ast_BoolOperation(EQUAL,expr1,expr2);
char* r1 = create_register();
List_Instr* list1 = compile_Expr(res,r1);
char* r2 = create_register();
char* a = "a";
Label* l1 = mkLab(a,list1);
char* b = "b";
Label* l2 = mkLab(b,list1);
List_Instr* list2 = compile_BoolExpr(be,r2,l1,l2);
printf("SYSCALL\n");
printListInstr(list2);
return 0;
}*/ |
C | /*
AA 3.3 - Consistncia de datas
Contexto
Verificaes de consistncia so importantes para os algoritmos.
O objetivo verificar se datas so vlidas e quais as relaes entre elas.
Informaes
Para esta atividade, so consideradas datas vlidas aquelas em que o nmero de
dias est nos limites usuais, o que depende do ms em questo. Assim, so
considerados as seguintes faixas de dias:
Ms Intervalo
Janeiro 1 a 31
Fevereiro 1 a 28
Maro 1 a 31
Abril 1 a 30
Maio 1 a 31
Junho 1 a 30
Julho 1 a 31
Agosto 1 a 31
Setembro 1 a 30
Outubro 1 a 31
Novembro 1 a 30
Dezembro 1 a 31
Anos bissextos no devem ser considerados, de forma que Fevereiro sempre ser
considerado com um mximo de 28 dias.
Os meses, que sero digitados na forma numrica, so vlidos na faixa de 1 a 12.
Para os anos, ser considerado que anos negativos simbolizem A.C, enquanto
positivos sejam D.C. O nico valor invlido para o ano 0.
Especificao
O trabalho deve fazer a leitura de duas datas, sendo que, para cada uma, devem
ser lidos separadamente dia, ms e ano (usando-se variveis inteiras).
Cada data deve ser verificada quanto sua validade pelos critrios apresentados
acima e tambm devem ser comparadas quanto cronologia, dizendo se so iguais,
se a primeira anterior segunda ou se a segunda anterior primeira.
Devem ser escritas as mensagens pertinentes.
Autor: FELIPE NOGUEIRA DE SOUZA 04/05/2014
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
//declarando e inicializando as variaveis
int mes1, dia1, ano1, validadeData1, mes2, dia2, ano2, validadeData2;
mes1 = 0;
dia1 = 0;
ano1 = 0;
validadeData1 = 0;
mes2 = 0;
dia2 = 0;
ano2 = 0;
validadeData2 = 0;
printf("\n*******************************************************************************");
printf("\n\n******************************* VALIDANDO DATAS *******************************");
printf("\n\n*******************************************************************************");
//solicitando e recebendo a primeira data
printf("\n\n\nPRIMEIRA DATA");
printf("\n\nDigite o dia: ");
scanf("%d", &dia1);
printf("\nDigite o mes conforme tabela abaixo \n\n Janeiro.....1 \n Fevereiro...2 \n Marco.......3 \n Abril.......4 \n Maio........5 \n Junho.......6 \n Julho.......7 \n Agosto......8 \n Setembro....9 \n Outubro....10 \n Novembro...11 \n Dezembro...12\n\nMes: ");
scanf("\n%d", &mes1);
printf("\n\nDigite o ano: ");
scanf("%d", &ano1);
//solicitando e recebendo a segunada data
printf("\n\n\nSEGUNDA DATA");
printf("\n\nDigite o dia: ");
scanf("%d", &dia2);
printf("\nDigite o mes conforme tabela abaixo \n\n Janeiro.....1 \n Fevereiro...2 \n Marco.......3 \n Abril.......4 \n Maio........5 \n Junho.......6 \n Julho.......7 \n Agosto......8 \n Setembro....9 \n Outubro....10 \n Novembro...11 \n Dezembro...12\n\nMes: ");
scanf("\n%d", &mes2);
printf("\n\nDigite o ano: ");
scanf("%d", &ano2);
//verificando a validade da data 1
if (((mes1 == 1 || mes1 == 3 || mes1 == 5 || mes1 == 7 || mes1 == 8 ||
mes1 == 10 || mes1 == 12) && (dia1 > 0 && dia1 < 32)&&(ano1 != 0))||
((mes1 == 4 || mes1 == 6 || mes1 == 9 || mes1 == 11) &&
(dia1 > 0 && dia1 < 31)&&(ano1 != 0))||((mes1 == 2)&&
(dia1 > 0 && dia1 < 29)&&(ano1 != 0)))
{
printf("\n\nA primeira data digitada %d/%d/%d e valida", dia1, mes1, ano1);
validadeData1 = 1;
}
else
{
printf("\n\nA primeira data digitada %d/%d/%d nao e valida", dia1, mes1, ano1);
}
//verificando a validade da data 2
if (((mes2 == 1 || mes2 == 3 || mes2 == 5 || mes2 == 7 || mes2 == 8 ||
mes2 == 10 || mes2 == 12) && (dia2 > 0 && dia2 < 32)&&(ano2 != 0))||
((mes2 == 4 || mes2 == 6 || mes2 == 9 || mes2 == 11) &&
(dia2 > 0 && dia2 < 31)&&(ano2 != 0))||((mes2 == 2)&&
(dia2 > 0 && dia2 < 29)&&(ano2 != 0)))
{
printf("\n\nA segunda data digitada %d/%d/%d e valida\n\n", dia2, mes2, ano2);
validadeData2 = 1;
}
else
{
printf("\n\nA segunda data digitada %d/%d/%d nao e valida\n\n", dia2, mes2, ano2);
}
if (validadeData1 == 1 && validadeData2 == 1)
{
if (ano1 == ano2)
{
if (mes1 == mes2)
{
if (dia1 == dia2)
{
printf("As datas sao iguais");
}
else if (dia1 > dia2)
{
printf("A segunda data e anterior a primeira");
}
else
{
printf("A primeira data e anterior a segunda");
}
}
else if (mes1 > mes2)
{
printf("A segunda data e anterior a primeira");
}
else
{
printf("A primeira data e anterior a segunda");
}
}
else if (ano1 > ano2)
{
printf("A segunda data e anterior a primeira");
}
else
{
printf("A primeira data e anterior a segunda");
}
}
else
{
printf("\n\nNao e possivel comparar devido a validade das datas");
}
printf("\n\n\n");
system("PAUSE");
return 0;
}
|
C | /*
* fork demo
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
static void sigchld_handler(int sig)
{
int status;
pid_t pid;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
printf("process %d exit\n", pid);
}
}
int main()
{
pid_t pid;
int res = 0;
signal(SIGCHLD, sigchld_handler);
// register SIGCHLD handler
struct sigaction chld_action;
chld_action.sa_handler = sigchld_handler;
chld_action.sa_flags = SA_NODEFER;
res = sigaction(SIGCHLD, &chld_action, NULL);
if (res == -1) {
perror("Oh! Can not catch SIGCHLD signal. :) ");
}
if ((pid = fork()) < 0) {
perror("fork error");
exit(-1);
} else if (pid == 0) {
printf("fork success process id: %d\n", getpid());
} else {
printf("parent process id: %d\n", getpid());
sleep(10);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.