language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
#include <fsdyn/integer.h>
#include "unixkit.h"
int main()
{
list_t *open_fds = unixkit_get_open_fds();
assert(open_fds);
list_elem_t *elem = list_get_first(open_fds);
while (elem) {
int fd = as_intptr(list_elem_get_value(elem));
fprintf(stderr, "fd: %d\n", fd);
elem = list_next(elem);
}
list_t *keep_fds = make_list();
list_append(keep_fds, as_integer(0));
list_append(keep_fds, as_integer(1));
list_append(keep_fds, as_integer(2));
pid_t pid = unixkit_fork(keep_fds);
assert(pid >= 0);
if (pid == 0) {
list_elem_t *elem = list_get_first(open_fds);
while (elem) {
int fd = as_intptr(list_elem_get_value(elem));
int flags = fcntl(fd, F_GETFD, 0);
if (fd >= 0 && fd <= 2)
assert(flags >= 0);
else if (flags >= 0)
/* allow for valgrind protected file descriptors */
assert(close(fd) < 0 && errno == EBADF);
else
assert(errno == EBADF);
elem = list_next(elem);
}
destroy_list(open_fds);
_exit(0);
}
destroy_list(open_fds);
for (;;) {
int wstatus;
if (waitpid(pid, &wstatus, 0) == pid) {
assert(WIFEXITED(wstatus));
break;
}
assert(errno == EINTR);
}
return EXIT_SUCCESS;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: msymkany <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/29 17:39:49 by msymkany #+# #+# */
/* Updated: 2017/01/30 14:41:21 by msymkany ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static t_lst *get_fd(const int fd, t_lst **frst)
{
t_lst *lst;
t_lst *new;
lst = *frst;
while (lst)
{
if (lst->fd == fd)
return (lst);
lst = lst->next;
}
if (!(new = (t_lst *)malloc(sizeof(t_list))))
return (NULL);
new->fd = fd;
new->data = NULL;
new->next = *frst;
*frst = new;
return (new);
}
static int read_line(char **cut, char **line, const int fd, ssize_t r)
{
char *n;
char *pt;
size_t i;
while ((n = ft_strchr(*cut, '\n')) == NULL && r != 0)
{
i = ft_strlen(*cut);
pt = ft_strdup(*cut);
ft_strdel(cut);
if (!(*cut = ft_strnew(i + BUFF_SIZE)) ||
(r = read(fd, *cut + i, BUFF_SIZE)) < 0)
return (-1);
ft_memcpy(*cut, pt, i);
ft_strdel(&pt);
}
if (r == 0 && n == NULL)
n = ft_strchr(*cut, '\0');
if (!(*line = ft_strsub(*cut, 0, n - *cut)))
return (-1);
n = ft_strdup(++n);
ft_strdel(cut);
if (!(*cut = ft_strdup(n)))
return (-1);
ft_strdel(&n);
return (r == 0 && **line == '\0' && **cut == '\0') ? 0 : 1;
}
int get_next_line(const int fd, char **line)
{
static t_lst *frst;
t_lst *lst;
ssize_t r;
r = BUFF_SIZE;
if (fd < 0 || !(line) || BUFF_SIZE <= 0)
return (-1);
lst = get_fd(fd, &frst);
if (!lst->data)
{
if (!(lst->data = ft_strnew(BUFF_SIZE + 1)) ||
(r = read(fd, lst->data, BUFF_SIZE)) < 0)
return (-1);
}
return (read_line(&lst->data, line, fd, r));
}
|
C
|
/************************************************************************
Copyright (c) IPADS@SJTU 2021. All rights reserve.
This file contains the pseudo-random generator provided by PENGLAI sdk.
It is used to generate 'seed' for SM2, and it can be used to generate
'key' and 'iv' for SM4.
Function List:
1.penglai_set_rand_seed // set random seed
2.penglai_read_rand // generate a random
**************************************************************************/
#include "Random.h"
#include "miracl.h"
#include <string.h>
static BOOL set_seed = FALSE;
/*
* FIX ME: A weird bug, if I(Qingyu Shang) remove below two variable's
* declaration, which are not used here, enclave will halt in mirsys().
* After locating the wrong code and doing objdump on elf file, I still
* have no idea with why these two global variable can help with it.
*/
char g_mem[MR_BIG_RESERVE(6)];
char g_mem_point[MR_ECP_RESERVE(2)];
/*
* User must set a real random as random number seed, otherwise
* function penglai_read_rand() just output the same result each
* time the random system initialized.
*
* In order to make 'gm' library available in both Host and Enclave,
* we let the random number seed be independent of sbi_ecall or time().
*/
void penglai_set_rand_seed(unsigned int seed)
{
mirsys(128, 16);
irand(seed);
set_seed = TRUE;
}
/*
* Generate a random number with 'size' bytes length. It can be
* used to generate Key and IV in symmetric encryption and so on.
* If random seed haven't been set, it will be set as 0.
*/
void penglai_read_rand(unsigned char rand[], int size)
{
big x;
int blocks, fill_size;
char mem[MR_BIG_RESERVE(1)];
memset(mem, 0, MR_BIG_RESERVE(1));
x = mirvar_mem(mem, 0);
if(!set_seed)
penglai_set_rand_seed(0);
blocks = (size + 32 - 1) / 32;
for(int i = 0; i < blocks; i++){
fill_size = (i == (blocks-1)) ? (size - (blocks-1) * 32) : 32;
/* generate random number '2 * fill_size' digits long to base 16 */
bigdig(2 * fill_size, 16, x);
big_to_bytes(fill_size, x, (char *)(rand + i * 32), TRUE);
}
}
|
C
|
//
// 2021 Spring - Automata and Formal Languages (03)
// Homework #1: Building a DFA simulator that accepts strings with prefix bbab
//
// Copyright (c) Prof. Jaehyeong Sim
// Department of Computer Science and Engineering, Ewha Womans University
//
#include <stdio.h>
#define MAX_NUM_STATES 10
#define MAX_NUM_INPUTS 16
#define NUM_SYMBOLS 2
// Definition of DFA
struct DFA {
int num_states; // the number of DFA states
char symbols[NUM_SYMBOLS]; // symbols
int trans[MAX_NUM_STATES][NUM_SYMBOLS]; // transitions
int idx_init; // an initial state
int idx_isFinal[MAX_NUM_STATES]; // final states
};
int main(int argc, char *argv[]) {
// declare struct DFA
struct DFA u1;
// assign values to member variables
u1.num_states = 6;
u1.symbols[0] = 'a';
u1.symbols[1] = 'b';
u1.trans[0][0] = 5;
u1.trans[0][1] = 1;
u1.trans[1][0] = 5;
u1.trans[1][1] = 2;
u1.trans[2][0] = 3;
u1.trans[2][1] = 5;
u1.trans[3][0] = 5;
u1.trans[3][1] = 4;
u1.trans[4][0] = 4;
u1.trans[4][1] = 4;
u1.trans[5][0] = 5;
u1.trans[5][1] = 5;
u1.idx_init = 0;
for (int i = 0; i < u1.num_states; i++) {
if (i == 4)
u1.idx_isFinal[i] = 1;
else
u1.idx_isFinal[i] = 0;
}
// do transitions according to input characters
int currentState = u1.idx_init;
for (int i = 0; i < MAX_NUM_INPUTS; i++) {
char inchar = argv[1][i];
if (inchar == '\0') {
break;
}
if (inchar == 'a')
currentState = u1.trans[currentState][0];
else if (inchar == 'b')
currentState = u1.trans[currentState][1];
else { //a, b 이외의 문자
printf("Rejected\n");
return 0;
}
}
// print the output
if (u1.idx_isFinal[currentState] == 1)
printf("Accepted\n");
else
printf("Rejected\n");
return 0;
}
|
C
|
#include "stdio.h"
// return a string with func
char *getName(void);
int main()
{
char *name;
name = getName();
printf("%s %p\n", name);
return 0;
}
char *getName(void)
{
char *name = "Hello";
printf("%p\n", name);
char name1[10] = {'H','e','l','l','o'};
printf("%p\n", name1);
return name;
}
|
C
|
/*H********************************************************************************/
/*!
\File plat-time.c
\Description
This module implements variations on the standard library time functions.
The originals had a number of problems with internal static storage,
bizarre parameter passing (pointers to input values instead of the
actual value) and time_t which is different on different platforms.
All these functions work with uint32_t values which provide a time
range of 1970-2107.
\Copyright
Copyright (c) 2005 Electronic Arts Inc.
\Version 01/11/2005 (gschaefer) First Version
*/
/********************************************************************************H*/
/*** Include files ****************************************************************/
#include <stdio.h>
#include <string.h>
#include "DirtySDK/platform.h"
#include "DirtySDK/dirtysock/dirtylib.h"
#if defined(DIRTYCODE_PS4)
#include <kernel.h>
#elif defined(DIRTYCODE_PC) || defined(DIRTYCODE_XBOXONE)
#include <windows.h>
#include <time.h>
#include <sys/types.h>
#include <sys/timeb.h>
#elif defined (DIRTYCODE_LINUX) || defined(DIRTYCODE_ANDROID) || defined(DIRTYCODE_APPLEIOS) || defined(DIRTYCODE_APPLEOSX)
#include <sys/time.h>
#endif
/*** Defines **********************************************************************/
/*** Type Definitions *************************************************************/
/*** Variables ********************************************************************/
static const char *_PlatTime_strWday[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL };
static const char *_PlatTime_strMonth[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL };
/*** Private functions ************************************************************/
/*F********************************************************************************/
/*!
\Function _ds_strtoint
\Description
Converts a string number to an integer. Does not support sign.
\Input *pStr - pointer to int to read
\Input *pValue - [out] storage for result
\Input iMaxDigits - max number of digits to convert
\Output
const char * - pointer past end of number
\Version 12/13/2012 (jbrookes)
*/
/********************************************************************************F*/
static const char *_ds_strtoint(const char *pStr, int32_t *pValue, int32_t iMaxDigits)
{
int32_t iNum, iDigit;
for (iNum = 0, iDigit = 0; ((*pStr >= '0') && (*pStr <= '9') && (iDigit < iMaxDigits)); pStr += 1, iDigit += 1)
{
iNum = (iNum * 10) + (*pStr & 15);
}
*pValue = iNum;
return(pStr);
}
/*** Public functions *************************************************************/
/*F********************************************************************************/
/*!
\Function ds_timeinsecs
\Description
Return time in seconds, or zero if not available
\Output uint64_t - number of elapsed seconds since Jan 1, 1970
\Version 01/12/2005 (gschaefer)
*/
/********************************************************************************F*/
uint64_t ds_timeinsecs(void)
{
return(NetTime());
}
/*F********************************************************************************/
/*!
\Function ds_timezone
\Description
This function returns the current system timezone as its offset from GMT in
seconds. There is no direct equivilent function in the standard C libraries.
\Output int32_t - local timezone offset from GMT in seconds
\Notes
The intent is to determine the timezone, so the offset intentionally does
not take daylight savings into account.
Do not use for GMT time determination.
\Version 11/06/2002 (jbrookes)
*/
/********************************************************************************F*/
int32_t ds_timezone(void)
{
time_t iGmt, iLoc;
static int32_t iZone = -1;
// just calc the timezone one time
if (iZone == -1)
{
time_t uTime = time(0);
struct tm *pTm, TmTime;
// convert to gmt time
pTm = gmtime(&uTime);
iGmt = (uint32_t)mktime(pTm);
// convert to local time
pTm = ds_localtime(&TmTime,(uint32_t)uTime);
iLoc = (uint32_t)mktime(pTm);
// calculate timezone difference
iZone = (int32_t)(iLoc - iGmt);
}
// return the timezone offset in seconds
return(iZone);
}
/*F********************************************************************************/
/*!
\Function ds_localtime
\Description
This converts the input GMT time to the local time as specified by the
system clock. This function follows the re-entrant localtime_r function
signature.
\Input *pTm - storage for localtime output
\Input elap - GMT time
\Output
struct tm * - pointer to localtime result
\Version 04/23/2008 (jbrookes)
*/
/********************************************************************************F*/
struct tm *ds_localtime(struct tm *pTm, uint64_t elap)
{
return(NetLocalTime(pTm, elap));
}
/*F********************************************************************************/
/*!
\Function ds_secstotime
\Description
Convert elapsed seconds to discrete time components. This is essentially a
ds_localtime() replacement with better syntax that is available on all platforms.
\Input *pTm - target component record
\Input elap - epoch time input
\Output struct tm * - returns tm if successful, NULL if failed
\Version 01/23/2000 (gschaefer)
*/
/********************************************************************************F*/
struct tm *ds_secstotime(struct tm *pTm, uint64_t elap)
{
int32_t year, leap, next, days, secs;
const int32_t *mon;
// table to find days per month
static const int32_t dayspermonth[24] = {
31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, // leap
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 // norm
};
// table to find day of the week
static const int32_t wday[] = {
0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4
};
// divide out secs within day and days
// (we ignore leap-seconds cause it requires tables and nasty stuff)
days = (int32_t)(elap / (24*60*60));
secs = (int32_t)(elap % (24*60*60));
// store the time info
pTm->tm_sec = secs % 60;
secs /= 60;
pTm->tm_min = secs % 60;
secs /= 60;
pTm->tm_hour = secs;
// determine what year we are in
for (year = 1970;; year = next) {
// calc the length of the year in days
leap = (((year & 3) == 0) && (((year % 100 != 0) || ((year % 400) == 0))) ? 366 : 365);
// see if date is within this year
if (days < leap)
break;
// estimate target year assuming every year is a leap year
// (this may underestimate the year, but will never overestimate)
next = year + (days / 366);
// make sure year got changed and force if it did not
/// (can happen on dec 31 of non-leap year)
if (next == year)
++next;
// subtract out normal days/year
days -= (next - year) * 365;
// add in leap years from previous guess
days += ((year-1)/4 - (year-1)/100 + (year-1)/400);
// subtract out leap years since new guess
days -= ((next-1)/4 - (next-1)/100 + (next-1)/400);
}
// save the year and day within year
pTm->tm_year = year - 1900;
pTm->tm_yday = days;
// calc the month
mon = dayspermonth + 12*(leap&1);
for (pTm->tm_mon = 0; days >= *mon; pTm->tm_mon += 1)
days -= *mon++;
// save the days
pTm->tm_mday = days + 1;
// calculate weekday using Sakamoto's algorithm, adjusted for m=[0...11]
year -= pTm->tm_mon < 2;
pTm->tm_wday = (year + year/4 - year/100 + year/400 + wday[pTm->tm_mon] + pTm->tm_mday) % 7;
// clear dst
pTm->tm_isdst = 0;
// return pointer to argument to make it closer to ds_localtime()
return(pTm);
}
/*F********************************************************************************/
/*!
\Function ds_timetosecs
\Description
Convert discrete components to elapsed time.
\Input *pTm - source component record
\Output
uint32_t - zero=failure, else epoch time
\Version 01/23/2000 (gschaefer)
*/
/********************************************************************************F*/
uint64_t ds_timetosecs(const struct tm *pTm)
{
uint64_t min, max, mid;
struct tm cmp;
int32_t res;
/* do a binary search using ds_secstotime to encode prospective time_t values.
though iterative, it requires a max of 32 iterations which is actually pretty
good considering the complexity of the calculation (this allows all the
time nastiness to remain in a single function). */
/* perform binary search (set max to 1/1/3000 to reduce 64-bit search space
and prevent overflow in 32bit days/secs calculations in ds_secstotime */
for (min = 0, mid = 0, res = 0, max = 32503680000; min <= max; )
{
/* test at midpoint -- since these are large unsigned values, they can overflow
in the (min+max)/2 case hense the individual divide and lost bit recovery */
mid = (min/2)+(max/2)+(min&max&1);
// do the time conversion
ds_secstotime(&cmp, mid);
// do the compare
if ((res = (cmp.tm_year - pTm->tm_year)) == 0) {
if ((res = (cmp.tm_mon - pTm->tm_mon)) == 0) {
if ((res = (cmp.tm_mday - pTm->tm_mday)) == 0) {
if ((res = (cmp.tm_hour - pTm->tm_hour)) == 0) {
if ((res = (cmp.tm_min - pTm->tm_min)) == 0) {
if ((res = cmp.tm_sec - pTm->tm_sec) == 0) {
// got an exact match!
break;
}
}
}
}
}
}
// force break once min/max converge (cannot do this within for condition as res will not be setup correctly)
if (min == max)
break;
// narrow the search range
if (res > 0)
max = mid-1;
else
min = mid+1;
}
// return converted time or zero if failed
return((res == 0) ? mid : 0);
}
/*F********************************************************************************/
/*!
\Function ds_plattimetotime
\Description
This converts the input platform-specific time data structure to the
generic time data structure.
\Input *pTm - generic time data structure to be filled by the function
\Input *pPlatTime - pointer to the platform-specific data structure
\Output
struct tm * - NULL=failure; else pointer to user-provided generic time data structure
\Notes
See NetPlattimeToTime() for input data format
\Version 05/08/2010 (mclouatre)
*/
/********************************************************************************F*/
struct tm *ds_plattimetotime(struct tm *pTm, void *pPlatTime)
{
return(NetPlattimeToTime(pTm, pPlatTime));
}
/*F********************************************************************************/
/*!
\Function ds_plattimetotimems
\Description
This function retrieves the current date time and fills in the
generic time data structure prrovided. It has the option of returning millisecond
which is not part of the generic time data structure
\Input *pTm - generic time data structure to be filled by the function
\Input *pImSec - output param for milisecond to be filled by the function (optional can be NULL)
\Output
struct tm * - NULL=failure; else pointer to user-provided generic time data structure
\Version 09/16/2014 (tcho)
*/
/********************************************************************************F*/
struct tm *ds_plattimetotimems(struct tm *pTm , int32_t *pImSec)
{
return(NetPlattimeToTimeMs(pTm, pImSec));
}
/*F********************************************************************************/
/*!
\Function ds_timetostr
\Description
Converts a date formatted in a number of common Unix and Internet formats
and convert to a struct tm.
\Input *pTm - input time stucture to be converted to string
\Input eConvType - user-selected conversion type
\Input bLocalTime - whether input time is local time or UTC 0 offset time.
\Input *pStrBuf - user-provided buffer to be filled with datetime string
\Input iBufSize - size of output buffer (must be at least 18 bytes to receive null-terminated yyyy-MM-ddTHH:mm:ssZ
\Output
char * - zero=failure, else epoch time
\Version 07/12/2012 (jbrookes)
*/
/********************************************************************************F*/
char *ds_timetostr(const struct tm *pTm, TimeToStringConversionTypeE eConvType, uint8_t bLocalTime, char *pStrBuf, int32_t iBufSize)
{
switch(eConvType)
{
case TIMETOSTRING_CONVERSION_ISO_8601:
ds_snzprintf(pStrBuf, iBufSize, "%04d-%02d-%02dT%02d:%02d:%02d%s",
pTm->tm_year+1900, pTm->tm_mon+1, pTm->tm_mday,
pTm->tm_hour, pTm->tm_min, pTm->tm_sec,
!bLocalTime ? "Z" : "");
break;
case TIMETOSTRING_CONVERSION_ISO_8601_BASIC:
ds_snzprintf(pStrBuf, iBufSize, "%04d%02d%02dT%02d%02d%02d%s",
pTm->tm_year+1900, pTm->tm_mon+1, pTm->tm_mday,
pTm->tm_hour, pTm->tm_min, pTm->tm_sec,
!bLocalTime ? "Z" : "");
break;
case TIMETOSTRING_CONVERSION_RFC_0822: // e.g. Wed, 15 Nov 1995 04:58:08 GMT
{
uint32_t tm_wday = ((unsigned)pTm->tm_wday < 7) ? pTm->tm_wday : 7;
uint32_t tm_mon = ((unsigned)pTm->tm_mon < 12) ? pTm->tm_mon : 12;
ds_snzprintf(pStrBuf, iBufSize, "%s, %2d %s %4d %02d:%02d:%02d GMT", _PlatTime_strWday[tm_wday], pTm->tm_mday,
_PlatTime_strMonth[tm_mon], pTm->tm_year+1900, pTm->tm_hour, pTm->tm_min, pTm->tm_sec);
break;
}
default:
// unsupported conversion type
pStrBuf = NULL;
break;
}
return(pStrBuf);
}
/*F********************************************************************************/
/*!
\Function ds_secstostr
\Description
Converts a datetime in epoch format to string
\Input elap - epoch time to convert to string
\Input eConvType - user-selected conversion type
\Input bLocalTime - whether input time is local time or UTC 0 offset time.
\Input *pStrBuf - user-provided buffer to be filled with datetime string
\Input iBufSize - size of output buffer (must be at least 18 bytes to receive null-terminated yyyy-MM-ddTHH:mm:ssZ
\Output
char * - zero=failure, else epoch time
\Version 02/26/2014 (jbrookes)
*/
/********************************************************************************F*/
char *ds_secstostr(uint64_t elap, TimeToStringConversionTypeE eConvType, uint8_t bLocalTime, char *pStrBuf, int32_t iBufSize)
{
struct tm TmTime;
return(ds_timetostr(ds_secstotime(&TmTime, elap), eConvType, bLocalTime, pStrBuf, iBufSize));
}
/*F********************************************************************************/
/*!
\Function ds_strtotime
\Description
Converts a date formatted in a number of common Unix and Internet formats
and convert to a struct tm.
\Input *pStr - textual date string
\Output uint32_t - zero=failure, else epoch time
\Notes
\verbatim
The following time formats are supported:
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
The following format is mentioned as needing to be readable by HTTP
but is not currently supported by this function:
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
\endverbatim
\Version 11/01/2002 (gschaefer)
*/
/********************************************************************************F*/
uint64_t ds_strtotime(const char *pStr)
{
int32_t i;
const char *s;
struct tm tm;
// reset the fields
ds_memset(&tm, -1, sizeof(tm));
// skip past any white space
while ((*pStr != 0) && (*pStr <= ' '))
{
pStr++;
}
// see if starts with day of week (RFC 822/1123, asctime)
for (i = 0; (s=_PlatTime_strWday[i]) != 0; ++i)
{
if ((pStr[0] == s[0]) && (pStr[1] == s[1]) && (pStr[2] == s[2]))
{
tm.tm_wday = i;
// skip name of weekday
while ((*pStr != ',') && (*pStr != ' ') && (*pStr != 0))
++pStr;
// skip the divider
while ((*pStr == ',') || (*pStr == ' '))
++pStr;
break;
}
}
// check for mmm dd (asctime)
if ((*pStr < '0') || (*pStr > '9'))
{
for (i = 0; (s=_PlatTime_strMonth[i]) != 0; ++i)
{
// look for a match
if ((pStr[0] != s[0]) || (pStr[1] != s[1]) || (pStr[2] != s[2]))
continue;
// found the month
tm.tm_mon = i;
// skip to the digits
while ((*pStr != 0) && ((*pStr < '0') || (*pStr > '9')))
++pStr;
// get the day of month
for (i = 0; ((*pStr >= '0') && (*pStr <= '9')); ++pStr)
i = (i * 10) + (*pStr & 15);
if (i > 0)
tm.tm_mday = i;
break;
}
}
// check for dd mmm (RFC 822/1123)
if ((tm.tm_mon < 0) && (pStr[0] >= '0') && (pStr[0] <= '9') &&
((pStr[1] > '@') || (pStr[2] > '@') || (pStr[3] > '@')))
{
// get the day
for (i = 0; ((*pStr >= '0') && (*pStr <= '9')); ++pStr)
i = (i * 10) + (*pStr & 15);
tm.tm_mday = i;
while (*pStr < '@')
++pStr;
// get the month
for (i = 0; (s=_PlatTime_strMonth[i]) != 0; ++i)
{
// look for a match
if ((pStr[0] != s[0]) || (pStr[1] != s[1]) || (pStr[2] != s[2]))
continue;
tm.tm_mon = i;
while ((*pStr != 0) && (*pStr != ' '))
++pStr;
break;
}
}
// check for xx/xx or xx/xx/xx (???)
if ((*pStr >= '0') && (*pStr <= '9') && (tm.tm_mon < 0))
{
// get the month
for (i = 0; ((*pStr >= '0') && (*pStr <= '9')); ++pStr)
i = (i * 10) + (*pStr & 15);
tm.tm_mon = i - 1;
if (*pStr != 0)
++pStr;
// get the day
for (i = 0; ((*pStr >= '0') && (*pStr <= '9')); ++pStr)
i = (i * 10) + (*pStr & 15);
tm.tm_mday = i;
if (*pStr != 0)
++pStr;
}
// check for year (RFC 822/1123)
while ((*pStr != 0) && ((*pStr < '0') || (*pStr > '9')))
++pStr;
// see if the year is here
if ((pStr[0] >= '0') && (pStr[0] <= '9') && (pStr[1] != ':') && (pStr[2] != ':'))
{
for (i = 0; ((*pStr >= '0') && (*pStr <= '9')); ++pStr)
i = (i * 10) + (*pStr & 15);
if (i > 999)
tm.tm_year = i;
else if (i >= 50)
tm.tm_year = 1900+i;
else
tm.tm_year = 2000+i;
// find next digit sequence
while ((*pStr != 0) && ((*pStr < '0') || (*pStr > '9')))
++pStr;
}
// save the hour (RFC 822/1123, asctime)
if ((*pStr >= '0') && (*pStr <= '9'))
{
i = (*pStr++ & 15);
if ((*pStr >= '0') && (*pStr <= '9'))
i = (i * 10) + (*pStr++ & 15);
tm.tm_hour = i;
if (*pStr == ':')
++pStr;
}
// save the minute (RFC 822/1123, asctime)
if ((*pStr >= '0') && (*pStr <= '9'))
{
i = (*pStr++ & 15);
if ((*pStr >= '0') && (*pStr <= '9'))
i = (i * 10) + (*pStr++ & 15);
tm.tm_min = i;
if (*pStr == ':')
++pStr;
}
// save the second (if present) (RFC 822/1123, asctime)
if ((*pStr >= '0') && (*pStr <= '9'))
{
i = (*pStr++ & 15);
if ((*pStr >= '0') && (*pStr <= '9'))
i = (i * 10) + (*pStr++ & 15);
tm.tm_sec = i;
}
// see if year is still remaining (asctime)
if (tm.tm_year < 0)
{
// see if any digits left
while ((*pStr != 0) && ((*pStr < '0') || (*pStr > '9')))
++pStr;
for (i = 0; ((*pStr >= '0') && (*pStr <= '9')); ++pStr)
i = (i * 10) + (*pStr & 15);
if (i > 999)
tm.tm_year = i;
}
// make year relative to 1900 (really dumb)
if (tm.tm_year > 1900)
tm.tm_year -= 1900;
// convert from struct tm to uint32_t and return to caller
return(ds_timetosecs(&tm));
}
/*F********************************************************************************/
/*!
\Function ds_strtotime2
\Description
Converts a date formatted in a number of common Unix and Internet formats
and convert to a struct tm.
\Input *pStr - textual date string
\Input eConvType - time format to convert from
\Output
uint32_t - zero=failure, else epoch time
\Notes
For supported conversion types other than ISO_8601, see documentation
for ds_strtotime().
\Version 12/13/2012 (jbrookes)
*/
/********************************************************************************F*/
uint64_t ds_strtotime2(const char *pStr, TimeToStringConversionTypeE eConvType)
{
uint64_t uTime = 0;
struct tm tm;
if (eConvType == TIMETOSTRING_CONVERSION_ISO_8601)
{
// format: YYYY-MM-DDTHH:MM:SSZ
if (strlen(pStr) < 19) // 'Z' is optional and ignored
{
return(0);
}
// read the date/time
pStr = _ds_strtoint(pStr, &tm.tm_year, 4) + 1; // get the year, skip hyphen
pStr = _ds_strtoint(pStr, &tm.tm_mon, 2) + 1; // get the month, skip hyphen
pStr = _ds_strtoint(pStr, &tm.tm_mday, 2) + 1; // get the day, skip 'T'
pStr = _ds_strtoint(pStr, &tm.tm_hour, 2) + 1; // get the hour, skip ':'
pStr = _ds_strtoint(pStr, &tm.tm_min, 2) + 1; // get the minute, skip ':'
_ds_strtoint(pStr, &tm.tm_sec, 2); // get the second
// adjust year and month
tm.tm_year -= 1900;
tm.tm_mon -= 1;
// convert from struct tm to uint32_t and return to caller
uTime = ds_timetosecs(&tm);
}
else if ((eConvType == TIMETOSTRING_CONVERSION_ASN1_UTCTIME) || (eConvType == TIMETOSTRING_CONVERSION_ASN1_GENTIME))
{
/* GeneralizedTime: .fff is optional
Local Time: YYYYMMDDHHMMSS.fff
UTC Time: YYYYMMDDHHMMSS.fffZ
Difference Time: YYYYMMDDHHMMSS.fff+-HHMM
UTCTime: like GeneralizedTime, but accuracy is to one minute or one second (no .fff, SS is optional, Z is implicit and not included).
Local Time: YYYYMMDDHHMMSS
UTC Time: YYMMDDHHMMSS
Difference Time: YYYYMMDDHHMMSS+-HHMM
Note: Fractional time, difference time, and UTC character, if present, are ignored */
if (eConvType == TIMETOSTRING_CONVERSION_ASN1_UTCTIME)
{
pStr = _ds_strtoint(pStr, &tm.tm_year, 2);
tm.tm_year += (tm.tm_year < 70) ? 2000 : 1900; // 2-year UTC time represents from 1970 to 2069
}
else
{
pStr = _ds_strtoint(pStr, &tm.tm_year, 4);
}
pStr = _ds_strtoint(pStr, &tm.tm_mon, 2);
pStr = _ds_strtoint(pStr, &tm.tm_mday, 2);
pStr = _ds_strtoint(pStr, &tm.tm_hour, 2);
pStr = _ds_strtoint(pStr, &tm.tm_min, 2);
_ds_strtoint(pStr, &tm.tm_sec, 2);
// adjust year and month
tm.tm_year -= 1900;
tm.tm_mon -= 1;
// convert from struct tm to uint32_t and return to caller
uTime = ds_timetosecs(&tm);
}
else
{
uTime = ds_strtotime(pStr);
}
return(uTime);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/**
* main - Entry point
* @argc: int parameter, argumennt count
* @argv: double pointer, argument strings
* Return: void, print change
*/
int main(int argc, char *argv[])
{
char *sum = argv[argc - 1];
int num = 0;
int val[] = {25, 10, 5, 2, 1};
int count = 0, i = 0;
if (argc != 2)
{
printf("Error\n");
return (1);
}
else if (atoi(sum) < 0)
{
printf("0\n");
return (0);
}
else
num = atoi(sum);
while (val[i] != '\0')
{
if (num >= val[i])
{
num -= val[i];
count++;
}
else
i++;
}
printf("%d\n", count + num);
return (0);
}
|
C
|
#include<stdio.h>
int main()
{
int i,j,n,a[12]={4,7,47,74,447,474,744,747,774,477},l,cnt=0;
scanf("%d",&n);
for(i=0;i<10;i++){
if(n%a[i]==0) {
printf("YES\n");
break;
}
else cnt++;
}
if(cnt==10) printf("NO\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstiter_main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lchety <lchety@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/18 14:01:59 by lchety #+# #+# */
/* Updated: 2016/11/26 16:57:26 by lchety ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "libido.h"
static void acme(t_list *elem)
{
elem->content = "FFF";
}
int main(void)
{
void (*f)(t_list *elem);
t_list *masterchief;
printf("<-----ft_lstiter----->\n");
f = acme;
masterchief = ft_lstnew("WWW", 3);
masterchief->next = ft_lstnew("WWW", 3);
masterchief->next->next = ft_lstnew("WWW", 3);
masterchief->next->next->next = ft_lstnew("WWW", 3);
ft_lstiter(masterchief, f);
if(strcmp(masterchief->content, "FFF") == 0)
{
TEST(1, "OK");
}
else
TEST(1, "FALSE : bad diff");
if(strcmp(masterchief->next->content, "FFF") == 0)
{
TEST(2, "OK");
}
else
TEST(2, "FALSE : bad diff");
if(strcmp(masterchief->next->next->content, "FFF") == 0)
{
TEST(3, "OK");
}
else
TEST(3, "FALSE : bad diff");
return (0);
}
|
C
|
#include <stdio.h>
#include "add.h"
int main(int argc, char *argv)
{
int sum;
int num1, num2;
num1 = num2 = 20;
sum = add(num1, num2);
printf("Sum of %d and %d is %d\n", num1, num2, sum);
}
|
C
|
#ifndef __UTILITY_IMPL_H__
#define __UTILITY_IMPL_H__
#include "utility.h"
TCHAR toLowerCase(TCHAR c)
{
if (c > 64 && c < 91)
c += 32;
return c;
}
void writeTextFile(LPCTSTR lpszPath, LPCTSTR lpszBuf, BOOL bAppend)
{
FILE * pFile;
pFile = (bAppend) ? (fopen(lpszPath, "a")) : (fopen(lpszPath, "w+"));
if (pFile!=NULL)
{
fputs (lpszBuf, pFile);
fclose (pFile);
}
}
void readTextFile(LPCTSTR lpszPath, LPTSTR lpszBuf, DWORD dwBufLen)
{
FILE *fp;
DWORD dwFileLen = 0;
fopen_s(&fp, lpszPath,"rb");
if (fp != NULL)
{
fseek(fp, 0, SEEK_END);
dwFileLen = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (dwFileLen > (dwBufLen-1))
dwFileLen = (dwBufLen-1);
fread(lpszBuf, dwFileLen, 1, fp);
fclose(fp);
}
else
dwFileLen = 0;
lpszBuf[dwFileLen] = NULL;
}
ULONG stringToULong(LPCTSTR lpszValue, ULONG nDefault)
{
const int MAX = 9;
size_t nIndex = 0;
size_t nCount = 0;
TCHAR c = lpszValue[0];
ULONG nPlace = 1;
ULONG nOutput = 0;
//count number of numeric chars (stop at MAX)
while (c != NULL)
{
c = lpszValue[nIndex++];
if (CHAR_ISNUMERIC(c))
{
nCount++;
if (nCount == MAX)
break;
}
}
//count backwards from index and collect numbers
if (nCount > 0)
{
nCount = 0;
while(nIndex > 0)
{
c = lpszValue[--nIndex];
if (CHAR_ISNUMERIC(c))
{
nOutput += ((LONG)c - 48) * nPlace;
nPlace = (nPlace * 10);
}
}
}
else
nOutput = nDefault;
return nOutput;
}
#endif
|
C
|
/* bsearch function */
#include "stdlib.h"
void *bsearch(const void *key, const void *base,
size_t nelem, size_t size, _Cmpfun *cmp)
{ /* search sorted table by binary chop */
const char *p;
size_t n;
for (p = (const char *)base, n = nelem; 0 < n;) {
/* check midpoint of whatever is left */
const size_t pivot = n >> 1;
const char *const q = p + size * pivot;
const int val = (*cmp)(key, q);
if (val < 0)
n = pivot; /*search below pivot */
else if (val == 0)
return ((void * )q);
else {
p = q + size;
n -= pivot + 1;
}
}
return (NULL);
}
|
C
|
#include <stdio.h>
void makesum(int n, int k, int ans[], int t) {
int i;
if (k == 0) {
return;
}
if (k == 1) {
ans[k] = n;
for (i = 1; i <= t; i++) {
printf("%d ", ans[i]);
}
puts("");
}
for (i = 1; i <= k; i++) {
ans[k] = i;
makesum (n - i, k - 1, ans, t);
}
}
int main() {
int input_n, input_k, ans[102];
scanf("%d %d", &input_n, &input_k);
makesum(input_n, input_k, ans, input_k);
return 0;
}
|
C
|
#include "session.h"
enum LoginUserStatus loginUser (struct sockaddr_in *cliaddr, char *id) {
Session *ss = findBySessionCliaddr(cliaddr);
if (ss == NULL || ss->status == USER_BLOCKED) return -1;
else if (ss->status == NOT_AUTHENTICATED || ss->status == AUTHENTICATED) return LU_EXISTED_ONE_USER;
User *us = findByUserId(id);
if (us == NULL) return LU_NOT_FOUND;
else if (us->status == BLOCKED) return LU_USER_BLOCKED;
else {
ss->user = us;
ss->status = NOT_AUTHENTICATED;
return LU_SUCCESS;
}
}
enum LoginPassStatus loginPass (struct sockaddr_in *cliaddr, char *pass) {
Session *ss = findBySessionCliaddr(cliaddr);
if (ss == NULL) return -1;
else if (ss->status == NOT_IDENTIFIED_USER) return LP_NOT_IDENTIFIED_USER;
else if (ss->status == AUTHENTICATED) return LP_EXISTED_ONE_USER;
// Da dang ki nguoi dung
if (!strcmp(ss->user->pass, pass)) { // Login success
ss->status = AUTHENTICATED;
ss->login_failed_count = 0;
return LP_SUCCESS;
} else { // Login fail
ss->login_failed_count++;
if (ss->login_failed_count >= MAX_LOGIN_FAILED) { // Login fail too much
// block user
ss->user->status = BLOCKED;
// remove user from session
ss->user = NULL;
ss->status = NOT_IDENTIFIED_USER;
ss->login_failed_count = 0;
return LP_USER_BLOCKED;
} else {
return LP_WRONG_PASS;
}
}
}
enum LogoutStatus logout (struct sockaddr_in *cliaddr, char *id, char *pass) {
Session *ss = findBySessionCliaddr(cliaddr);
if (ss == NULL) return -1;
else if (ss->status == NOT_IDENTIFIED_USER) return LO_NOT_IDENTIFIED_USER;
User *us = findByUserId(id);
// id khong ton tai hoac sai nguoi dung
if (us == NULL || us != ss->user) return LO_WRONG_USER;
// Dung nguoi dung da dang nhap
if (ss->status == NOT_AUTHENTICATED // Da ton tai user nhung chua dang nhap
|| !strcmp(us->pass, pass)) { // Dung password -> Dang xuat thanh cong
ss->user = NULL;
ss->status = NOT_IDENTIFIED_USER;
ss->login_failed_count = 0;
return LO_SUCCESS;
} else { // Sai password
return LO_WRONG_PASS;
}
}
enum SessionStatus sessionStatus (struct sockaddr_in *cliaddr) {
Session *ss = findBySessionCliaddr(cliaddr);
if (ss == NULL) return -1;
return ss->status;
}
_Bool removeSession (struct sockaddr_in *cliaddr) {
int target = findBySessionCliaddr(cliaddr);
if (target == -1) return FN_ERROR;
for (int i = target; i < session_count - 1; i++) {
copySession(session + i, session + i + 1);
}
session_count--;
return FN_SUCCESS;
}
_Bool addSession (User *user, enum SessionStatus status, struct sockaddr_in *cliaddr, int login_failed_count) {
if (isFullNoSession()) return FN_ERROR;
session[session_count].user = user;
session[session_count].status = status;
session[session_count].cliaddr = cliaddr;
session[session_count].login_failed_count = login_failed_count;
session_count++;
return FN_SUCCESS;
}
_Bool newSession (struct sockaddr_in *cliaddr) {
if (isFullNoSession()) return FN_ERROR;
session[session_count].user = NULL;
session[session_count].status = NOT_IDENTIFIED_USER;
session[session_count].cliaddr = cliaddr;
session[session_count].login_failed_count = 0;
session_count++;
return FN_SUCCESS;
}
Session *findBySessionCliaddr (struct sockaddr_in *cliaddr) {
for (int i = 0; i < session_count; i++) {
if (isEqualSockAddrIn(session[i].cliaddr, cliaddr))
return (session + i);
}
return NULL;
}
int indexOfSession (struct sockaddr_in *cliaddr) {
for (int i = 0; i < session_count; i++) {
if (isEqualSockAddrIn(session[i].cliaddr, cliaddr))
return i;
}
return -1;
}
void copySession (Session *src, Session *dest) {
dest->user = src->user;
dest->status = src->status;
dest->cliaddr = src->cliaddr;
dest->login_failed_count = src->login_failed_count;
}
_Bool isFullNoSession () {
if (session_count > MAX_SESSION) {
printf("Number of sessions is full!\n");
return 1;
}
return 0;
}
_Bool isEqualSockAddrIn (struct sockaddr_in *addr1, struct sockaddr_in *addr2) {
return (addr1->sin_addr.s_addr == addr2->sin_addr.s_addr && addr1->sin_port == addr2->sin_port);
}
|
C
|
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#define F_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
static struct flock lock_it, unlock_it;
static int lock_fd = -1;
void my_lock_init(char *path)
{
struct stat st;
int r;
r = stat(path, &st);
lock_fd = open(path, O_CREAT | O_WRONLY, F_MODE);
if(lock_fd < 0) {
perror("open lock file failed\n");
exit(EXIT_FAILURE);
}
/* lock setup*/
lock_it.l_type = F_WRLCK;
lock_it.l_whence = SEEK_SET;
lock_it.l_start = 0;
lock_it.l_len = 0;
/* unlock setup*/
unlock_it.l_type = F_UNLCK;
unlock_it.l_whence = SEEK_SET;
unlock_it.l_start = 0;
unlock_it.l_len = 0;
}
void my_lock_wait()
{
int s;
while((s = fcntl(lock_fd, F_SETLKW, &lock_it)) < 0) {
if(errno == EINTR) {
continue;
}
else {
perror("fcntl() failed to release lock\n");
exit(EXIT_FAILURE);
}
}
}
void my_lock_release()
{
if(fcntl(lock_fd, F_SETLKW, &unlock_it) < 0) {
perror("fcntl() failed to release lock\n");
exit(EXIT_FAILURE);
}
}
|
C
|
#include "../framework.h"
#define IMAGES 10
#include "images/digits6.c"
//const uint8_t COLORS[IMAGES] = {
// 0b111111, //0
// 0b110110, //1
// 0b001111, //2
// 0b110011, //3
// 0b001011, //4
// 0b000011, //5
// 0b001100, //6
// 0b010111, //7
// 0b110100, //8
// 0b111100, //9
//};
const uint8_t COLORS[IMAGES] = {
0b111111, //0
0b000011, //5
0b001011, //4
0b001111, //2
0b001100, //6
0b111100, //9
0b110100, //8
0b110110, //1
0b110011, //3
0b010111, //7
};
void initGame()
{
setFrameLength(100);
}
//void gameLoop()
//{
// if (buttonsHit & (BUTTON_RIGHT | BUTTON_DOWN)) {
// image = (image + 1) % IMAGES;
// buttonsHit = 0;
// }
// if (buttonsHit & (BUTTON_LEFT | BUTTON_UP)) {
// image = (image + IMAGES - 1) % IMAGES;
// buttonsHit = 0;
// }
// uint8_t y, x;
// for (y = 0; y < DISPLAY_HEIGHT; y++)
// {
// for (x = 0; x < DISPLAY_WIDTH; x++) {
// display[DISPLAY_WIDTH - 1 - x][y] = (DIGITS5[image][y] & (1 << x)) ? COLORS[image] : 0;
// }
// }
//}
void gameLoop()
{
if (buttonsPressed) {
uint8_t y, x;
for (y = 0; y < DISPLAY_HEIGHT; y++)
{
for (x = 0; x < DISPLAY_WIDTH; x++) {
uint8_t color = y / 3 * 4 + x / 2;
display[x][y] = color >= IMAGES ? 0 : COLORS[color];
}
}
return;
}
uint8_t dx = frameCounter % (DIGIT_WIDTH * IMAGES);
uint8_t y, x;
for (y = 0; y < DISPLAY_HEIGHT; y++)
{
for (x = 0; x < DISPLAY_WIDTH; x++) {
uint8_t image = (x + dx) / DIGIT_WIDTH % IMAGES;
uint8_t dxi = DIGIT_WIDTH - 1 - (x + dx) % DIGIT_WIDTH;
display[x][y] = (DIGITS5[image][y] & (1 << dxi)) ? COLORS[image] : 0;
}
}
}
|
C
|
#include "image.h"
#include "memory.h"
#include "plugin.h"
#include "context.h"
#include "log.h"
#include "format.h"
#include <string.h>
#include <assert.h>
#include <stdio.h>
static bool validate_image(ImgloadImage img)
{
if (!img->data_format_initialized || !img->compression_initialized)
{
print_to_log(img->context, IMGLOAD_LOG_ERROR, "Data format or compression not initialized after image load!\n");
return false;
}
return true;
}
ImgloadErrorCode IMGLOAD_API imgload_image_init(ImgloadContext ctx, ImgloadImage* image, ImgloadIO* io,
void* io_ud)
{
assert(ctx != NULL);
assert(image != NULL);
ImgloadImage img = mem_reallocz(ctx, NULL, sizeof(struct ImgloadImageImpl));
if (img == NULL)
{
return IMGLOAD_ERR_OUT_OF_MEMORY;
}
img->context = ctx;
img->io.funcs = *io;
img->io.ud = io_ud;
ImgloadPlugin current = img->context->plugins.head;
while (current != NULL)
{
if (current->funcs.probe(current, img))
{
// Found the right plugin, now initialize the plugin for this image
ImgloadErrorCode err = current->funcs.init_image(current, img);
if (err != IMGLOAD_ERR_NO_ERROR)
{
imgload_image_free(img);
return err;
}
if (!validate_image(img))
{
imgload_image_free(img);
return IMGLOAD_ERR_PLUGIN_ERROR;
}
img->plugin = current;
*image = img;
return IMGLOAD_ERR_NO_ERROR;
}
image_io_seek(img, 0, SEEK_SET);
current = current->next;
}
// Unsupported format
mem_free(ctx, img);
return IMGLOAD_ERR_UNSUPPORTED_FORMAT;
}
size_t IMGLOAD_API imgload_image_num_subimages(ImgloadImage img)
{
assert(img != NULL);
return img->n_frames;
}
ImgloadErrorCode IMGLOAD_API imgload_image_get_property(ImgloadImage img, size_t subimage, ImgloadProperty prop,
ImgloadPropertyType type, void* val_out)
{
assert(img != NULL);
if (subimage >= img->n_frames)
{
return IMGLOAD_ERR_OUT_OF_RANGE;
}
PropertyValue* property = &img->frames[subimage].properties[prop];
if (!property->initialized)
{
return IMGLOAD_ERR_NO_DATA;
}
if (type != property->type)
{
return IMGLOAD_ERR_WRONG_TYPE;
}
switch(type)
{
case IMGLOAD_PROPERTY_TYPE_UINT32:
*(uint32_t*)val_out = property->value.uint32;
break;
case IMGLOAD_PROPERTY_TYPE_INT32:
*(int32_t*)val_out = property->value.int32;
break;
case IMGLOAD_PROPERTY_TYPE_FLAOT:
*(float*)val_out = property->value.float_val;
break;
case IMGLOAD_PROPERTY_TYPE_DOUBLE:
*(double*)val_out = property->value.double_val;
break;
case IMGLOAD_PROPERTY_TYPE_STRING:
*(const char**)val_out = property->value.str;
break;
case IMGLOAD_PROPERTY_TYPE_COMPLEX:
*(void**)val_out = property->value.complex;
break;
}
return IMGLOAD_ERR_NO_ERROR;
}
ImgloadFormat IMGLOAD_API imgload_image_data_format(ImgloadImage img)
{
assert(img != NULL);
assert(img->data_format_initialized);
return img->data_format;
}
ImgloadCompression IMGLOAD_API imgload_image_compression(ImgloadImage img)
{
assert(img != NULL);
assert(img->compression_initialized);
return img->compression;
}
ImgloadErrorCode IMGLOAD_API imgload_image_transform_data(ImgloadImage img, ImgloadFormat requested, uint64_t param)
{
assert(img != NULL);
img->conv.do_convert = true;
img->conv.requested = requested;
img->conv.param = param;
// Transform all currently loaded data
for (size_t i = 0; i < img->n_frames; ++i)
{
for (size_t j = 0; j < img->frames[i].n_mipmaps; ++j)
{
Mipmap* mipmap = &img->frames[i].mipmaps[j];
if (mipmap->raw.has_data)
{
ImgloadImageData new_data;
ImgloadErrorCode err = format_change(img, img->data_format, &mipmap->raw.image, &new_data);
mipmap->raw.image = new_data;
if (err != IMGLOAD_ERR_NO_ERROR)
{
// The image format is in an inconsistent state now and should not be used anymore
return err;
}
}
}
}
img->data_format = requested;
return IMGLOAD_ERR_NO_ERROR;
}
ImgloadErrorCode IMGLOAD_API imgload_image_read_data(ImgloadImage img)
{
assert(img != NULL);
assert(img->plugin != NULL);
if (img->plugin->funcs.read_image)
{
return img->plugin->funcs.read_image(img->plugin, img);
}
// No read function => data must have been initialized earlier
return IMGLOAD_ERR_NO_ERROR;
}
size_t IMGLOAD_API imgload_image_num_mipmaps(ImgloadImage img, size_t subimage)
{
assert(img != NULL);
assert(subimage < img->n_frames);
return img->frames[subimage].n_mipmaps;
}
ImgloadErrorCode IMGLOAD_API imgload_image_compressed_data(ImgloadImage img, size_t subimage, size_t mipmap, ImgloadImageData* data_out)
{
assert(img != NULL);
assert(subimage < img->n_frames);
assert(mipmap < img->frames[subimage].n_mipmaps);
if (img->compression == IMGLOAD_COMPRESSION_NONE)
{
return IMGLOAD_ERR_NO_DATA;
}
if (!img->frames[subimage].mipmaps[mipmap].compressed.has_data)
{
return IMGLOAD_ERR_NO_DATA;
}
// Everything seems to be alright
*data_out = img->frames[subimage].mipmaps[mipmap].compressed.image;
return IMGLOAD_ERR_NO_ERROR;
}
ImgloadErrorCode IMGLOAD_API imgload_image_data(ImgloadImage img, size_t subimage, size_t mipmap, ImgloadImageData* data_out)
{
assert(img != NULL);
assert(subimage < img->n_frames);
assert(mipmap < img->frames[subimage].n_mipmaps);
if (img->frames[subimage].mipmaps[mipmap].raw.has_data)
{
// Data is already present
*data_out = img->frames[subimage].mipmaps[mipmap].raw.image;
return IMGLOAD_ERR_NO_ERROR;
}
// Raw data is not available but the plugin could do lazy decompression
if (img->plugin->funcs.decompress_data != NULL)
{
ImgloadErrorCode err = img->plugin->funcs.decompress_data(img->plugin, img, subimage, mipmap);
if (err == IMGLOAD_ERR_NO_ERROR)
{
if (img->frames[subimage].mipmaps[mipmap].raw.has_data)
{
// Data has been loaded by plugin
*data_out = img->frames[subimage].mipmaps[mipmap].raw.image;
return IMGLOAD_ERR_NO_ERROR;
}
}
else
{
return err;
}
}
return IMGLOAD_ERR_NO_DATA;
}
static void free_mipmap_data(ImgloadContext ctx, MipmapData* data)
{
// Make sure that memory is allocated and we actually need to free the memory
if (data->image.data != NULL)
{
mem_free(ctx, data->image.data);
}
}
ImgloadErrorCode IMGLOAD_API imgload_image_free(ImgloadImage image)
{
assert(image != NULL);
if (image->plugin)
{
// If there is a plugin registered, deinitialize it when freeing the image
if (image->plugin->funcs.deinit_image != NULL)
{
image->plugin->funcs.deinit_image(image->plugin, image);
}
}
for (size_t i = 0; i < image->n_frames; ++i)
{
ImageFrame* frame = &image->frames[i];
PropertyValue* val = &frame->properties[i];
if (val->initialized && val->type == IMGLOAD_PROPERTY_TYPE_STRING)
{
mem_free(image->context, val->value.str);
}
Mipmap* mipmaps = frame->mipmaps;
if (mipmaps != NULL)
{
for (size_t mipmap = 0; mipmap < frame->n_mipmaps; ++mipmap)
{
free_mipmap_data(image->context, &mipmaps[mipmap].compressed);
free_mipmap_data(image->context, &mipmaps[mipmap].raw);
}
mem_free(image->context, mipmaps);
}
}
mem_free(image->context, image->frames);
mem_free(image->context, image);
return IMGLOAD_ERR_NO_ERROR;
}
size_t IMGLOAD_API image_io_read(ImgloadImage img, uint8_t* buf, size_t size)
{
assert(img != NULL);
return img->io.funcs.read(img->io.ud, buf, size);
}
int64_t IMGLOAD_API image_io_seek(ImgloadImage img, int64_t offset, int whence)
{
assert(img != NULL);
return img->io.funcs.seek(img->io.ud, offset, whence);
}
ImgloadErrorCode image_allocate_frames(ImgloadImage img, size_t num_frames)
{
assert(img != NULL);
if (num_frames <= img->n_frames)
{
img->n_frames = num_frames;
// All frames already allocated
return IMGLOAD_ERR_NO_ERROR;
}
ImageFrame* new_frames = (ImageFrame*)mem_reallocz(img->context, img->frames, num_frames * sizeof(*img->frames));
if (new_frames == NULL)
{
return IMGLOAD_ERR_OUT_OF_MEMORY;
}
img->frames = new_frames;
img->n_frames = num_frames;
return IMGLOAD_ERR_NO_ERROR;
}
ImgloadErrorCode image_allocate_mipmaps(ImgloadImage img, size_t subframe, size_t mipmaps)
{
assert(img != NULL);
assert(subframe < img->n_frames);
ImageFrame* frame = &img->frames[subframe];
if (mipmaps <= frame->n_mipmaps)
{
frame->n_mipmaps = mipmaps;
// Already enough allocated
return IMGLOAD_ERR_NO_ERROR;
}
Mipmap* new_data = (Mipmap*)mem_reallocz(img->context, NULL, mipmaps * sizeof(*frame->mipmaps));
if (new_data == NULL)
{
return IMGLOAD_ERR_OUT_OF_MEMORY;
}
frame->n_mipmaps = mipmaps;
frame->mipmaps = new_data;
return IMGLOAD_ERR_NO_ERROR;
}
ImgloadErrorCode image_set_compressed_data(ImgloadImage img, size_t subframe, size_t mipmap,
ImgloadImageData* data, bool transfer_ownership)
{
Mipmap* mipmap1 = &img->frames[subframe].mipmaps[mipmap];
mipmap1->compressed.image = *data;
if (!transfer_ownership)
{
// Memory wasn't allocated by us so we need to copy it.
mipmap1->compressed.image.data = mem_realloc(img->context, NULL, data->data_size);
if (mipmap1->compressed.image.data == NULL)
{
return IMGLOAD_ERR_OUT_OF_MEMORY;
}
memcpy(mipmap1->compressed.image.data, data->data, data->data_size);
}
mipmap1->compressed.has_data = true;
return IMGLOAD_ERR_NO_ERROR;
}
ImgloadErrorCode image_set_data(ImgloadImage img, size_t subframe, size_t mipmap,
ImgloadImageData* data, bool transfer_ownership)
{
Mipmap* mipmap1 = &img->frames[subframe].mipmaps[mipmap];
mipmap1->raw.image = *data;
if (!transfer_ownership)
{
// Memory wasn't allocated by us so we need to copy it.
mipmap1->raw.image.data = mem_realloc(img->context, NULL, data->data_size);
if (mipmap1->raw.image.data == NULL)
{
return IMGLOAD_ERR_OUT_OF_MEMORY;
}
memcpy(mipmap1->raw.image.data, data->data, data->data_size);
}
mipmap1->raw.has_data = true;
if (img->context->flags & IMGLOAD_CONTEXT_FLIP_IMAGES)
{
// A buffer for holding one line of the image
uint8_t* buffer = (uint8_t*) mem_realloc(img->context, NULL, data->stride);
if (buffer == NULL)
{
print_to_log(img->context, IMGLOAD_LOG_ERROR, "Failed to allocate buffer for flipping image!");
return IMGLOAD_ERR_OUT_OF_MEMORY;
}
for (size_t d = 0; d < data->depth; ++d)
{
uint8_t* image_data = ((uint8_t*)data->data) + (d * data->height * data->stride);
// Images that have a height that's not divisible by 2 don't need to be handled
// specially because the row in the middle of the image doesn't need to be mirrored
size_t height_half = data->height / 2;
for (size_t y = 0; y < height_half; ++y)
{
uint8_t* top = image_data + y * data->stride;
uint8_t* bottom = image_data + (data->height - y - 1) * data->stride;
memcpy(buffer, top, data->stride);
memcpy(top, bottom, data->stride);
memcpy(bottom, buffer, data->stride);
}
}
mem_free(img->context, buffer);
}
if (img->conv.do_convert)
{
ImgloadImageData converted_data;
ImgloadErrorCode err = format_change(img, img->plugin_data_format, &mipmap1->raw.image, &converted_data);
if (err != IMGLOAD_ERR_NO_ERROR)
{
return err;
}
}
return IMGLOAD_ERR_NO_ERROR;
}
|
C
|
#include<stdio.h>
void main()
{
int arr[20],i,n,max1=0,max2=0;
printf("enter size of array\n");
scanf("%d",&n);
printf("enter the elements of array\n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
{
if(arr[i] > max1)
{
max1 = arr[i];
}
else if(arr[i] > max2 && arr[i] < max1)
{
max2 = arr[i];
}
}
printf("First largest = %d\n", max1);
printf("Second largest = %d\n", max2);
}
|
C
|
#include<stdio.h>
int add(int,int);
int sub(int,int);
int mul(int,int);
int div(int,int);
int main()
{
int a,b,addition,subract,multi,division;
printf("Enter a and b value:\n");
scanf("%d %d",&a,&b);
printf("\n");
addition=add(a,b);
subract=sub(a,b);
multi=mul(a,b);
division=div(a,b);
printf(" add=%d\n sub=%d\n mul=%d\n div=%d\n",addition,subract,multi,division);
return 0;
}
int add(int a,int b)
{
int c=a+b;
return c;
}
int sub(int a,int b)
{
int c=a-b;
return c;
}
int mul(int a,int b)
{
int c=a*b;
return c;
}
int div(int a,int b)
{
int c=a/b;
return c;
}
|
C
|
void rotate(int **matrix, int matrixRowSize, int matrixColSize)
{
int up, down, left, right, len, i, t;
up = 0;
down = matrixRowSize - 1;
left = 0;
right = matrixColSize - 1;
while (up < down && left < right) {
len = right - left;
for (i = 0; i < len; i++) {
t = matrix[down - i][left];
matrix[down - i][left] = matrix[down][right - i];
matrix[down][right - i] = matrix[up + i][right];
matrix[up + i][right] = matrix[up][left + i];
matrix[up][left + i] = t;
}
up++;
down--;
left++;
right--;
}
}
int main(void)
{
int a[] = {1, 2, };
int b[] = { 3, 4, };
int *c[] = {a, b};
rotate(c, 2, 2);
return(0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#include <unistd.h>
#include "./paging.h"
#include "./memory.h"
#include "./util.h"
struct process_startup_args {
int pid;
int nloop;
};
// test address
#define BASE_USER_SPACE_ADDRESS 0x100000000000
static void *process(void *arg)
{
struct process_startup_args *argp = arg;
int pid = argp->pid;
int nloop = argp->nloop;
pgd_t *pgd = pgd_alloc();
for (int i = 0; i < nloop; i++) {
unsigned long addr = BASE_USER_SPACE_ADDRESS + (i * 4096);
__do_page_fault(pid, pgd, addr);
}
return NULL;
}
static void usage(char *prog)
{
fprintf(stderr, "usage: %s [-p process count] [-l loop count] [-m megabytes]\n", prog);
fprintf(stderr, "default: 2 processes, 10 loop, 4MiB\n");
}
int megabytes = 4;
static void dump_memory(void)
{
void *physical_memory = get_physical_memory();
puts("{");
printf("\"physical memory\":{");
printf("\"size\":\"%dMiB\",", byte_to_MiB(PHYSICAL_MEMORY_SIZE));
printf("\"range\": {");
printf("\"start\":\"%p\",", physical_memory);
printf("\"end\":\"%p\"},", physical_memory + PHYSICAL_MEMORY_SIZE);
printf("\"page flames\":%d},\n", num_page_frames);
printf("\"page data\": [\n");
for (int i = 0; i < PHYSICAL_MEMORY_SIZE; i+= PAGE_SIZE) {
char *p = physical_memory + i;
char *next = physical_memory + (i + PAGE_SIZE);
if (*p) {
printf("%s", p);
if (*next)
printf(",\n");
else
printf("\n");
}
}
printf("]\n}\n");
}
int main(int argc, char **argv)
{
int nproc = 2;
int nloop = 10;
int opt;
pthread_t *threads;
while ((opt = getopt(argc, argv, "hp:l:m:")) != -1) {
switch (opt) {
case 'p':
nproc = atoi(optarg);
break;
case 'l':
nloop = atoi(optarg);
break;
case 'm':
megabytes = atoi(optarg);
break;
case 'h':
usage(argv[1]);
exit(0);
default:
printf("[*]unknown option %c\n", opt);
usage(argv[0]);
exit(-1);
}
}
setup_physical_memory();
void *physical_memory = get_physical_memory();
paging_init();
threads = malloc(sizeof(pthread_t) * nproc);
assert(threads);
memset(threads, 0x0, sizeof(pthread_t) * nproc);
for (int i = 0; i < nproc; i++) {
struct process_startup_args *arg = malloc(sizeof(struct process_startup_args));
assert(arg);
arg->pid = i + 1;
arg->nloop = nloop;
int ret = pthread_create(&threads[i], NULL, process, arg);
assert(!ret);
}
for (int i = 0; i < nproc; i++)
pthread_join(threads[i], NULL);
dump_memory();
free(threads);
free(physical_memory);
return 0;
}
|
C
|
#include "unp.h"
#define MAXLINE 4096
#define SA struct sockaddr
int main(int argc, char **argv){
/*
send message to parent, indicating that the xterm is processing....
*/
/*
here every message which user needs to read, needs to be sent through
pipe. Here, 3 is for pipe's write end(dup2 function), because if it is
showed here, it will process to exit(0), then the message will flash and
disappear.
*/
char buff[MAXLINE];
strcpy(buff, "xterm processing......");
write(3, buff, strlen(buff)+1 );
memset(buff,0,MAXLINE);
int sockfd, readn;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
//argc != 2, shows that no ip address is comming in....
if(argc != 2){
strcpy(buff, "IP address missing...");
write(3, buff, strlen(buff)+1 );
memset(buff,0,MAXLINE);
exit(0);
}
//socket(); error handle;
if( (sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){
strcpy(buff, "socket error...");
write(3, buff, strlen(buff)+1 );
memset(buff,0,MAXLINE);
exit(0);
}
//set the address of the server, for client to connect server;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(60000);
//presentation to numeric;
if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
strcpy(buff, "inet_pton error...");
write(3, buff, strlen(buff)+1 );
memset(buff,0,MAXLINE);
exit(0);
}
//connect(); error handle;
int test_conn = connect(sockfd, (SA *) &servaddr, sizeof(servaddr));
if(test_conn < 0){
strcpy(buff, "can not connect server...");
write(3, buff, strlen(buff)+1 );
memset(buff,0,MAXLINE);
exit(0);
}
//read(), read from sockfd;
while ( (readn = read(sockfd,recvline,MAXLINE)) >0) {
recvline[readn] = 0;
if(fputs(recvline,stdout) == EOF){
strcpy(buff, "fputs error...");
write(3, buff, strlen(buff)+1 );
memset(buff,0,MAXLINE);
exit(0);
}
}
//server terminated, so a FIN(EOF) is send, read() returns 0;
//Here we inform the user that server has been terminated;
if(readn == 0){
strcpy(buff, "the server terminated, read() returns 0.");
write(3, buff, strlen(buff)+1 );
memset(buff,0,MAXLINE);
exit(0);
}
//read error;
if(readn<0){
strcpy(buff, "read error...");
write(3, buff, strlen(buff)+1 );
memset(buff,0,MAXLINE);
exit(0);
}
exit(0);
}
|
C
|
/*
* Copyright 2002-2011, The TenDRA Project.
* Copyright 1997, United Kingdom Secretary of State for Defence.
*
* See doc/copyright/ for the full copyright terms.
*/
#include <string.h>
#include <shared/error.h>
#include <shared/string.h>
#include "calculus.h"
#include "code.h"
#include "common.h"
#include "lex.h"
#include "output.h"
#include "suffix.h"
#include "type_ops.h"
#include <out/token.h>
/*
* PRINT SIMPLE TOKENS
*
* This routine prints the simple tokens for a type named nm with short
* name ns. e is true for simply dereferenced types.
*/
static void
print_simple_tok(char *nm, char *ns, int e, int lst)
{
/* SIZE token */
output("%pt %xc : SIZE(%e) : SIZE_%e #\n\n", nm, ns);
/* Assign token */
output("%pt PROC(\\\n");
output("\t%xr : PTR(%e) :,\\\n\t%xr : %e :\\\n ) ", nm, nm);
output(e ? "%xr : void :" : "STATEMENT");
output(" COPY_%e #\n\n", ns);
/* Dereference token */
output("%pt PROC(\\\n");
output("\t%xr : PTR(%e) :", nm);
if (e) {
output("\\\n ) %xr : %e :", nm);
} else {
output(",\\\n\t%xl : %e :\\\n ) STATEMENT", nm);
}
output(" DEREF_%e #\n\n", ns);
if (lst) {
/* CONS token */
output("%pt PROC(\\\n");
output("\t%xr : %e :,\\\n\t%xr : LIST(%e) :,\\\n", nm, nm);
output("\t%xl : LIST(%e) :\\\n", nm);
output(" ) STATEMENT CONS_%e #\n\n", ns);
/* UN_CONS token */
output("%pt PROC(\\\n");
output("\t%xl : %e :,\\\n", nm);
output("\t%xl : LIST(%e) :,\\\n", nm);
output("\t%xr : LIST(%e) :\\\n", nm);
output(" ) STATEMENT UN_CONS_%e #\n\n", ns);
/* DESTROY_CONS token */
output("%pt PROC(\\\n");
output("\t%xr : DESTROYER :,\\\n\t%xl : %e :,\\\n", nm);
output("\t%xl : LIST(%e) :,\\\n", nm);
output("\t%xr : LIST(%e) :\\\n", nm);
output(" ) STATEMENT DESTROY_CONS_%e #\n\n", ns);
if (allow_stack) {
/* PUSH token */
output("%pt PROC(\\\n");
output("\t%xr : %e :,\\\n", nm);
output("\t%xl : STACK(%e) :\\\n", nm);
output(" ) STATEMENT PUSH_%e #\n\n", ns);
/* POP token */
output("%pt PROC(\\\n");
output("\t%xl : %e :,\\\n", nm);
output("\t%xl : STACK(%e) :\\\n", nm);
output(" ) STATEMENT POP_%e #\n\n", ns);
}
}
/* Interface commands */
output("%pi SIZE_%e COPY_%e DEREF_%e\n", ns, ns, ns);
if (lst) {
output("%pi CONS_%e UN_CONS_%e DESTROY_CONS_%e\n", ns, ns, ns);
if (allow_stack) {
output("%pi PUSH_%e POP_%e\n", ns, ns);
}
}
output("\n\n");
}
/*
* PRINT SIMPLE TOKENS FOR TYPE OPERATIONS
*
* This routine prints the simple tokens for the type operation op.
* The tokens are named using nm. e is true for simply dereferenced types.
*/
static void
print_type_ops_tok(char *op, char *nm, int e)
{
/* Size token */
output("%pt PROC(\\\n\tTYPE t\\\n");
output(" ) %xc : SIZE(%s(t)) : SIZE_%s #\n\n", op, nm);
/* Assign token */
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(%s(t)) : e1,\\\n", op);
output("\t%xr : %s(t) : e2 |\\\n", op);
output("\tEXP e1, EXP e2\\\n } ");
output(e ? "%xr : void :" : "STATEMENT");
output(" COPY_%s #\n\n", nm);
/* Dereference token */
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(%s(t)) : e", op);
if (e) {
output(" |\\\n\tEXP e\\\n");
output(" } %xr : %s(t) : ", op);
} else {
output("1,\\\n\t%xl : %s(t) : e2 |\\\n", op);
output("\tEXP e1, EXP e2\\\n");
output(" } STATEMENT ");
}
output("DEREF_%s #\n\n", nm);
/* CONS token */
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : %s(t) : e2,\\\n", op);
output("\t%xr : LIST(%s(t)) : e3,\\\n", op);
output("\t%xl : LIST(%s(t)) : e4 |\\\n", op);
output("\tEXP e2, EXP e3, EXP e4\\\n");
output(" } STATEMENT CONS_%s #\n\n", nm);
/* UN_CONS token */
output("%pt PROC {\\\n");
output("\tTYPE t, %xl : %s(t) : e2,\\\n", op);
output("\t%xl : LIST(%s(t)) : e3,\\\n", op);
output("\t%xr : LIST(%s(t)) : e4 |\\\n", op);
output("\tEXP e2, EXP e3, EXP e4\\\n");
output(" } STATEMENT UN_CONS_%s #\n\n", nm);
/* DESTROY_CONS token */
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : DESTROYER : e1,\\\n");
output("\t%xl : %s(t) : e2,\\\n", op);
output("\t%xl : LIST(%s(t)) : e3,\\\n", op);
output("\t%xr : LIST(%s(t)) : e4 |\\\n", op);
output("\tEXP e1, EXP e2, EXP e3, EXP e4\\\n");
output(" } STATEMENT DESTROY_CONS_%s #\n\n", nm);
if (allow_stack) {
/* PUSH token */
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : %s(t) : e2,\\\n", op);
output("\t%xl : STACK(%s(t)) : e3 |\\\n", op);
output("\tEXP e2, EXP e3\\\n");
output(" } STATEMENT PUSH_%s #\n\n", nm);
/* POP token */
output("%pt PROC {\\\n");
output("\tTYPE t, %xl : %s(t) : e2,\\\n", op);
output("\t%xl : STACK(%s(t)) : e3 |\\\n", op);
output("\tEXP e2, EXP e3\\\n");
output(" } STATEMENT POP_%s #\n\n", nm);
}
/* Interface commands */
output("%pi SIZE_%s COPY_%s DEREF_%s\n", nm, nm, nm);
output("%pi CONS_%s UN_CONS_%s DESTROY_CONS_%s\n", nm, nm, nm);
if (allow_stack) {
output("%pi PUSH_%s POP_%s\n", nm, nm);
}
output("\n\n");
}
/*
* PRINT BASIC TYPES (TOKEN VERSION)
*
* This routine prints the token versions of the basic type definitions.
*/
static void
print_types_tok(void)
{
comment("Primitive types");
LOOP_PRIMITIVE {
CLASS_ID_P c = DEREF_ptr(prim_id(CRT_PRIMITIVE));
char *pn = DEREF_string(cid_name(c));
char *pd = DEREF_string(prim_defn(CRT_PRIMITIVE));
if (!streq(pn, pd))
{
output("typedef %PD %PN;\n");
}
}
output("\n\n");
comment("Basic types");
output("#ifndef %X_DESTR_DEFINED\n");
output("#define %X_DESTR_DEFINED\n");
output("typedef void (*DESTROYER)();\n");
output("#endif\n\n");
output("%pt PROC(TYPE) TYPE PTR #\n");
output("%pt PROC(TYPE) TYPE LIST #\n");
if (allow_stack) {
output("%pt PROC(TYPE) TYPE STACK #\n");
}
if (allow_vec) {
output("%pt VARIETY %X_dim #\n");
output("%pt PROC(TYPE) TYPE VEC #\n");
output("%pt PROC(TYPE) TYPE VEC_PTR #\n");
}
output("%pt PROC(TYPE) TYPE SIZE #\n\n");
output("%pi PTR LIST ");
if (allow_stack) {
output("STACK ");
}
if (allow_vec) {
output("%X_dim VEC VEC_PTR ");
}
output("SIZE\n\n\n");
comment("Enumeration type definitions");
LOOP_ENUM {
output("%pt VARIETY %EN #\n");
output("%pi %EN\n");
}
output("\n\n");
comment("Union type definitions");
LOOP_UNION {
output("%pt TYPE %UN #\n");
output("%pi %UN\n");
}
output("\n\n");
print_struct_defn();
comment("Function declarations");
output("extern void destroy_%X();\n");
output("extern void dummy_destroy_%X();\n");
output("#ifdef %X_IO_ROUTINES\n");
output("extern unsigned crt_%X_alias;\n");
output("extern void clear_%X_alias(void);\n");
output("#endif\n");
output("\n\n");
}
/*
* PRINT POINTER CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the pointer constructs.
*/
static void
print_ptr_tok(void)
{
comment("Pointer token specifications");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(t) : e1, %xr : SIZE(t) : e2 |\\\n");
output("\tEXP e1, EXP e2\\\n");
output(" } %xr : PTR(t) : STEP_ptr #\n\n");
output("%pt PROC(\\\n\tTYPE t\\\n");
output(" ) %xc : PTR(t) : NULL_ptr #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : int : IS_NULL_ptr #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(t) : e1, %xr : PTR(t) : e2 |\\\n");
output("\tEXP e1, EXP e2\\\n");
output(" } %xr : int : EQ_ptr #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : SIZE(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : PTR(t) : MAKE_ptr #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(t) : e1, %xr : SIZE(t) : e2 |\\\n");
output("\tEXP e1, EXP e2\\\n");
output(" } %xr : void : DESTROY_ptr #\n\n");
output("%pt PROC(\\\n\tTYPE t\\\n");
output(" ) %xr : PTR(t) : UNIQ_ptr #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : void : DESTROY_UNIQ_ptr #\n\n");
output("%pi STEP_ptr NULL_ptr IS_NULL_ptr EQ_ptr\n");
output("%pi MAKE_ptr DESTROY_ptr\n\n");
output("#ifdef %X_IO_ROUTINES\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : void * : VOIDSTAR_ptr #\n");
output("%pi VOIDSTAR_ptr\n");
output("#endif\n\n");
print_type_ops_tok("PTR", "ptr", 1);
}
/*
* PRINT LIST CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the list constructs.
*/
static void
print_list_tok(void)
{
comment("List token specifications");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : PTR(t) : HEAD_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : PTR(LIST(t)) : PTR_TAIL_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : LIST(t) : TAIL_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e1 |\\\n");
output("\tEXP e1\\\n");
output(" } %xr : unsigned : LENGTH_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e1 |\\\n");
output("\tEXP e1\\\n");
output(" } %xr : LIST(t) : END_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e1 |\\\n");
output("\tEXP e1\\\n");
output(" } %xr : LIST(t) : REVERSE_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e1, %xr : LIST(t) : e2 |\\\n");
output("\tEXP e1, EXP e2\\\n");
output(" } %xr : LIST(t) : APPEND_list #\n\n");
output("%pt PROC(\\\n\tTYPE t\\\n");
output(" ) %xc : LIST(t) : NULL_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : int : IS_NULL_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e1, %xr : LIST(t) : e2 |\\\n");
output("\tEXP e1, EXP e2\\\n");
output(" } %xr : int : EQ_list #\n\n");
output("%pt PROC(\\\n\tTYPE t\\\n");
output(" ) %xr : LIST(t) : UNIQ_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : void : DESTROY_UNIQ_list #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e1, %xr : SIZE(t) : e2 |\\\n");
output("\tEXP e1, EXP e2\\\n");
output(" } STATEMENT DESTROY_list #\n\n");
output("%pi HEAD_list PTR_TAIL_list TAIL_list\n");
output("%pi LENGTH_list END_list REVERSE_list APPEND_list\n");
output("%pi NULL_list IS_NULL_list EQ_list\n");
output("%pi UNIQ_list DESTROY_UNIQ_list DESTROY_list\n\n");
output("#ifdef %X_IO_ROUTINES\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : void * : VOIDSTAR_list #\n");
output("%pi VOIDSTAR_list\n");
output("#endif\n\n");
print_type_ops_tok("LIST", "list", 1);
}
/*
* PRINT STACK CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the stack constructs.
*/
static void
print_stack_tok(void)
{
comment("Stack token specifications");
output("%pt PROC(\\\n\tTYPE t\\\n");
output(" ) %xc : STACK(t) : NULL_stack #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : STACK(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : int : IS_NULL_stack #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : STACK(t) : e1 |\\\n");
output("\tEXP e1\\\n");
output(" } %xr : LIST(t) : LIST_stack #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : LIST(t) : e1 |\\\n");
output("\tEXP e1\\\n");
output(" } %xr : STACK(t) : STACK_list #\n\n");
output("%pi NULL_stack IS_NULL_stack LIST_stack STACK_list\n\n");
print_type_ops_tok("STACK", "stack", 1);
}
/*
* PRINT VECTOR CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the vector constructs.
*/
static void
print_vec_tok(void)
{
comment("Vector token specifications");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : VEC(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : %X_dim : DIM_vec #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(VEC(t)) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : PTR(t) : PTR_ptr_vec #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : PTR(VEC(t)) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : %X_dim : DIM_ptr_vec #\n\n");
output("%pt PROC(\\\n\tTYPE t\\\n");
output(" ) %xr : VEC(t) : NULL_vec #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : SIZE(t) : e1,\\\n");
output("\t%xr : %X_dim : e2,\\\n");
output("\t%xl : VEC(t) : e3 |\\\n");
output("\tEXP e1, EXP e2, EXP e3\\\n");
output(" } STATEMENT MAKE_vec #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : VEC(t) : e1, %xr : SIZE(t) : e2 |\\\n");
output("\tEXP e1, EXP e2\\\n");
output(" } STATEMENT DESTROY_vec #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : VEC(t) : e1,\\\n");
output("\t%xr : SIZE(t) : e2, %xr : int : e3,\\\n");
output("\t%xr : int : e4, %xl : VEC(t) : e5 |\\\n");
output("\tEXP e1, EXP e2, EXP e3, EXP e4, EXP e5\\\n");
output(" } STATEMENT TRIM_vec #\n\n");
output("%pi DIM_vec PTR_ptr_vec DIM_ptr_vec\n");
output("%pi NULL_vec MAKE_vec DESTROY_vec TRIM_vec\n\n");
print_type_ops_tok("VEC", "vec", 0);
}
/*
* PRINT VECTOR POINTER CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the vector pointer
* constructs.
*/
static void
print_vec_ptr_tok(void)
{
comment("Vector pointer token specifications");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : VEC(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : VEC_PTR(t) : VEC_PTR_vec #\n\n");
output("%pt PROC {\\\n");
output("\tTYPE t, %xr : VEC_PTR(t) : e |\\\n");
output("\tEXP e\\\n");
output(" } %xr : PTR(t) : PTR_vec_ptr #\n\n");
output("%pi VEC_PTR_vec PTR_vec_ptr\n\n");
print_type_ops_tok("VEC_PTR", "vec_ptr", 0);
}
/*
* PRINT SIZE CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the size constructs.
*/
static void
print_size_tok(void)
{
comment("Size token specifications");
output("%pt PROC {\\\n");
output("\tTYPE t, VARIETY v,\\\n");
output("\t%xr : SIZE(t) : e1, %xr : v : e2 |\\\n");
output("\tEXP e1, EXP e2\\\n");
output(" } %xr : SIZE(t) : SCALE #\n\n");
output("%pi SCALE\n\n\n");
}
/*
* PRINT PRIMITIVE CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the primitive constructs.
*/
static void
print_prim_tok(void)
{
comment("Definitions for primitive %PN");
print_simple_tok("%PN", "%PM", 1, 1);
}
/*
* PRINT ENUMERATION CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the enumeration constructs.
*/
static void
print_enum_tok(void)
{
int lst = DEREF_int(en_lists(CRT_ENUM));
comment("Definitions for enumeration %EN");
print_enum_consts();
print_simple_tok("%EN", "%EM", 1, lst);
}
/*
* PRINT STRUCTURE CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the structure constructs.
*/
static void
print_struct_tok(void)
{
STRUCTURE_P base = DEREF_ptr(str_base(CRT_STRUCTURE));
comment("Definitions for structure %SN");
LOOP_STRUCTURE_COMPONENT {
output("%pt PROC(%xr : PTR(%SN) :) ");
output("%xr : PTR(%CT) : %SM_%CN #\n");
output("%pi %SM_%CN\n\n");
}
output("%pt PROC(\\\n");
LOOP_STRUCTURE_COMPONENT {
string v = DEREF_string(cmp_value(CRT_COMPONENT));
if (v == NULL)
{
output("\t%xr : %CT :,\\\n");
}
}
output("\t%xr : PTR(%SN) :\\\n");
output(" ) STATEMENT MAKE_%SM #\n");
output("%pi MAKE_%SM\n\n");
if (!IS_NULL_ptr(base)) {
CLASS_ID_P id = DEREF_ptr(str_id(base));
char *nt = DEREF_string(cid_name(id));
char *nm = DEREF_string(cid_name_aux(id));
output("%pt PROC(\\\n");
output("\t%xr : PTR(%SN) :\\\n");
output(" ) %xr : PTR(%s) : CONVERT_%SM_%s #\n", nt, nm);
output("%pi CONVERT_%SM_%s\n\n", nm);
}
print_simple_tok("%SN", "%SM", 0, 1);
}
/*
* PRINT UNION CONSTRUCTS (TOKEN VERSION)
*
* This routine prints the token versions of the union constructs.
*/
static void
print_union_tok(void)
{
UNION_P base = DEREF_ptr(un_base(CRT_UNION));
comment("Definitions for union %UN");
output("#define ORDER_%UM ((unsigned)%UO)\n");
output("%pt %xc : %UN : NULL_%UM #\n");
output("%pt PROC(%xr : %UN :) %xr : int : IS_NULL_%UM #\n");
output("%pt PROC(%xr : %UN :, %xr : %UN :) ");
output("%xr : int : EQ_%UM #\n");
output("%pi NULL_%UM IS_NULL_%UM EQ_%UM\n\n");
if (!IS_NULL_ptr(base)) {
CLASS_ID_P id = DEREF_ptr(un_id(base));
char *nt = DEREF_string(cid_name(id));
char *nm = DEREF_string(cid_name_aux(id));
output("%pt PROC(%xr : %UN :) %xr : %s : CONVERT_%UM_%s #\n",
nt, nm);
output("%pi CONVERT_%UM_%s\n\n", nm);
}
print_simple_tok("%UN", "%UM", 1, 1);
return;
}
/*
* PRINT THE MAIN TOKEN OUTPUT FILE
*
* This routine prints the token specifications for the objects above.
*/
static void
print_main_tok(char *dir)
{
open_file(dir, MAIN_PREFIX, MAIN_SUFFIX);
if (extra_headers) {
output("#include \"%s_bscs.h\"\n\n", MAIN_PREFIX);
}
output("#ifndef %X_NAME\n");
output("#define %X_NAME%t40\"%X\"\n");
output("#define %X_VERSION%t40\"%V\"\n");
output("#define %X_SPECIFICATION%t40%d\n", 1);
output("#define %X_IMPLEMENTATION%t40%d\n", 0);
output("#endif\n\n\n");
print_proto();
print_types_tok();
print_ptr_tok();
print_list_tok();
if (allow_stack) {
print_stack_tok();
}
if (allow_vec) {
print_vec_tok();
print_vec_ptr_tok();
}
print_size_tok();
LOOP_PRIMITIVE print_prim_tok();
LOOP_ENUM print_enum_tok();
LOOP_STRUCTURE print_struct_tok();
LOOP_UNION print_union_tok();
if (extra_headers) {
output("#include \"%s_term.h\"\n\n", MAIN_PREFIX);
}
close_file();
}
/*
* PRINT ARGUMENTS FOR A TOKENISED UNION CONSTRUCTOR
*
* This routine prints the list of arguments for a tokenised union
* constructor and similar functions. lv is true if all the arguments
* are lvalues.
*/
static void
print_cons_tok_args(int lv, int d)
{
char *a = "%xr";
char *b = "%xl";
if (lv) {
char *c = a;
a = b;
b = c;
}
LOOP_UNION_COMPONENT {
string v = DEREF_string(cmp_value(CRT_COMPONENT));
if (v == NULL || d == 0)
{
output("\\\n\t%e : %CT :,", a);
}
}
LOOP_FIELD_COMPONENT {
string v = DEREF_string(cmp_value(CRT_COMPONENT));
if (v == NULL || d == 0)
{
output("\\\n\t%e : %CT :,", a);
}
}
output("\\\n\t%e : %UN :", b);
}
/*
* PRINT FIELD SELECTOR OPERATIONS
*
* This routine prints the operations on field selectors (token version).
* rng gives the number of elements in the field set (if appropriate).
* al is true if the field is aliased.
*/
static void
print_field_tok(int rng, int al)
{
char *f = (rng ? "%FN_etc" : "%FN");
LOOP_FIELD_COMPONENT {
output("%pt PROC(%xr : %UN :)\\\n");
output(" %xr : PTR(%CT) : ");
output("%UM_%e_%CN #\n", f);
output("%pi %UM_%e_%CN\n\n", f);
}
/* Component constructor */
output("%pt PROC(");
if (rng) {
output("\\\n\t%xr : unsigned :,");
}
print_cons_tok_args(0, 1);
output("\\\n ) STATEMENT MAKE_%UM_%e #\n", f);
output("%pi MAKE_%UM_%e\n\n", f);
/* Tag modifier */
if (rng) {
output("%pt PROC(");
output("\\\n\t%xr : unsigned :,");
output("\\\n\t%xr : %UN :");
output("\\\n ) STATEMENT MODIFY_%UM_%e #\n", f);
output("%pi MODIFY_%UM_%e\n\n", f);
}
/* Component deconstructor */
if (field_not_empty()) {
output("%pt PROC(");
print_cons_tok_args(1, 0);
output("\\\n ) STATEMENT DECONS_%UM_%e #\n", f);
output("%pi DECONS_%UM_%e\n\n", f);
}
/* Component destructor */
output("%pt PROC(");
output("\\\n\t%xr : DESTROYER :,");
print_cons_tok_args(1, 0);
output("\\\n ) STATEMENT DESTROY_%UM_%e #\n", f);
output("%pi DESTROY_%UM_%e\n\n", f);
/* Aliasing tokens */
if (al && !rng) {
output("#ifdef %X_IO_ROUTINES\n\n");
output("%pt PROC(\\\n");
output("\t%xl : %UN :,\\\n");
output("\t%xr : unsigned :\\\n");
output(" ) STATEMENT NEW_ALIAS_%UM_%FN #\n");
output("%pi NEW_ALIAS_%UM_%FN\n\n");
output("%pt PROC(%xr : %UN :)\\\n ");
output("%xr : unsigned : GET_ALIAS_%UM_%FN #\n");
output("%pt PROC(%xr : %UN :, %xr : unsigned :)\\\n ");
output("%xr : void : SET_ALIAS_%UM_%FN #\n");
output("%pt PROC(%xr : unsigned :)\\\n ");
output("%xr : %UN : FIND_ALIAS_%UM_%FN #\n\n");
output("%pi GET_ALIAS_%UM_%FN SET_ALIAS_%UM_%FN ");
output("FIND_ALIAS_%UM_%FN\n\n");
output("#endif\n\n");
}
output("\n");
}
/*
* PRINT THE UNION OPERATIONS OUTPUT FILE
*
* For each union in the calculus there is an operations file.
*/
static void
print_union_ops_tok(char *dir, char *un)
{
open_file(dir, un, OPS_SUFFIX);
if (extra_headers) {
output("#include \"%s%s\"\n", MAIN_PREFIX, MAIN_SUFFIX);
output("#include <%s_ops.h>\n\n", MAIN_PREFIX);
}
comment("Operations for union %UN");
output("%pt PROC(%xr : %UN :) %xr : unsigned : TAG_%UM #\n");
output("%pi TAG_%UM\n\n\n");
/* Operations on common components */
LOOP_UNION_COMPONENT {
comment("Operations for component %CN of union %UN");
output("%pt PROC(%xr : %UN :)\\\n");
output(" %xr : PTR(%CT) : %UM_%CN #\n");
output("%pi %UM_%CN\n\n");
}
/* Operations on field components */
LOOP_UNION_FIELD {
int rng = DEREF_int(fld_set(CRT_FIELD));
int hash = DEREF_int(fld_flag(CRT_FIELD));
int al = (hash ? 1 : 0);
if (rng)
{
comment("Operations for field set %FN_etc of union %UN");
output("%pt %xc : unsigned : %UM_%FN_etc_tag #\n");
output("%pt PROC(%xr : %UN :) ");
output("%xr : int : IS_%UM_%FN_etc #\n");
output("%pi %UM_%FN_etc_tag IS_%UM_%FN_etc\n\n");
print_field_tok(rng, al);
}
comment("Operations for field %FN of union %UN");
output("%pt %xc : unsigned : %UM_%FN_tag #\n");
output("%pt PROC(%xr : %UN :) %xr : int : IS_%UM_%FN #\n");
output("%pi %UM_%FN_tag IS_%UM_%FN\n\n");
print_field_tok(0, al);
}
/* Map tables */
LOOP_UNION_MAP {
int hash = DEREF_int(map_flag(CRT_MAP));
comment("Map %MN on union %UN");
output("%pt PROC(\\\n");
output("\t%xr : %UN :");
if (hash)
{
output(",\\\n\t%xr : DESTROYER :");
}
LOOP_MAP_ARGUMENT output(",\\\n\t%xr : %AT :");
output("\\\n ) %xr : %MR : %MN_%UM #\n ");
output("%pi %MN_%UM\n\n\n");
}
/* End of file */
close_file();
}
/*
* MAIN ACTION (TOKEN VERSION)
*
* This routine prints all the output files for the calculus (token
* version).
*/
void
main_action_tok(char *dir)
{
int ign = 0;
output_c_code = 2;
print_main_tok(dir);
LOOP_UNION {
LIST(MAP_P)maps;
CLASS_ID_P cid = DEREF_ptr(un_id(CRT_UNION));
char *un = DEREF_string(cid_name_aux(cid));
print_union_ops_tok(dir, un);
maps = DEREF_list(un_map(CRT_UNION));
if (!IS_NULL_list(maps))
{
print_union_map_c(dir, un);
print_union_hdr_c(dir, un);
ign = 1;
}
}
if (ign) {
open_file(dir, IGNORE_PREFIX, DEF_SUFFIX);
comment("Map ignore macros");
LOOP_UNION {
LOOP_UNION_MAP output("#define IGNORE_%MN_%UM%t40%d\n", 1);
}
output("\n");
close_file();
}
if (extra_asserts) {
open_file(dir, ASSERT_PREFIX, DEF_SUFFIX);
comment("Dummy assertion function definitions");
close_file();
}
}
|
C
|
typedef struct Personne{
char* nom;
char* prenom;
char* sexe;
int nbr_enfant;
char** enfants;
char* id;
struct Personne* suivant;
}Personne;
void afficherMenu(){
printf(" *** Gestion de personnel ***");
printf("\n\n 1- Ajouter une personne");
printf("\n 2- Supprimer une personne");
printf("\n 3- Mise a jour d'une personne");
printf("\n 4- Imprimer les donnees");
printf("\n 0- Quitter\n\n");
}
bool ajouterPersonne(Personne* A){ // Ajout au queue du liste chainee A
printf(" *** Gestion de personnel ***\n\n");
printf("==> Ajout d'une personne:");
Personne* p = NULL;
p = (Personne*)malloc(sizeof(Personne));
if(p == NULL){
printf("Allocation echouee _1:(");
return false;
}
else{
//Ajout des valeurs
printf("\n");
p->nom = (char*)malloc(20 * sizeof(char));
p->prenom = (char*)malloc(20 * sizeof(char));
p->sexe = (char*)malloc(10 * sizeof(char));
p->id = (char*)malloc(TAILLE_ID * sizeof(char));
if( (p->nom == NULL) || (p->prenom == NULL) || (p->sexe == NULL) || (p->id == NULL) ){
printf("Allocation echouee _2");
return false;
}
printf(" Nom = "); scanf("%s",p->nom);
printf(" Prenom = "); scanf("%s",p->prenom);
printf(" Sexe = "); scanf("%s",p->sexe);
printf(" Nombre d enfants = "); scanf("%d",&p->nbr_enfant);
int n = p->nbr_enfant;
if(n < 0){ //si c'est negatif, on le considere comme nulle
p->nbr_enfant = 0;
printf(" Nombre d enfants = 0");
}
else{ // n >= 0
if(n > 0){ // n != 0
int i = 0;
p->enfants = (char**)malloc(n * sizeof(char*));
if(p->enfants == NULL){
printf("Allocation echouee _3");
return false;
}
while(i < n){
p->enfants[i] = (char*)malloc(TAILLE_ID * sizeof(char));
if(p->enfants[i] == NULL){
printf("Allocation echouee _%d",4+i);
return false;
}
printf(" -Entrer l'id du **%d** enfant : ",i+1);
scanf("%s",p->enfants[i]);
i++;
}
}
}
printf(" Identifient personnel (%d caracteres) = ",TAILLE_ID); scanf("%s",p->id);
//Ajout a la liste
p->suivant = NULL;
if(A == NULL){
A = p;
}
else{
Personne *tmp = A;
while(tmp->suivant != NULL){
tmp = tmp->suivant;
}
tmp->suivant = p;
}
return true;
}
}
void supprimerPersonne(Personne* A, char* p_nom){
Personne * tmp = A;
while((tmp->suivant->nom != p_nom) && (tmp->suivant != NULL)){
tmp = tmp->suivant;
}
Personne *a_supp = tmp;
tmp->suivant = tmp->suivant->suivant;
free(a_supp);
}
void dataToFile(char* filename, Personne* A){
FILE* f = NULL;
f = fopen(filename, "w");
Personne* tmp = A;
/*while(tmp != NULL){
fprintf(f, "Nom\tPrenom\tSexe\tNombre denfants\tIdentifiant");
fprintf(f, "%s\t%s\t%s\t%d\t%s\n\n", tmp->nom, tmp->prenom, tmp->sexe, tmp->nbr_enfant, tmp->id);
tmp = tmp->suivant;
}*/
fprintf(f, "Nom\tPrenom\tSexe\tNombre denfants\tIdentifiant\n");
fprintf(f, "%s\t%s\t%s\t%d\t%s\n\n", A->nom, A->prenom, A->sexe, A->nbr_enfant, A->id);
fclose(f);
}
|
C
|
#include <stdio.h>
int a=2,b=3,c=6,d=7;
void func (int **p) {*p = &b;}
void main()
{
int *ptrA = &a;
int *ptrB = &b;
int **ptrC;
int **ptrD;
printf("If we set **ptr, we consider as two level pointer\n");
printf(" ----------- \n");
printf(" | C | context: c value, *ptr1, **ptr2\n");
printf(" ----------- address: &c, *&ptr1, &*ptr1, *ptr2\n");
printf("\n");
printf(" |^|\n");
printf(" ----------- \n");
printf(" | ptr1 | context: &c, *&ptr1, &*ptr1, *ptr2\n");
printf(" ----------- address: &ptr1, &*ptr2, *&ptr2\n");
printf("\n");
printf(" |^|\n");
printf(" ----------- \n");
printf(" | ptr2 | context: &ptr1, &*ptr2, *&ptr2\n");
printf(" ----------- address: &ptr2\n");
printf("\n");
printf("in **ptr, ptr pinter to another pointer(*ptr) and *ptr pointer to a address\n");
printf("For example: \n");
printf("We define variable c (address(&c): %p, value(c) = %d\n",&c,c);
int *ptr1;
printf("and also define a pointer (int * ptr1)(address(&ptr1): %p\n",&ptr1);
int **ptr2;
printf(" a pointer (int **ptr2)(address(&ptr2): %p \n", &ptr2);
ptr1 = &c;
printf("then ptr1 = &c\n");
ptr2 = &ptr1;
printf(" ptr2 = &ptr1\n");
printf("c's value read by c: %d ,*ptr1: %d , **ptr2: %d\n", c, *ptr1, **ptr2);
printf("c's address read by &c: %p, *&ptr1: %p, &*ptr1: %p, *ptr2: %p\n",&c, *&ptr1,&*ptr1,*ptr2);
printf("ptr1 address read by &ptr1: %p, &*ptr2: %p, *&ptr2: %p\n", &ptr1,&*ptr2,*&ptr2);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <cs50.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
//Ensure proper usage.
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
//Get in the image file.
char *image = argv[1];
//Open the image file.
FILE *inptr = fopen(argv[1], "r");
//Error if the image cannot be opened.
if (inptr == NULL)
{
fprintf(stderr, "Cannot open %s.\n", image);
return 2;
}
FILE *img = NULL;
char filename[8];
int number = 0;
BYTE buffer[512];
int JPEGFOUND = 0;//<< 0 means not found / 1 means found
while (fread(buffer, 512, 1, inptr) == 1)
{
//Read the image file. (1 block = 512 bytes)
//fread(buffer, 1, 512, inptr); // Decided 512 block & each block = 1 bytes as the end of file occur bytes <= 512 bytes
//Start of a jpeg?
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0) //do not understand......
{
//print out the jpeg found.
sprintf(filename, "%03i.jpg", number);
img = fopen(filename, "w");
number += 1;
JPEGFOUND = 1;
}
if(JPEGFOUND == 1)
{
fwrite(buffer, 512, 1, img);
}
}
fclose(img);
fclose(inptr);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct Node{
int data;
struct Node* prev;
};
int push(int data);
int pop(void);
struct Node* tos;
struct Node * createNode(int data);
void printStack();
int main(){
char press;
int tmp;
printf("1- Push\n");
printf("2- Pop\n");
printf("3- Print stack\n");
printf("3- Exit\n");
press=1;
while(press!='4'){
printf("enter a number ");
press=getch();
switch(press){
case '1':
printf("enter data ");
scanf("%d",&tmp);
push(tmp);
break;
case '2':
pop();
break;
case '3':
printStack();
break;
}
}
return 0;
}
struct Node * createNode(int data){
struct Node * ptr=(struct Node*)malloc(sizeof(struct Node));
if(ptr){
ptr->data=data;
ptr->prev=NULL;
}
return ptr;
}
int push(int data){
int ret=0;
struct Node * cur=createNode(data);
if(cur){
ret=1;
if(!tos){
tos=cur;
}else{
cur->prev=tos;
tos=cur;
}
}
return ret;
}
int pop(){
int ret=-1;
struct Node * tmp;
if(tos){
tmp=tos;
ret=tos->data;
tos=tos->prev;
free(tmp);
}
return ret;
}
void printStack(){
struct Node*ptr=tos;
while(ptr){
printf("%d ",ptr->data);
ptr=ptr->prev;
}
puts("");
}
|
C
|
#include<stdio.h>
int main(){
int x,y;
scanf("%d",&x);
y=x<<1;
printf("%d\n",y);
}
|
C
|
#include <stdio.h>
#include "variadic_functions.h"
/**
*printch - prints a character
*@list: the va_list or arguments that passed a function
*Return: nothing
*/
void printch(va_list list)
{
printf("%c", va_arg(list, int));
}
/**
*printin - prints an integers
*@list: the va_list or arguments that passed a function
*Return: nothing
*/
void printin(va_list list)
{
printf("%d", va_arg(list, int));
}
/**
*printfl - prints a float
*@list: the va_list or arguments that passed a function
*Return: nothing
*/
void printfl(va_list list)
{
printf("%f", va_arg(list, double));
}
/**
*printst - prints a string
*@list: the va_list or arguments that passed a function
*Return: nothing
*/
void printst(va_list list)
{
char *string;
string = va_arg(list, char *);
if (string == NULL)
string = "(nil)";
printf("%s", string);
}
/**
*print_all - function that prints anything
*@format: list of types arguments that passed a function
*Return: nothing
*/
void print_all(const char * const format, ...)
{
va_list printformat;
int i, countformat = 0;
char *nothing = "";
char *commaspace = ", ";
char *last = nothing;
type_t datatype[] = {
{"c", printch},
{"i", printin},
{"f", printfl},
{"s", printst},
{NULL, NULL}};
va_start(printformat, format);
while (format != NULL && format[countformat] != '\0')
{
i = 0;
while (datatype[i].data != NULL)
{
if (format[countformat] == *(datatype[i].data))
{
printf("%s", last);
(datatype[i].correctformat)(printformat);
last = commaspace;
}
i++;
}
countformat++;
}
printf("\n");
va_end(printformat);
}
|
C
|
#include "mysockfunctions.h"
#include <stdint.h>
#define LISTENQ 10
#define MAXLINE 10000
int main (int argc, char **argv) {
int listenfd, connfd, n;
struct sockaddr_in servaddr;
char recvline[MAXLINE + 1];
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr)); // inicializando com zeros
servaddr.sin_family = AF_INET; // utilizando ipv4
servaddr.sin_addr.s_addr = INADDR_ANY; // deixando escutar em qualquer IP
servaddr.sin_port = 0; // deixando a porta automatica
// associando a porta e ip ao socket
Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
// Descobrindo a porta que foi escolhida
socklen_t len = sizeof(servaddr);
GetSockName(listenfd, (struct sockaddr *)&servaddr, &len);
printf("IP: %s\n", inet_ntoa(servaddr.sin_addr));
printf("Porta: %d\n\n", ntohs(servaddr.sin_port));
// escutando no socket, esperando um pedido de conexão
Listen(listenfd, LISTENQ);
for ( ; ; ) {
memset(recvline, 0, strlen(recvline));
// aceitando pedido de conexão no socket
connfd = Accept(listenfd, (struct sockaddr *) NULL, NULL);
while((n = Read(connfd, recvline, MAXLINE)) > 0) {
// printf("n:%d\n", n);
printf("%s", recvline);
Write(connfd, recvline, strlen(recvline));
memset(recvline, 0, strlen(recvline));
}
Close(connfd);
}
return(0);
}
|
C
|
/* BEGIN main */
/* C Program to create the random-access file for the RandomAccessFile example
* Ian F. Darwin, http://www.darwinsys.com/
*/
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <machine/endian.h>
const off_t OFFSET = 1234; // off_t is a C "typedef", usually == long integer
const char* FILENAME = "random.dat";
const int MODE = 0644;
const char* MESSAGE = "Ye have sought, and ye have found!\r\n";
int
main(int argc, char **argv) {
int fd;
int java_offset;
if ((fd = creat(FILENAME, MODE)) < 0) {
perror(FILENAME);
return 1;
}
/* Java's DataStreams etc. are defined to be in network byte order */
java_offset = htonl(OFFSET);
if (write(fd, &java_offset, sizeof java_offset) < 0) {
perror("write");
return 1;
}
if (lseek(fd, OFFSET, SEEK_SET) < 0) {
perror("seek");
return 1;
}
if (write(fd, MESSAGE, strlen(MESSAGE)) != strlen(MESSAGE)) {
perror("write2");
return 1;
}
if (close(fd) < 0) {
perror("close!?");
return 1;
}
return 0;
}
/* END main */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "definizioni.h"
int main ()
{
int i, j;
int somma;
printf ("Hello world....\n");
printf ("Digita il primo numero:");
scanf ("%d", &i);
printf ("Digita il seondo numero:");
scanf ("%d", &j);
somma = operazione_somma (i,j);
printf ("la somma è: %d\n", somma);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** Projet MINISHELL2
** File description:
** function for treat str with fork
*/
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "my.h"
#include "myinc.h"
#include "struct.h"
int my_check_str(char *str)
{
int i = 0;
for (; str[i]; ++i) {
if (str[i] == '/')
return (1);
}
return (0);
}
int my_access_path(list_t *list, char *str)
{
pid_t son;
int satuts = 0;
if (access(str, X_OK) == 0) {
fils = fork();
if (fils == 0) {
execve(str, list->arg, list->cpy_env);
exit(1);
} else {
waitpid(&son, &status, NULL);
my_putstr(strsignal(&status));
}
return (1);
}
return (0);
}
int other_builtins(list_t *list)
{
char *str = NULL;
for (int i = 0; list->cpy_path[i]; ++i) {
if (my_check_str(list->arg[0]) == 0) {
str = my_strcat(list->cpy_path[i], list->arg[0]);
if (my_access_path(list, str) == 1)
return (1);
free(str);
} else {
if (my_access_path(list, list->arg[0]) == 1)
return (1);
}
}
my_putstr(list->arg[0]);
my_putstr(": Command not found.\n");
return (0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_tools2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lguiller <lguiller@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/15 13:40:09 by lguiller #+# #+# */
/* Updated: 2020/09/29 13:25:19 by lguiller ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
void put_n_space(long n)
{
long i;
i = -1;
while (n < 20 && ++i < n)
ft_putstr(" ");
}
void print_mode(mode_t mode)
{
if (S_ISBLK(mode))
ft_putstr("b");
else if (S_ISCHR(mode))
ft_putstr("c");
else if (S_ISFIFO(mode))
ft_putstr("p");
else if (S_ISLNK(mode))
ft_putstr("l");
else if (S_ISSOCK(mode))
ft_putstr("s");
else if (S_ISDIR(mode))
ft_putstr("d");
else
ft_putstr("-");
}
void print_right(mode_t mode)
{
static const char *rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x",
"rw-", "rwx"};
char bits[10];
ft_strcpy(&bits[0], rwx[(mode >> 6) & 7]);
ft_strcpy(&bits[3], rwx[(mode >> 3) & 7]);
ft_strcpy(&bits[6], rwx[mode & 7]);
if (mode & S_ISUID)
bits[2] = (mode & S_IXUSR) ? 's' : 'S';
if (mode & S_ISGID)
bits[5] = (mode & S_IXGRP) ? 's' : 'S';
if (mode & S_ISVTX)
bits[8] = (mode & S_IXOTH) ? 't' : 'T';
bits[9] = '\0';
ft_putstr(bits);
}
void print_uid_gid(long *max_len, struct stat stat)
{
struct passwd *uid;
struct group *gid;
uid = getpwuid((long)stat.st_uid);
gid = getgrgid((long)stat.st_gid);
put_n_space(1);
if (uid)
ft_putstr(uid->pw_name);
else
ft_putnbr((int)stat.st_uid);
put_n_space(max_len[2] - ((uid) ? (long)ft_strlen(uid->pw_name)
: (long)nb_len(stat.st_uid)));
put_n_space(2);
if (gid)
ft_putstr(gid->gr_name);
else
ft_putnbr((int)stat.st_gid);
put_n_space(max_len[3] - ((gid) ? (long)ft_strlen(gid->gr_name)
: (long)nb_len(stat.st_gid)));
}
long get_month_diff(long file_rawtime)
{
long actual_rawtime;
time(&actual_rawtime);
return (ft_fabs(actual_rawtime - file_rawtime) / SEC_TO_MONTH);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Random.h"
int main(int argc, char *argv[]) {
int* randomArr;
randomArr = getRandom(5,300,RANDOM_SIZE);
int i;
for(i=0;i<RANDOM_SIZE;i++)
printf("[%d]%d\n",i,randomArr[i]);
return 0;
}
|
C
|
# include<stdio.h>
void main()
{
int i=0, j=0;
char str[10];
int flag=0;
clrscr();
printf("Enter string");
scanf("%s", str);
while(str[i]!=NULL)
{
i++;
}
i--;
while (j!=i)
{
if (str[i]==str[j])
{
flag=1;
}
else
{
flag=2;
break;
}
j++;
i--;
}
if (flag==1)
{
printf("%s is palindrom",str);
}
else
{
printf("%s is not palindrom",str);
}
getch();
}
|
C
|
//**********************************************************************
//
// Copyright (c) 2004
// PathEngine
// Lyon, France
//
// All Rights Reserved
//
//**********************************************************************
//#ifndef CLIB_STDLIB_INCLUDED
//#define CLIB_STDLIB_INCLUDED
//
//inline long
//strtol(const char* ptr, char** endPtr, int base)
//{
//// assertD(base == 10);
// long result = 0;
// while(*ptr == ' ')
// {
// ptr++;
// }
// bool negate = false;
// if(*ptr == '-')
// {
// negate = true;
// ptr++;
// }
// if(*ptr == '+')
// {
// ptr++;
// }
//
// if(!(*ptr >= '0' && *ptr <= '9'))
// {
// if(endPtr)
// {
// const char *const* endPtr2 = const_cast<const char *const*>(endPtr);
// *endPtr2 = ptr;
// }
// return 0;
// }
//
// do
// {
// int digit = *ptr++;
// digit -= '0';
//
// //.... assumes no overflow
// result *= 10;
// result += digit;
// }
// while(*ptr >= '0' && *ptr <= '9');
//
// if(endPtr)
// {
// const char *const* endPtr2 = const_cast<const char *const*>(endPtr);
// *endPtr2 = ptr;
// }
// if(negate)
// {
// result = -result;
// }
// return result;
//}
//
//inline unsigned long
//strtoul(const char* ptr, char** endPtr, int base)
//{
//// assertD(base == 10);
// unsigned long result = 0;
// while(*ptr == ' ')
// {
// ptr++;
// }
// if(*ptr == '+')
// {
// ptr++;
// }
//
// if(!(*ptr >= '0' && *ptr <= '9'))
// {
// if(endPtr)
// {
// const char *const* endPtr2 = const_cast<const char *const*>(endPtr);
// *endPtr2 = ptr;
// }
// return 0;
// }
//
// do
// {
// int digit = *ptr++;
// digit -= '0';
//
// //.... assumes no overflow
// result *= 10;
// result += digit;
// }
// while(*ptr >= '0' && *ptr <= '9');
//
// if(endPtr)
// {
// const char *const* endPtr2 = const_cast<const char *const*>(endPtr);
// *endPtr2 = ptr;
// }
// return result;
//}
//
//#endif
#include <stdlib.h>
|
C
|
#ifndef lint
#ifdef sccs
static char sccsid[] = "@(#)expandpath.c 20.16 93/06/28 SMI";
#endif
#endif
/*
* (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents
* pending in the U.S. and foreign countries. See LEGAL NOTICE
* file for terms of the license.
*/
/*
* Sun Microsystems, Inc.
*/
/*-
Handles:
~/ => home dir
~user/ => user's home dir
If the environment variable a = "foo" and b = "bar" then:
$a => foo
$a$b => foobar
$a.c => foo.c
xxx$a => xxxfoo
${a}! => foo!
\$a => \$a
*/
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <ctype.h>
#include <string.h>
#include <xview_private/portable.h>
/* input name in nm, pathname output to buf. */
void
expand_path(nm, buf)
register char *nm, *buf;
{
register char *s, *d;
char lnm[MAXPATHLEN];
int q;
register char *trimchars = "\n \t";
char *getenv();
/* Strip off leading & trailing whitespace and cr */
while (XV_INDEX(trimchars, *nm) != NULL)
nm++;
s = nm + (q = strlen(nm)) - 1;
while (q-- && XV_INDEX(trimchars, *s) != NULL)
*s = '\0';
s = nm;
d = lnm;
q = nm[0] == '\\' && nm[1] == '~';
/* Expand inline environment variables */
while (*d++ = *s) {
if (*s == '\\') {
if (*(d - 1) = *++s) {
s++;
continue;
} else
break;
} else if (*s++ == '$') {
register char *start = d;
register braces = *s == '{';
register char *value;
while (*d++ = *s)
if (braces ? *s == '}' : !(isalnum(*s) || *s == '_') )
break;
else
s++;
*--d = 0;
value = getenv(braces ? start + 1 : start);
if (value) {
for (d = start - 1; *d++ = *value++;);
d--;
if (braces && *s)
s++;
}
}
}
/* Expand ~ and ~user */
nm = lnm;
s = "";
if (nm[0] == '~' && !q) { /* prefix ~ */
if (nm[1] == '/' || nm[1] == 0) { /* ~/filename */
if (s = getenv("HOME")) {
if (*++nm)
nm++;
}
} else { /* ~user/filename */
register char *nnm;
register struct passwd *pw;
for (s = nm; *s && *s != '/'; s++);
nnm = *s ? s + 1 : s;
*s = 0;
pw = (struct passwd *) getpwnam(nm + 1);
if (pw == 0) {
*s = '/';
s = "";
} else {
nm = nnm;
s = pw->pw_dir;
}
}
}
d = buf;
if (*s) {
while (*d++ = *s++);
*(d - 1) = '/';
}
s = nm;
while (*d++ = *s++);
}
|
C
|
#include <stdio.h>
int main()
{
double a,b,c,tri,d,e;
scanf("%lf%lf%lf",&a,&b,&c);
tri=((a*c)/2);
printf("%lf\n%lf\n%lf",d,e,tri);
return 0;
}
|
C
|
// The reader first solution to the readers and writers problem.
// As long as there are readers in existence, upcoming writers cannot start.
// Writers may starve.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
// Total number of readers and writers.
#define NUMBER_OF_THREADS 10000
// Binary semaphore for synchronising access to the resource.
sem_t sync;
// Mutex lock for mutual exclusion on reading or writing readerCount.
pthread_mutex_t lock_reader;
// The current number of readers.
int readerCount;
// The value to read and write.
int value;
void * reader() {
pthread_mutex_lock(&lock_reader);
readerCount++;
if (readerCount == 1) {
// Block any upcoming writers if there are readers currently in existence.
// Or go to sleep if there is a writer currently writing, and hence blocking any other upcoming readers by not releasing the mutex lock.
sem_wait(&sync);
}
pthread_mutex_unlock(&lock_reader);
// The reading is outside the critical section so that multiple readers can read in parallel.
printf("A reader reads %d.\n", value);
pthread_mutex_lock(&lock_reader);
readerCount--;
if (readerCount == 0) {
// Unblock the writers if there is currently no reader in existence.
sem_post(&sync);
}
pthread_mutex_unlock(&lock_reader);
pthread_exit(NULL);
}
void * writer() {
// Block any upcoming readers and writers if there is a writer currently writing.
// Or go to sleep if there are readers currently in existence or a writer currently writing.
sem_wait(&sync);
value = rand();
printf("A writer writes %d.\n", value);
// Unblock the readers and writers after the writer has finished.
sem_post(&sync);
pthread_exit(NULL);
}
int main() {
// Initialise the semaphore and the mutex.
sem_init(&sync, 0, 1);
pthread_mutex_init(&lock_reader, NULL);
// Create the reader and writer threads.
pthread_t rwThreads[NUMBER_OF_THREADS];
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
int threadType = rand() % 2;
if (threadType == 0) {
// Create a reader thread.
pthread_create(&rwThreads[i], NULL, reader, NULL);
} else {
// Create a writer thread.
pthread_create(&rwThreads[i], NULL, writer, NULL);
}
}
// Tell the main thread to wait for all threads to finish.
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
pthread_join(rwThreads[i], NULL);
}
printf("Final value: %d.\n", value);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "object.h"
#include "misc.h"
struct location {
const char *description;
const char *tag;
}
locs[] = {
{"an open field", "field"},
{"a little cave", "cave"}
};
#define numberOfLocations (sizeof(locs) / sizeof(*locs))
static unsigned locationOfPlayer = 0;
void executeLook(const char *noun) {
if (noun != NULL && strcmp(noun, "around") == 0) {
printf("You are in %s\n", player->location->description);
listOfObjectsAtLocation(player->location);
} else {
OBJECT *obj = parseObject(noun);
DISTANCE distance = distanceTo(obj);
if (distance >= distUnknownObject) {
printf("I don't understand what you want to see.\n");
} else if (distance == distNotHere) {
printf("You don't see any %s here.\n", noun);
} else if (distance == distOverthere) {
printf("Too far away, move closer please.\n");
} else if (distance == distHereContained) {
printf("Hard to see, try to get it first.\n");
} else {
printf("%s\n", obj->details);
listOfObjectsAtLocation(obj);
}
}
}
static void movePlayer(OBJECT *passage) {
printf("%s", passage->textGo);
if (passage->destination != NULL) {
player->location = passage->destination;
printf("\n");
executeLook("around");
}
}
void executeGo(const char *noun) {
OBJECT *obj = parseObject(noun);
DISTANCE distance = distanceTo(obj);
if (distance >= distUnknownObject) {
printf("I don't understand where you want to go.\n");
} else if (distance == distLocation) {
printf("You are already there");
} else if (distance == distOverthere) {
movePlayer(getPassageTo(obj));
} else if (distance == distHere) {
movePlayer(obj);
} else if (distance < distNotHere) {
printf("You cannot get any closer than this.\n");
} else {
printf("You do not see any %s here.\n", noun);
}
}
|
C
|
#include "main.h"
#include "Arrays_Queue.h"
int main()
{
QUEUE Que;
int pVal ;
Queue_Init(&Que,10); /* 队列初始化 */
Enter_Queue(&Que, 7);
Enter_Queue(&Que, 8);
Enter_Queue(&Que, 12); /* 入队 */
Queue_Traverse(&Que); /* 遍历队列 */
Out_Queue(&Que, &pVal); /* 出队 */
Queue_Traverse(&Que); /* 遍历队列 */
printf("delete value is %d\n",pVal);
Queue_free(Que.pBase); /* 释放内存 */
printf("OK\n");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack_draw_term.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: odrinkwa <odrinkwa@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/24 19:56:33 by odrinkwa #+# #+# */
/* Updated: 2019/10/26 14:40:32 by odrinkwa ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
static void print_stars(int count)
{
while (count-- > 0)
ft_printf("*");
}
static int get_size_stack_elem(t_stack *a, t_dlist *curr_el)
{
int i;
i = 0;
while (i < a->len_all)
{
if (a->array_int[i] == int_content(curr_el))
return ((i + 1) / a->coef_star_size);
i++;
}
return (0);
}
static void pretty_print_aux(t_stack *a, t_dlist *curr_a,
t_dlist *curr_b, int width)
{
int i;
i = 1;
while (curr_a != NULL || curr_b != NULL)
{
SETCOLOR(F_RED);
if (curr_a != NULL)
{
ft_printf("% *d ", a->max_len_elem + 2, int_content(curr_a));
print_stars(get_size_stack_elem(a, curr_a));
curr_a = curr_a->next;
}
GOTOINLINE(width);
SETCOLOR(F_GREEN);
if (curr_b != NULL)
{
ft_printf("% *d ", a->max_len_elem + 2, int_content(curr_b));
print_stars(get_size_stack_elem(a, curr_b));
curr_b = curr_b->next;
}
ft_printf("\n");
i++;
}
}
void pretty_print_stack(t_stack *a, t_stack *b)
{
int width;
t_dlist *curr_a;
t_dlist *curr_b;
curr_a = (a != NULL) ? a->top : NULL;
curr_b = (b != NULL) ? b->top : NULL;
width = a->len_all + 15;
pretty_print_aux(a, curr_a, curr_b, width);
RESET_COLOR();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age;
printf("what is your age shambhu?\n");
scanf("%d",&age);
if (age > 20)
{
printf("timi ta budo vaechau yarr\n");
}
if (age < 20)
{
printf("kancho raichau yarr\n");
}
if (age == 40)
{
printf("aba ta budeskal lagecha yarr\n");
}
else
{
printf("mara mula\n");
}
return 0;
}
|
C
|
#include<stdlib.h>
struct stack
{
char data;
struct stack* link;
};
struct stack *top=NULL,*temp;
void push(char data)
{
temp=(struct stack*)malloc(1*sizeof(sizeof(struct stack)));
if(top==NULL)
{
temp->link=NULL;
top=temp;
}
else
{
temp->link=top;
top=temp;
}
}
char pop()
{
int data;
data=top->data;
temp=top;
top=top->link;
free(temp);
return data;
}
void convert(char in[])
{
char post()
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define BUFSIZE 1024
void error_exit(char *message);
int main(int argc, char **argv) {
int client_fd;
char message[BUFSIZE];
int str_len, ret;
struct sockaddr_in server_addr;
fd_set fs_status;
if (argc != 3) {
printf("Usage : %s <IP> <port>\n", argv[0]);
exit(1);
}
client_fd = socket(PF_INET, SOCK_STREAM, 0);
if (client_fd == -1)
error_exit("client_fdet() error");
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
ret = connect(client_fd, (struct sockaddr*) &server_addr,
sizeof(server_addr));
if (ret == -1)
error_exit("connect() error!");
printf("client_fd = %d\n", client_fd);
while (1) {
FD_ZERO(&fs_status);
FD_SET(0, &fs_status);
FD_SET(client_fd, &fs_status);
select(client_fd+1, &fs_status, 0, 0, 0);
if (FD_ISSET(0, &fs_status) == 1) {
str_len = read(0, message, BUFSIZE);
write(client_fd, message, str_len);
if (message[0] == 'q')
{
close(client_fd);
return 0;
}
} else if (FD_ISSET(client_fd, &fs_status)) {
str_len = read(client_fd, message, BUFSIZE);
printf("[server : ");
fflush(stdout);
write(1, message, str_len-1);
printf("]\n");
}
}
return 0;
}
void error_exit(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
|
C
|
/*
* Block Cipher Modes of Operation
* @author Dani Huertas
* @email huertas.dani@gmail.com
*
*/
#include "pcbc.h"
static uint8_t *tmp = NULL;
size_t pcbc(blockcipher_fn cipher, uint8_t direction,
uint8_t *in,
uint8_t *out,
uint8_t *iv,
uint8_t *key,
size_t key_size,
size_t block_size,
size_t length,
uint8_t last) {
size_t res = block_size;
uint8_t in_xd[block_size];
if (tmp == NULL) {
// first block, create tmp buffer
tmp = malloc(block_size);
memcpy(tmp, iv, block_size);
}
if (direction == ENCRYPT) {
bc_xor(in, tmp, in_xd, block_size);
}
(*cipher)(direction, direction == ENCRYPT ? in_xd : in, out, key, key_size);
if (direction == ENCRYPT) {
bc_xor(in, out, tmp, block_size);
}
if (direction == DECRYPT) {
bc_xor(out, tmp, out, block_size);
bc_xor(in, out, tmp, block_size);
}
if (last) {
free(tmp);
tmp = NULL;
}
return res;
}
|
C
|
/* CS261- HW1 - Program4.c*/
/* Name:
* Date:
* Solution description:
*/
#include <stdio.h>
#include <stdlib.h>
struct student{
char initials[2];
int score;
};
void sort(struct student* stud, int n){
/*Sort n studdents based on their initials*/
if(n==0)
return;
struct student temp;
int i, j;
for(i=0; i<n-1; i++){
for(j=0; j<n-1; j++){
if(stud[j].initials[0] > stud[j+1].initials[0]){
temp= stud[j];
stud[j]= stud[j+1];
stud[j+1]=temp;
}
else if(stud[j].initials[0] == stud[j+1].initials[0]){
if(stud[j].initials[1] > stud[j+1].initials[1]){
temp= stud[j];
stud[j]= stud[j+1];
stud[j+1]=temp;
}
}
}
}
}
int main(){
/*Declare an integer n and assign it a value.*/
int n=10;
/*Allocate memory for n stud using malloc.*/
struct student* stud= malloc(n* sizeof(struct student));
int i, x;
/*Generate random IDs and scores for the n stud, using rand().*/
for(i=0; i<n; i++){
stud[i].initials[0]= rand()%26 + 'A';
stud[i].initials[1]= rand()%26 + 'A';
stud[i].score= rand()%101;
}
/*Print the contents of the array of n stud.*/
for(i=0; i<n; i++){
x=i+1;
printf("%d. %c%c %d\n", x, stud[i].initials[0], stud[i].initials[1], stud[i].score);
}
/*Pass this array along with n to the sort() function*/
sort(stud, n);
/*Print the contents of the array of n stud.*/
for(i=0; i<n; i++){
x=i+1;
printf("%d. %c%c %d\n", x, stud[i].initials[0], stud[i].initials[1], stud[i].score);
}
return 0;
}
|
C
|
//sum of elements in zig zag sequence in given matrix
/*1 2 3
4 5 6
7 8 9*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int r,c,arr[100][100],i,j,sum=0;
printf("enter no. of rows and columns:\n");
scanf("%d%d",&r,&c);
if(r!=c)
{
printf("zig zag sum not possible");
exit(1);
}
printf("enter the matrix:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&arr[i][j]);
}
for(i=0;i<r;i++)
{
if(i==0||i==r-1)
{
for(j=0;j<c;j++)
sum+=arr[i][j];
}
else
sum+=arr[i][c-i-1];
}
printf("the zig zag sum of matrix is %d",sum);
return 0;
}
|
C
|
#ifndef FUNCIONES_H_INCLUDED
#define FUNCIONES_H_INCLUDED
float sumar(float operando1, float operando2); // funcion de la suma entre dos operandos
float restar(float operando1, float operando2); // funcion de la resta entre dos operandos
float multiplicar(float operando1, float operando2); // funcion de la multiplicacion entre dos operandos
float dividir(float operando1, float operando2); // funcion de la division entre 2 operandos
float factorial(float n); // funcion que calcula el factorial
int menu(float num1, float num2); //funcion del menu
#endif // FUNCIONES_H_INCLUDED
|
C
|
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
int main(void){
FILE* fp=fopen("./ftest.txt","w");
char buf[80];
int ret=0;
memset(buf,0,sizeof(buf)); //qingkong
printf("input data into file\n");
fgets(buf,sizeof(buf),stdin);
// PRINTF("file descriptor= %d\n",fd);
//printf("\n the string is %s\n",buf);
// close(fd);
ret = fwrite(buf,4,sizeof(buf),fp);
//fwrite(buf,sizeof(buf),1,fp);
printf("number of item write to file=%d\n",ret);
fclose(fp);
return 0;
}
|
C
|
#include<stdio.h>
int main(int argc, char *argv[]) {
puts("Hello World");
printf("%d\n",argc);
int i = 0;
for(i =0 ; i< argc; i++) {
printf("%s\n",argv[i]);
}
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a,add,sub,mul,mod,div,x,y;
printf("Enter two numbers x & y :\n");
scanf("%d%d",&x,&y);
printf("1=Addition\n");
printf("2=Subtraction\n");
printf("3=Multiplication\n");
printf("4=Division\n");
printf("5=Modulus\n");
printf("Enter your choice\n:");
scanf("%d",&a);
switch(a)
{
case 1: add = x + y;
printf("addition of %d and %d is= %d\n",x,y,add);
break;
case 2: sub = x - y;
printf("subtraction of %d and %d is= %d\n",x,y,sub);
break;
case 3: mul = x * y;
printf("multiplication of %d and %d is= %d\n",x,y,mul);
break;
case 4: div = x / y;
printf("division of %d and %d is= %d\n",x,y,div);
break;
case 5: mod = x % y;
printf("modulus of %d and %d is= %d\n",x,y,mod);
break;
default :
printf("wrong choice");
}
}
|
C
|
/* demo pipe
with 2 args
like pipe who sort = who | sort
who's output to sort's input.
*/
#include<stdio.h>
#include<unistd.h>
#define oops(m,x) {perror(m); exit(x);}
main(int argc, int *argv[])
{
int pipefd[2];
int pid;
if(argc != 3)
oops("usage: pipe cmd1 cmd2\n" ,1 );
if(pipe(pipefd)== -1 )
oops("could not make pipe",2);
if ((pid = fork()) == -1)
oops("could not fork",3);
if (pid > 0)
{
//in parent, parent proc will exec argv[2]
close(pipefd[1]); //perent not need wirte
if(dup2(pipefd[0],0) == -1)
oops("could not redirect stdin of parent",3);
close(pipefd[0]);
execlp(argv[2],argv[2],NULL);
oops(argv[2],4); // exec error then , run this
}
//in child, child proc will exec argv[1]
close(pipefd[0]) ; //child not need read
if(dup2(pipefd[1],1) == -1)
oops("could not redirect stdout of child",5);
close(pipefd[1]);
execlp(argv[1],argv[1],NULL);
oops(argv[1],6);
}
|
C
|
#include <stdio.h>
int main(){
char c;
printf("Entrez un caractére : \n");
scanf("%c", &c);
if(c >= 'a' && c <= 'z'){
switch (c) {
case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': printf("C'est une voyelle !");
break;
default: printf("C'est une consonne !");
}
} else {
printf("L'entree n'est pas un caractère alphabétique");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lst_associative_set.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: felix <felix@student.42lyon.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/15 13:06:59 by fgalaup #+# #+# */
/* Updated: 2021/03/16 15:53:45 by felix ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_lst_associative_set(t_list **list, char *key, void *value)
{
t_associative *associative;
associative = ft_lst_get_associative(*list, key);
if (associative != NULL)
{
if (associative->value != NULL)
ft_managed_free(associative->value);
}
else
{
associative = ft_managed_malloc(sizeof(t_associative));
if (associative == NULL)
return (NULL);
associative->key = key;
if (!(ft_lstnew_front(list, associative, ft_managed_free)))
return (NULL);
}
associative->value = value;
return (*list);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* write01.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cbruno <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/21 14:17:01 by cbruno #+# #+# */
/* Updated: 2019/11/18 15:37:09 by cbruno ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../include/editor.h"
t_bool write_flag_2(int fd, t_flag *flag)
{
if (!(write(fd, &flag->texture, sizeof(unsigned))))
return (false);
if (!(write(fd, &flag->top[0], sizeof(float))))
return (false);
if (!(write(fd, &flag->top[1], sizeof(float))))
return (false);
if (!(write(fd, &flag->top[0], sizeof(float))))
return (false);
if (!(write(fd, &flag->width, sizeof(float))))
return (false);
if (!(write(fd, &flag->heigth, sizeof(float))))
return (false);
return (true);
}
t_bool write_flag(t_flag *flag, int fd)
{
int i;
if (flag == NULL)
{
i = 0;
if (!(write(fd, &i, sizeof(int))))
return (false);
}
else
{
i = 1;
if (!(write(fd, &i, sizeof(int))))
return (false);
if (write_flag_2(fd, flag) == false)
return (false);
}
return (true);
}
t_bool write_wall_list_2(int fd, t_wall_lst *current)
{
if (!(write(fd, ¤t->wall->start[0], sizeof(float))))
return (false);
if (!(write(fd, ¤t->wall->start[1], sizeof(float))))
return (false);
if (!(write(fd, ¤t->wall->end[0], sizeof(float))))
return (false);
if (!(write(fd, ¤t->wall->end[1], sizeof(float))))
return (false);
if (!(write(fd, ¤t->wall->next_sector, sizeof(int))))
return (false);
if (!(write(fd, ¤t->wall->b_texture, sizeof(unsigned))))
return (false);
if (!(write(fd, ¤t->wall->m_texture, sizeof(unsigned))))
return (false);
if (!(write(fd, ¤t->wall->t_texture, sizeof(unsigned))))
return (false);
if (write_flag(current->wall->flag, fd) != true)
return (false);
return (true);
}
t_bool write_wall_list(t_core *core, int fd)
{
t_wall_lst *current;
int nbr_wall;
current = core->wall_list;
nbr_wall = get_nbr_wall(current, 0);
if (!(write(fd, &nbr_wall, sizeof(int))))
return (false);
while (current != NULL)
{
if (write_wall_list_2(fd, current) == false)
return (false);
current = current->next;
}
return (true);
}
|
C
|
#include<stdio.h>
#include<locale.h>
int main(){
setlocale(LC_ALL,"Portuguese");
int entrada, i,flag = 0;
printf("\nPor favor digite um nmero:\n");
scanf("%d",&entrada);
for(i = 2; i < entrada ; i++ ){
if(entrada%i == 0){
printf("O nmero no primo!%d");
break;
}
}
if( i == entrada){
printf("\nO nmero primo!\n");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* draw_texture_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmurray <lmurray@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/29 12:58:34 by lmurray #+# #+# */
/* Updated: 2021/02/08 22:27:18 by lmurray ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../headers/cub3d.h"
void draw_texture_vertical(t_cub3d *cub, t_image *tex, int x)
{
unsigned int color;
int y;
color = 0;
cub->texture.step_tex = 1.0 * tex->height / cub->window.height_ln;
cub->texture.pos_tex = (cub->window.top_wall - cub->window.res_height / 2 +\
cub->window.height_ln / 2) * cub->texture.step_tex;
y = cub->window.top_wall;
while (y < cub->window.bottom_wall)
{
cub->texture.y_tex = (int)(cub->texture.pos_tex) & (tex->height - 1);
cub->texture.pos_tex += cub->texture.step_tex;
color = get_pix_color(tex, cub->texture.x_tex, \
cub->texture.y_tex);
draw_pix(cub, x, y, color);
y++;
}
}
/*
** Function: unsigned int get_pix_color()
**
** Arguments: tex where we take colors, x - coordinate in tex,
** y - coordinate in tex
**
** return: color in decimal rgb
**
** Description: fn take decimal format color rgb
*/
unsigned int get_pix_color(t_image *texture, int x, int y)
{
unsigned int color;
color = 0;
x = abs(x);
y = abs(y);
color = (*(int *)(texture->content + ((x + (y * texture->width)) * \
(texture->btp / 8))));
return (color);
}
|
C
|
#ifndef LIBABACUS_TABLE_H
#define LIBABACUS_TABLE_H
#include "basetype.h"
#include "custom.h"
#include "refcount.h"
#include "result.h"
#include "trie.h"
/**
* A struct that represents a structure
* similar to a symbol table. This structure
* is used to keep track of definitions such
* as types, functions, and variables in an
* environment with scopes.
*/
struct libab_table_s {
/**
* The "parent" scope of this table.
*/
libab_ref parent;
/**
* The hash table used to store the data.
*/
libab_trie trie;
};
/**
* Enum that represents the type of a table
* entry.
*/
enum libab_table_entry_variant_e {
ENTRY_VALUE,
ENTRY_BASETYPE,
ENTRY_OP,
ENTRY_TYPE_PARAM
};
/**
* An entry in the table.
*/
struct libab_table_entry_s {
/**
* The type of this entry.
*/
enum libab_table_entry_variant_e variant;
/**
* Union that holds the various types of
* data that this entry could hold.
*/
union {
libab_operator op;
libab_basetype* basetype;
libab_ref value;
libab_ref type_param;
} data_u;
};
typedef struct libab_table_s libab_table;
typedef enum libab_table_entry_variant_e libab_table_entry_variant;
typedef struct libab_table_entry_s libab_table_entry;
/**
* Initializes the given table.
* @param table the table to initialize.
*/
void libab_table_init(libab_table* table);
/**
* Searches for the given string in the table, comparing
* values to a given reference as an extra filtering step.
* @param table the table to search.
* @param string the string to search for.
* @param data the data to compare against potential values.
* @param compare the comparison function to use.
* @return the table entry, or NULL if an entry was not found.
*/
libab_table_entry* libab_table_search_filter(libab_table* table,
const char* string, void* data,
compare_func compare);
/**
* Searches for the given string in the table.
* @param table the table to search.
* @param string the string to search for.
* @return the table entry, or NULL if an entry was not found.
*/
libab_table_entry* libab_table_search(libab_table* table, const char* string);
/**
* Searches for the given string in the table, returning a value only
* if it is an operator.
* @param table the table to search.
* @param string the string to search for.
* @param type the type of operator to search for (infix, prefix, postfix)
* @return the found operator, or NULL if it was not found.
*/
libab_operator* libab_table_search_operator(libab_table* table,
const char* string, int type);
/**
* Searches for a given string in the table,
* returning the entry that holds it only if it is an operator.
* @param table the table to search.
* @param string the string to search for.
* @param type the type of operator to search for (infix, prefix, postfix)
* @return the entry, or NULL if it was not found.
*/
libab_table_entry* libab_table_search_entry_operator(libab_table* table,
const char* string,
int type);
/**
* Searches for the given basetype in the table, returning a value
* only if it's a basetype.
* @param table the table to search.
* @param string the string to search for.
* @return the found basetype, or NULL if it was not found.
*/
libab_basetype* libab_table_search_basetype(libab_table* table,
const char* string);
/**
* Searches for the given basetype in the table, returning a table
* entry only if it holds a basetype.
* @param table to table to search.
* @param string the string to search for.
* @return the entry holding the basetype, or NULL if it was not found.
*/
libab_table_entry* libab_table_search_entry_basetype(libab_table* table,
const char* string);
/**
* Searches for the given value in the table.
* @param table the table to search.
* @param string the table entry key.
* @param ref the reference to store the result into.
*/
void libab_table_search_value(libab_table* table, const char* string,
libab_ref* ref);
/**
* Searches for a value with the given name in the table,
* and returns an entry that holds it.
* @param table the table to search.
* @param string the tabe entry key.
* @return the table entry holding the value, or NULL if it was not found.
*/
libab_table_entry* libab_table_search_entry_value(libab_table* table,
const char* string);
/**
* Searches for the given type parameter in the table.
* @param table the table to search in.
* @param string the key to search for.
* @param ref the reference to store the type into.
*/
void libab_table_search_type_param(libab_table* table, const char* string,
libab_ref* ref);
/**
* Searches for the given type parameter in the table.
* @param table the table to search in.
* @param string the key to search for.
* @return the table entry holding the type parameter, or NULL.
*/
libab_table_entry* libab_table_search_entry_type_param(libab_table* table,
const char* string);
/**
* Stores the given entry in the table under the given key.
* @param table the table to store the entry into.
* @param string the string to use as the key.
* @param entry the new entry to put into the table.
* @return the result of the insertion, which could be LIBAB_MALLOC.
*/
libab_result libab_table_put(libab_table* table, const char* string,
libab_table_entry* entry);
/**
* Sets the parent of the given table.
* @param table the table whose parent to set.
* @param parent a valid reference to a parent table.
*/
void libab_table_set_parent(libab_table* table, libab_ref* parent);
/**
* Clears the table.
* @param table the table to clear.
*/
void libab_table_clear(libab_table* table);
/**
* Frees the resources allocated by the
* given table.
* @param table the table to free.
*/
void libab_table_free(libab_table* table);
/**
* Comparison function used to search the table for a prefix operator.
*/
int libab_table_compare_op_prefix(const void* left, const void* right);
/**
* Comparison function used to search the table for a infix operator.
*/
int libab_table_compare_op_infix(const void* left, const void* right);
/**
* Comparison function used to search the table for a postfix operator.
*/
int libab_table_compare_op_postfix(const void* left, const void* right);
/**
* Comparison function used to search the table for a value.
*/
int libab_table_compare_value(const void* left, const void* right);
/**
* Comparison function used to search the table for a basetype.
*/
int libab_table_compare_basetype(const void* left, const void* right);
/**
* Frees the given table entry.
* @param entry the entry to free.
*/
void libab_table_entry_free(libab_table_entry* entry);
#endif
|
C
|
/*
Linked Lists are linear data structure. A singly linked list is formed
by connecting nodes from one to other in a linear fashion i.e. one node is
connected to second and it is connected to other and so on.
Each node of a linked list contains two elements
1. Data - the data is stored in this part
2. Next (or link) - the address of the node which is to be connected
to this node is stored in *next.
Unlike arrays, nodes are not stored in a sequential manner in the memory, instead
they are stored randomly in the memory and we access the node using the address of that memory.
The outflow of the link list can be understood using the below figure.
|data|next|---->|data|next|----> |data|next|
*/
// Linked List Implementaion
#include<stdio.h>
#include<stdlib.h>
// The structure of node of linked list as described above.
struct node
{
int data;
struct node *next;
};
// Method to insert a new node in
void append(struct node ** ,int );
void display(struct node *);
void del(struct node **,int);
// User driven code main() method for implementing linked list.
int main(void)
{
// Start pointer to store the address of first node.
struct node *start=NULL;
int n,m;
// The loop will continue running until the user itself terminates the program.
do
{
printf("\nEnter Choice \n1. Append \n2.Display \n3.Delete \n5.Quit ");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\nEnter no. of your choice");
scanf("%d",&m);
append(&start,m);
break;
case 2:
display(start);
break;
case 3:
printf("\nEnter no. to delete from list");
scanf("%d",&m);
del(&start,m);
break;
case 4:
exit(0);
default:
printf("\nplease enter a valid choice");
}
} while(1);
return 0;
}
// Method to insert node into the linked list.
void append(struct node **ps, int x)
{
struct node *p, *temp;
// Creating a new node for insertion.
p=(struct node *)malloc(sizeof(struct node));
p->data = x;
p->next = NULL;
// If the node to be inserted is the first node.
if(*ps == NULL)
{
*ps=p;
}
// If it is not first not, we'll traverse to the last node
// and then join the new node there.
else
{
temp=*ps;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=p;
}
}
// Display method to show the data of the linked list.
void display(struct node *p)
{
int count=1;
if(p==NULL)
{
printf("\nlist is empty");
}
else
{
printf("\nList is : ");
while(p !=NULL)
{
count++;
printf("%d ",p->data);
p=p->next;
}
}
}
// Method to delete a node from the linked list.
void del(struct node **ps, int x)
{
struct node *temp, *p;
// Condition for list is empty
if(*ps==NULL)
{
printf("\nList is empty");
return;
}
temp=*ps;
// If provided node is the first node of the list.
if((*ps)->data==x)
{
*ps=temp->next;
free(temp);
printf("\nNode Deleted ");
return;
}
// In other conditions.
while(temp!=NULL && temp->data!=x)
{
p=temp;
temp=temp->next;
}
// If the data provided is not present in the list.
if(temp==NULL)
{
printf("\nData is not availaible in the list ");
}
else
{
p->next=temp->next;
free(temp);
printf("\nNode Deleted");
}
}
|
C
|
#include<stdio.h>
int main()
{
char str[50];
int i;
int cnt;
printf("\nenter your name :");
scanf("%[^\n]s", str);
for(i=0, cnt=0;str[i]!='\0';i++)
if(str[i] == ' ' && str[i+1]!= ' ')
cnt++;
printf("\nnumber of words : %d" ,cnt+1);
return 0;
}
|
C
|
//Check if was imported yet
#ifndef COORDINATE_H
//Define as imported
#define COORDINATE_H
//Coordinate data type
typedef struct coordinate {
short x_coord, y_coord;
int cost;
};
//Coordinate Queue data type(queue of coordinates)
typedef struct coordinate_queue {
//Address in memory of coordinate
struct coordinate* address;
//tail coordinate
struct coordinate* tail;
//head coordinate
struct coordinate* head;
};
//Functional Definitions
void initialize(struct coordinate_queue*, int);
void destroy(struct coordinate_queue*);
int empty(struct coordinate_queue*);
void enqueue(struct coordinate_queue*, short, short, int);
struct coordinate* dequeue(struct coordinate_queue*);
//Import complete
#endif
|
C
|
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#define NR_END 1
#define FREE_ARG char*
#define NRANSI
#define SWAP(a, b) itemp=(a);(a)=(b);(b)=itemp;
#define M 7
#define NSTACK 50
void nrerror(char error_text[])
/* Numerical Recipes standard error handler */
{
fprintf(stderr,"Numerical Recipes run-time error...\n");
fprintf(stderr,"%s\n",error_text);
fprintf(stderr,"...now exiting to system...\n");
exit(1);
}
int *ivector(long nl, long nh)
/* allocate an int vector with subscript range v[nl..nh] */
{
int *v;
v=(int *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(int)));
if (!v) nrerror("allocation failure in ivector()");
return v-nl+NR_END;
}
void free_ivector(int *v, long nl, long nh)
/* free an int vector allocated with ivector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void iindexx(unsigned long n, long arr[], unsigned long indx[]){
unsigned long i,indxt,ir=n,itemp,j,k,l=1;
int jstack=0,*istack;
long a;
istack=ivector(1,NSTACK);
for (j=1;j<=n;j++) indx[j]=j;
for (;;) {
if (ir-l < M) {
for (j=l+1;j<=ir;j++) {
indxt=indx[j];
a=arr[indxt];
for (i=j-1;i>=l;i--) {
if (arr[indx[i]] <= a) break;
indx[i+1]=indx[i];
}
indx[i+1]=indxt;
}
if (jstack == 0) break;
ir=istack[jstack--];
l=istack[jstack--];
} else {
k=(l+ir) >> 1;
SWAP(indx[k],indx[l+1]);
if (arr[indx[l]] > arr[indx[ir]]) {
SWAP(indx[l],indx[ir])
}
if (arr[indx[l+1]] > arr[indx[ir]]) {
SWAP(indx[l+1],indx[ir])
}
if (arr[indx[l]] > arr[indx[l+1]]) {
SWAP(indx[l],indx[l+1])
}
i=l+1;
j=ir;
indxt=indx[l+1];
a=arr[indxt];
for (;;) {
do i++; while (arr[indx[i]] < a);
do j--; while (arr[indx[j]] > a);
if (j < i) break;
SWAP(indx[i],indx[j])
}
indx[l+1]=indx[j];
indx[j]=indxt;
jstack += 2;
if (jstack > NSTACK) nrerror("NSTACK too small in indexx.");
if (ir-i+1 >= j-l) {
istack[jstack]=ir;
istack[jstack-1]=i;
ir=j-1;
} else {
istack[jstack]=j-1;
istack[jstack-1]=l;
l=i;
}
}
}
free_ivector(istack,1,NSTACK);
}
void indexx(unsigned long n, float arr[], unsigned long indx[]){
unsigned long i,indxt,ir=n,itemp,j,k,l=1;
int jstack=0,*istack;
float a;
istack=ivector(1,NSTACK);
for (j=1;j<=n;j++) indx[j]=j;
for (;;) {
if (ir-l < M) {
for (j=l+1;j<=ir;j++) {
indxt=indx[j];
a=arr[indxt];
for (i=j-1;i>=l;i--) {
if (arr[indx[i]] <= a) break;
indx[i+1]=indx[i];
}
indx[i+1]=indxt;
}
if (jstack == 0) break;
ir=istack[jstack--];
l=istack[jstack--];
} else {
k=(l+ir) >> 1;
SWAP(indx[k],indx[l+1]);
if (arr[indx[l]] > arr[indx[ir]]) {
SWAP(indx[l],indx[ir])
}
if (arr[indx[l+1]] > arr[indx[ir]]) {
SWAP(indx[l+1],indx[ir])
}
if (arr[indx[l]] > arr[indx[l+1]]) {
SWAP(indx[l],indx[l+1])
}
i=l+1;
j=ir;
indxt=indx[l+1];
a=arr[indxt];
for (;;) {
do i++; while (arr[indx[i]] < a);
do j--; while (arr[indx[j]] > a);
if (j < i) break;
SWAP(indx[i],indx[j])
}
indx[l+1]=indx[j];
indx[j]=indxt;
jstack += 2;
if (jstack > NSTACK) nrerror("NSTACK too small in indexx.");
if (ir-i+1 >= j-l) {
istack[jstack]=ir;
istack[jstack-1]=i;
ir=j-1;
} else {
istack[jstack]=j-1;
istack[jstack-1]=l;
l=i;
}
}
}
free_ivector(istack,1,NSTACK);
}
#undef M
#undef NSTACK
#undef SWAP
#undef NRANSI
|
C
|
/********************************
* Fichier affiche_suite_entiers.c
* Livre "Exercices corrigés de développement système sous Linux"
*
* (c) 2018 P. Alain, J. Chevelu, V. Thion
*
********************************/
#include <stdio.h> // fprintf
#include <unistd.h> // sleep
#include <stdlib.h> // exit
int main(void)
{
int i;
for (i = 1; i < 31; i++) {
printf("%d\n", i);
sleep(1);
}
exit(EXIT_SUCCESS);
}
|
C
|
/*
* Or Paz
* 311250708
*/
#include <stdio.h>
#include <memory.h>
typedef void (*functionPtr)(char*,char*);
typedef enum specialChar {
eNone = 0x0,
eWin = 0x000d000a,
eMac = 0x000d,
eLinux = 0x000a
} specialChar;
/**
* this func copy file from source to destantion.
* @param src - source file.
* @param dst - destantion file.
*/
void copyWithoutFlags (FILE* src, FILE* dst);
/**
* this func copy file from source to destantion but we want to save destantion file in another os.
* @param src - source file.
* @param dst - destantion file.
* @param os1 - the os that src file was create - part of argument.
* @param os2 - the os that dst file was create - part of argument.
* @param pFunc - pointer to function (swap, keep or dump)
*/
void copyBetweenOS(FILE* src, FILE* dst, char* osSrc, char* osDst , functionPtr pFunc);
/**
* this function check the os was inserted and return the new line encoding that belong to os.
* @param osSrc - the os that src file was create
* @param osDst - the os that dst file was create
* @param src - source file.
* @param dst - destantion file.
*/
void checkSpecial(char* osSrc,char* osDst, specialChar* src, specialChar* dst);
/**
* this func swap between 2 argument by adress.
* @param a - argument type char*
* @param b - argument type char*
*/
void swap(char* a, char* b);
/**
* this func check how much os args insert.
* @param argv -parameters
* @return the number of os args.
*/
int CheckOsArgValid(char* argv[]);
/**
* this func check how much files args insert.
* @param argv -parameters
* @return the number of files args.
*/
int CheckFilesArgValid(char* argv[]);
/**
* do noting. for '-keep' insertion.
* @param a - argument type char*
* @param b - argument type char*
*/
void keep(char* a, char* b);
/**
* do noting. for mission 2 .
* @param a - argument type char*
* @param b - argument type char*
*/
void dump(char* a, char* b);
/**
* this func check if the source file was written in little endian or big
* @param s - char* s (array of 2)
* @return return 1 if is little and 0 if is it big.
*/
int is_file_little_endian(char* s);
int CheckFilesArgValid(char* argv[])
{
int count = 0;
char *p1=NULL, *p2=NULL;
if(argv[1] && argv[2]) {
// search '.' in args
p1 = strstr(argv[1], ".");
p2 = strstr(argv[2], ".");
}
if(p1 && p2)
{
count = 2;
}
return count;
}
int CheckOsArgValid(char* argv[]) {
int count = 0;
if (argv[3] != NULL) {
// count the os that insert
count += !strcmp(argv[3], "-win");
count += !strcmp(argv[3], "-mac");
count += !strcmp(argv[3], "-unix");
}
if (argv[4] != NULL) {
count += !strcmp(argv[4], "-win");
count += !strcmp(argv[4], "-mac");
count += !strcmp(argv[4], "-unix");
}
return count;
}
void swap(char* a, char* b)
{
char temp = *a;
*a = *b;
*b = temp;
}
void keep(char* a, char* b)
{
return;
}
void dump(char* a, char* b)
{
return;
}
int is_file_little_endian(char* s) {
if(s[1] == -1)
{
return 0;
}
return 1;
}
void checkSpecial(char* osSrc,char* osDst, specialChar* src, specialChar* dst) {
// check which symbol of os was insert.
if (!strcmp(osSrc, "-win")) {
*src = eWin;
}
else if (!strcmp(osSrc, "-mac")) {
*src = eMac;
}
else if (!strcmp(osSrc, "-unix")) {
*src = eLinux;
}
// check which symbol of os we want to convert.
if (!strcmp(osDst, "-win")) {
*dst = eWin;
}
else if (!strcmp(osDst, "-mac")) {
*dst = eMac;
}
else if (!strcmp(osDst, "-unix")) {
*dst = eLinux;
}
}
void copyWithoutFlags(FILE* src, FILE* dst) {
char buffer[2];
size_t bytes;
// regular copy.
while( 0 < (bytes=fread(buffer, sizeof(char), 2, src))) {
fwrite(buffer, sizeof(char), bytes, dst);
}
}
//int islitel( char* buffer, int *isendline, src, dst)
//{
// int retval = 0;
// if( (buffer[0] == 0x0a || buffer[0] == 0x0d) && buffer[1] == 0x0 )
// {
// retval = 1;
// }
// else if()
//}
void copyBetweenOS(FILE* src, FILE* dst,char* osSrc, char* osDst, functionPtr pFunc) {
char buffer[2];
char temp[2];
size_t bytes;
// size_t endFile=0;
specialChar src1 = eNone;
specialChar dst1 = eNone;
checkSpecial(osSrc, osDst, &src1, &dst1);
// while (!endline){
// bytes = fread(buffer, sizeof(char), 2, src);
// endline = isendline(buffer);
// if(!endline)
// {
// pFunc(&buffer[0], &buffer[1]);
// fwrite(buffer, sizeof(char), bytes, dst);
// }
//}
bytes = fread(buffer, sizeof(char), 2, src);
if (!is_file_little_endian(buffer))
{
// big endian.
pFunc(&buffer[0],&buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
while (fread(buffer, sizeof(char), bytes, src)) {
// if()
if (src1 != dst1) {
// if the first argument of os is -win
if( (buffer[0] == 0x0a || buffer[0] == 0x0d) && buffer[1] == 0x0 )
{
}
if (src1 == eWin) {
if (buffer[1] == 0x0d) {
fread(temp, sizeof(char), bytes, src);
// we want dont lose the previous char therefore we save in temp.
if (temp[1] == 0x0a) {
buffer[0] = 0;
buffer[1] = dst1;
} else {
/* pointer to function . in mission 2 enter 'dump' function
in mission 3 we insert swap/keep function */
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
buffer[0] = temp[0];
buffer[1] = temp[1];
}
}
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
// if the second argument of os is -win
} else if (dst1 == eWin) {
// write the encoding new line to file.
if (buffer[1] == eMac || buffer[1] == eLinux) {
buffer[1] = 0x0d;
buffer[0] = 0x00;
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
buffer[1] = 0x0a;
buffer[0] = 0x00;
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
} else {
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
}
// if dst OS isn't windows
} else {
if (buffer[1] == src1) {
buffer[0] = 0;
buffer[1] = dst1;
}
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
}
}
// if src is equal to dst (same OS)
else
{
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
}
}
}
// little endian
else
{
pFunc(&buffer[0],&buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
while (fread(buffer, sizeof(char), bytes, src))
{
if(src1 != dst1) {
// if the first argument of os is -win
if (src1 == eWin) {
if (buffer[0] == 0x0d) {
fread(temp, sizeof(char), bytes, src);
// we want dont lose the previous char therefore we save in temp.
if (temp[0] == 0x0a) {
buffer[1] = 0x00;
buffer[0] = dst1;
} else {
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
buffer[0] = temp[0];
buffer[1] = temp[1];
}
}
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
// if the second argument of os is -win
} else if (dst1 == eWin) {
// write the encoding new line to file.
if (buffer[0] == eMac || buffer[0] == eLinux) {
buffer[0] = 0x0d;
buffer[1] = 0x00;
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
buffer[0] = 0x0a;
buffer[1] = 0x00;
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
} else {
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
}
}
// if dst OS isn't windows
else
{
if (buffer[0] == src1) {
buffer[1] = 0;
buffer[0] = dst1;
}
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
}
}
// if src is equal to dst (same OS)
else
{
pFunc(&buffer[0], &buffer[1]);
fwrite(buffer, sizeof(char), bytes, dst);
}
}
}
}
int main(int argc, char *argv[]) {
FILE *src = NULL;
FILE *dst = NULL;
functionPtr pFunc;
int osCount = CheckOsArgValid(argv);
int filesCount = CheckFilesArgValid(argv);
if (filesCount == 2) {
src = fopen(argv[1], "rb");
if (src == NULL) {
return 0;
}
//open dst
dst = fopen(argv[2], "wb");
if (dst == NULL) {
return 0;
}
switch (argc) {
//mission1
case 3:
copyWithoutFlags(src, dst);
break;
case 5:
// mission 2.
if (osCount == 2) {
pFunc = &dump;
if (strcmp(argv[3], argv[4]) == 0) {
copyWithoutFlags(src, dst);
} else {
copyBetweenOS(src, dst, argv[3], argv[4], dump);
}
break;
case 6:
// mission 3
{
pFunc = &dump;
if (!strcmp(argv[5], "-keep")) {
pFunc = &keep;
} else if (!strcmp(argv[5], "-swap")) {
pFunc = &swap;
}
copyBetweenOS(src, dst, argv[3], argv[4], pFunc);
}
break;
}
default:
break;
}
fclose(src);
fclose(dst);
return 0;
}
}
|
C
|
#include "user_database.h"
Node **database_link_list;
void load_data_base(){
database_link_list=create_link_list();
FILE *fin=(FILE *)fopen("account.txt","r");
if(fin==NULL){
printf("Don't exist file contain database\n");
exit(1);
return ;
}
char name[MAXLENNAME],password[MAXLENPASSWORD];
int status=-1;
while(fscanf(fin,"%s%*c%s%*c%d%*c",name,password,&status),!feof(fin)){
add_new_node(database_link_list,strdup(name),strdup(password),status);
//printf("%s,%s,%d\n",name,password,status);
}
fclose(fin);
// return database_link_list;
}
//export data from database_link_list to account.txt
void export_to_data_file(){
Node *top=(*database_link_list);
FILE* fout=fopen("account.txt","w");
while(top!=NULL){
fprintf(fout,"%s %s %d\n",top->name,top->password,top->status);
top=top->next;
}
fclose(fout);
}
//check all character in string s is number or not
// find user info in database
//user: [out]point to save the user info
//name: [in] user id
//return value: -1 if not found user id,-2 if account is block,-3 if account is already sign-in in at least one process
int search_userid(Node**user,char *name){
Node *searchresult=search(database_link_list,name);
if (searchresult==NULL){
*user=NULL;
return -1;
}
else if (searchresult->status==0){
*user=NULL;
return -2;
}
// check if account is already sign-in yet or not
if (searchresult!=NULL && searchresult->islogin==1){
*user=NULL;
return -3;
}
*user=searchresult;
}
|
C
|
//Jay Shah
//1-9-20
//Lab 1 Part 2
//implements quantitative comparisons between circuit switching and packet switching
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double fact(int);
int main(int argc, char *argv[]){
double linkBandwidth =atoi(argv[1]);
double userBandwidth = atoi(argv[2]);
double tPSuser = atof(argv[3]);
double nPSusers = atoi(argv[4]);
double nCSusers = linkBandwidth/userBandwidth;
printf("%lf circuit switched users are supported\n" ,nCSusers);
double pPSusers = tPSuser;
printf("%lg is the probability that a user is busy trasnmiting\n" ,pPSusers);
double pPSusersNotBusy = 1-pPSusers;
printf("%lg is the probability that one specific other user is not busy\n",pPSusersNotBusy);
double all = pow((1-pPSusers),(nPSusers-1));
printf("%lg is the probability that all of the other specific other users are not busy\n",all);
double one_user = pPSusers*(pow(pPSusersNotBusy,(nPSusers-1)));
printf("%lg is the probability that one user is transmitting and remaining users are not transmitting\n",one_user);
double exact = nPSusers*pPSusers*(pow(pPSusersNotBusy,(nPSusers-1)));
printf("%lg is the probability that exactly one of the nPSusers is busy\n",exact);
double ten = (pow(pPSusers,10))*(pow(pPSusersNotBusy,(nPSusers-10)));
printf("%lg is the probability that 10 specific users of nPSusers are transmitting and the others are idle\n",ten);
double binomial_coeff = ((fact(nPSusers))/((fact(10))*(fact(nPSusers- 10))));
binomial_coeff = binomial_coeff*(pow(pPSusers,10))*(pow(pPSusersNotBusy,nPSusers-10));
printf("%lg is the probability that any 10 users of nPSusers are transmitting and the others are idle\n",binomial_coeff);
int i;
double prob1=0;
for(i=11;i<nPSusers;i++) {
prob1 += fact(nPSusers)/(fact(i)*fact(nPSusers-i))*pow(pPSusers, i) * pow(pPSusersNotBusy,nPSusers-i);
}
printf("%lg is the probability that more than 10 users of nPSusers are transmitting and the others are idle\n",prob1);
return 0;
}
double fact(int n) {
if(n>=1)
return n*fact(n-1);
else
return 1;
}
|
C
|
/* Max Schweitzer
ECE 373
Homework 3 - PCI LED Driver
This code implements a user space program to
test a basic PCI driver that can blink an LED.
4/22/18
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#define LENGTH 256
#define LED0_MASK 0x0000000F
int main()
{
int fd;
uint32_t toSend = 0;
uint32_t toRead = 0;
fd = open("/dev/hw3_pci", O_RDWR);
if (fd < 0)
{
printf("Open error: %d\n", fd);
return 1;
}
int ret;
// First, lets read the current value.
ret = read(fd, &toRead, sizeof(uint32_t));
if (ret < 0)
{
printf("Error reading");
return 1;
}
printf("Was read: 0x%08x\n", toRead);
// Turn on LED0
toSend = 0;
// Read, modify, write so we don't clobber reserved bits.
toRead = toRead & (~LED0_MASK);
toSend = toRead | 0x0000000e;
printf("Will write: 0x%08x\n", toSend);
ret = write(fd, &toSend, sizeof(uint32_t));
if (ret < 0)
{
printf("Error writing!");
return 1;
}
// Overwrite before we read again.
toRead = 0;
ret = read(fd, &toRead, sizeof(uint32_t));
if (ret < 0)
{
printf("Error reading");
return 1;
}
printf("Was read after write: 0x%08x\n", toRead);
sleep(2);
// Turn off LED0
toSend = 0;
// Read modify write
toRead = toRead & (~LED0_MASK);
toSend = toRead | 0x0000000f;
printf("Will write: 0x%08x\n", toSend);
ret = write(fd, &toSend, sizeof(uint32_t));
if (ret < 0)
{
printf("Error writing!");
return 1;
}
ret = close(fd);
return ret;
}
|
C
|
/*******************************************************
uOLED-160-GMD1 Driver for Arduino
Code: Oscar Gonzalez
August 2007
www.bricogeek.com
*******************************************************/
#define OLED_BAUDRATE 9600//57600
#define OLED_RESETPIN 8 // PIN of reset
#define OLED_INITDELAYMS 5000
// Initialisation routine
#define OLED_DETECT_BAUDRATE 0x55
// Drawing routines
#define OLED_CLEAR 0x45
#define OLED_BKGCOLOR 0x42
#define OLED_COPYPASTE 0x63
#define OLED_LINE 0x4C
#define OLED_CIRCLE 0x43
#define OLED_CIRCLEFILL 0x69
#define OLED_PUTPIXEL 0x50
#define OLED_READPIXEL 0x52
#define OLED_RECTANGLE 0x72
#define OLED_PAINTAREA 0x70
// Text properties
#define OLED_SETFONTSIZE 0x46
#define OLED_FONT5X7 0x01
#define OLED_FONT8X8 0x02
#define OLED_FONT8X12 0x03
#define OLED_TEXTFORMATED 0x54
// OLED Control
#define OLED_COMMAND_CONTROL 0x59
#define OLED_COMMAND_DISPLAY 0x01
#define OLED_COMMAND_CONTRAST 0x02
#define OLED_COMMAND_POWER 0x03
#define OLED_ACK 0x06 // Ok
#define OLED_NAK 0x15 // Error
void OLED_ResetDisplay()
{
digitalWrite(OLED_RESETPIN, LOW);
delay(20);
digitalWrite(OLED_RESETPIN, HIGH);
delay(20);
}
char OLED_GetResponse()
{
byte incomingByte = OLED_ACK;
// Wait for data avaliable
while (!Serial.available()) { delay(1); }
// Read incoming byte
incomingByte = Serial.read();
return incomingByte;
}
// Initialise OLED display. You must first activate a serial comunication!
void OLED_Init()
{
// First reset display
OLED_ResetDisplay();
delay(OLED_INITDELAYMS); // Wait for init
// Autodetect baudrate
printByte(OLED_DETECT_BAUDRATE);
OLED_GetResponse();
}
// Get 16bits value from RGB (0 to 63, 565 format)
int GetRGB(int red, int green, int blue)
{
char text[255];
int outR = ((red * 31) / 255);
int outG = ((green * 63) / 255);
int outB = ((blue * 31) / 255);
return (outR << 11) | (outG << 5) | outB;
}
void OLED_Clear()
{
printByte(OLED_CLEAR); // Pixel write
delay(20);
OLED_GetResponse();
}
void OLED_PutPixel(char x, char y, int color)
{
// Putpixel
printByte(OLED_PUTPIXEL); // Pixel write
printByte(x); // x
printByte(y);
// Color
printByte(color >> 8); // MSB
printByte(color & 0xFF); // LSB
OLED_GetResponse();
}
void OLED_DrawLine(char x1, char y1, char x2, char y2, int color)
{
// Line drawing
printByte(OLED_LINE); // Line
printByte(x1); // x1
printByte(y1); // y1
printByte(x2); // x2
printByte(y2); // y2
// Color
printByte(color >> 8); // MSB
printByte(color & 0xFF); // LSB
OLED_GetResponse();
}
void OLED_DrawRectangle(char x, char y, char width, char height, char filled, int color)
{
//int color = 0xFFFF;
// Rectangle drawing
printByte(OLED_RECTANGLE);
printByte(x); // x1
printByte(y); // y1
printByte(x+width); // x2
printByte(y+height); // y1
// Color
printByte(color >> 8); // MSB
printByte(color & 0xFF); // LSB
/*
if (filled == 1) { printByte(0x01); } // Filled
else { printByte(0x00); } // Outline
*/
OLED_GetResponse();
}
void OLED_DrawCircle(char x, char y, char radius, char filled, int color)
{
printByte(OLED_CIRCLE);
printByte(x); // x
printByte(y); // y
printByte(radius); // radius
// Color
printByte(color >> 8); // MSB
printByte(color & 0xFF); // LSB
OLED_GetResponse();
}
/*
Change font format:
FontType can be:
OLED_FONT5X7
OLED_FONT8X8
OLED_FONT8X12
*/
void OLED_SetFontSize(char FontType)
{
printByte(OLED_SETFONTSIZE);
printByte(FontType);
OLED_GetResponse();
}
void OLED_DrawText(char column, char row, char font_size, char *mytext, int color)
{
//char mytext[] = "Arkanoid by pK";
printByte(0x73); // s (Formated text)
//printByte(column); // column
// Adjust to center of the screen (26 Columns at font size 0)
int newCol = 13 - (strlen(mytext)/2);
//printByte(newCol); // column
printByte(column); // column
printByte(row); // row
printByte(font_size); // font size (0 = 5x7 font, 1 = 8x8 font, 2 = 8x12 font)
// Color
printByte(color >> 8); // MSB
printByte(color & 0xFF); // LSB
for (int i=0 ; i<strlen(mytext) ; i++)
{
printByte(mytext[i]); // character to write
}
printByte(0x00); // string terminator (always 0x00)
OLED_GetResponse();
}
void OLED_DrawSingleChar(char column, char row, char font_size, char MyChar, int color)
{
printByte(OLED_TEXTFORMATED); // T (Formated)
printByte(MyChar);
printByte(column);
printByte(row);
// Color
printByte(color >> 8); // MSB
printByte(color & 0xFF); // LSB
OLED_GetResponse();
}
|
C
|
//12864ʱʵ
///**************************************/
#include<reg51.h>
#include<intrins.h>
#include "QC12864B.h"
/**************************************/
#define uchar unsigned char
#define uint unsigned int
//˿ڶ
sbit LCD_CS=P2^6;
sbit LCD_SID=P2^5; //
sbit LCD_SCLK=P2^7; //ʱ
sbit LCD_RST=P3^4;
sbit LCD_PSB=P3^2;
uchar code table1[]={"**˫ģ**"}; //Ҫʾַ
uchar code table2[]={"ٶ--·--ʱ"};
/**************************************/
//ʱ
/**************************************/
void Delay_ms(uchar n)
{
uchar i;
uchar j;
for(i=0;i<n;i++)
for(j=0;j<125;j++) //1ms
_nop_();
}
/**************************************/
//зһֽ
/**************************************/
void LCD_sendbyte(uchar byte)
{
uchar i;
for(i=0;i<8;i++)
{
LCD_SCLK=0; //ʱ
_nop_();
LCD_SID=(bit)(byte&0x80); //λ
LCD_SCLK=1; //ط
byte=byte<<1; //һλ
}
}
/****************************************/
//дָ
/****************************************/
void LCD_write_com(uchar com)
{
LCD_CS=1;
LCD_sendbyte(0xf8); //5ġ1һ,11111,RW(0),RS(0),0
LCD_sendbyte(0xf0&com); //ȡλݷδͣ
//ÿֽڵݱֽ
//λڵһֽڵĸλ
LCD_sendbyte(0xf0&(com<<4)); //λڵڶֽڵĸλ
LCD_CS=0;
Delay_ms(10); //вֶ֧ɼæʱ
}
/******************************************/
//д
/******************************************/
void LCD_write_dat(uchar dat)
{
LCD_CS=1;
LCD_sendbyte(0xfa); //5ġ1һ,11111,RW(0),RS(1),0
LCD_sendbyte(0xf0&dat); //ȡλݷδͣ
//ÿֽڵݱֽ
//λڵһֽڵĸλ
LCD_sendbyte(0xf0&(dat<<4)); //λڵڶֽ
LCD_CS=0;
Delay_ms(10);
}
/********************************************/
//LCDʼ
/********************************************/
void LCD_init(void)
{
Delay_ms(5);
LCD_RST=1;
LCD_RST=0;
LCD_RST=1;
LCD_PSB=0;
LCD_write_com(0x30); //ѡָ
LCD_write_com(0x0c); //ʾα꣬
LCD_write_com(0x01); //ʾĻDDRAMλַΪ00H
Delay_ms(5); //ʱϳ1.6ms ˼Ӵʱ
LCD_write_com(0x02); //DDRAMλַλ,˴òظ
LCD_write_com(0x06); //趨ƣʾƶ
}
/***************************************************/
//ʾַ
/***************************************************/
void LCD_Setaddress(uchar x,uchar y)
{ //ַӵ1е1пʼ0ʼ
uchar addr;
switch(x)
{
case 1: addr=0x80+y-1;
break;
case 2: addr=0x90+y-1;
break;
case 3: addr=0x88+y-1;
break;
case 4: addr=0x98+y-1;
break;
default : break;
}
LCD_write_com(addr); //ַʾʼַ
}
/*****************************************************/
//ַʾڹ̶λ
/*****************************************************/
void LCD_Putstring( uchar x, uchar y, uchar *pData )
{
LCD_Setaddress(x,y);
while( *pData != '\0' )
{
LCD_write_dat( *pData++ );
}
}
void LCD_Putuint( uchar x, uchar y, uint z )
{
if(z<100)
{
uchar z1,z2;
z1=z/10;
z2=z%10;
LCD_Setaddress(x,y);
LCD_write_dat( 0x30);
LCD_write_dat( 0x30+z1 );
LCD_write_dat( 0x30+z2 );
}
else
if(z>99&&z<999)
{
uchar z1,z2,z3;
z1=z/100;
z2=z%100/10;
z3=z%100%10;
LCD_Setaddress(x,y);
LCD_write_dat( 0x30+z1 );
LCD_write_dat( 0x30+z2 );
LCD_write_dat( 0x30+z3);
}
else
LCD_Putstring(x,y,"ʱ");
}
void LCD_Putfloatv( uchar x, uchar y, float z )
{
uchar z1,z2;
z1=(uchar)z;
z2=(z-z1)*10;
if(z>=10)
{
LCD_Putstring(x,y,"");
}
else
{
LCD_Setaddress(x,y);
LCD_write_dat( 0x30+z1 );
LCD_write_dat( 0x2e );
LCD_write_dat( 0x30+z2 );
}
}
void LCD_Putfloats( uchar x, uchar y, float z )
{
if(z>=20)
{
LCD_Putstring(x,y,"");
}
else
{
uchar z0,z1,z2,z3;
z0=z*10;
z1=z0/100;
z2=(z0%100)/10;
z3=(z0%100)%10;
LCD_Setaddress(x,y);
LCD_write_dat(0x30+z1);
LCD_write_dat(0x30+z2);
LCD_write_dat(0x2e);
LCD_write_dat(0x30+z3);
}
}
void LCDinit(void)
{
LCD_init();
LCD_Putstring(1,2,table1);
LCD_Putstring(2,1,table2);
LCD_Putstring(3,1,"A:");
LCD_Putstring(4,1,"B:");
LCD_Putstring(3,8," s");
LCD_Putstring(4,8," s");
}
void receiveA(float Av,float As,uint At)
{
LCD_Putfloatv(3,2,Av);
LCD_Putfloats(3,4,As);
LCD_Putuint(3,7,At);
}
void receiveB(float Bv,float Bs,uint Bt)
{
LCD_Putfloatv(4,2,Bv);
LCD_Putfloats(4,4,Bs);
LCD_Putuint(4,7,Bt);
}
|
C
|
#include<stdio.h>
#include<stdint.h>
#include<inttypes.h>
int main()
{
int i;
int32_t i32; //32 bit integer
int_least8_t i8; //smallest 8 bit
int_fast8_t imax; //fastest minimum
uintmax_t uimax; //biggest signed integers
i32 = 1004; //biggest unsigned inter
printf("me32 = %d\n", i32);
printf("me32 = %" "d" "\n", i32);
printf("me32 = %" PRId32 "\n", i32); //ũ ü
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int array[101], b[101], n, l=0;
printf("Input n: ");
scanf("%d", &n);
for (int i=0; i<=n; i++)
{
printf("Input array[%d]: ",i);
scanf("%d",&array[i]);
}
for (int i=0; i<=n; i++)
{
if (array[i]%2 == 0)
{
l++;
b[l] = i;
printf("%d ",b[l]);
}
}
printf("\n");
return 0;
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
#include <errno.h>
#define N 128
int main(int argc,const char* argv[])
{
int sockfd;
int acceptfd;
int ret_recv;
int on=1;
struct sockaddr_in serveraddr,clientaddr;
char buf[N];
int bufer_size;
if(argc <3)
{
fprintf(stderr,"Usage:%s <serverip> <port>\n",argv[0]);
exit(EXIT_FAILURE);
}
if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) <0)
{
perror("fail to socket\n");
exit(EXIT_FAILURE);
}
serveraddr.sin_family=AF_INET;
serveraddr.sin_addr.s_addr=inet_addr(argv[1]);
serveraddr.sin_port=htons(atoi(argv[2]));
socklen_t addrlen=sizeof(struct sockaddr);
socklen_t optlen=sizeof(int);
/* if((getsockopt(acceptfd, SOL_SOCKET, SO_SNDBUF,&bufer_size, &optlen)) <0)
{
perror("fail to getsockopt\n");
exit(EXIT_FAILURE);
}
*/
struct timeval tv;
tv.tv_sec=2;
tv.tv_usec=0;
if((setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST,&on,optlen)) < 0)
{
perror("fial to setsockopt\n");
exit(EXIT_FAILURE);
}
while(1)
{
/*
ret_recv = recvfrom(sockfd, buf, strlen(buf), 0,(struct sockaddr*)&clientaddr, &addrlen);
if(ret_recv <0)
{
perror("fail to recv\n");
exit(EXIT_FAILURE);
}
printf("server:%s\n",buf);
if(strncmp(buf,"quit",4) == 0)
{
break;
}
strcat(buf,"hello ");
*/
printf("server:");
fgets(buf, N, stdin);
buf[strlen(buf)-1] = '\0';
if(sendto(sockfd, buf, strlen(buf),0, (struct sockaddr*)&serveraddr,addrlen) < 0 )
{
perror("fail to send\n");
exit(EXIT_FAILURE);
}
}
return 0;
}
|
C
|
/* Author: Pierre-Jerome Bergeron
This is the Vardi EM algorithm from Biometrika (1989).
Provided as is. If you publish something using this code, please make sure to mention me....
*/
//This little function counts the number of time each unique entry appears
//in a sorted vector
void countsorted (double *x, int *nx, double *y) {
int i, j=0;
y[0]=1;
for (i=1; i<*nx; i++) {
if (x[i]==x[i-1]) y[j]++;
else {j++; y[j]=1;}
}
}
//These functions are going to be used at some point
void insert_value(double *value, double *superset, int *nx, double *subset, int *ny, double *f, double *results) {
int i, j=0;
for (i=0; i<*nx; i++) {
if (j<*ny) {
if (superset[i]==subset[j]) {
results[i]=f[j];
j++;
}
else results[i]=value[0];
}
else results[i]=value[0];
}
}
//This is the Vardi algorithm coded in C
void vardir(double *x, double *y, int *m, int *n, double *tj, int *h,
int *maxiter, double *tol, double *pvec, int *iter,
double *xu, int *mx, double *yu, int *ny){
int i,j, finished=0;
double pold[h[0]],pnew[*h],val=0.0;
double xcounts[mx[0]], ycounts[ny[0]],txcounts[h[0]], tycounts[h[0]];
double tcounts[h[0]], tpk[h[0]],temp,tmp;
for (i=0;i<*mx;i++) {
xcounts[i]=0.0;
}
for (i=0;i<*ny;i++) {
ycounts[i]=0.0;
}
for (i=0;i<*h;i++) {
txcounts[i]=0.0;
tycounts[i]=0.0;
}
/*Initializing xcounts, ycounts, tcounts, pold */
countsorted(x,m,xcounts);
countsorted(y,n,ycounts);
iter[0]=0;
insert_value(&val,tj,h,xu,mx,xcounts,txcounts);
insert_value(&val,tj,h,yu,ny,ycounts,tycounts);
for (i=0;i<*h;i++) {
tcounts[i]=txcounts[i]+tycounts[i];
pold[i]=tcounts[i]/h[0];
}
while ((iter[0]<maxiter[0]) && (!finished)) {
temp=0.0;
for (j=h[0];j>0;j--) {
temp+=pold[j-1]/tj[j-1];
tpk[j-1]=tycounts[j-1]/temp;
} //for j in h:1
temp=0.0;
for (j=0;j<*h;j++) {
temp+=tpk[j];
pnew[j]=(1.0/(m[0]+n[0]))*(txcounts[j]+(1.0/tj[j])*pold[j]*temp);
}
tmp=0.0;
for (j=0;j<*h;j++) {
if (pold[j]<pnew[j])
tmp+=pnew[j]-pold[j];
else
tmp+=pold[j]-pnew[j];
}
if (tmp<*tol) finished=1;
for (j=0;j<*h;j++) {
pold[j]=pnew[j];
}
iter[0]++;
} //while
for (j=0;j<h[0];j++) pvec[j]=pnew[j];
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Persona.h"
#include "Pregunta.h"
Persona* personas;
Pregunta* preguntas;
void histogramaFrecuencia();
void histogramaEdad();
int main()
{
int NUM_PERS = 10;
int NUM_PREG = 10;
int NUM_RESP = 6;
int i,j,k;
personas = (Persona*)malloc(NUM_PERS*sizeof(Persona));
Persona_construc(personas,"Erick",60);
Persona_construc(personas+1,"Ale",20);
Persona_construc(personas+2,"Juan",18);
Persona_construc(personas+3,"Andres",38);
Persona_construc(personas+4,"Vero",110);
Persona_construc(personas+5,"Jaime",42);
Persona_construc(personas+6,"Ruben",21);
Persona_construc(personas+7,"Carolina",76);
Persona_construc(personas+8,"Mike",35);
Persona_construc(personas+9,"John",50);
preguntas = (Pregunta*)malloc(NUM_PREG*sizeof(Pregunta));
//Inicializar preguntas
for (j = 0; j < NUM_PREG; j++){
char* nombre = (char*)malloc(20*sizeof(char));
sprintf(nombre,"Pregunta %i", (j+1));
Pregunta_construc(preguntas+j,nombre);
for(i = 0; i < NUM_RESP; i++){
char nombre2[20];
sprintf(nombre2,"Respuesta %i de %i", &i,&j);
Pregunta_setRespuestaTxt(preguntas+j,i,nombre2);
}
}
//Respuestas random
for (j = 0; j < NUM_PERS; j++){
for (i = 0; i < NUM_PREG; i++){
srand (time(NULL)+i+j);
Persona_setRespuesta(personas+j,i,rand()%5);
}
}
//Imprimir histograma
int temp;
for (k = 0; k < NUM_PREG; k++){
printf("Pregunta %i \n", (k+1));
for (j = 0; j < NUM_RESP; j++){
printf(" %i ", (j+1));
temp = 0;
for (i = 0; i < NUM_PERS; i++){
int* res = (personas+i)->res;
if (*(res+k) == j){
temp++;
}
}
printf("(%i) ", temp);
for (i = 0; i < temp; i++)
printf("*");
printf("\n");
}
}
//Imprimir histograma edades
int r1,r2,r3,r4,r5;
for (k = 0; k < NUM_PREG; k++){
printf("Pregunta %i \n", (k+1));
for (j = 0; j < NUM_RESP; j++){
printf(" %i ", (j+1));
r1 = r2 = r3 = r4 = r5 = 0;
temp = 0;
for (i = 0; i < NUM_PERS; i++){
int* res = (personas+i)->res;
if (*(res+k) == j){
temp++;
int edad = (personas+i)->edad;
if (edad >= 18 && edad <= 25) r1++;
if (edad >= 26 && edad <= 35) r2++;
if (edad >= 36 && edad <= 45) r3++;
if (edad >= 46 && edad <= 65) r4++;
if (edad >= 65 && edad <= 120) r5++;
}
}
printf("(%i)\n",temp);
printf(" 18 - 25 ");
for (i = 0; i < r1; i++) printf("*");
printf("\n");
printf(" 26 - 35 ");
for (i = 0; i < r2; i++) printf("*");
printf("\n");
printf(" 36 - 45 ");
for (i = 0; i < r3; i++) printf("*");
printf("\n");
printf(" 46 - 65 ");
for (i = 0; i < r4; i++) printf("*");
printf("\n");
printf(" 65 - 120 ");
for (i = 0; i < r5; i++) printf("*");
printf("\n");
}
}
return 0;
}
|
C
|
#include <gtk/gtk.h>
/* Surface to store current scribbles */
static cairo_surface_t *surface = NULL;
static void
clear_surface(void)
{
cairo_t *cr;
cr = cairo_create(surface);
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_paint(cr);
cairo_destroy(cr);
}
/* Create a new surface of the appropriate size to store our scribbles */
static gboolean
configure_event_cb(GtkWidget *widget,
GdkEventConfigure *event,
gpointer data)
{
if (surface)
cairo_surface_destroy(surface);
surface = gdk_window_create_similar_surface(gtk_widget_get_window(widget),
CAIRO_CONTENT_COLOR,
gtk_widget_get_allocated_width(widget),
gtk_widget_get_allocated_height(widget));
/* Initialize the surface to white */
clear_surface();
/* We've handled the configure event, no need for further processing. */
return TRUE;
}
/* Redraw the screen from the surface. Note that the ::draw
* signal receives a ready-to-be-used cairo_t that is already
* clipped to only draw the exposed areas of the widget
*/
static gboolean
draw_cb(GtkWidget *widget,
cairo_t *cr,
gpointer data)
{
cairo_set_source_surface(cr, surface, 0, 0);
cairo_paint(cr);
return FALSE;
}
/* Draw a rectangle on the surface at the given position */
static void
draw_brush(GtkWidget *widget,
gdouble x,
gdouble y)
{
cairo_t *cr;
/* Paint to the surface, where we store our state */
cr = cairo_create(surface);
cairo_rectangle(cr, x - 3, y - 3, 6, 6);
cairo_fill(cr);
cairo_destroy(cr);
/* Now invalidate the affected region of the drawing area. */
gtk_widget_queue_draw_area(widget, x - 3, y - 3, 6, 6);
}
/* Handle button press events by either drawing a rectangle
* or clearing the surface, depending on which button was pressed.
* The ::button-press signal handler receives a GdkEventButton
* struct which contains this information.
*/
static gboolean
button_press_event_cb(GtkWidget *widget,
GdkEventButton *event,
gpointer data)
{
/* paranoia check, in case we haven't gotten a configure event */
if (surface == NULL)
return FALSE;
if (event->button == GDK_BUTTON_PRIMARY)
{
draw_brush(widget, event->x, event->y);
}
else if (event->button == GDK_BUTTON_SECONDARY)
{
clear_surface();
gtk_widget_queue_draw(widget);
}
/* We've handled the event, stop processing */
return TRUE;
}
/* Handle motion events by continuing to draw if button 1 is
* still held down. The ::motion-notify signal handler receives
* a GdkEventMotion struct which contains this information.
*/
static gboolean
motion_notify_event_cb(GtkWidget *widget,
GdkEventMotion *event,
gpointer data)
{
/* paranoia check, in case we haven't gotten a configure event */
if (surface == NULL)
return FALSE;
if (event->state & GDK_BUTTON1_MASK)
draw_brush(widget, event->x, event->y);
/* We've handled it, stop processing */
return TRUE;
}
static void
close_window(void)
{
if (surface)
cairo_surface_destroy(surface);
}
static void
activate(GtkApplication *app,
gpointer user_data)
{
GtkWidget *window;
GtkWidget *frame;
GtkWidget *drawing_area;
window = gtk_application_window_new(app);
gtk_window_set_title(GTK_WINDOW(window), "Drawing Area");
g_signal_connect(window, "destroy", G_CALLBACK(close_window), NULL);
gtk_container_set_border_width(GTK_CONTAINER(window), 8);
frame = gtk_frame_new(NULL);
gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN);
gtk_container_add(GTK_CONTAINER(window), frame);
drawing_area = gtk_drawing_area_new();
/* set a minimum size */
gtk_widget_set_size_request(drawing_area, 100, 100);
gtk_container_add(GTK_CONTAINER(frame), drawing_area);
/* Signals used to handle the backing surface */
g_signal_connect(drawing_area, "draw",
G_CALLBACK(draw_cb), NULL);
g_signal_connect(drawing_area, "configure-event",
G_CALLBACK(configure_event_cb), NULL);
/* Event signals */
g_signal_connect(drawing_area, "motion-notify-event",
G_CALLBACK(motion_notify_event_cb), NULL);
g_signal_connect(drawing_area, "button-press-event",
G_CALLBACK(button_press_event_cb), NULL);
/* Ask to receive events the drawing area doesn't normally
* subscribe to. In particular, we need to ask for the
* button press and motion notify events that want to handle.
*/
gtk_widget_set_events(drawing_area, gtk_widget_get_events(drawing_area) | GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK);
gtk_widget_show_all(window);
}
int main(int argc,
char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE);
g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
status = g_application_run(G_APPLICATION(app), argc, argv);
g_object_unref(app);
return status;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lista.h"
#include "formaC.h"
#include "formaL.h"
#include "formaR.h"
#include "formaT.h"
#include "hidrante.h"
#include "quadra.h"
#include "radio.h"
#include "semaforo.h"
typedef struct no{
void *elemento;
struct no *ant;
struct no *prox;
}No;
typedef struct lista{
No *primeiro;
No *ultimo;
}Lista;
typedef struct listacidade{
listaStruct listaQuadras;
listaStruct listaRadios;
listaStruct listaSemaforos;
listaStruct listaHidrantes;
listaStruct listaCirculos;
listaStruct listaLinhas;
listaStruct listaRetangulos;
listaStruct listaTexto;
}listaCidade;
listaStruct criaLista(){
Lista *lista = (Lista*)malloc(sizeof(Lista));
lista->primeiro = NULL;
lista->ultimo = NULL;
return lista;
}
Cidade criaCidade(){
listaCidade *lista;
lista = (listaCidade*)malloc(sizeof(listaCidade));
lista->listaQuadras = criaLista();
lista->listaRadios = criaLista();
lista->listaSemaforos = criaLista();
lista->listaHidrantes = criaLista();
lista->listaCirculos = criaLista();
lista->listaLinhas = criaLista();
lista->listaRetangulos = criaLista();
lista->listaTexto = criaLista();
return lista;
}
Cidade getListaQuadras(Cidade lista){
listaCidade *list = (listaCidade*)lista;
return list->listaQuadras;
}
Cidade getListaRadios(Cidade lista){
listaCidade *list = (listaCidade*)lista;
return list->listaRadios;
}
Cidade getListaSemaforos(Cidade lista){
listaCidade *list = (listaCidade*)lista;
return list->listaSemaforos;
}
Cidade getListaHidrantes(Cidade lista){
listaCidade *list = (listaCidade*)lista;
return list->listaHidrantes;
}
Cidade getListaCirculos(Cidade lista){
listaCidade *list = (listaCidade*)lista;
return list->listaCirculos;
}
Cidade getListaLinhas(Cidade lista){
listaCidade *list = (listaCidade*)lista;
return list->listaLinhas;
}
Cidade getListaRetangulos(Cidade lista){
listaCidade *list = (listaCidade*)lista;
return list->listaRetangulos;
}
Cidade getListaTexto(Cidade lista){
listaCidade *list = (listaCidade*)lista;
return list->listaTexto;
}
listaStruct insereElemento(listaStruct lista, tipo elemento){
Lista *list = (Lista*)lista;
No* node = (No*)malloc(sizeof(No));
node->elemento = elemento;
if(list->primeiro == NULL){ /*se a lista esta vazia*/
node->ant = NULL; /*o anterior aponta para null*/
list->primeiro = node; /*o primeiro elemento da lista é node*/
}
else{ /*senao*/
list->ultimo->prox = node; /*o prox do ultimo elemento adicionado aponta para o novo node*/
node->ant = list->ultimo; /*o ponteiro de anterior aponta pro ultimo elemento adicionado*/
}
node->prox = NULL;
list->ultimo = node;
return list;
}
listaStruct insertBefore(listaStruct lista, tipo elemento, tipo elemento_2){
Lista *list = (Lista*)lista;
No* node = (No*)malloc(sizeof(No));
node->elemento = elemento;
No* inicio = list->primeiro;
No *aux_1;
No *aux_2;
while (inicio != NULL){
if(inicio == elemento_2){
if(inicio == list->primeiro){
aux_1 = inicio;
aux_1->ant = node;
node->prox = aux_1;
node->ant = NULL;
list->primeiro = node;
return list;
}
else if(inicio!= list->primeiro){
aux_1 = inicio;
aux_2 = inicio->ant;
node->ant = aux_2;
node->prox = aux_1;
aux_1->ant = node;
aux_2->prox = node;
return list;
}
}
inicio = inicio->prox;
}
return NULL;
}
listaStruct insertAfter(listaStruct lista, tipo elemento, tipo elemento_2){
Lista *list = (listaStruct)lista;
No* node = (No*)malloc(sizeof(No));
node->elemento = elemento;
No *inicio = list->primeiro;
No *aux_1;
No *aux_2;
while(inicio != NULL){
if(inicio == elemento_2){
if(inicio == list->ultimo){
aux_1 = inicio;
aux_1->prox = node;
node->prox = NULL;
node->ant = aux_1;
list->ultimo = node;
return list;
}
else if(inicio!= list->ultimo){
aux_1 = inicio;
aux_2 = inicio->prox;
aux_1->prox = node;
aux_2->ant = node;
node->ant = aux_1;
node->prox = aux_2;
return list;
}
}
inicio = inicio->prox;
}
return NULL;
}
void removeElemento(listaStruct l, tipo elemento){
Lista* lista = (Lista*) l;
No *aux, *aux2;
aux = lista->primeiro;
while (aux!=NULL){
if(aux->elemento == elemento){
if (aux==lista->primeiro){
lista->primeiro = aux->prox;
lista->primeiro->ant = NULL;
}
if(aux==lista->ultimo){
lista->ultimo = aux->ant;
lista->ultimo->prox = NULL;
}
aux2 = aux->prox;
aux2->ant = aux->ant;
if(aux->ant!=NULL){
aux->ant->prox = aux2;
}
free(aux->elemento);
free(aux);
break;
}
aux = aux->prox;
}
}
void liberaLista(listaStruct lista){
Lista *list = (Lista*)lista;
No *node = list->primeiro;
No *aux;
while(node != NULL){
aux = node->prox;
free(node->elemento);
free(node);
node = aux;
}
free(lista);
}
Node getFirst(listaStruct lista){
Lista *list = (Lista*)lista;
No *node = list->primeiro;
if(list->primeiro == NULL){
return NULL;
}
return node;
}
Node getLast(listaStruct lista){
Lista *list = (Lista*)lista;
No *node = list->ultimo;
if(list->ultimo == NULL){
return NULL;
}
return node;
}
Node getPrevious(Node elemento){
No* node = (No*)elemento;
return node->ant;
}
Node getNext(Node elemento){
No* node = (No*)elemento;
return node->prox;
}
tipo getElemento(Node elemento){
No *node = (No*)elemento;
return node->elemento;
}
void imprimeLista(listaStruct l, char c){
Lista *list = (Lista*)l;
No *node = list->primeiro;
while(node != NULL){
if(c == 'r'){
printf("%s, %lf, %lf, %s, %s\n", getRadioId(getElemento(node)), getRadioX(getElemento(node)), getRadioY(getElemento(node)), getRadioCFill(getElemento(node)), getRadioCStroke(getElemento(node)));
}
else if(c == 'h'){
printf("%s, %lf, %lf, %s, %s\n", getHidranteId(getElemento(node)), getHidranteX(getElemento(node)), getHidranteY(getElemento(node)), getHidranteCFill(getElemento(node)), getHidranteCStroke(getElemento(node)));
}
else if(c == 'q'){
printf("%s, %lf, %lf, %lf, %lf,%s, %s\n", getQuadraCep(getElemento(node)), getQuadraX(getElemento(node)), getQuadraY(getElemento(node)), getQuadraW(getElemento(node)), getQuadraH(getElemento(node)), getQuadraCFill(getElemento(node)), getQuadraCStroke(getElemento(node)));
}
else if(c == 's'){
printf("%s, %lf, %lf, %s, %s\n", getSemaforoId(getElemento(node)), getSemaforoX(getElemento(node)), getSemaforoY(getElemento(node)), getSemaforoCFill(getElemento(node)), getSemaforoCStroke(getElemento(node)));
}
else if(c == 'c'){
printf("%d, %lf, %lf, %lf, %s, %s\n", getCirculoId(getElemento(node)), getCirculoR(getElemento(node)), getCirculoX(getElemento(node)), getCirculoY(getElemento(node)), getCirculoCorb(getElemento(node)), getCirculoCorp(getElemento(node)));
}
else if(c == 'a'){
printf("%d, %lf, %lf, %lf, %lf, %s, %s\n", getRetanguloId(getElemento(node)), getRetanguloW(getElemento(node)), getRetanguloH(getElemento(node)), getRetanguloX(getElemento(node)), getRetanguloY(getElemento(node)), getRetanguloCorb(getElemento(node)), getRetanguloCorp(getElemento(node)));
}
else if(c == 't'){
printf("%d, %lf, %lf, %s, %s, %s\n", getTextoId(getElemento(node)), getTextoX(getElemento(node)), getTextoY(getElemento(node)), getTextoCorb(getElemento(node)), getTextoCorp(getElemento(node)), getTextoText(getElemento(node)));
}
node = node->prox;
}
}
int tamanhoLista(listaStruct lista){
Lista *list = (Lista*)lista;
int tamanho = 0;
No *node = list->primeiro;
while(node != NULL){
tamanho += 1;
node = node->prox;
}
return tamanho;
}
Node comparaIdH(Cidade listacidade, char *id){
listaStruct listH = getListaHidrantes(listacidade);
Node no = getFirst(listH);
tipo elemento;
do{
elemento = getElemento(no);
if(strcmp(getHidranteId(elemento), id) == 0){
return elemento;
}
no = getNext(no);
}while(no != NULL);
return NULL;
}
Node comparaIdQ(Cidade listacidade, char *id){
listaStruct listQ = getListaQuadras(listacidade);
Node no = getFirst(listQ);
tipo elemento;
do{
elemento = getElemento(no);
if(strcmp(getQuadraCep(elemento), id) == 0){
return elemento;
}
no = getNext(no);
}while(no != NULL);
return NULL;
}
Node comparaIdR(Cidade listacidade, char *id){
listaStruct listR = getListaRadios(listacidade);
Node no = getFirst(listR);
tipo elemento;
do{
elemento = getElemento(no);
if(strcmp(getRadioId(elemento), id) == 0){
return elemento;
}
no = getNext(no);
}while(no != NULL);
return NULL;
}
Node comparaIdS(Cidade listacidade, char *id){
listaStruct listS = getListaSemaforos(listacidade);
Node no = getFirst(listS);
tipo elemento;
do{
elemento = getElemento(no);
if(strcmp(getSemaforoId(elemento), id) == 0){
return elemento;
}
no = getNext(no);
}while(no != NULL);
return NULL;
}
|
C
|
/* ziplist是经过特殊编码的双向链接列表,旨在提高内存效率。 它存储字符串和整数值,其中整数被编码为实际整数,而不是一系列字符。
* 它允许在O(1)时间在列表的任一侧进行推和弹出操作。 但是,由于每个操作都需要重新分配zip列表使用的内存,因此实际的复杂性与
* zip列表使用的内存量有关。
*
* ----------------------------------------------------------------------------
*
* ZIPLIST总体布局
* ======================
*
* ziplist的总体布局如下:
*
* 头部节点 | 真实节点数据 | 结尾标志
* <zlbytes> <zltail> <zllen> | <entry> <entry> ... <entry> |<zlend>
*
* 注意:如果没有另外指定,所有字段都以 little endian存储。
*
* <uint32_t zlbytes>是一个无符号整数,用于保存ziplist占用的字节数,包括zlbytes字段本身的四个字节。 需要存储该值,
* 以便能够调整整个结构的大小,而无需先遍历它。
*
* <uint32_t zltail>是列表中最后一个条目的偏移量。 这允许在列表的另一端进行弹出操作,而无需完全遍历。
*
* <uint16_t zllen>是条目数。当条目数超过2 ^ 16-2时,此值将设置为2 ^ 16-1,我们需要遍历整个列表以了解其包含多少项。
*
* <uint8_t zlend>是代表ziplist末尾的特殊条目。 编码为等于255的单个字节。没有其他普通条目以设置为255的字节开头。
*
* ZIPLIST 实体节点
* ===============
*
* ziplist中的每个条目都以包含两个信息的元数据作为前缀。 首先,存储前一个条目的长度,以便能够从后到前遍历列表。
* 第二,提供条目编码。 它表示条目类型,整数或字符串,对于字符串,还表示字符串有效负载的长度。 因此,完整的条目存储如下:
*
* 前一个节点长度 | 编码格式 | 节点数据
* <prevlen> | <encoding> | <entry-data>
*
* 有时,编码代表条目本身,就像后面将要看到的小整数一样。 在这种情况下,<entry-data>部分丢失了,我们可以这样:
*
* 前一个节点长度 | 编码格式
* <prevlen> | <encoding>
*
* 上一个条目的长度<prevlen>以下列方式进行编码:如果此长度小于254个字节,则它将仅消耗一个字节来表示该长度,这是一个无符号
* 的8位整数。 当长度大于或等于254时,它将占用5个字节。 第一个字节设置为254(FE),以指示随后的值更大。 其余4个字节将
* 前一个条目的长度作为值。
*
* 因此,实际上,条目是通过以下方式编码的:
*
* <prevlen from 0 to 253> <encoding> <entry>
*
* 或者,如果先前的条目长度大于253个字节,则使用以下编码:
*
* 0xFE <4 bytes unsigned little endian prevlen> <encoding> <entry>
*
* 条目的编码字段取决于条目的内容。 当条目是字符串时,编码第一个字节的前2位将保存用于存储字符串长度的编码类型,然后是字符串
* 的实际长度。 当条目是整数时,前2位都设置为1。接下来的2位用于指定在此标头之后将存储哪种整数。 不同类型和编码的概述如下。
* 第一个字节始终足以确定条目的类型。
*
* |00pppppp| - 1 byte
* 长度小于或等于63个字节(6位)的字符串值。
* "pppppp" 表示无符号的6位长度.
*
* |01pppppp|qqqqqqqq| - 2 bytes
* 长度小于或等于16383字节(14位)的字符串值。
* 重要说明:14位数字存储在big endian中。
*
* |10000000|qqqqqqqq|rrrrrrrr|ssssssss|tttttttt| - 5 bytes
* 长度大于或等于16384个字节的字符串值。仅第一个字节后的4个字节表示最大长度为32 ^ 2-1。 第一个字节的低6位未使用且设置为零。
* 重要说明:32位数字存储在big endian中。
*
* |11000000| - 3 bytes
* 整数编码为int16_t(2个字节)。
* |11010000| - 5 bytes
* 整数编码为int32_t(4个字节)。
* |11100000| - 9 bytes
* 整数编码为int64_t(8个字节)。
* |11110000| - 4 bytes
* 整数编码为24位带符号(3个字节)。
* |11111110| - 2 bytes
* 整数编码为8位带符号(1个字节)。
* |1111xxxx| - (xxxx在0000和1101之间)4位整数。
*
* 0到12之间的无符号整数。编码值实际上是1到13,因为不能使用0000和1111,因此应从编码的4位值中减去1以获得正确的值。
* |11111111| - ziplist特殊条目的结尾。
*
* 像ziplist标头一样,所有整数都以little endian字节顺序表示,即使此代码在big endian 系统中编译也是如此。
*
* ZIPLISTS 实例:
* ===========================
*
* 下面是一个包含两个表示字符串“ 2”和“ 5”的元素的ziplist。 它由15个字节组成,我们在视觉上将其分为几部分:
*
* [0f 00 00 00] [0c 00 00 00] [02 00] [00 f3] [02 f6] [ff]
* | | | | | |
* zlbytes zltail entries "2" "5" end
*
* 前4个字节代表数字15,即整个ziplist组成的字节数。后4个字节是找到最后一个ziplist条目的偏移量,即12,实际上,
* 最后一个条目“ 5”在ziplist内的偏移量12处。下一个16位整数表示ziplist中的元素数,由于其中只有两个元素,因此其
* 值为2。最后,“ 00 f3”是代表数字2的第一个条目。它由前一个条目长度(由于这是我们的第一个条目)而为零和与编码
* | 1111xxxx |相对应的字节F3组成。 xxxx在0001和1101之间。我们需要删除“ F”个高阶位1111,并从“ 3”中减去1,
* 因此输入值为“ 2”。下一个条目的前缀是02,因为第一个条目正好由两个字节组成。条目本身F6的编码方式与第一个条目完全
* 相同,并且6-1 = 5,因此条目的值为5。最后,特殊条目FF向ziplist的结尾发出信号。
*
* 在上面的字符串中添加另一个值为“ Hello World”的元素,使我们能够显示ziplist如何编码小字符串。 我们将仅显示条目
* 本身的十六进制转储。 想象一下上面的ziplist中存储“ 5”的条目后面的字节:
*
* [02] [0b] [48 65 6c 6c 6f 20 57 6f 72 6c 64]
*
* 第一个字节02是上一个条目的长度。 下一个字节代表| 00pppppp |模式中的编码 这表示该条目是一个长度<pppppp>的字符串,
* 因此0B表示其后是11个字节的字符串。 从第三个字节(48)到最后一个字节(64),只有“ Hello World”的ASCII字符。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include "zmalloc.h"
#include "util.h"
#include "ziplist.h"
#include "endianconv.h"
#include "redisassert.h"
#define ZIP_END 255 ///ziplist的结尾标志
///对于每个条目前面的“ prevlen”字段,前一个条目的最大字节数仅用一个字节表示。 否则,它表示为FF AA BB CC DD,
///其中AA BB CC DD是4个字节的无符号整数,表示上一个条目len。
#define ZIP_BIG_PREVLEN 254
/// 不同的编码/长度的种类
#define ZIP_STR_MASK 0xc0 ///字符串类型的长度 1100 0000
#define ZIP_INT_MASK 0x30 ///INT类型长度 0011 0000
#define ZIP_STR_06B (0 << 6) ///字符串的长度编码 0000 0000
#define ZIP_STR_14B (1 << 6) ///字符串的长度编码 0100 0000
#define ZIP_STR_32B (2 << 6) ///字符串的长度编码 1000 0000
#define ZIP_INT_16B (0xc0 | 0<<4) ///整数类型编码 1100 0000
#define ZIP_INT_32B (0xc0 | 1<<4) ///整数类型编码 1101 0000
#define ZIP_INT_64B (0xc0 | 2<<4) ///整数类型编码 1110 0000
#define ZIP_INT_24B (0xc0 | 3<<4) ///整数类型编码 1111 0000
#define ZIP_INT_8B 0xfe //1111 1110
///4位整数立即编码| 1111xxxx | xxxx在0001和1101之间。
#define ZIP_INT_IMM_MASK 0x0f ///0000 1111
#define ZIP_INT_IMM_MIN 0xf1 ///1111 0001
#define ZIP_INT_IMM_MAX 0xfd ///1111 1101
///24位能够表示的最大整数值和最小整数整数值
#define INT24_MAX 0x7fffff ///0111 1111 1111 1111 1111 1111
#define INT24_MIN (-INT24_MAX - 1) ///1000 0000 0000 0000 0000 0000
///宏定义,用于确定是否为字符串。 字符串从不以“11”作为第一个字节的最高有效位开头。
#define ZIP_IS_STR(enc) (((enc) & ZIP_STR_MASK) < ZIP_STR_MASK)
/* Return total bytes a ziplist is composed of. */
///获取整个ziplist的字节总数,*((uint32_t*)(zl))的意思就是先将zl强制转化为32位的无符号整数,然后通过指针
///就可以访问这个数对应内存的4个字节的信息。
#define ZIPLIST_BYTES(zl) (*((uint32_t*)(zl)))
/* Return the offset of the last item inside the ziplist. */
///获取压缩表终止位置到起始位置的偏移量
#define ZIPLIST_TAIL_OFFSET(zl) (*((uint32_t*)((zl)+sizeof(uint32_t))))
/* Return the length of a ziplist, or UINT16_MAX if the length cannot be
* determined without scanning the whole ziplist. */
///获取整个压缩表中节点的个数
#define ZIPLIST_LENGTH(zl) (*((uint16_t*)((zl)+sizeof(uint32_t)*2)))
/* The size of a ziplist header: two 32 bit integers for the total
* bytes count and last item offset. One 16 bit integer for the number
* of items field. */
///获取压缩表表头的长度
#define ZIPLIST_HEADER_SIZE (sizeof(uint32_t)*2+sizeof(uint16_t))
/* Size of the "end of ziplist" entry. Just one byte. */
///获取压缩表结尾标识符的长度
#define ZIPLIST_END_SIZE (sizeof(uint8_t))
/* Return the pointer to the first entry of a ziplist. */
///获取压缩表节点开始的位置
#define ZIPLIST_ENTRY_HEAD(zl) ((zl)+ZIPLIST_HEADER_SIZE)
/* Return the pointer to the last entry of a ziplist, using the last entry offset inside the ziplist header. */
///返回压缩表尾节点的位置
#define ZIPLIST_ENTRY_TAIL(zl) ((zl)+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)))
/* Return the pointer to the last byte of a ziplist, which is, the end of ziplist FF entry. */
///返回压缩表结尾标识符的位置(大小为一个字节)
#define ZIPLIST_ENTRY_END(zl) ((zl)+intrev32ifbe(ZIPLIST_BYTES(zl))-1)
/* 增加ziplist标头中的项目数字段。 请注意,此宏永远不会溢出无符号的16位整数,因为条目总是一次被压入一个。 当达到UINT16_MAX时,
* 我们希望计数保持在那里,以表示需要进行全面扫描才能获取ziplist中的项目数。
*/
#define ZIPLIST_INCR_LENGTH(zl,incr) { \ ///增加zipList的长度
if (ZIPLIST_LENGTH(zl) < UINT16_MAX) \ ///如果当前ziplist的长度小于uint16的最大值
ZIPLIST_LENGTH(zl) = intrev16ifbe(intrev16ifbe(ZIPLIST_LENGTH(zl))+incr); \ ///给ziplist的len增加incr
}
///我们使用此功能来接收有关ziplist条目的信息。 请注意,这并不是数据的实际编码方式,而是我们为了方便操作而通过函数填充的内容。
///该结构体定义为ziplist中存储实体的数据结构定义:
/// 前一个节点长度 | 编码格式 | 节点数据
/// <prevlen> | <encoding> | <entry-data>
typedef struct zlentry {
unsigned int prevrawlensize; ///编码前驱节点的长度所需要的字节大小
unsigned int prevrawlen; ///前驱节点的长度
unsigned int lensize; ///编码当前节点长度所需要的字节大小
unsigned int len; ///当前节点的大小
unsigned int headersize; ///当前节点头部长度prevrawlensize + lensize.
unsigned char encoding; ///当前节点采用的编码格式
unsigned char *p; ///指向当前节点的指针
} zlentry;
#define ZIPLIST_ENTRY_ZERO(zle) { \ ///初始化一个节点
(zle)->prevrawlensize = (zle)->prevrawlen = 0; \ ///将前驱节点的编码长度、长度设置为0
(zle)->lensize = (zle)->len = (zle)->headersize = 0; \ ///将该节点的编码长度、长度、头部大小设置为0
(zle)->encoding = 0; \ ///将该节点的编码格式设置为0
(zle)->p = NULL; \ ///初始化指向该节点的指针为NULL
}
/// 从“ ptr”指向的字节中提取编码,并将其设置到zlentry结构的“ encoding”字段中。
#define ZIP_ENTRY_ENCODING(ptr, encoding) do { \
(encoding) = (ptr[0]); \
if ((encoding) < ZIP_STR_MASK) (encoding) &= ZIP_STR_MASK; \
} while(0)
/// 返回存储“encoding”编码格式所需要的字节大小。
unsigned int zipIntSize(unsigned char encoding) {
switch(encoding) {
case ZIP_INT_8B: return 1; ///如果是ZIP_INT_8B, 需要1个节点
case ZIP_INT_16B: return 2; ///如果是ZIP_INT_16B, 需要2个节点
case ZIP_INT_24B: return 3; ///如果是ZIP_INT_24B, 需要3个节点
case ZIP_INT_32B: return 4; ///如果是ZIP_INT_32B, 需要4个节点
case ZIP_INT_64B: return 8; ///如果是ZIP_INT_64B, 需要8个节点
}
if (encoding >= ZIP_INT_IMM_MIN && encoding <= ZIP_INT_IMM_MAX)
return 0; /* 4 bit immediate */
panic("Invalid integer encoding 0x%02X", encoding); ///不合法的编码格式
return 0;
}
/*在'p'中写入数据的encoidng标头。如果p为NULL,则仅返回编码此长度所需的字节数。参数:
*
*'encoding'是我们用于该条目的编码。对于单字节小立即数,它可以是ZIP_INT_*或ZIP_STR_*,或者在ZIP_INT_IMM_MIN和ZIP_INT_IMM_MAX之间。
*
*'rawlen'仅用于ZIP_STR_*编码,并且是此条目表示的srting的长度。
*
*该函数返回存储在“p”中的编码/长度报头使用的字节数。
*/
unsigned int zipStoreEntryEncoding(unsigned char *p, unsigned char encoding, unsigned int rawlen) {
unsigned char len = 1, buf[5];
if (ZIP_IS_STR(encoding)) { ///如果是字符串编码
///尽管给出了编码,但可能未为字符串设置编码,因此我们在这里使用原始长度来确定它。
if (rawlen <= 0x3f) { ///如果字符串长度小于或者等于 0x3f
if (!p) return len; ///如果传入的p为NULL,直接返回len,也就是一个字节
buf[0] = ZIP_STR_06B | rawlen; ///否则,让buf[0] = ZIP_STR_06B | rawlen (|为位运算中的或运算符)
} else if (rawlen <= 0x3fff) {///如果rawlen的长度大于0x3f并且小于0x3fff
len += 1; ///长度变为两个字节
if (!p) return len; ///如果p为NULL,返回len,两个字节
buf[0] = ZIP_STR_14B | ((rawlen >> 8) & 0x3f); ///将编码格式的高8位写入到buf[0]
buf[1] = rawlen & 0xff; ///将编码格式的低8为写到buf[1]中
} else { ///如果rawlen大于0x3fff
len += 4; ///将长度变为5个字节
if (!p) return len; ///如果p为NULL,直接返回len =5
buf[0] = ZIP_STR_32B; ///将编码格式的高8位写入到buf[0]中
buf[1] = (rawlen >> 24) & 0xff; ///1111 1111写入buf[1]
buf[2] = (rawlen >> 16) & 0xff; ///1111 1111写入buf[2]
buf[3] = (rawlen >> 8) & 0xff; ///1111 1111写入buf[3]
buf[4] = rawlen & 0xff; ///1111 1111写入buf[4]
}
} else { ///如果不是字符串编码,那么就应该是整数编码
if (!p) return len; ///整数用一个字节表示,如果p为NULL,直接返回
buf[0] = encoding; ///将编码格式保存到buf[0]中
}
memcpy(p,buf,len); ///将编码格式写入到p所指的地址中
return len; ///返回编码长度
}
/* 解码以'ptr'编码的条目编码类型和数据长度(字符串的字符串长度,用于整数条目的整数的字节数)。'encoding'变量将保存
* 条目编码,'lensize'变量将保留 保留编码条目长度所需的字节数,“ len”变量将保留条目长度。
*/
///从ptr对应的地址空间中去除节点信息,包括encoding、lensize、len
#define ZIP_DECODE_LENGTH(ptr, encoding, lensize, len) do { \
ZIP_ENTRY_ENCODING((ptr), (encoding)); ///cong ptr中取出编码格式并将它复制给encoding \
if ((encoding) < ZIP_STR_MASK) { ///如果编码格式为字符串编码 \
if ((encoding) == ZIP_STR_06B) { ///如果是6位的字符串编码,他的编码长度需要一个字节 \
(lensize) = 1; \
(len) = (ptr)[0] & 0x3f; ///将字节长度保存到len中 \
} else if ((encoding) == ZIP_STR_14B) { ///如果是14位字符编码,他的编码长度需要2个字节 \
(lensize) = 2; \
(len) = (((ptr)[0] & 0x3f) << 8) | (ptr)[1]; ///将当前的字节长度保存到len中 \
} else if ((encoding) == ZIP_STR_32B) { ///如果是32位的编码格式,需此案吗长度需要5个字节 \
(lensize) = 5; \
(len) = ((ptr)[1] << 24) | \
((ptr)[2] << 16) | \
((ptr)[3] << 8) | \
((ptr)[4]); ///将字节长度保存到len中 \
} else { ///否则,为不合法的编码格式 \
panic("Invalid string encoding 0x%02X", (encoding)); \
} \
} else { ///如果不是字符串编码,那就是整数编码 \
(lensize) = 1; ///整数编码用1个字节保存 \
(len) = zipIntSize(encoding); ///保存整数的编码的长度 \
} \
} while(0);
///对p所指的当前节点的前驱节点的长度进行编码,并将其写入“p”。 这仅使用较大的编码(在__ziplistCascadeUpdate中需要)。
int zipStorePrevEntryLengthLarge(unsigned char *p, unsigned int len) {
if (p != NULL) { ///如果p不为空
p[0] = ZIP_BIG_PREVLEN; ///这里使用较大的编码,也就是len的字节大于254
memcpy(p+1,&len,sizeof(len)); ///从p+1处开始拷贝len
memrev32ifbe(p+1);
}
return 1+sizeof(len); ///返回需要的编码数5
}
///对p所指的当前节点的前驱节点的长度进行编码,并将其写入“p”。 如果“ p”为NULL,则返回编码此长度所需的字节数。
unsigned int zipStorePrevEntryLength(unsigned char *p, unsigned int len) {
if (p == NULL) { ///如果p为空
return (len < ZIP_BIG_PREVLEN) ? 1 : sizeof(len)+1; ///如果len小于254,返回1,如果大于等于254,返回5
} else { ///如果p不为空
if (len < ZIP_BIG_PREVLEN) { ///如果len小于254
p[0] = len; ///将len保存到p[0]中
return 1; ///返回1
} else { ///如果len大于等于254,则需要调用zipStorePrevEntryLengthLarge()函数进行处理
return zipStorePrevEntryLengthLarge(p,len);
}
}
}
/// 获取ptr节点所指的前驱节点的长度的字节数。 并将保存到变量'prevlensize'中
#define ZIP_DECODE_PREVLENSIZE(ptr, prevlensize) do { \
if ((ptr)[0] < ZIP_BIG_PREVLEN) { ///如果前驱节点长度小于254,就用1个字节来编码,否则需要5个字节编码 \
(prevlensize) = 1; \
} else { \
(prevlensize) = 5; \
} \
} while(0);
///获取ptr节点所指的前驱节点的长度,以及用于编码前一个元素长度的字节数。“ptr”必须指向条目的前缀(前驱节点的长度,
///以便向后遍历元素)。前一个节点的长度存储在“prevlen”中,编码前一个节点长度所需的字节数保存在“prevlensize”中。
#define ZIP_DECODE_PREVLEN(ptr, prevlensize, prevlen) do { \
ZIP_DECODE_PREVLENSIZE(ptr, prevlensize); ///从ptr所指的地中取出编码前驱节点所需要的字节数 \
if ((prevlensize) == 1) { ///如果前驱节点的编码长度为 \
(prevlen) = (ptr)[0]; ///从ptr[0]取出值 \
} else if ((prevlensize) == 5) { ///如果前驱节点编码长度 \
assert(sizeof((prevlen)) == 4); ///因为ptr[0]是标示0xfe \
memcpy(&(prevlen), ((char*)(ptr)) + 1, 4); ///将值拷贝到prelen中 \
memrev32ifbe(&prevlen); \
} \
} while(0);
/* 给定指向节点前缀的prevlen信息的指针'p',如果前一个节点的大小发生变化,此函数将返回编码prevlen所需的字节数之差。
* 因此,如果A是现在用于编码“prevlen”字段的字节数。
* B是如果将前一个元素更新为大小为“len”的元素,则对“prevlen”进行编码所需的字节数。
* 然后函数返回B-A
* 因此,如果需要更多空间,则函数返回正数;如果需要较少空间,则函数返回负数;如果需要相同空间,则函数返回零。
*/
int zipPrevLenByteDiff(unsigned char *p, unsigned int len) {
unsigned int prevlensize;
ZIP_DECODE_PREVLENSIZE(p, prevlensize); ///获取前驱节点所需要的字节数大小
return zipStorePrevEntryLength(NULL, len) - prevlensize; ///计算len所需要的字节数大小减去原来的字节数大小
}
///返回'p'指向的节点所使用的字节总数。
unsigned int zipRawEntryLength(unsigned char *p) {
unsigned int prevlensize, encoding, lensize, len; ///声明节点中的各个变量
ZIP_DECODE_PREVLENSIZE(p, prevlensize); ///返回前驱节点的字节数,并保存到prelensize中
ZIP_DECODE_LENGTH(p + prevlensize, encoding, lensize, len);///取出当前节点的编码格式,编码节点所需要的字节数,节点的长度
return prevlensize + lensize + len; ///返回当前节点的大小,它是有前驱节点的大小+当前节点编码所需要的字节数+节点长度
}
///检查'entry'指向的字符串是否可以编码为整数。将整数值存储在“v”中,并将其编码存储在“encoding”中。
int zipTryEncoding(unsigned char *entry, unsigned int entrylen, long long *v, unsigned char *encoding) {
long long value;
if (entrylen >= 32 || entrylen == 0) return 0; ///如果节点太长,超过了long long所能表示的范围,或者太短为0,就直接返回
if (string2ll((char*)entry,entrylen,&value)) { ///将entry字符串转化为long long类型的整数病保存在value中
///很好,可以对字符串进行编码。 请检查可以容纳此值的最小编码类型。
if (value >= 0 && value <= 12) { ///如果value的值大于0并且小于12
*encoding = ZIP_INT_IMM_MIN+value; ///就将其编码格式设置为ZIP_INT_IMM_MIN+value
} else if (value >= INT8_MIN && value <= INT8_MAX) { ///如果vlaue能用8位表示
*encoding = ZIP_INT_8B; ///将它的编码格式设置为ZIP_INT_8B
} else if (value >= INT16_MIN && value <= INT16_MAX) {///如果vlaue能用16位表示
*encoding = ZIP_INT_16B;///将它的编码格式设置为ZIP_INT_16B
} else if (value >= INT24_MIN && value <= INT24_MAX) {///如果vlaue能用24位表示
*encoding = ZIP_INT_24B;///将它的编码格式设置为ZIP_INT_24B
} else if (value >= INT32_MIN && value <= INT32_MAX) {///如果vlaue能用32位表示
*encoding = ZIP_INT_32B;///将它的编码格式设置为ZIP_INT_32B
} else { ///如果是其他的情况,就用64位来表示
*encoding = ZIP_INT_64B;///将它的编码格式设置为ZIP_INT_64B
}
*v = value; ///将value的值赋值给v
return 1; ///返回1
}
return 0;
}
/// 将整数'value'存储在'p'中,编码为'encoding'
void zipSaveInteger(unsigned char *p, int64_t value, unsigned char encoding) {
int16_t i16;
int32_t i32;
int64_t i64;
if (encoding == ZIP_INT_8B) { ///如果编码格式为ZIP_INT_8B
((int8_t*)p)[0] = (int8_t)value; ///讲这个数强制转化为int8保存到p[0]中
} else if (encoding == ZIP_INT_16B) {///如果编码格式为ZIP_INT_16B
i16 = value; ///将value保存到i16中
memcpy(p,&i16,sizeof(i16)); ///讲i16中的值复制到p中
memrev16ifbe(p);
} else if (encoding == ZIP_INT_24B) {///如果编码格式为ZIP_INT_24B
i32 = value<<8;
memrev32ifbe(&i32);
memcpy(p,((uint8_t*)&i32)+1,sizeof(i32)-sizeof(uint8_t));
} else if (encoding == ZIP_INT_32B) {///如果编码格式为ZIP_INT_32B
i32 = value;
memcpy(p,&i32,sizeof(i32));
memrev32ifbe(p);
} else if (encoding == ZIP_INT_64B) {///如果编码格式为ZIP_INT_64B
i64 = value;
memcpy(p,&i64,sizeof(i64));
memrev64ifbe(p);
} else if (encoding >= ZIP_INT_IMM_MIN && encoding <= ZIP_INT_IMM_MAX) {
/// 无需执行任何操作,该值存储在编码本身中。
} else {
assert(NULL);
}
}
/// 从'p'中读取编码为'encoding'的整数
int64_t zipLoadInteger(unsigned char *p, unsigned char encoding) {
int16_t i16;
int32_t i32;
int64_t i64, ret = 0;
if (encoding == ZIP_INT_8B) { ///如果编码格式为ZIP_INT_8B
ret = ((int8_t*)p)[0]; ///则直接返回p[0]位置的数据即可
} else if (encoding == ZIP_INT_16B) { //////如果编码格式为ZIP_INT_16B
memcpy(&i16,p,sizeof(i16)); ///需要从p开始,读取i16长度,然后将这段内存表示的值保存到i16中
memrev16ifbe(&i16);
ret = i16; ///讲结果赋值给ret
} else if (encoding == ZIP_INT_32B) {
memcpy(&i32,p,sizeof(i32));
memrev32ifbe(&i32);
ret = i32;
} else if (encoding == ZIP_INT_24B) {
i32 = 0;
memcpy(((uint8_t*)&i32)+1,p,sizeof(i32)-sizeof(uint8_t));
memrev32ifbe(&i32);
ret = i32>>8;
} else if (encoding == ZIP_INT_64B) {
memcpy(&i64,p,sizeof(i64));
memrev64ifbe(&i64);
ret = i64;
} else if (encoding >= ZIP_INT_IMM_MIN && encoding <= ZIP_INT_IMM_MAX) {///如果编码在ZIP_INT_IMM_MIN和ZIP_INT_IMM_MAX之间
///ZIP_INT_IMM_MIN值为1, 编码时加上了1,所以最后需要减去1
ret = (encoding & ZIP_INT_IMM_MASK)-1;
} else {
assert(NULL);
}
return ret;
}
///返回一个节点,其中包含有关节点的所有信息。
void zipEntry(unsigned char *p, zlentry *e) {
ZIP_DECODE_PREVLEN(p, e->prevrawlensize, e->prevrawlen); ///获取p所指的节点的前驱节点的编码所需要的字节数以及长度
ZIP_DECODE_LENGTH(p + e->prevrawlensize, e->encoding, e->lensize, e->len); ///获取当前的编码格式,编码所需要的字节数,以及长度
e->headersize = e->prevrawlensize + e->lensize; ///设置节点的头部
e->p = p; ///设置当前节点的指针
}
///创建一个新的空压缩表
unsigned char *ziplistNew(void) {
unsigned int bytes = ZIPLIST_HEADER_SIZE+ZIPLIST_END_SIZE; ///获取表头大小和表尾大小的和
unsigned char *zl = zmalloc(bytes); ///申请内存空间
ZIPLIST_BYTES(zl) = intrev32ifbe(bytes); ///bytes成员初始化
ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(ZIPLIST_HEADER_SIZE); ///初始化为节点偏移量,将其值设置为头结点的大小
ZIPLIST_LENGTH(zl) = 0; ///节点的长度为0
zl[bytes-1] = ZIP_END; ///将最后一个字节设置为0xff
return zl;
}
///调整压缩列表的大小。
unsigned char *ziplistResize(unsigned char *zl, unsigned int len) {
zl = zrealloc(zl,len); ///重新给zl分配空间,
ZIPLIST_BYTES(zl) = intrev32ifbe(len); ///更新zl的总字节数
zl[len-1] = ZIP_END; ///修改zl的结尾标识符的位置
return zl;
}
/* 插入节点导致ziplist产生大的抖动:
*
* 插入节点时,我们需要将下一个节点的prevlen字段设置为插入节点的长度。 可能会发生此该节点长度无法以1字节编码的情况,并且下一个
* 节点需要增大一点以容纳5字节编码的prevlen。 这可以自动完成,因为这仅在已经插入节点时发生(这会导致重新分配和移动)。 但是,
* 编码prevlen可能会要求该节点也要增长。 当存在大小接近ZIP_BIG_PREVLEN的连续节点时,此效果可能会遍及整个ziplist,因此我
* 们需要检查prevlen是否可以在每个连续节点中进行编码。
*
* 请注意,这种效果也可以反向发生,编码prevlen字段所需的字节可能会缩小,导致后面的节点都缩小,这样就会导致压缩表“抖动”,
* 针对于这种情况,采取的措施就是不进行处理,让prevlen长度比需要的长。所以最终是要处理上面的那种情况。
*
* 指针“p”指向不需要更新的第一个节点,它是对后续节点的检查,而不是当前所指的节点,因为当前这个节点在插入的时候已经已经完成了各项数据填充
* 已经内存空间的分配。
*/
unsigned char *__ziplistCascadeUpdate(unsigned char *zl, unsigned char *p) {
size_t curlen = intrev32ifbe(ZIPLIST_BYTES(zl)), rawlen, rawlensize; ///获取当前节点保存总的字节数
size_t offset, noffset, extra;
unsigned char *np;
zlentry cur, next;
while (p[0] != ZIP_END) { ///遍历这个压缩表,只要没有遇到结尾标识符,就一直遍历下去
zipEntry(p, &cur); ///将p所指的内存的节点信息保存到cur结构体中
rawlen = cur.headersize + cur.len; ///如果当前节点的长度
rawlensize = zipStorePrevEntryLength(NULL,rawlen);///计算当前节点编码所需要的字节数
/* Abort if there is no next entry. */
if (p[rawlen] == ZIP_END) break; ///如果下一个位置就是结尾标志符,表示已经遍历完压缩表了,直接跳出循环
zipEntry(p+rawlen, &next); ///否则获取下一个节点,将它保存到next中
///如果下一个节点记录的前驱节点长度编码的字节数和当前节点的长度相等,说明下一个节点有足够的空来保存前驱节点的长度的值,所以
///新加入这个节点不会发生抖动,直接跳出循环就行了
if (next.prevrawlen == rawlen) break;
///如果下一个节点记录的前驱节点的长度编码字节数和比当前节点的长度要小,插入这个节点的时候,就需要考虑将下一个节点的header进行
///扩大操作
if (next.prevrawlensize < rawlensize) {
/* The "prevlen" field of "next" needs more bytes to hold
* the raw length of "cur". */
offset = p-zl; ///记录当p指针到zl开始位置的偏移量
extra = rawlensize-next.prevrawlensize; ///计算下一个节点需要扩大的空间字节数
zl = ziplistResize(zl,curlen+extra); ///调整压缩表的空间
p = zl+offset; ///调整p指针到zl开始位置的偏移量
np = p+rawlen; ///获取下一个节点的指针
noffset = np-zl; ///下一个节点指针的偏移量
///一个元素不是tail元素时,更新tail偏移量。
if ((zl+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))) != np) {
ZIPLIST_TAIL_OFFSET(zl) = ntrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+extra);
}
///移动next节点到新的位置
memmove(np+rawlensize, p+next.prevrawlensize, urlen-noffset-next.prevrawlensize-1);
///将next节点的header以rawlen进行重新编码,并且更新节点中的prevrawlensize和prevrawlen信息
zipStorePrevEntryLength(np,rawlen);
p += rawlen;///将p移动至下一个节点
curlen += extra; ///更新压缩表的长度
} else { ///如果下一个节点的prevrawlensize够对当前进行编码,就不进行操作,包括缩小操作
if (next.prevrawlensize > rawlensize) {
///如果next为5个字节,但是上一个节点只需要1个字节,会用5个字节空间将1个字节重新编码,但是空间大小不会变
zipStorePrevEntryLengthLarge(p+rawlen,rawlen);
} else {
zipStorePrevEntryLength(p+rawlen,rawlen);///如果next保存的前驱节点编码字节数和当前节点一样,就只需要更新数值即可
}
///从这个地方开始,后面的节点都不会发生”抖动“了, 跳出循环即可
break;
}
}
return zl; ///返回调整后的压缩表
}
///从“p”开始删除连续的num个节点。 返回指向ziplist的指针。
unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsigned int num) {
unsigned int i, totlen, deleted = 0;
size_t offset;
int nextdiff = 0;
zlentry first, tail;
zipEntry(p, &first); ///将p的信息保存到first中
for (i = 0; p[0] != ZIP_END && i < num; i++) { ///遍历压缩表,当遇到ZIP_END或者i>=num,跳出循环
p += zipRawEntryLength(p); ///将p移动到下一个节点开始的位置
deleted++; ///删除的数加1
}
totlen = p-first.p; ///totalen为删除后链表的长度
if (totlen > 0) { ///如果删除后还剩余有节点
if (p[0] != ZIP_END) { ///此时p指向最后一个删除的节点后面的那个节点,如果这个是压缩表结束的位置
///与当前的prevrawlen相比,在该节点中存储prevrawlen可能会增加或减少所需的字节数。 总是有存
///储空间,因为它以前是由一个条目存储的,现在该条目已被删除。
nextdiff = zipPrevLenByteDiff(p,first.prevrawlen);
///请注意,当p向后跳转时,总是有空间:如果新的上一个条目很大,则删除的元素之一具有5个字节的prevlen
///标头,因此可以确定至少有5个字节的空闲空间,而我们只需要4个字节即可。* /
p -= nextdiff;
///将first的前驱节点的长度信息保存到p节点中
zipStorePrevEntryLength(p,first.prevrawlen);
///更结尾标识符的偏移量
ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))-totlen);
///当尾部包含多个节点时,我们还需要考虑“ nextdiff”。 否则,更改prevlen的大小不会影响* tail *偏移量。
///记录当前p所指向的节点信息
zipEntry(p, &tail);
///
if (p[tail.headersize+tail.len] != ZIP_END) {
ZIPLIST_TAIL_OFFSET(zl) =intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
}
/* Move tail to the front of the ziplist */
///移动数据
memmove(first.p,p, intrev32ifbe(ZIPLIST_BYTES(zl))-(p-zl)-1);
} else {
///所有的节点都已经删除了,当前的节点是表的尾节点,所以只要更新tail的offset即可
ZIPLIST_TAIL_OFFSET(zl) =
intrev32ifbe((first.p-zl)-first.prevrawlen);
}
///整理删除节点后的内存空间
offset = first.p-zl;
///调用ziplistResize函数调整内存大小
zl = ziplistResize(zl, intrev32ifbe(ZIPLIST_BYTES(zl))-totlen+nextdiff);
ZIPLIST_INCR_LENGTH(zl,-deleted); ///修改压缩表的节点计数器
p = zl+offset; ///将p指向压缩表的第一个元素
/* When nextdiff != 0, the raw length of the next entry has changed, so
* we need to cascade the update throughout the ziplist */
///由于删除节点,所以需要检查是否需要进行连锁更新
if (nextdiff != 0)
zl = __ziplistCascadeUpdate(zl,p);
}
return zl;
}
///在压缩表中插入一个节点(p的位置进行插入)
unsigned char *__ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
size_t curlen = intrev32ifbe(ZIPLIST_BYTES(zl)), reqlen; ///获取当前压缩表的总字节数
unsigned int prevlensize, prevlen = 0;
size_t offset;
int nextdiff = 0; ///用来记录是否会导致连锁更新
unsigned char encoding = 0;
long long value = 123456789; ///初始化以避免警告。 使用易于查看的值是否由于某种原因而未初始化使用它。
zlentry tail;
/* Find out prevlen for the entry that is inserted. */
if (p[0] != ZIP_END) { ///如果插入的地方不是尾节点
ZIP_DECODE_PREVLEN(p, prevlensize, prevlen); ///需要那个p指向节点的prevlensize和prevlen
} else { ///如果是尾节点
unsigned char *ptail = ZIPLIST_ENTRY_TAIL(zl); ///获取到压缩表的尾节点地址
if (ptail[0] != ZIP_END) { ///如果p指向的是最后一个节点,而不是压缩表终止符
prevlen = zipRawEntryLength(ptail); ///获取到最后这个节点的长度,该值将作为插入节点中的prelen
}
}
///尝试这个节点是否可以被压缩,就是讲字符串转化为整数,如果可以的话,转化的结果保存到value中,讲采用的编码格式保存在encoding中
if (zipTryEncoding(s,slen,&value,&encoding)) {
reqlen = zipIntSize(encoding); ///获取编码长度所需要的字节数
} else {
reqlen = slen; ///如果说不能压缩,就将slen保存到reqlen中
}
/* We need space for both the length of the previous entry and
* the length of the payload. */
reqlen += zipStorePrevEntryLength(NULL,prevlen); ///计算保存插入节点的前驱节点长度所需要的字符数
reqlen += zipStoreEntryEncoding(NULL,encoding,slen); ///记录保存当前节点所需要的字符数
///如果说插入的节点不是在压缩表的末尾的位置,需要确认插入后是否会导致压缩表”抖动“
int forcelarge = 0;
nextdiff = (p[0] != ZIP_END) ? zipPrevLenByteDiff(p,reqlen) : 0; ///检查p指向的节点是否能够编码新节点的长度
if (nextdiff == -4 && reqlen < 4) { ///
nextdiff = 0;
forcelarge = 1;
}
offset = p-zl; ///需要记录这个偏移量,因为进行内存充分配的时候可能会导致节点地址发生改变
zl = ziplistResize(zl,curlen+reqlen+nextdiff); ///进行大小调整操作
p = zl+offset; ///重新分配地址后,需要计算出p的新地址
///如果有必要,需要移动内存和更新尾节点的偏移量
if (p[0] != ZIP_END) { ///如果新节点之后还有节点
/* Subtract one because of the ZIP_END bytes */
memmove(p+reqlen,p-nextdiff,curlen-offset-1+nextdiff); ///需要移动内存,为新插入节点腾开空间
///在下一个节点中编码该条目的原始长度。
if (forcelarge)
zipStorePrevEntryLengthLarge(p+reqlen,reqlen);
else
zipStorePrevEntryLength(p+reqlen,reqlen);
///在压缩表头中更新尾节点的偏移量
ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+reqlen);
/* When the tail contains more than one entry, we need to take
* "nextdiff" in account as well. Otherwise, a change in the
* size of prevlen doesn't have an effect on the *tail* offset. */
///如果新节点后面还有多个节点,需要将nextdiff也要计算到尾节点的偏移量中
zipEntry(p+reqlen, &tail); ///
if (p[reqlen+tail.headersize+tail.len] != ZIP_END) {
ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
}
} else {
///如果新节点就是尾节点,更新压缩表表头的尾节点的偏移量
ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(p-zl);
}
/* When nextdiff != 0, the raw length of the next entry has changed, so
* we need to cascade the update throughout the ziplist */
///如果nextdiff不等于0,表示已经在下一个节点中也发生了更新,所以可能会导致连锁更新
if (nextdiff != 0) {
offset = p-zl;
zl = __ziplistCascadeUpdate(zl,p+reqlen); ///进行连锁更新
p = zl+offset;
}
/* Write the entry */
p += zipStorePrevEntryLength(p,prevlen); ///将前度节点的prevlen写入到新节点头中
p += zipStoreEntryEncoding(p,encoding,slen); ///新节点的编码,长度写入到节点头中
if (ZIP_IS_STR(encoding)) { ///如果编码是字符串类型
memcpy(p,s,slen); ///就将这个字符串拷贝到p位置
} else {
zipSaveInteger(p,value,encoding); ///如果是整数类型,就将值和编码写入节点中
}
ZIPLIST_INCR_LENGTH(zl,1); ///压缩表的节点个数加1
return zl;
}
/* 通过将“second”追加到“first”来合并ziplist“ first”和“ second”。
*
* 注意:较大的ziplist被重新分配以包含新的合并的ziplist。 结果可以使用“第一”或“第二”。 未使用的参数将被释放并设置为NULL。
*
* 调用此函数后,输入参数不再有效,因为它们已被更改并就地释放。
*
* 结果ziplist是“first”的内容,然后是“second”。
*
* 失败时:如果无法合并,则返回NULL。
* 成功时:返回合并的ziplist(这是“ first”或“ second”的扩展版本,还释放其他未使用的输入ziplist,并将输入ziplist参数
* 设置为等于新重新分配的ziplist返回值。
*/
///合并两个压缩表,将second追加到first后面
unsigned char *ziplistMerge(unsigned char **first, unsigned char **second) {
if (first == NULL || *first == NULL || second == NULL || *second == NULL) ///如果说只要有一个参数为空,就可以停止合并
return NULL;
if (*first == *second) ///如果两个压缩表是同一个压缩表,不能进行合并
return NULL;
size_t first_bytes = intrev32ifbe(ZIPLIST_BYTES(*first)); ///获取第一个压缩表的字节数
size_t first_len = intrev16ifbe(ZIPLIST_LENGTH(*first)); ///获取第一个压缩表的节点数
size_t second_bytes = intrev32ifbe(ZIPLIST_BYTES(*second)); ///获取第二个压缩表的字节数
size_t second_len = intrev16ifbe(ZIPLIST_LENGTH(*second)); ///获取第二个压缩表节点数
int append;
unsigned char *source, *target;
size_t target_bytes, source_bytes;
///选择最大的ziplist,以便我们就地调整大小。 我们还必须跟踪是否正在添加或添加到目标ziplist。
if (first_len >= second_len) {
///保留first,second附加到first。
target = *first;
target_bytes = first_bytes;
source = *second;
source_bytes = second_bytes;
append = 1; ///标志位,用来标志first为target,second为source
} else {
///保留second,first附加到second。
target = *second;
target_bytes = second_bytes;
source = *first;
source_bytes = first_bytes;
append = 0;///标志位,用来标志second为target,first为source
}
///计算最终各项数据的大小
size_t zlbytes = first_bytes + second_bytes -
ZIPLIST_HEADER_SIZE - ZIPLIST_END_SIZE; ///计算合并后所有的字节数
size_t zllength = first_len + second_len; ///计算合并后压缩表的节点个数
///判断合并后的长度是否超过UINT16_MAX,如果超过了将其值设为UINT16_MAX
zllength = zllength < UINT16_MAX ? zllength : UINT16_MAX;
///把两个压缩表的尾节点偏移量记录下来
size_t first_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*first));
size_t second_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*second));
///从新申请target的内存空间,新的内存空间大小为zlbytes
target = zrealloc(target, zlbytes);
if (append) { ///如果是first为target,second为source
/* append == appending to target */
/* Copy source after target (copying over original [END]):
* [TARGET - END, SOURCE - HEADER] */
memcpy(target + target_bytes - ZIPLIST_END_SIZE,
source + ZIPLIST_HEADER_SIZE,
source_bytes - ZIPLIST_HEADER_SIZE); ///直接将source中的内存拷贝到target后面
} else { ///如果是second为target,first为source
/* !append == prepending to target */
/* Move target *contents* exactly size of (source - [END]),
* then copy source into vacataed space (source - [END]):
* [SOURCE - END, TARGET - HEADER] */
memmove(target + source_bytes - ZIPLIST_END_SIZE,
target + ZIPLIST_HEADER_SIZE,
target_bytes - ZIPLIST_HEADER_SIZE); ///先将second移动到后面的位置
memcpy(target, source, source_bytes - ZIPLIST_END_SIZE); ///将first写入到second前面
}
///更新头结点的各种信息
ZIPLIST_BYTES(target) = intrev32ifbe(zlbytes); ///更新压缩表头结点中的zlbytes
ZIPLIST_LENGTH(target) = intrev16ifbe(zllength); ///更新压缩表头结点中的zllength
/* New tail offset is:
* + N bytes of first ziplist
* - 1 byte for [END] of first ziplist
* + M bytes for the offset of the original tail of the second ziplist
* - J bytes for HEADER because second_offset keeps no header. */
ZIPLIST_TAIL_OFFSET(target) = intrev32ifbe(
(first_bytes - ZIPLIST_END_SIZE) +
(second_offset - ZIPLIST_HEADER_SIZE)); ///更新压缩表头结点中的尾节点偏移量
///讲second追加到first之后,我们还需要判断是否需要进行连锁更新操作
target = __ziplistCascadeUpdate(target, target+first_offset);
///释放掉不用的内存
if (append) { ///如果是first为target,second为source
zfree(*second); ///释放掉second
*second = NULL;
*first = target;
} else { ///如果是second为target,first为source
zfree(*first); ///释放掉first
*first = NULL;
*second = target;
}
return target;
}
///讲长度为slen的字符串push到zl中,where表示push的地方,可以是头部,也可以是尾部
unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where) {
unsigned char *p;
p = (where == ZIPLIST_HEAD) ? ZIPLIST_ENTRY_HEAD(zl) : ZIPLIST_ENTRY_END(zl);
return __ziplistInsert(zl,p,s,slen); ///进行插入操作
}
/* Returns an offset to use for iterating with ziplistNext. When the given
* index is negative, the list is traversed back to front. When the list
* doesn't contain an element at the provided index, NULL is returned. */
///查询下标为index除的节点地址
unsigned char *ziplistIndex(unsigned char *zl, int index) {
unsigned char *p;
unsigned int prevlensize, prevlen = 0;
if (index < 0) { ///如果index小于0,表示倒数第index个节点
index = (-index)-1; ///计算出它从尾到头的遍历次数
p = ZIPLIST_ENTRY_TAIL(zl); ///获取到zl的尾节点
if (p[0] != ZIP_END) { ///如果不是空表
ZIP_DECODE_PREVLEN(p, prevlensize, prevlen); ///获取上一个节点的prevlensize和prevlen
while (prevlen > 0 && index--) { ///如果前驱节点存在并且还没有到达索引的位置
p -= prevlen; ///计算出前驱节点的地址,并修改p指针
ZIP_DECODE_PREVLEN(p, prevlensize, prevlen); ///更新p中的prevlensize和prevlen
}
}
} else { ///如果index大于0,就从头到尾的方式进行遍历
p = ZIPLIST_ENTRY_HEAD(zl); ///获取到第一个节点的位置
while (p[0] != ZIP_END && index--) { ///如果还没有到尾节点并且也没有到达寻找的下标
p += zipRawEntryLength(p); ///更新p的值,指向下一个节点
}
}
return (p[0] == ZIP_END || index > 0) ? NULL : p; ///如果找到了就返回,没找到就返回NULL
}
///返回指向ziplist中下一个节点的指针。 zl是指向ziplist的指针,p是指向当前节点的指针,返回'p'的下一个节点,如果不存在返回NULL。
unsigned char *ziplistNext(unsigned char *zl, unsigned char *p) {
((void) zl);
if (p[0] == ZIP_END) { ///如果p为尾节点,则直接返回NULL
return NULL;
}
p += zipRawEntryLength(p); ///获取到p的下一个节点
if (p[0] == ZIP_END) { ///如果p已经指向了尾节点,直接返回NULL
return NULL;
}
return p;
}
///返回p的前驱节点
unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p) {
unsigned int prevlensize, prevlen = 0;
/* Iterating backwards from ZIP_END should return the tail. When "p" is
* equal to the first element of the list, we're already at the head,
* and should return NULL. */
if (p[0] == ZIP_END) { ///如果p指向结尾标识符,表示列表为空
p = ZIPLIST_ENTRY_TAIL(zl); ///找到尾节点的位置
return (p[0] == ZIP_END) ? NULL : p; ///如果说尾节点为节点成员,则直接返回,否则只是一个结尾标识符,返回NULL
} else if (p == ZIPLIST_ENTRY_HEAD(zl)) { ///如果说p是压缩表的头节点,那个没有前驱节点,直接返回null
return NULL;
} else {
ZIP_DECODE_PREVLEN(p, prevlensize, prevlen); ///如果p是中间的节点,那么获取上一个节点的prevlensize和prevlen
assert(prevlen > 0);
return p-prevlen; ///返回前驱节点的地址
}
}
///获取由'p'指向的节点,并根据节点的编码存储在'*sstr'或'sval'中。 “*sstr”始终设置为NULL,以便能够确定是否设置了字符串指针或整数值。
///如果'p'指向ziplist的末尾,则返回0,否则返回1。
unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *slen, long long *sval) {
zlentry entry;
if (p == NULL || p[0] == ZIP_END) return 0; ///如果p为空或者p指向压缩表结尾 标识符,则直接返回
if (sstr) *sstr = NULL;
zipEntry(p, &entry); ///将p节点中的信息保存到entry中
if (ZIP_IS_STR(entry.encoding)) { ///如果采用的字符串编码
if (sstr) { ///如果sstr不为NULL
*slen = entry.len; ///返回节点长度
*sstr = p+entry.headersize; ///返回字符串
}
} else { ///如果是整数编码格式
if (sval) { ///如果sval不为NULL
*sval = zipLoadInteger(p+entry.headersize,entry.encoding); ///将值保存到sval中
}
}
return 1;
}
///在p所指的位置插入节点,如果p是压缩表中的节点,则讲这个新节点插入到p的前面
unsigned char *ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
return __ziplistInsert(zl,p,s,slen);
}
///从ziplist中删除由 *p指向的节点。还要在适当位置更新p,以便在删除条目时可以遍历ziplist。
unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p) {
size_t offset = *p-zl; ///保存p节点的偏移量
zl = __ziplistDelete(zl,*p,1); ///进行节点删除,1表示只要删除一个节点即可
/* Store pointer to current element in p, because ziplistDelete will
* do a realloc which might result in a different "zl"-pointer.
* When the delete direction is back to front, we might delete the last
* entry and end up with "p" pointing to ZIP_END, so check this. */
*p = zl+offset; ///将p指向新的节点
return zl;
}
///在压缩表中删除从index开始,num个节点
unsigned char *ziplistDeleteRange(unsigned char *zl, int index, unsigned int num) {
unsigned char *p = ziplistIndex(zl,index); ///需要先定位index所指的地址
return (p == NULL) ? zl : __ziplistDelete(zl,p,num); ///如果p不存在则直接返回,否则进行节点删除操作
}
///比较p所指向的节点和sstr,如果相等返回1,不相等返回0
unsigned int ziplistCompare(unsigned char *p, unsigned char *sstr, unsigned int slen) {
zlentry entry;
unsigned char sencoding;
long long zval, sval;
if (p[0] == ZIP_END) return 0; ///如果p指向结尾标识符,则直接返回
zipEntry(p, &entry); ///将p节点信息保存到entry中
if (ZIP_IS_STR(entry.encoding)) { ///如果是字符编码
/* Raw compare */
if (entry.len == slen) { ///判断字符串长度是否相等
return memcmp(p+entry.headersize,sstr,slen) == 0; ///如果长度相等,就进行字符串值比较
} else {
return 0; ///如果长度不相等,就返回0
}
} else { ///如果是整数编码方式
/* Try to compare encoded values. Don't compare encoding because
* different implementations may encoded integers differently. */
if (zipTryEncoding(sstr,slen,&sval,&sencoding)) { ///如果sstr能够转化为整数
zval = zipLoadInteger(p+entry.headersize,entry.encoding); ///获取p所指向的节点的整数的值
return zval == sval; ///进行对比
}
}
return 0; ///如果不相等,统统返回0
}
/* Find pointer to the entry equal to the specified entry. Skip 'skip' entries
* between every comparison. Returns NULL when the field could not be found. */
///查找和vstr值相等的节点。 在每个比较之间跳过“skip”节点。 找不到字段时返回NULL。
unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int vlen, unsigned int skip) {
int skipcnt = 0;
unsigned char vencoding = 0;
long long vll = 0;
while (p[0] != ZIP_END) { ///遍历整个压缩表
unsigned int prevlensize, encoding, lensize, len;
unsigned char *q;
ZIP_DECODE_PREVLENSIZE(p, prevlensize); ///获取p指向的节点的head中的prevlensize
ZIP_DECODE_LENGTH(p + prevlensize, encoding, lensize, len); ///获取当前节点的编码、lensize以及len
q = p + prevlensize + lensize; ///获取p的后继节点,并且其复制给q
if (skipcnt == 0) {
if (ZIP_IS_STR(encoding)) { ///如果编码格式为字符串编码
if (len == vlen && memcmp(q, vstr, vlen) == 0) { ///如果两个字符串长度相等,并且字符串内容相等
return p; ///返回p
}
} else { ///如果是整数编码
if (vencoding == 0) { ///如果vstr没有进行过编码操作,就进行一次,以后就不在执行了 , 用vencoding来标识
if (!zipTryEncoding(vstr, vlen, &vll, &vencoding)) {
vencoding = UCHAR_MAX;
}
/* Must be non-zero by now */
assert(vencoding);
}
/* Compare current entry with specified entry, do it only
* if vencoding != UCHAR_MAX because if there is no encoding
* possible for the field it can't be a valid integer. */
if (vencoding != UCHAR_MAX) {
long long ll = zipLoadInteger(q, encoding); ///获取q的整数数值
if (ll == vll) { ///进行数值比较
return p;
}
}
}
skipcnt = skip; ///重设skipcnt的值
} else {
/* Skip entry */
skipcnt--; ///跳过skip个节点
}
p = q + len; ///指向下一个节点
}
return NULL;
}
///返回压缩表中的节点数量
unsigned int ziplistLen(unsigned char *zl) {
unsigned int len = 0;
if (intrev16ifbe(ZIPLIST_LENGTH(zl)) < UINT16_MAX) { ///如果节点的数量少于UINT16_MAX
len = intrev16ifbe(ZIPLIST_LENGTH(zl));///直接返回len的值
} else {
unsigned char *p = zl+ZIPLIST_HEADER_SIZE; ///如果大于UINT16_MAX, 需要采用遍历的开始来进行统计
while (*p != ZIP_END) {
p += zipRawEntryLength(p);
len++;
}
///设置节点的数量
if (len < UINT16_MAX) ZIPLIST_LENGTH(zl) = intrev16ifbe(len);
}
return len;
}
///返回压缩表总的字符数
size_t ziplistBlobLen(unsigned char *zl) {
return intrev32ifbe(ZIPLIST_BYTES(zl));
}
///格式化打印
void ziplistRepr(unsigned char *zl) {
unsigned char *p;
int index = 0;
zlentry entry;
printf(
"{total bytes %d} "
"{num entries %u}\n"
"{tail offset %u}\n",
intrev32ifbe(ZIPLIST_BYTES(zl)),
intrev16ifbe(ZIPLIST_LENGTH(zl)),
intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)));
p = ZIPLIST_ENTRY_HEAD(zl);
while(*p != ZIP_END) {
zipEntry(p, &entry);
printf(
"{\n"
"\taddr 0x%08lx,\n"
"\tindex %2d,\n"
"\toffset %5ld,\n"
"\thdr+entry len: %5u,\n"
"\thdr len%2u,\n"
"\tprevrawlen: %5u,\n"
"\tprevrawlensize: %2u,\n"
"\tpayload %5u\n",
(long unsigned)p,
index,
(unsigned long) (p-zl),
entry.headersize+entry.len,
entry.headersize,
entry.prevrawlen,
entry.prevrawlensize,
entry.len);
printf("\tbytes: ");
for (unsigned int i = 0; i < entry.headersize+entry.len; i++) {
printf("%02x|",p[i]);
}
printf("\n");
p += entry.headersize;
if (ZIP_IS_STR(entry.encoding)) {
printf("\t[str]");
if (entry.len > 40) {
if (fwrite(p,40,1,stdout) == 0) perror("fwrite");
printf("...");
} else {
if (entry.len &&
fwrite(p,entry.len,1,stdout) == 0) perror("fwrite");
}
} else {
printf("\t[int]%lld", (long long) zipLoadInteger(p,entry.encoding));
}
printf("\n}\n");
p += entry.len;
index++;
}
printf("{end}\n\n");
}
#ifdef REDIS_TEST
#include <sys/time.h>
#include "adlist.h"
#include "sds.h"
#define debug(f, ...) { if (DEBUG) printf(f, __VA_ARGS__); }
static unsigned char *createList() {
unsigned char *zl = ziplistNew();
zl = ziplistPush(zl, (unsigned char*)"foo", 3, ZIPLIST_TAIL);
zl = ziplistPush(zl, (unsigned char*)"quux", 4, ZIPLIST_TAIL);
zl = ziplistPush(zl, (unsigned char*)"hello", 5, ZIPLIST_HEAD);
zl = ziplistPush(zl, (unsigned char*)"1024", 4, ZIPLIST_TAIL);
return zl;
}
static unsigned char *createIntList() {
unsigned char *zl = ziplistNew();
char buf[32];
sprintf(buf, "100");
zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
sprintf(buf, "128000");
zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
sprintf(buf, "-100");
zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
sprintf(buf, "4294967296");
zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
sprintf(buf, "non integer");
zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
sprintf(buf, "much much longer non integer");
zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
return zl;
}
static long long usec(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
}
static void stress(int pos, int num, int maxsize, int dnum) {
int i,j,k;
unsigned char *zl;
char posstr[2][5] = { "HEAD", "TAIL" };
long long start;
for (i = 0; i < maxsize; i+=dnum) {
zl = ziplistNew();
for (j = 0; j < i; j++) {
zl = ziplistPush(zl,(unsigned char*)"quux",4,ZIPLIST_TAIL);
}
/* Do num times a push+pop from pos */
start = usec();
for (k = 0; k < num; k++) {
zl = ziplistPush(zl,(unsigned char*)"quux",4,pos);
zl = ziplistDeleteRange(zl,0,1);
}
printf("List size: %8d, bytes: %8d, %dx push+pop (%s): %6lld usec\n",
i,intrev32ifbe(ZIPLIST_BYTES(zl)),num,posstr[pos],usec()-start);
zfree(zl);
}
}
static unsigned char *pop(unsigned char *zl, int where) {
unsigned char *p, *vstr;
unsigned int vlen;
long long vlong;
p = ziplistIndex(zl,where == ZIPLIST_HEAD ? 0 : -1);
if (ziplistGet(p,&vstr,&vlen,&vlong)) {
if (where == ZIPLIST_HEAD)
printf("Pop head: ");
else
printf("Pop tail: ");
if (vstr) {
if (vlen && fwrite(vstr,vlen,1,stdout) == 0) perror("fwrite");
}
else {
printf("%lld", vlong);
}
printf("\n");
return ziplistDelete(zl,&p);
} else {
printf("ERROR: Could not pop\n");
exit(1);
}
}
static int randstring(char *target, unsigned int min, unsigned int max) {
int p = 0;
int len = min+rand()%(max-min+1);
int minval, maxval;
switch(rand() % 3) {
case 0:
minval = 0;
maxval = 255;
break;
case 1:
minval = 48;
maxval = 122;
break;
case 2:
minval = 48;
maxval = 52;
break;
default:
assert(NULL);
}
while(p < len)
target[p++] = minval+rand()%(maxval-minval+1);
return len;
}
static void verify(unsigned char *zl, zlentry *e) {
int len = ziplistLen(zl);
zlentry _e;
ZIPLIST_ENTRY_ZERO(&_e);
for (int i = 0; i < len; i++) {
memset(&e[i], 0, sizeof(zlentry));
zipEntry(ziplistIndex(zl, i), &e[i]);
memset(&_e, 0, sizeof(zlentry));
zipEntry(ziplistIndex(zl, -len+i), &_e);
assert(memcmp(&e[i], &_e, sizeof(zlentry)) == 0);
}
}
int ziplistTest(int argc, char **argv) {
unsigned char *zl, *p;
unsigned char *entry;
unsigned int elen;
long long value;
/* If an argument is given, use it as the random seed. */
if (argc == 2)
srand(atoi(argv[1]));
zl = createIntList();
ziplistRepr(zl);
zfree(zl);
zl = createList();
ziplistRepr(zl);
zl = pop(zl,ZIPLIST_TAIL);
ziplistRepr(zl);
zl = pop(zl,ZIPLIST_HEAD);
ziplistRepr(zl);
zl = pop(zl,ZIPLIST_TAIL);
ziplistRepr(zl);
zl = pop(zl,ZIPLIST_TAIL);
ziplistRepr(zl);
zfree(zl);
printf("Get element at index 3:\n");
{
zl = createList();
p = ziplistIndex(zl, 3);
if (!ziplistGet(p, &entry, &elen, &value)) {
printf("ERROR: Could not access index 3\n");
return 1;
}
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
printf("\n");
} else {
printf("%lld\n", value);
}
printf("\n");
zfree(zl);
}
printf("Get element at index 4 (out of range):\n");
{
zl = createList();
p = ziplistIndex(zl, 4);
if (p == NULL) {
printf("No entry\n");
} else {
printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
return 1;
}
printf("\n");
zfree(zl);
}
printf("Get element at index -1 (last element):\n");
{
zl = createList();
p = ziplistIndex(zl, -1);
if (!ziplistGet(p, &entry, &elen, &value)) {
printf("ERROR: Could not access index -1\n");
return 1;
}
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
printf("\n");
} else {
printf("%lld\n", value);
}
printf("\n");
zfree(zl);
}
printf("Get element at index -4 (first element):\n");
{
zl = createList();
p = ziplistIndex(zl, -4);
if (!ziplistGet(p, &entry, &elen, &value)) {
printf("ERROR: Could not access index -4\n");
return 1;
}
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
printf("\n");
} else {
printf("%lld\n", value);
}
printf("\n");
zfree(zl);
}
printf("Get element at index -5 (reverse out of range):\n");
{
zl = createList();
p = ziplistIndex(zl, -5);
if (p == NULL) {
printf("No entry\n");
} else {
printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
return 1;
}
printf("\n");
zfree(zl);
}
printf("Iterate list from 0 to end:\n");
{
zl = createList();
p = ziplistIndex(zl, 0);
while (ziplistGet(p, &entry, &elen, &value)) {
printf("Entry: ");
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
} else {
printf("%lld", value);
}
p = ziplistNext(zl,p);
printf("\n");
}
printf("\n");
zfree(zl);
}
printf("Iterate list from 1 to end:\n");
{
zl = createList();
p = ziplistIndex(zl, 1);
while (ziplistGet(p, &entry, &elen, &value)) {
printf("Entry: ");
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
} else {
printf("%lld", value);
}
p = ziplistNext(zl,p);
printf("\n");
}
printf("\n");
zfree(zl);
}
printf("Iterate list from 2 to end:\n");
{
zl = createList();
p = ziplistIndex(zl, 2);
while (ziplistGet(p, &entry, &elen, &value)) {
printf("Entry: ");
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
} else {
printf("%lld", value);
}
p = ziplistNext(zl,p);
printf("\n");
}
printf("\n");
zfree(zl);
}
printf("Iterate starting out of range:\n");
{
zl = createList();
p = ziplistIndex(zl, 4);
if (!ziplistGet(p, &entry, &elen, &value)) {
printf("No entry\n");
} else {
printf("ERROR\n");
}
printf("\n");
zfree(zl);
}
printf("Iterate from back to front:\n");
{
zl = createList();
p = ziplistIndex(zl, -1);
while (ziplistGet(p, &entry, &elen, &value)) {
printf("Entry: ");
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
} else {
printf("%lld", value);
}
p = ziplistPrev(zl,p);
printf("\n");
}
printf("\n");
zfree(zl);
}
printf("Iterate from back to front, deleting all items:\n");
{
zl = createList();
p = ziplistIndex(zl, -1);
while (ziplistGet(p, &entry, &elen, &value)) {
printf("Entry: ");
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
} else {
printf("%lld", value);
}
zl = ziplistDelete(zl,&p);
p = ziplistPrev(zl,p);
printf("\n");
}
printf("\n");
zfree(zl);
}
printf("Delete inclusive range 0,0:\n");
{
zl = createList();
zl = ziplistDeleteRange(zl, 0, 1);
ziplistRepr(zl);
zfree(zl);
}
printf("Delete inclusive range 0,1:\n");
{
zl = createList();
zl = ziplistDeleteRange(zl, 0, 2);
ziplistRepr(zl);
zfree(zl);
}
printf("Delete inclusive range 1,2:\n");
{
zl = createList();
zl = ziplistDeleteRange(zl, 1, 2);
ziplistRepr(zl);
zfree(zl);
}
printf("Delete with start index out of range:\n");
{
zl = createList();
zl = ziplistDeleteRange(zl, 5, 1);
ziplistRepr(zl);
zfree(zl);
}
printf("Delete with num overflow:\n");
{
zl = createList();
zl = ziplistDeleteRange(zl, 1, 5);
ziplistRepr(zl);
zfree(zl);
}
printf("Delete foo while iterating:\n");
{
zl = createList();
p = ziplistIndex(zl,0);
while (ziplistGet(p,&entry,&elen,&value)) {
if (entry && strncmp("foo",(char*)entry,elen) == 0) {
printf("Delete foo\n");
zl = ziplistDelete(zl,&p);
} else {
printf("Entry: ");
if (entry) {
if (elen && fwrite(entry,elen,1,stdout) == 0)
perror("fwrite");
} else {
printf("%lld",value);
}
p = ziplistNext(zl,p);
printf("\n");
}
}
printf("\n");
ziplistRepr(zl);
zfree(zl);
}
printf("Regression test for >255 byte strings:\n");
{
char v1[257] = {0}, v2[257] = {0};
memset(v1,'x',256);
memset(v2,'y',256);
zl = ziplistNew();
zl = ziplistPush(zl,(unsigned char*)v1,strlen(v1),ZIPLIST_TAIL);
zl = ziplistPush(zl,(unsigned char*)v2,strlen(v2),ZIPLIST_TAIL);
/* Pop values again and compare their value. */
p = ziplistIndex(zl,0);
assert(ziplistGet(p,&entry,&elen,&value));
assert(strncmp(v1,(char*)entry,elen) == 0);
p = ziplistIndex(zl,1);
assert(ziplistGet(p,&entry,&elen,&value));
assert(strncmp(v2,(char*)entry,elen) == 0);
printf("SUCCESS\n\n");
zfree(zl);
}
printf("Regression test deleting next to last entries:\n");
{
char v[3][257] = {{0}};
zlentry e[3] = {{.prevrawlensize = 0, .prevrawlen = 0, .lensize = 0,
.len = 0, .headersize = 0, .encoding = 0, .p = NULL}};
size_t i;
for (i = 0; i < (sizeof(v)/sizeof(v[0])); i++) {
memset(v[i], 'a' + i, sizeof(v[0]));
}
v[0][256] = '\0';
v[1][ 1] = '\0';
v[2][256] = '\0';
zl = ziplistNew();
for (i = 0; i < (sizeof(v)/sizeof(v[0])); i++) {
zl = ziplistPush(zl, (unsigned char *) v[i], strlen(v[i]), ZIPLIST_TAIL);
}
verify(zl, e);
assert(e[0].prevrawlensize == 1);
assert(e[1].prevrawlensize == 5);
assert(e[2].prevrawlensize == 1);
/* Deleting entry 1 will increase `prevrawlensize` for entry 2 */
unsigned char *p = e[1].p;
zl = ziplistDelete(zl, &p);
verify(zl, e);
assert(e[0].prevrawlensize == 1);
assert(e[1].prevrawlensize == 5);
printf("SUCCESS\n\n");
zfree(zl);
}
printf("Create long list and check indices:\n");
{
zl = ziplistNew();
char buf[32];
int i,len;
for (i = 0; i < 1000; i++) {
len = sprintf(buf,"%d",i);
zl = ziplistPush(zl,(unsigned char*)buf,len,ZIPLIST_TAIL);
}
for (i = 0; i < 1000; i++) {
p = ziplistIndex(zl,i);
assert(ziplistGet(p,NULL,NULL,&value));
assert(i == value);
p = ziplistIndex(zl,-i-1);
assert(ziplistGet(p,NULL,NULL,&value));
assert(999-i == value);
}
printf("SUCCESS\n\n");
zfree(zl);
}
printf("Compare strings with ziplist entries:\n");
{
zl = createList();
p = ziplistIndex(zl,0);
if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
printf("ERROR: not \"hello\"\n");
return 1;
}
if (ziplistCompare(p,(unsigned char*)"hella",5)) {
printf("ERROR: \"hella\"\n");
return 1;
}
p = ziplistIndex(zl,3);
if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
printf("ERROR: not \"1024\"\n");
return 1;
}
if (ziplistCompare(p,(unsigned char*)"1025",4)) {
printf("ERROR: \"1025\"\n");
return 1;
}
printf("SUCCESS\n\n");
zfree(zl);
}
printf("Merge test:\n");
{
/* create list gives us: [hello, foo, quux, 1024] */
zl = createList();
unsigned char *zl2 = createList();
unsigned char *zl3 = ziplistNew();
unsigned char *zl4 = ziplistNew();
if (ziplistMerge(&zl4, &zl4)) {
printf("ERROR: Allowed merging of one ziplist into itself.\n");
return 1;
}
/* Merge two empty ziplists, get empty result back. */
zl4 = ziplistMerge(&zl3, &zl4);
ziplistRepr(zl4);
if (ziplistLen(zl4)) {
printf("ERROR: Merging two empty ziplists created entries.\n");
return 1;
}
zfree(zl4);
zl2 = ziplistMerge(&zl, &zl2);
/* merge gives us: [hello, foo, quux, 1024, hello, foo, quux, 1024] */
ziplistRepr(zl2);
if (ziplistLen(zl2) != 8) {
printf("ERROR: Merged length not 8, but: %u\n", ziplistLen(zl2));
return 1;
}
p = ziplistIndex(zl2,0);
if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
printf("ERROR: not \"hello\"\n");
return 1;
}
if (ziplistCompare(p,(unsigned char*)"hella",5)) {
printf("ERROR: \"hella\"\n");
return 1;
}
p = ziplistIndex(zl2,3);
if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
printf("ERROR: not \"1024\"\n");
return 1;
}
if (ziplistCompare(p,(unsigned char*)"1025",4)) {
printf("ERROR: \"1025\"\n");
return 1;
}
p = ziplistIndex(zl2,4);
if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
printf("ERROR: not \"hello\"\n");
return 1;
}
if (ziplistCompare(p,(unsigned char*)"hella",5)) {
printf("ERROR: \"hella\"\n");
return 1;
}
p = ziplistIndex(zl2,7);
if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
printf("ERROR: not \"1024\"\n");
return 1;
}
if (ziplistCompare(p,(unsigned char*)"1025",4)) {
printf("ERROR: \"1025\"\n");
return 1;
}
printf("SUCCESS\n\n");
zfree(zl);
}
printf("Stress with random payloads of different encoding:\n");
{
int i,j,len,where;
unsigned char *p;
char buf[1024];
int buflen;
list *ref;
listNode *refnode;
/* Hold temp vars from ziplist */
unsigned char *sstr;
unsigned int slen;
long long sval;
for (i = 0; i < 20000; i++) {
zl = ziplistNew();
ref = listCreate();
listSetFreeMethod(ref,(void (*)(void*))sdsfree);
len = rand() % 256;
/* Create lists */
for (j = 0; j < len; j++) {
where = (rand() & 1) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
if (rand() % 2) {
buflen = randstring(buf,1,sizeof(buf)-1);
} else {
switch(rand() % 3) {
case 0:
buflen = sprintf(buf,"%lld",(0LL + rand()) >> 20);
break;
case 1:
buflen = sprintf(buf,"%lld",(0LL + rand()));
break;
case 2:
buflen = sprintf(buf,"%lld",(0LL + rand()) << 20);
break;
default:
assert(NULL);
}
}
/* Add to ziplist */
zl = ziplistPush(zl, (unsigned char*)buf, buflen, where);
/* Add to reference list */
if (where == ZIPLIST_HEAD) {
listAddNodeHead(ref,sdsnewlen(buf, buflen));
} else if (where == ZIPLIST_TAIL) {
listAddNodeTail(ref,sdsnewlen(buf, buflen));
} else {
assert(NULL);
}
}
assert(listLength(ref) == ziplistLen(zl));
for (j = 0; j < len; j++) {
/* Naive way to get elements, but similar to the stresser
* executed from the Tcl test suite. */
p = ziplistIndex(zl,j);
refnode = listIndex(ref,j);
assert(ziplistGet(p,&sstr,&slen,&sval));
if (sstr == NULL) {
buflen = sprintf(buf,"%lld",sval);
} else {
buflen = slen;
memcpy(buf,sstr,buflen);
buf[buflen] = '\0';
}
assert(memcmp(buf,listNodeValue(refnode),buflen) == 0);
}
zfree(zl);
listRelease(ref);
}
printf("SUCCESS\n\n");
}
printf("Stress with variable ziplist size:\n");
{
stress(ZIPLIST_HEAD,100000,16384,256);
stress(ZIPLIST_TAIL,100000,16384,256);
}
return 0;
}
#endif
|
C
|
// exmaple of duplication C assigned twice
#include <stdio.h>
void increment(int C)
{
int C = 1;
int A = 12;
A = A + C;
printf("%d",C);
}
void main()
{
int C = 2;
C = 4;
increment(C);
printf("%d", C);
}
|
C
|
#include "bazadanych.h"
void zerujBufor()
{
int i = 0;
for(i = 0; i < MAXBUFOR; i++)
bufor[i] = 0;
}
void zapelnijBufor(FILE *plik)
{
zerujBufor();
fgets(bufor, 1024, plik);
bufor[strlen(bufor) - 1] = 0; // usuniecie znaku '\n' z konca bufora
if(bufor[strlen(bufor) - 1] == 13) // usuniecie z bufora znaku carriage return gdy wczytujemy tekst z pliku
bufor[strlen(bufor) - 1] = 0;
}
int walidacjaNazwy(FILE *plik)
{
int i = 0;
zapelnijBufor(plik);
if(bufor[0] <= 'z' && bufor[0] >= 'a')
bufor[0] = bufor[0] - 'a' + 'A';
if(!(bufor[0] <= 'Z' && bufor[0] >= 'A'))
return 0;
for(i = 1; i < MAXNAZWA; i++)
if(!(bufor[i] >= 'a' && bufor[i] <= 'z' || bufor[i] >= 'A' && bufor[i] <= 'Z' || bufor[i] == ' ' || bufor[i] == 0))
return 0;
bufor[MAXNAZWA - 1] = 0;
return 1;
}
int walidacjaNumeru(FILE *plik)
{
int i = 0;
zapelnijBufor(plik);
if(strlen(bufor) != 5)
return 0;
for(i = 0; i < MAXNUMER; i++)
if(!(bufor[i] >= '0' && bufor[i] <= '9' || bufor[i] == 0))
return 0;
if(bufor[MAXNUMER - 1] != 0 || !bufor[0])
return 0;
bufor[MAXNUMER - 1] = 0;
return 1;
}
int walidacjaCzestosci(FILE *plik)
{
int i = 0;
zapelnijBufor(plik);
for(i = 0; i < MAXCZESTOSC; i++)
if(!((bufor[i] <= 'z' && bufor[i] >= 'a') || bufor[i] == 0))
return 0;
if(bufor[MAXCZESTOSC - 1] != 0 || bufor[0] == 0)
return 0;
bufor[MAXCZESTOSC - 1] = 0;
return 1;
}
int walidacjaDzialu(FILE *plik)
{
int i = 0;
zapelnijBufor(plik);
if(bufor[0] <= 'z' && bufor[0] >= 'a')
bufor[0] = bufor[0] - 'a' + 'A';
if(bufor[0] == 0 || bufor[MAXDZIAL - 1] != 0 || !(bufor[0] <= 'Z' && bufor[0] >= 'A'))
return 0;
for(i = 1; i < MAXDZIAL; i++)
if(!((bufor[i] <= 'z' && bufor[i] >= 'a') || bufor[i] == 0))
return 0;
bufor[MAXDZIAL - 1] = 0;
return 1;
}
int walidacjaInterakcji(FILE *plik)
{
zapelnijBufor(plik);
if(!(bufor[0] == '1' || bufor[0] == '2' || bufor[0] == '3' || bufor[0] == '4' || bufor[0] == '5' || bufor[0] == '6' || bufor[0] == '7' || bufor[0] == '8' || bufor[0] == '9' || bufor[0] == 'a' || bufor[0] == 'b' || bufor[0] == 'c') || bufor[1] != 0)
return 0;
return 1;
}
int walidacjaModyfikacji(FILE *plik)
{
zapelnijBufor(plik);
if(!(bufor[0] == '1' || bufor[0] == '2' || bufor[0] == '3') || bufor[1] != 0)
return 0;
return 1;
}
int walidacjaWyjscia(FILE *plik)
{
zapelnijBufor(plik);
if(bufor[1] != 0 || !(bufor[0] == 'T' || bufor[0] == 'N'))
return 0;
return 1;
}
int walidacjaDzialuZPliku(FILE *plik, char *dzial)
{
if(!walidacjaDzialu(plik));
return 0;
strcpy(dzial, bufor);
return 1;
}
int walidacjaGazetyZPliku(FILE *plik, char *dzial, char *nazwa, char *numer, char *czestosc)
{
if(!walidacjaDzialu(plik))
return 0;
strcpy(dzial, bufor);
if(!walidacjaNazwy(plik))
return 0;
strcpy(nazwa, bufor);
if(!walidacjaNumeru(plik))
return 0;
strcpy(numer, bufor);
if(!walidacjaCzestosci(plik))
return 0;
strcpy(czestosc, bufor);
return 1;
}
int walidacjaPliku(char *oz, char *nazwaPliku, char *haslo)
{
int i = 0;
char tab[1024];
zapelnijBufor(stdin);
if(bufor[0] == 'K' && bufor[1] == 0)
return 1;
if(sscanf(bufor, "%s %s %s %s", oz, nazwaPliku, haslo, tab) > 3)
return 0;
oz[20] = 0;
nazwaPliku[20] = 0;
haslo[20] = 0;
if(!(!strcmp("odczyt", oz) || !strcmp("zapis", oz))){
return 0;
}
if(strlen(nazwaPliku) < 5 ||!(!strcmp(".txt", nazwaPliku + strlen(nazwaPliku) - 4) || !strcmp(".ula", nazwaPliku + strlen(nazwaPliku) - 4)))
return 0;
if(strlen(haslo) > 20)
return 0;
for(i = 0; i < strlen(nazwaPliku) - 4; i++)
if(!(nazwaPliku[i] <= 'z' && nazwaPliku[i] >= 'a' || nazwaPliku[i] <= 'Z' && nazwaPliku[i] >= 'A'))
return 0;
return 1;
}
|
C
|
#include <stdio.h>
int main(){
int n,i,y=0,k=0,s=0,flag=1;
scanf("%d",&n);
int x[n];
scanf("%d",&x[0]);
scanf("%d",&x[1]);
if(x[0]==x[1]){
flag=0;
}
for(i=2;i<n;i++){
scanf("%d",&x[i]);
while(s!=EOF){
if(x[0]<=x[1])
k=0;
else
k=1;
s--;
}
if(i%2==k){
if(x[i-1]<=x[i])
flag=0;
}
else{
if(x[i-1]>=x[i])
flag=0;
}
}
printf("%d\n",flag);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdbool.h>
#include "student.h"
void parse_file(char file[], char db[])
{
char line_buf[255];
FILE* fptr;
fptr = fopen(file, "r");
while(!feof(fptr))
{
fscanf(fptr, "%[^\n] ", line_buf);
char cmd[32];
char nume[50];
int an, id, inmat, buget;
sscanf(line_buf, "%s", cmd);
if( strcmp(cmd, "adauga") == 0 ) {
sscanf(line_buf, "%s %s %d %d %d", cmd, nume, &an, &inmat, &buget);
add_student(db, nume, an, inmat, buget);
}
else if( strcmp(cmd, "modifica") == 0) {
sscanf(line_buf, "%s %d %d %d %d", cmd, &id, &an, &inmat, &buget);
mod_student(db, id, an, inmat, buget);
}
else if( strcmp(cmd, "cauta-id") == 0) {
sscanf(line_buf, "%s %d ", cmd, &id);
src_student_id(db, id);
}
else if( strcmp(cmd, "cauta-nume") == 0) {
sscanf(line_buf, "%s %s", cmd, nume);
src_student_name(db, nume);
}
else if( strcmp(cmd, "listeaza") == 0)
list_students(db);
}
fclose(fptr);
}
void print_help(){
printf("Usage:\n"\
"badcrew [commands] [database]\n"\
"If [database] doesn't exist it will be created\n");
}
int main(int argc, char** argv) {
if( argc != 3 )
print_help();
else
parse_file(argv[1], argv[2]);
}
|
C
|
#include <stdio.h>
#include <locale.h>
//Faça um programa para calcular a área de um retângulo.
int main()
{
setlocale(LC_ALL, "Portuguese");
double h, b, area;
printf("Informe o comprimento dos lados do retângulo (altura, base): ");
scanf("%lf %lf", &h, &b);
area = h * b;
printf("Área = %.2lf, Altura = %.2lf, Base = %.2lf", area, h, b);
getchar();
return 0;
}
|
C
|
#include <stdio.h>
void arrange(int scores[], int size){
//配列変数resultを用意
const int Nsize = size;
int result[Nsize];
printf("scores = ");//引数のscores配列の出力
for(int i=0; i<size; i++){
printf("%d ",scores[i]);
result[i] = scores[i];
for(int a = i; a>0; a--){
//若い数字の配列と比較し並び替える
if(result[a] > result[a-1]){
int Otrade = result[a];
int Ttrade = result[a-1];
result[a-1] = Otrade;
result[a] = Ttrade;
}
}
}
printf("\nresult = ");//scoresの中身を大きい順に並べたresultを出力
for(int i=0; i<size; i++){
printf("%d ",result[i]);
}
}
int main(){
const int SIZE = 6; //定数として配列のサイズを宣言
int scores[SIZE] = {100, 60, 70, 100, 90, 80};
//処理コード
arrange(scores, SIZE);
return 0;
}
|
C
|
//ָ:
//ҵмڵ㣬Ҫֻܱһ
SListNode* SListFindMidNode(SListNode* list)
{
if (list == NULL || list->_next == NULL)
{
return list;
}
else
{
SListNode* slow = list;
SListNode* fast = list->_next->_next;
while (fast)
{
slow = slow->_next;
fast = fast->_next;
if (fast)
{
fast = fast->_next;
}
}
return slow;
}
}
//ҵĵkڵ㣬Ҫֻܱһ
SListNode* SListFindTailKNode(SListNode* list, size_t k)
{
SListNode* slow = list;
SListNode* fast = list;
while (k--)
{
if (fast)
fast = fast->_next;
else
return NULL;
}
while (fast)
{
slow = slow->_next;
fast = fast->_next;
}
return slow;
}
//ɾĵK
void SListDelTailKNode(SListNode** plist, size_t k)
{
SListNode* pos = SListFindTailKNode(*plist, k);
SList_Erase(plist, pos);
}
|
C
|
//steve Tan z5237560
//Date Oct. 2019
#include <stdio.h>
int main(void) {
double totalNumber, marksAwarded;
double percentage;
//define the variable.
printf("Enter the total number of marks in the exam: ");
scanf("%lf", &totalNumber);
printf("Enter the number of marks the student was awarded: ");
scanf("%lf", &marksAwarded);
//input the information.
percentage = (marksAwarded / totalNumber) * 100;
//calculate the percentage.
printf("The student scored %.0lf%% in this exam.\n", percentage);
return 0;
}
|
C
|
//
// main.c
// 2-Player Math Game
//
// Created by Jacob Cho on 2014-10-07.
// Copyright (c) 2014 Jacob Cho. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Player {
char *name;
int lives;
int score;
};
enum {
addition,
subtraction,
multiplication,
division
} Operator;
typedef struct Player Player;
int randNum(int n);
bool hasLives(Player a, Player b);
bool checkAnswer(int num1, int operator, int num2, int answer);
void playerTurn(Player player, int num1, int operator, int num2);
int main(int argc, const char * argv[]) {
// Initialize Player A
Player playerA;
playerA.lives = 3;
playerA.score = 0;
playerA.name = "Player 1";
// Initialize Player B
Player playerB;
playerB.lives = 3;
playerA.score = 0;
playerB.name = "Player 2";
char name[10];
char name2[10];
// Ask for player names
printf("Player 1: Please enter your name\n");
fgets(name, 10, stdin);
playerA.name = name;
printf("Your name is now %s\n", playerA.name);
printf("Player 2: Please enter your name\n");
fgets(name2, 10, stdin);
playerB.name = name2;
printf("Your name is now %s\n", playerB.name);
while (hasLives(playerA, playerB)) {
int num1 = randNum(21);
int num2 = randNum(21);
int operator = randNum(4);
char answer[10];
int answerNum;
// Player 1 takes a turn
playerTurn(playerA, num1, operator, num2);
fgets(answer,10,stdin);
answerNum = atoi(answer);
if (checkAnswer(num1, operator, num2, answerNum)) {
playerA.score++;
printf("Correct! %s score is now: %d\n",playerA.name, playerA.score);
}
else {
playerA.lives--;
printf("Wrong! %s lives is now: %d\n",playerA.name, playerA.lives);
}
// Player 2 takes a turn
num1 = randNum(21);
num2 = randNum(21);
operator = randNum(4);
playerTurn(playerB, num1, operator, num2);
fgets(answer,10,stdin);
answerNum = atoi(answer);
if (checkAnswer(num1, operator, num2, answerNum)) {
playerB.score++;
printf("Correct! %s score is now: %d\n",playerB.name, playerB.score);
}
else {
playerB.lives--;
printf("Wrong! %s lives is now: %d\n",playerB.name, playerB.lives);
}
}
printf("Game Over!\n");
return 0;
}
int randNum(int n) {
int r = (int)(arc4random() % n);
return r;
}
bool hasLives(Player a, Player b) {
Player playerA = a;
Player playerB = b;
if (playerA.lives == 0) {
printf("Player A loses!\n");
return false;
}
else if (playerB.lives == 0) {
printf("Player B loses!\n");
return false;
}
return true;
}
bool checkAnswer(int num1, int operator, int num2, int answer) {
int sum;
switch (operator) {
case addition:
sum = num1 + num2;
if (answer == sum) {
return true;
}
break;
case subtraction:
sum = num1 - num2;
if (answer == sum) {
return true;
}
break;
case multiplication:
sum = num1 * num2;
if (answer == sum) {
return true;
}
break;
case division:
if (num2 == 0) num2 = randNum(21);
sum = num1 / num2;
if (answer == sum) {
return true;
}
break;
default:
return false;
break;
}
return false;
}
void playerTurn(Player player, int num1, int operator, int num2) {
switch (operator) {
case addition:
printf("%s: What does %d + %d equal?\n", player.name, num1, num2);
break;
case subtraction:
printf("%s: What does %d - %d equal?\n", player.name, num1, num2);
break;
case multiplication:
printf("%s: What does %d * %d equal?\n", player.name, num1, num2);
break;
case division:
printf("%s: What does %d / %d equal?\n", player.name, num1, num2);
break;
default:
break;
}
}
|
C
|
#include "AdjMatrix.h"
/* ضλ */
int PositionVex(AMGraph g,char ch)
{
int i;
for(i=0;i<g.vexnum;i++)
if(g.vexs[i]==ch)
return i;
return -1;
}
/* ͼ(ڽӾ) */
AMGraph* CreateAdjMatrix()
{
int vlen;
int elen;
int i,p1,p2;
char *vexs;
char (*edges)[2];
AMGraph *pG;
//ȡͱ
printf("붥:");
scanf("%d",&vlen);
printf(":");
scanf("%d",&elen);
getchar();
//ٿռڴͱ
vexs = (char *)malloc(sizeof(char) * vlen);
edges = (char(*)[2])malloc(sizeof(char)*elen*2);
//öͱߵϢ
printf("붥:");
for(i = 0;i < vlen;i++)
scanf("%c",&vexs[i]);
getchar();
printf("(:AB):\n");
for(i = 0;i < elen;i++)
{
scanf("%c%c",&edges[i][0],&edges[i][1]);
getchar();
}
//ݵͱߵϢڽӾͼ
if((pG=(AMGraph*)malloc(sizeof(AMGraph)))==NULL)
return NULL;
memset(pG,0,sizeof(AMGraph));
pG->vexnum=vlen;
pG->edgnum=elen;
for(i=0;i<pG->vexnum;i++)
{
pG->vexs[i]=vexs[i];
}
for(i=0;i<pG->edgnum;i++)
{
p1=PositionVex(*pG,edges[i][0]);
p2=PositionVex(*pG,edges[i][1]);
pG->matrix[p1][p2]=1;
pG->matrix[p2][p1]=1;
}
return pG;
}
/* ͼ(ڽӾ) */
void PrintAdjMatrix(AMGraph G)
{
int i,j;
printf("Adjacency Matrix:\n");
for(i=0;i<G.vexnum;i++)
{
for(j=0;j<G.vexnum;j++)
printf("%d ",G.matrix[i][j]);
printf("\n");
}
}
|
C
|
#include "lists.h"
/**
* add_nodeint_end - Adds a new node to the end of @head
*
* @head: Singly linked list
* @n: Value for new node to be added to end of @head
*
* Return: (Success) Address of newly created node
* (Failure) NULL
*/
listint_t *add_nodeint_end(listint_t **head, const int n)
{
listint_t *new, *current;
new = malloc(sizeof(listint_t));
if (new == NULL)
{
return (NULL);
}
new->n = n;
new->next = NULL;
if (*head == NULL)
{
*head = new;
return (new);
}
current = *head;
while (current->next != NULL)
{
current = current->next;
}
current->next = new;
return (new);
}
|
C
|
/*
* Title : Time Duration Counter and Converter to Second (MenghitungDurasiWaktudanKonversiKeDetik.c)
* Program Description : To Calculate Time Duration and Convert It to Second Written in C Language Code.
* Author : Muhammad Hasbi, S.T.
* Interface : Console
* IDE : Dev-C++ 5.11
* Operating System : Windows 8 Pro
*/
#include<stdio.h>
typedef struct
{
long int hh,mm,ss;
}jam;
jam j1,j2,j3;
long int totalwaktu1,totalwaktu2,totalwaktu3;
long int sisa;
main()
{
printf("Time Duration Counter and Converter Console Program \n");
printf("masukkan nilai dari waktu awal (hh:mm:ss) \n");
scanf("%ld %ld %ld",&j1.hh,&j1.mm,&j1.ss);
printf("masukkan nilai dari waktu akhir (hh:mm:ss) \n");
scanf("%ld %ld %ld",&j2.hh,&j2.mm,&j2.ss);
totalwaktu1=(j1.hh*3600)+(j1.mm*60)+j1.ss;
totalwaktu2=(j2.hh*3600)+(j2.mm*60)+j2.ss;
totalwaktu3=totalwaktu2-totalwaktu1;
j3.hh=totalwaktu3/3600;
sisa=totalwaktu3%3600;
j3.mm=sisa/60;
j3.ss=sisa%60;
printf("durasi waktu anda adalah: %ld %s \n",totalwaktu3," Detik.");
printf("durasi waktu anda adalah: %ld %s %ld %s %ld %s \n",j3.hh," Jam",j3.mm," Menit",j3.ss," Detik.");
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<time.h>
int* thread(char s[])
{
int pos = 0;
while(1)
{
printf("\033[s");
//设置光标位置
printf("\033[%d;%dH", 5, 5);
//清除从光标到行尾的内容
printf("\033[K");
printf("%s", s[pos]);
pos = (pos+1)%3;
printf("\033[u");
fflush(stdout);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t thid1, thid2;
int i;
char s[100];
printf("\033[%d;%dH", 30, 5);
//创建线程
if( pthread_create(&thid,NULL,(void*)thread,(void*)&i)
!= 0 )
{
printf("Error!\n");
exit(1);
}
if( pthread_create(&thid2,NULL,(void*)thread,(void*)&i)
!= 0 )
{
printf("Error!\n");
exit(1);
}
while(1)
{
printf("\033[%d;%dH", 30, 5);
scanf("%s", s);
printf("\033[%d;%dH", 30, 5);
printf("\033[K");
printf("\033[%d;%dH%s", 20, 5, s);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int* arrayFill(int *arr, int n) // Filling first array with elements.
{
for(int i = 0; i<n; i++)
{
printf("Enter element №%d\n", i+1);
scanf("%i", &arr[i]);
}
return arr;
}
void arrayCopy(int *arr, int *arr2, int n) // Copying elements from first array to second
{
for(int i = 0; i<n; i++)
{
arr2[i] = arr[i];
}
}
void arrayPrint(int *arr2, int n) // Printing elements of the second(copied) array.
{
for(int i = 0; i<n; i++)
{
printf("%d element of array = %d\n", i+1, arr2[i]);
}
}
int main(void)
{
int n;
printf("Enter amount of elements:\n");
scanf("%d", &n);
int *arr = (int*)malloc(n*sizeof(int));
int *arr2 = (int*)malloc(n*sizeof(int));
arrayFill(arr, n);
arrayCopy(arr, arr2, n);
arrayPrint(arr2,n);
free(arr);
free(arr2);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <ctype.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
extern pthread_mutex_t thread_mutex;
typedef struct {
int fd;
int value;
} ssInit;
ssInit ssInitInfo;
pthread_t sstid;
void *sevenSegThreadFunc(void *arg) {
time_t rawtime;
struct tm* timeinfo;
while(1) {
time(&rawtime);
timeinfo = localtime(&rawtime);
ssInitInfo.value = (timeinfo->tm_hour+9)%24 * 10000 + timeinfo->tm_min * 100 + timeinfo->tm_sec;
// pthread_mutex_lock(&thread_mutex);
// printf("Locked @ 7Seg\n");
write(ssInitInfo.fd, &ssInitInfo.value, 4);
// pthread_mutex_unlock(&thread_mutex);
// printf("Unlocked @ 7Seg\n");
}
pthread_exit(NULL);
}
pthread_t sevenSegWorker(int number) {
ssInitInfo.fd = open("/dev/7segdrv", O_RDWR);
ssInitInfo.value = number;
pthread_create(&sstid, NULL, sevenSegThreadFunc, NULL);
return sstid;
}
void sevenSegChanger(int number) {
ssInitInfo.value = number;
}
void sevenSegCancel(void) {
pthread_cancel(sstid);
close(ssInitInfo.fd);
}
|
C
|
void fair_surf(bspl,lu,lv,knot_u, knot_v)
/* Fairs B-spline control net.
Input: bspl: B-spline control net (one coordinate only)
lu,lv: no. of intervals in u- and v-direction
knots_u, knots_v: knot vectors in u- and v-direction
Output: as input
*/
float bspl[20][20],knot_u[],knot_v[];
int lu,lv;
{
int i,j,lu2,lv2;
float b[20];
lu2=lu+2; lv2=lv+2;
for(i=0; i<= lu2; i++)
{
for(j=0; j<=lv2; j++) b[j]=bspl[i][j]; /* grab i-th row*/
fair_bspline(b,knot_v,lv,0,lv); /* fair row */
for(j=0; j<=lv2; j++) bspl[i][j]=b[j]; /* put row back */
}
for(j=0; j<= lv2; j++)
{
for(i=0; i<=lu2; i++) b[i]=bspl[i][j]; /* grab j-th col*/
fair_bspline(b,knot_u,lu,0,lu); /* fair col */
for(i=0; i<=lu2; i++) bspl[i][j]=b[i]; /* put col back */
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<sys/stat.h>
void main(int n, char **argv)
{
int semid = semget(atoi(argv[1]), 1, IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
if(semid == -1)
{
perror("ERROR");
semid = semget(atoi(argv[1]),1, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
}
printf("semaphore id %d\n", semid);
int shmid = shmget(atoi(argv[1]), 20, IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR);
if(shmid == -1)
{
perror("ERROR");
shmid = shmget(atoi(argv[1]), 20, S_IRUSR|S_IWUSR);
}
printf("shmid %d\n", shmid);
struct shmid_ds shm_ds;
shmctl(shmid, IPC_STAT, &shm_ds);
//printf("address %p \n", p);
struct sembuf msg;
msg.sem_flg = SEM_UNDO;
msg.sem_num = 0;
msg.sem_op = 0;
if(semop(semid, &msg, 1) == -1)
perror("Error");
//write(STDIN_FILENO,p,20);
msg.sem_flg = SEM_UNDO;
msg.sem_num = 0;
msg.sem_op = 1;
if(semop(semid, &msg, 1) == -1)
perror("Error");
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "semaphore.h"
void sem_init(sem_s* sem, unsigned int val) {
sem->compteur = val;
sem->ctx_curr = NULL;
}
void sem_down(sem_s* sem) {
irq_disable();
sem->compteur--;
// printf("sem_down()->compteur = %i\n", sem->compteur);
if (sem->compteur < 0) {
cctx->sem_next_ctx = sem->ctx_curr;
sem->ctx_curr = cctx;
cctx->ctx_state = CTX_SEM;
irq_enable();
yield();
}
else {
irq_enable();
}
}
void sem_up(sem_s* sem) {
irq_disable();
sem->compteur++;
// printf("sem_up()->compteur = %i\n", sem->compteur);
if (sem->compteur <= 0) {
sem->ctx_curr->ctx_state = CTX_EXEC;
sem->ctx_curr = sem->ctx_curr->sem_next_ctx;
}
irq_enable();
}
|
C
|
/*
* Jake Halloran
* Yahtzee implementation for CS 0449 Project 4
* Last Edited: 4/9/16
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define NUM_DICE 5
#define NUM_TURNS 13
int upper_data[6];
int lower_data[7];
int has_bonus;
int roll[5];
int needs_rolled[5];
int score_pos_used[13];
int score;
int dice_values[6];
int top_full;
int bottom_full;
//Takes an array of dice and rolls any dice that has a 1
//At the matching index in the needs_rolled array of equal length
void roll_dice(){
int i;
char die[1];
//Open the driver to read from
FILE * dice_file = fopen("/dev/dice","r");
for(i = 0;i<NUM_DICE;i++){
if(needs_rolled[i]==1){
fread(die,1,1,dice_file);
roll[i] = die[0] + 1;
needs_rolled[i] = 0;
}
}
fclose(dice_file);
return;
}
//Comparator for dice for qsort
int int_cmp(const void *a, const void *b){
return(*(int *)a - *(int *)b);
}
//Gets user reroll choice
int get_dice_to_roll(){
char line[1000], *p, *e;
int temp = 0;
char temp_char;
printf("\nWhich dice to reroll? Enter 0 for none (1-5): ");
//Uses fgets and string processing to read in an indeterminate number of ints and then mark those dice
//to be rerolled.
fgets(line, sizeof(line), stdin);
p = line;
for(p = line; ;p = e){
temp = strtod(p,&e);
if (p==e){
break;
}
//If the user enteres a zero, skip rerolling
if(temp == 0){
return 0;
}
if(temp>0&&temp<6){
needs_rolled[temp-1] = 1;
}
}
return 1;
}
//Displays a menu of user places to store the dice score
//Returns the users selection
int display_menu(){
int user_select = 0;
//Selects point section to display
printf("Place dice into: \n1) Upper Section\n2) Lower Section\n");
while(user_select!=1 && user_select !=2){
printf("\nSelection: ");
scanf("%d",&user_select);
if((user_select==1&&top_full==6)||(user_select==2&&bottom_full==7)){
printf("Sorry, that section is full.\n");
user_select = 0;
}
}
//Upper section that is just the name of the dice values
if(user_select ==1){
user_select = 0;
top_full++;
printf("\n\nPlace dice into:\n1) Ones\n2) Twos\n3) Threes\n");
printf("4) Fours\n5) Fives\n6) Sixes\n");
while(user_select<1|| user_select>6){
printf("\nSelection (1-6): ");
scanf("%d",&user_select);
if(score_pos_used[user_select-1]&&user_select>0&&user_select<7){
printf("You have already used that score position please seleect again.");
user_select = 0;
}
}
return user_select;
}
//Lower section display
user_select = 0;
bottom_full++;
printf("\n\nPlace dice into: \n1) Three of a Kind\n2) Four of a Kind: \n3) Small Straight\n");
printf("4) Large Straight\n5) Full House\n6) Yahtzee\n7) Chance");
while(user_select<1||user_select>7){
printf("\nSelection (1-7): ");
scanf("%d",&user_select);
if(score_pos_used[user_select+5]&&user_select>0&&user_select<8){
printf("You have already used that score position please seleect again.");
user_select = 0;
}
}
return(user_select+6);
}
//Stores the user's latest turn wherever they choose
void store_dice(int choice){
int i =0;
int j =0;
int sum = 0;
for(i = 0;i<NUM_DICE;i++){
sum+=roll[i];
}
//Upper data section points calculated by multiplying the recureance of the value by the value
if(choice<7){
upper_data[choice-1] = dice_values[choice-1]*choice;
score_pos_used[choice-1] = 1;
score+=upper_data[choice-1];
return;
}
//If user has 3 of a kind store the dice sum otherwise store 0
if(choice == 7){
for(i = 0;i<6;i++){
if(dice_values[i]>=3){
lower_data[0] = sum;
score_pos_used[6] = 1;
score+=sum;
return;
}
}
lower_data[choice -7] = 0;
score_pos_used[choice-1] = 1;
return;
}
//If user has 4 of a kind store the dice sum otherwise store 0
else if(choice == 8){
for(i = 0;i<6;i++){
if(dice_values[i]>=4){
lower_data[choice-7] = sum;
score_pos_used[choice-1] = 1;
score+=sum;
return;
}
}
lower_data[choice -7] = 0;
score_pos_used[choice-1] = 1;
return;
}
//If user has a small straight stores 30 otherwise stores 0
else if(choice == 9){
if(dice_values[2]>0&&dice_values[3]>0){
if((dice_values[0]>0&&dice_values[1]>0)||(dice_values[1]>0&&dice_values[4]>0)
||(dice_values[4]>0&&dice_values[5]>0)){
lower_data[choice-7] = 30;
score_pos_used[choice-1] = 1;
score+=30;
return;
}
}
lower_data[choice -7] = 0;
score_pos_used[choice-1] = 1;
return;
}
//If user has large straight stores 40 otherwise stores 0
else if(choice == 10){
if(dice_values[1]>0&&dice_values[2]>0&&dice_values[3]>0&&dice_values[4]>0){
if(dice_values[0]>0||dice_values[5]>0){
lower_data[choice-7] = 40;
score_pos_used[choice-1] = 1;
score+=40;
return;
}
}
lower_data[choice -7] = 0;
score_pos_used[choice-1] = 1;
return;
}
//If user has full house store 25 otherwise store 0
else if(choice == 11){
for(i = 0; i<6; i++){
if(dice_values[i] == 3){
for(j=0;j<6;j++){
if(dice_values[j]==2){
lower_data[choice-7] = 25;
score_pos_used[choice-1] = 1;
score+=25;
return;
}
}
}
}
lower_data[choice -7] = 0;
score_pos_used[choice-1] = 1;
return;
}
//If the user has a yahtzee stores 50 otherwise stores 0
else if(choice == 12){
for(i=0;i<6;i++){
if(dice_values[i]==5){
lower_data[choice-7] = 50;
score_pos_used[choice-1] = 1;
score+=50;
return;
}
}
lower_data[choice-7] = 0;
score_pos_used[choice-1] = 1;
return;
}
//If user has picked chance, just store dice sum
else if(choice==13){
lower_data[choice-7] = sum;
score_pos_used[choice-1] = 1;
score+=sum;
return;
}
}
//Displays the user's score after storing the latest turn
void display_score(){
int i =0;
printf("\nYour score: %d\n",score);
printf("\nOnes: ");
if(score_pos_used[i]==1) {printf("%d",upper_data[i++]);}
else {i++;}
printf("\nTwos: ");
if(score_pos_used[i]==1) {printf("%d",upper_data[i++]);}
else {i++;}
printf("\nThrees: ");
if(score_pos_used[i]==1) {printf("%d",upper_data[i++]);}
else {i++;}
printf("\nFours: ");
if(score_pos_used[i]==1) {printf("%d",upper_data[i++]);}
else {i++;}
printf("\nFives: ");
if(score_pos_used[i]==1) {printf("%d",upper_data[i++]);}
else {i++;}
printf("\nSixes: ");
if(score_pos_used[i]==1) {printf("%d",upper_data[i++]);}
else {i++;}
printf("\nUpper Section Bonus: ");
if(has_bonus) {printf("%d",(35));}
else {printf("0");}
printf("\nThree of a Kind: ");
if(score_pos_used[i]==1) {printf("%d",lower_data[i-6]); i++;}
else {i++;}
printf("\nFour of a Kind: ");
if(score_pos_used[i]==1) {printf("%d",lower_data[i-6]); i++;}
else {i++;}
printf("\nSmall Straight: ");
if(score_pos_used[i]==1) {printf("%d",lower_data[i-6]); i++;}
else {i++;}
printf("\nLarge Straight: ");
if(score_pos_used[i]==1) {printf("%d",lower_data[i-6]); i++;}
else {i++;}
printf("\nFull House: ");
if(score_pos_used[i]==1) {printf("%d",lower_data[i-6]); i++;}
else {i++;}
printf("\nYahtzee: ");
if(score_pos_used[i]==1) {printf("%d",lower_data[i-6]); i++;}
else {i++;}
printf("\nChance: ");
if(score_pos_used[i]==1){ printf("%d",lower_data[i-6]); i++;}
else {i++;}
}
//Calls the score storing funciton and then the score display funciton
void get_points(){
int i =0;
int bonus_sum = 0;
//Resets the dice values
for(i = 0;i<6;i++){
dice_values[i]=0;
}
//Stores the number of times each face was in the roll
for(i = 0;i<NUM_DICE;i++){
dice_values[roll[i]-1]++;
}
int choice = display_menu();
store_dice(choice);
//adds the bonus if necessary
if(!has_bonus){
for(i=0;i<6;i++){
bonus_sum += upper_data[i];
}
if(bonus_sum>=63){
score+=35;
has_bonus=1;
}
}
//Displays the current score
display_score();
}
//Represents an individual turn in yahtzee
void play_turn(){
int roll_count = 0;
int i =0;
//Initialize dice for turn
for(i = 0;i<NUM_DICE;i++){
roll[i]=0;
needs_rolled[i]=1;
}
roll_dice(); //initial dice roll
printf("\nYour roll: \n");
printf("%d %d %d %d %d\n",roll[0],roll[1],roll[2],roll[3],roll[4]);
//Rerolls desired dice or user enters 0 to skip rerolling
if(get_dice_to_roll()){
roll_dice();
printf("\nYour second roll: \n");
printf("%d %d %d %d %d\n",roll[0],roll[1],roll[2],roll[3],roll[4]);
//Rolls third and final time if desired
if(get_dice_to_roll()){
roll_dice();
printf("\nYour third roll: \n");
printf("%d %d %d %d %d\n",roll[0],roll[1],roll[2],roll[3],roll[4]);
}
}
printf("\n");
qsort(roll,NUM_DICE,sizeof(int),int_cmp); //sorts the roll for ease of processing
get_points(); //calls subfunction to allow uesr to pick point value of roll
}
//Initalizes global variables and then calls the play_turn function 13 times
int main(void){
srand(time(NULL));
char play_again = 'y';
int i = 0;
char temp_char;
while(play_again=='y'){
//Reset score and bonus
score = 0;
has_bonus = 0;
//Reset the top and bottom full markers
top_full = 0;
bottom_full = 0;
//Initialize score holders for game
lower_data[0] = 0;
for(i = 0;i<6;i++){
lower_data[i+1] = upper_data[i] = -1;
}
//reset score position holder
for(i =0;i<13;i++) {
score_pos_used[i] = 0;
}
//Loop 13 turns
printf("\nBeginning Game of Yahtzee\n");
for(i =0; i < NUM_TURNS; i++){
play_turn();
printf("\n");
scanf("%c",&temp_char);
}
//Allows user to start a new game
play_again = 'k';
while(play_again!='n' && play_again!='y'){
printf("\nDo you want to play again? (y/n): ");
scanf("%c",&play_again);
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<fcntl.h>
#include<netinet/in.h>
#include<netdb.h>
void error_handling(char *message);
int main(int argc, char **argv)
{
int sock;
struct sockaddr_in serv_addr;
char message[BUFSIZ];
int str_len;
if(argc!=3) {
printf("Usage: %s <IP> <port> \n",argv[0]);
exit(1);
}
sock=socket(PF_INET,SOCK_STREAM,0);
if(sock==-1)
error_handling("socket() error");
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(argv[1]);
serv_addr.sin_port=htons(atoi(argv[2]));
if(connect(sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr))==-1)
error_handling("connet() error");
while(1) {
//메시지 입력 및 전송
fputs("전송할 메세지를 입력하세요 (q to quit):" ,stdout);
fgets(message,BUFSIZ,stdin);
if(!strcmp(message,"q\n")) break;
write(sock,message,strlen(message));
//메시지 수신 및 출력
str_len=read(sock,message,BUFSIZ-1);
message[str_len]=0;
printf("서버로부터 전송된 메시지 :%s\n",message);
}
close(sock);
return 0;
}
void error_handling(char *message) {
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *random_array(int n);
int main(void)
{
srand(time(NULL));
int *array = random_array(100);
for (int i = 0; i < 100; i++) {
printf("array[%d] = %d\n", i, array[i]);
}
free(array);
return 0;
}
int *random_array(int n)
{
int *array;
array = calloc(n, sizeof(array));
if (array != NULL) {
for (int i = 0; i < n; i++) {
array[i] = rand()%100;
}
}
return array;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.