file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/147205.c | #include <sys/time.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
void *proc();
int shared_number;
main()
{
int i;
pthread_t new_thread;
int sleep_time;
int seed;
shared_number = 1;
printf("Enter a positive integer for seed: ");
scanf("%d",&seed);
srand48(seed); /* initialize seed of random number stream */
/* thr_create(NULL,0,proc,NULL,0,&new_thread);*/
pthread_create(&new_thread,NULL,proc,NULL);
/* create new thread */
for (i = 0; i < 50; i++)
{
printf("MAIN THREAD: i = %d, shared_number = %d\n",i,shared_number);
sleep_time = 100000.0*drand48(); /* generate random sleep time */
printf("sleep time = %d microseconds\n",sleep_time);
usleep(sleep_time);
shared_number = shared_number + 2;
}
pthread_join(new_thread,NULL);
printf("MAIN THREAD: DONE\n");
}
void *proc()
{
int i = 0;
int DONE;
DONE = 0;
while (!DONE)
{
i++;
if (i%10000 == 0)
printf("CHILD THREAD: i = %d,shared_number = %d\n",i,shared_number);
if (i > 5000000)
DONE = 1;
}
printf("CHILD THREAD: DONE\n");
}
|
the_stack_data/67326669.c | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex;
int a=99;
void do_sig(int signum) {
printf("in signal: %ld\n", pthread_self());
pthread_mutex_lock(&mutex);
printf("do_sig...\n");
a = 0;
pthread_mutex_unlock(&mutex);
return;
}
void * thread_func_one(void *arg) {
int i = 0;
sigset_t signal_mask; //屏蔽47
sigemptyset (&signal_mask);
sigaddset(&signal_mask, 47);
int rc = pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
if(rc != 0) {
printf("block sigpipe error\n");
}
while(1) {
pthread_mutex_lock(&mutex);
for(i = 0; i < 10; i++) {
printf("in thread:%ld %d...\n", pthread_self(), i + 1);
//pthread_mutex_lock(&mutex);
sleep(1);
}
pthread_mutex_unlock(&mutex);
printf("-----------------\n");
sleep(1); //必须睡
}
return NULL;
}
int main() { //起线程1一直占用锁 主线程接受信号然后调信号函数 信号回调中阻塞等待锁 ------>如果线程1不sleep1则信号回调中一直拿不到锁 然后傻屌测试再去发信号 而此时接受信号的不是主线程了而是线程1 又造成死锁
//造成死锁的原因是什么? 就是线程1接受了信号 应该让线程1屏蔽这个信号
pthread_t pid;
if (signal(47, do_sig) == SIG_ERR) {
perror("signal");
exit(1);
}
pthread_mutex_init(&mutex, NULL);
if(0 != pthread_create( &pid, NULL, thread_func_one, NULL)) {
printf("pthread create failed!/n");
return -1;
}
pthread_join(pid, NULL);
return 0;
}
int main1(void) { //只有一个主线程 主进程一直占用锁 一旦信号来了则打断主进程再去加锁 造成死锁
if (signal(47, do_sig) == SIG_ERR) {
perror("signal");
exit(1);
}
pthread_mutex_init(&mutex, NULL);
int i = 0;
while(1) {
pthread_mutex_lock(&mutex);
for(i = 0; i < 10; i++) {
printf("in main %d...\n", i + 1);
//pthread_mutex_lock(&mutex);
sleep(1);
}
pthread_mutex_unlock(&mutex);
printf("-----------------\n");
}
return 0;
}
int main0(void) { //必须-lpthread 如果不链就不会出现死锁 很奇怪
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex1);
a = 777;
pthread_mutex_lock(&mutex1);
pthread_mutex_unlock(&mutex1);
printf("-----------a = %d\n", a);
pthread_mutex_destroy(&mutex1);
return 0;
}
|
the_stack_data/20451188.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include "wait.h"
/* The files are in csv format */
#define OFILE "file5.csv"
#define IFILE1 "file2.csv"
#define PFILE "NPCx.csv"
#define TRUE 1
#define FALSE 0
double x_apc, x_pre; //inputs continuous
//Continuous variables and Outputs
extern double v_aggregate; //output continuous g
unsigned char VSP, VS;
/* The tick counter */
/* It is static to hide it inside this file */
static size_t tick = 0;
/* The output file pointer */
FILE *fo = NULL;
/* The input file pointer */
FILE *fi1 = NULL;
FILE *fp = NULL;
static inline unsigned char getValue(unsigned char t, char* e){
assert(t == TRUE || t == FALSE);
return t;
}
/* Read input x from file */
/* Read input x from file */
void readInput() {
static unsigned char count = 0;
/* The check here is very expensive! */
if(0 == count) {
fi1 = fopen(IFILE1, "r");
if (fi1 == NULL){
perror(IFILE1);
exit(1);
}
++count;
}
/* The format of input is 1 line/tick */
/* for the events above the format is: */
/*
ON, ON_Value, C, C_Value, B, B_Value, OFF, OFF_Value
*/
char in1[256];
while (fgets(in1,255,fi1) == NULL ){
perror("No input");
waitFor();
//exit(1);
}
//else{
// input 1
char *ret = NULL, *v = NULL;
ret = strtok(in1, ",");
if(ret == NULL){
/* This means nothing found! */
/* Set all events to false */
perror("NULL strtok error");
exit(1);
}
while(ret != NULL) {
v = strtok(NULL, ",");
if (v != NULL) {
if (strcmp(ret, "x_apc") == 0){
x_apc = atof(v);
}
}
else {
perror("NULL while scanning input");
exit(1);
}
/* Read the next one! */
ret = strtok(NULL, ",");
}
fprintf(stdout, "%s:%f tick:%ld\n", "x_apc", x_apc, tick);
fflush(stdout);
}
/* Read previous state */
void readPreviousState() {
static unsigned char count = 0;
/* The check here is very expensive! */
if(0 == count) {
fp = fopen(PFILE, "r");
if (fp == NULL){
perror(PFILE);
exit(1);
}
++count;
}
/* The format of input is 1 line/tick */
/* for the events above the format is: */
/*
ON, ON_Value, C, C_Value, B, B_Value, OFF, OFF_Value
*/
char pre[256];
while (fgets(pre,255,fp) == NULL ){
perror("No input");
waitFor();
}
char *retp = NULL, *vp = NULL;
retp = strtok(pre, ",");
if(retp == NULL){
/* This means nothing found! */
perror("NULL strtok error");
exit(1);
}
while(retp != NULL) {
vp = strtok(NULL, ",");
if (vp != NULL) {
if (strcmp(retp, "x1") == 0){
x_pre = atof(vp);
}
}
else {
perror("NULL while scanning input");
exit(1);
}
/* Read the next one! */
retp = strtok(NULL, ",");
}
fprintf(stdout, "%s:%f tick:%ld\n","x_pre", x_pre, tick);
fflush(stdout);
}
/* Write output x to file */
void writeOutput(){
static unsigned char count = 0;
if (0 == count){
fo = fopen(OFILE, "w");
if (fo == NULL){
perror(OFILE);
exit(1);
}
fclose(fo);
++count;
}
// each write...
fo = fopen(OFILE, "a");
if (fo == NULL){
perror(OFILE);
exit(1);
}
fprintf(fo, "VS,0,VSP,0,g,%f\n",v_aggregate);
fflush(fo);
fclose(fo);
tick++;
}
|
the_stack_data/321499.c | #define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <time.h>
#define PI 3.14159265
int sinp(double d)
{
double s = sin(d * (PI / 180));
return (int) ((s * 100) * 0.8) + 80;
}
int cosp(double d)
{
double s = cos(d * (PI / 180));
return (int) ((s * 100) * 0.8) + 80;
}
int main(void)
{
while(true)
for (double d = 0;d < 360;d++)
{
int ps = sinp(d);
int pc = cosp(d);
for (int i = 0;i < ps;i++)
printf(" ");
printf("X\n");
for (int i = 0;i < pc;i++)
printf(" ");
printf("Y\n");
struct timespec tp;
tp.tv_nsec = (1000 * 1000 * 3);
tp.tv_sec = 0;
nanosleep(&tp, NULL);
}
return 0;
}
|
the_stack_data/150143990.c | /* * Copyright 2022 Yury Gribov
*
* The MIT License (MIT)
*▫
* Use of this source code is governed by MIT license that can be
* found in the LICENSE.txt file.
*/
#include <stdlib.h>
#ifdef __clang__
# define noipa optnone
#elif __GNUC__ < 8
# define noipa noinline,noclone
#endif
int *buf;
__attribute__((noipa))
int error() {
return buf[1];
}
int main() {
buf = (int *)malloc(1);
return error();
}
|
the_stack_data/167331667.c | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
void show(int t,int h){
for(int i=1; i < (t>h?h:t);i++){
printf(" ");
}
if(t==h&&t)printf("OUCH!!!");
else{
printf((t>h?"H":"T"));
for(int i=(t>h?h:t)+1;i<(t>h?t:h);i++)printf(" ");
printf((t>h?"T":"H"));
}
for(int i=(t>h?t:h);i<80;i++)printf(" ");
printf("\r");
fflush(stdout);
}
int main(){
printf("BANG !!!!!\nAND THEY'RE OFF !!!!!\n");
srand(time(NULL));
for(int h=0,t=0;1;sleep(1)){
switch(rand()%10){
case 0:
case 1:
case 2:
case 3:
case 4:
t+=3;
break;
case 5:
case 6:
t-=6;
if(t<0)t=0;
break;
case 7:
case 8:
case 9:
t++;
}
switch(rand()%10){
case 0:
case 1:
break;
case 2:
case 3:
h+=9;
break;
case 4:
h-=12;
if(h<0)h=0;
break;
case 5:
case 6:
case 7:
h+=1;
break;
case 8:
case 9:
h--;
if(h<0)h=0;
}
if(h>=70&&t>=70){
puts("\nTIE!");
break;
}
if(h>=70){
puts("\nHARE WINS!!! YAY!!!");
break;
}
if(t>=70){
puts("\nTORTOISE WINS!!! YAY!!! ");
break;
}
show(t,h);
}
} |
the_stack_data/206394536.c | /*
* multi-server.c
*/
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include <time.h> /* for time() */
#include <netdb.h> /* for gethostbyname() */
#include <signal.h> /* for signal() */
#include <sys/stat.h> /* for stat() */
#define MAXPENDING 5 /* Maximum outstanding connection requests */
#define DISK_IO_BUF_SIZE 4096
static void die(const char *message)
{
perror(message);
exit(1);
}
/*
* Create a listening socket bound to the given port.
*/
static int createServerSocket(unsigned short port)
{
int servSock;
struct sockaddr_in servAddr;
/* Create socket for incoming connections */
if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
die("socket() failed");
/* Construct local address structure */
memset(&servAddr, 0, sizeof(servAddr)); /* Zero out structure */
servAddr.sin_family = AF_INET; /* Internet address family */
servAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
servAddr.sin_port = htons(port); /* Local port */
/* Bind to the local address */
if (bind(servSock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0)
die("bind() failed");
/* Mark the socket so it will listen for incoming connections */
if (listen(servSock, MAXPENDING) < 0)
die("listen() failed");
return servSock;
}
/*
* A wrapper around send() that does error checking and logging.
* Returns -1 on failure.
*
* This function assumes that buf is a null-terminated string, so
* don't use this function to send binary data.
*/
ssize_t Send(int sock, const char *buf)
{
size_t len = strlen(buf);
ssize_t res = send(sock, buf, len, 0);
if (res != len) {
perror("send() failed");
return -1;
}
else
return res;
}
/*
* HTTP/1.0 status codes and the corresponding reason phrases.
*/
static struct {
int status;
char *reason;
} HTTP_StatusCodes[] = {
{ 200, "OK" },
{ 201, "Created" },
{ 202, "Accepted" },
{ 204, "No Content" },
{ 301, "Moved Permanently" },
{ 302, "Moved Temporarily" },
{ 304, "Not Modified" },
{ 400, "Bad Request" },
{ 401, "Unauthorized" },
{ 403, "Forbidden" },
{ 404, "Not Found" },
{ 500, "Internal Server Error" },
{ 501, "Not Implemented" },
{ 502, "Bad Gateway" },
{ 503, "Service Unavailable" },
{ 0, NULL } // marks the end of the list
};
static inline const char *getReasonPhrase(int statusCode)
{
int i = 0;
while (HTTP_StatusCodes[i].status > 0) {
if (HTTP_StatusCodes[i].status == statusCode)
return HTTP_StatusCodes[i].reason;
i++;
}
return "Unknown Status Code";
}
/*
* Send HTTP status line followed by a blank line.
*/
static void sendStatusLine(int clntSock, int statusCode)
{
char buf[1000];
const char *reasonPhrase = getReasonPhrase(statusCode);
// print the status line into the buffer
sprintf(buf, "HTTP/1.0 %d ", statusCode);
strcat(buf, reasonPhrase);
strcat(buf, "\r\n");
// We don't send any HTTP header in this simple server.
// We need to send a blank line to signal the end of headers.
strcat(buf, "\r\n");
// For non-200 status, format the status line as an HTML content
// so that browers can display it.
if (statusCode != 200) {
char body[1000];
sprintf(body,
"<html><body>\n"
"<h1>%d %s</h1>\n"
"</body></html>\n",
statusCode, reasonPhrase);
strcat(buf, body);
}
// send the buffer to the browser
Send(clntSock, buf);
}
/*
* Handle static file requests.
* Returns the HTTP status code that was sent to the browser.
*/
static int handleFileRequest(
const char *webRoot, const char *requestURI, int clntSock)
{
int statusCode;
FILE *fp = NULL;
// Compose the file path from webRoot and requestURI.
// If requestURI ends with '/', append "index.html".
char *file = (char *)malloc(strlen(webRoot) + strlen(requestURI) + 100);
if (file == NULL)
die("malloc failed");
strcpy(file, webRoot);
strcat(file, requestURI);
if (file[strlen(file)-1] == '/') {
strcat(file, "index.html");
}
// See if the requested file is a directory.
// Our server does not support directory listing.
struct stat st;
if (stat(file, &st) == 0 && S_ISDIR(st.st_mode)) {
statusCode = 403; // "Forbidden"
sendStatusLine(clntSock, statusCode);
goto func_end;
}
// If unable to open the file, send "404 Not Found".
fp = fopen(file, "rb");
if (fp == NULL) {
statusCode = 404; // "Not Found"
sendStatusLine(clntSock, statusCode);
goto func_end;
}
// Otherwise, send "200 OK" followed by the file content.
statusCode = 200; // "OK"
sendStatusLine(clntSock, statusCode);
// send the file
size_t n;
char buf[DISK_IO_BUF_SIZE];
while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
if (send(clntSock, buf, n, 0) != n) {
// send() failed.
// We log the failure, break out of the loop,
// and let the server continue on with the next request.
perror("\nsend() failed");
break;
}
}
// fread() returns 0 both on EOF and on error.
// Let's check if there was an error.
if (ferror(fp))
perror("fread failed");
func_end:
// clean up
free(file);
if (fp)
fclose(fp);
return statusCode;
}
int main(int argc, char *argv[])
{
// Ignore SIGPIPE so that we don't terminate when we call
// send() on a disconnected socket.
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
die("signal() failed");
if (argc != 3) {
fprintf(stderr, "usage: %s <server_port> <web_root>\n", argv[0]);
exit(1);
}
unsigned short servPort = atoi(argv[1]);
const char *webRoot = argv[2];
int servSock = createServerSocket(servPort);
char line[1000];
char requestLine[1000];
int statusCode;
struct sockaddr_in clntAddr;
for (;;) {
/*
* wait for a client to connect
*/
// initialize the in-out parameter
unsigned int clntLen = sizeof(clntAddr);
int clntSock = accept(servSock, (struct sockaddr *)&clntAddr, &clntLen);
if (clntSock < 0)
die("accept() failed");
FILE *clntFp = fdopen(clntSock, "r");
if (clntFp == NULL)
die("fdopen failed");
/*
* Let's parse the request line.
*/
char *method = "";
char *requestURI = "";
char *httpVersion = "";
if (fgets(requestLine, sizeof(requestLine), clntFp) == NULL) {
// socket closed - there isn't much we can do
statusCode = 400; // "Bad Request"
goto loop_end;
}
char *token_separators = "\t \r\n"; // tab, space, new line
method = strtok(requestLine, token_separators);
requestURI = strtok(NULL, token_separators);
httpVersion = strtok(NULL, token_separators);
char *extraThingsOnRequestLine = strtok(NULL, token_separators);
// check if we have 3 (and only 3) things in the request line
if (!method || !requestURI || !httpVersion ||
extraThingsOnRequestLine) {
statusCode = 501; // "Not Implemented"
sendStatusLine(clntSock, statusCode);
goto loop_end;
}
// we only support GET method
if (strcmp(method, "GET") != 0) {
statusCode = 501; // "Not Implemented"
sendStatusLine(clntSock, statusCode);
goto loop_end;
}
// we only support HTTP/1.0 and HTTP/1.1
if (strcmp(httpVersion, "HTTP/1.0") != 0 &&
strcmp(httpVersion, "HTTP/1.1") != 0) {
statusCode = 501; // "Not Implemented"
sendStatusLine(clntSock, statusCode);
goto loop_end;
}
// requestURI must begin with "/"
if (!requestURI || *requestURI != '/') {
statusCode = 400; // "Bad Request"
sendStatusLine(clntSock, statusCode);
goto loop_end;
}
// make sure that the requestURI does not contain "/../" and
// does not end with "/..", which would be a big security hole!
int len = strlen(requestURI);
if (len >= 3) {
char *tail = requestURI + (len - 3);
if (strcmp(tail, "/..") == 0 ||
strstr(requestURI, "/../") != NULL)
{
statusCode = 400; // "Bad Request"
sendStatusLine(clntSock, statusCode);
goto loop_end;
}
}
/*
* Now let's skip all headers.
*/
while (1) {
if (fgets(line, sizeof(line), clntFp) == NULL) {
// socket closed prematurely - there isn't much we can do
statusCode = 400; // "Bad Request"
goto loop_end;
}
if (strcmp("\r\n", line) == 0 || strcmp("\n", line) == 0) {
// This marks the end of headers.
// Break out of the while loop.
break;
}
}
/*
* At this point, we have a well-formed HTTP GET request.
* Let's handle it.
*/
statusCode = handleFileRequest(webRoot, requestURI, clntSock);
loop_end:
/*
* Done with client request.
* Log it, close the client socket, and go back to accepting
* connection.
*/
fprintf(stderr, "%s \"%s %s %s\" %d %s\n",
inet_ntoa(clntAddr.sin_addr),
method,
requestURI,
httpVersion,
statusCode,
getReasonPhrase(statusCode));
// close the client socket
fclose(clntFp);
} // for (;;)
return 0;
}
|
the_stack_data/212643997.c | /* badcount.c -- the situation of wrong parameters */
#include <stdio.h>
int main(void)
{
int n = 4;
int m = 5;
float f = 7.0f;
float g = 8.0f;
printf("%d\n", n, m); /* Too many parameters */
printf("%d %d %d\n", n); /* Too little parameters */
printf("%d %d\n", f, g); /* The type of parameters don't match */
return 0;
} |
the_stack_data/220456151.c | #include <stdio.h>
void main()
{
float n1;
float n2;
float result;
scanf("%f %f",&n1,&n2);
result=n1/n2;
printf("%.2f\n",result);
}
|
the_stack_data/62637183.c | #if bios == 1
#include <pxe/tftp.h>
#include <pxe/pxe.h>
#include <lib/real.h>
#include <lib/print.h>
#include <lib/libc.h>
#include <mm/pmm.h>
#include <lib/blib.h>
uint32_t get_boot_server_info(void) {
struct pxenv_get_cached_info cachedinfo = { 0 };
cachedinfo.packet_type = 2;
pxe_call(PXENV_GET_CACHED_INFO, ((uint16_t)rm_seg(&cachedinfo)), (uint16_t)rm_off(&cachedinfo));
struct bootph *ph = (struct bootph*)(void *) (((((uint32_t)cachedinfo.buffer) >> 16) << 4) + (((uint32_t)cachedinfo.buffer) & 0xFFFF));
return ph->sip;
}
bool tftp_open(struct file_handle *handle, uint32_t server_ip, uint16_t server_port, const char *name) {
int ret = 0;
if (!server_ip) {
server_ip = get_boot_server_info();
}
struct PXENV_UNDI_GET_INFORMATION undi_info = { 0 };
ret = pxe_call(UNDI_GET_INFORMATION, ((uint16_t)rm_seg(&undi_info)), (uint16_t)rm_off(&undi_info));
if (ret) {
return false;
}
//TODO figure out a more proper way to do this.
uint16_t mtu = undi_info.MaxTranUnit - 48;
struct pxenv_get_file_size fsize = {
.status = 0,
.sip = server_ip,
};
strcpy((char*)fsize.name, name);
ret = pxe_call(TFTP_GET_FILE_SIZE, ((uint16_t)rm_seg(&fsize)), (uint16_t)rm_off(&fsize));
if (ret) {
return false;
}
handle->size = fsize.file_size;
handle->is_memfile = true;
struct pxenv_open open = {
.status = 0,
.sip = server_ip,
.port = (server_port) << 8,
.packet_size = mtu
};
strcpy((char*)open.name, name);
ret = pxe_call(TFTP_OPEN, ((uint16_t)rm_seg(&open)), (uint16_t)rm_off(&open));
if (ret) {
print("tftp: Failed to open file %x or bad packet size", open.status);
return false;
}
mtu = open.packet_size;
uint8_t *buf = conv_mem_alloc(mtu);
handle->fd = ext_mem_alloc(handle->size);
size_t progress = 0;
bool slow = false;
while (progress < handle->size) {
struct pxenv_read read = {
.boff = ((uint16_t)rm_off(buf)),
.bseg = ((uint16_t)rm_seg(buf)),
};
ret = pxe_call(TFTP_READ, ((uint16_t)rm_seg(&read)), (uint16_t)rm_off(&read));
if (ret) {
panic("tftp: Read failure");
}
memcpy(handle->fd + progress, buf, read.bsize);
progress += read.bsize;
if (read.bsize < mtu && !slow && progress < handle->size) {
slow = true;
print("tftp: Server is sending the file in smaller packets (it sent %d bytes), download might take longer.\n", read.bsize);
}
}
uint16_t close = 0;
ret = pxe_call(TFTP_CLOSE, ((uint16_t)rm_seg(&close)), (uint16_t)rm_off(&close));
if (ret) {
panic("tftp: Close failure");
}
pmm_free(buf, mtu);
return true;
}
#endif
|
the_stack_data/96770.c | // EXPECT: 0
int main() {
return 0 || 0;
} |
the_stack_data/9477.c | /**
@file win32.c
@brief ENet Win32 system specific functions
*/
#ifdef WIN32
#include <time.h>
#define ENET_BUILDING_LIB 1
#include "enet/enet.h"
static enet_uint32 timeBase = 0;
int
enet_initialize (void)
{
WORD versionRequested = MAKEWORD (1, 1);
WSADATA wsaData;
if (WSAStartup (versionRequested, & wsaData))
return -1;
if (LOBYTE (wsaData.wVersion) != 1||
HIBYTE (wsaData.wVersion) != 1)
{
WSACleanup ();
return -1;
}
timeBeginPeriod (1);
return 0;
}
void
enet_deinitialize (void)
{
timeEndPeriod (1);
WSACleanup ();
}
enet_uint32
enet_time_get (void)
{
return (enet_uint32) timeGetTime () - timeBase;
}
void
enet_time_set (enet_uint32 newTimeBase)
{
timeBase = (enet_uint32) timeGetTime () - newTimeBase;
}
int
enet_address_set_host (ENetAddress * address, const char * name)
{
struct hostent * hostEntry;
hostEntry = gethostbyname (name);
if (hostEntry == NULL ||
hostEntry -> h_addrtype != AF_INET)
{
unsigned long host = inet_addr (name);
if (host == INADDR_NONE)
return -1;
address -> host = host;
return 0;
}
address -> host = * (enet_uint32 *) hostEntry -> h_addr_list [0];
return 0;
}
int
enet_address_get_host_ip (const ENetAddress * address, char * name, size_t nameLength)
{
char * addr = inet_ntoa (* (struct in_addr *) & address -> host);
if (addr == NULL)
return -1;
strncpy (name, addr, nameLength);
return 0;
}
int
enet_address_get_host (const ENetAddress * address, char * name, size_t nameLength)
{
struct in_addr in;
struct hostent * hostEntry;
in.s_addr = address -> host;
hostEntry = gethostbyaddr ((char *) & in, sizeof (struct in_addr), AF_INET);
if (hostEntry == NULL)
return enet_address_get_host_ip (address, name, nameLength);
strncpy (name, hostEntry -> h_name, nameLength);
return 0;
}
int
enet_socket_bind (ENetSocket socket, const ENetAddress * address)
{
struct sockaddr_in sin;
memset (& sin, 0, sizeof (struct sockaddr_in));
sin.sin_family = AF_INET;
if (address != NULL)
{
sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);
sin.sin_addr.s_addr = address -> host;
}
else
{
sin.sin_port = 0;
sin.sin_addr.s_addr = INADDR_ANY;
}
return bind (socket,
(struct sockaddr *) & sin,
sizeof (struct sockaddr_in)) == SOCKET_ERROR ? -1 : 0;
}
int
enet_socket_listen (ENetSocket socket, int backlog)
{
return listen (socket, backlog < 0 ? SOMAXCONN : backlog) == SOCKET_ERROR ? -1 : 0;
}
ENetSocket
enet_socket_create (ENetSocketType type)
{
return socket (PF_INET, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
}
int
enet_socket_set_option (ENetSocket socket, ENetSocketOption option, int value)
{
int result = SOCKET_ERROR;
switch (option)
{
case ENET_SOCKOPT_NONBLOCK:
{
u_long nonBlocking = (u_long) value;
result = ioctlsocket (socket, FIONBIO, & nonBlocking);
break;
}
case ENET_SOCKOPT_BROADCAST:
result = setsockopt (socket, SOL_SOCKET, SO_BROADCAST, (char *) & value, sizeof (int));
break;
case ENET_SOCKOPT_REUSEADDR:
result = setsockopt (socket, SOL_SOCKET, SO_REUSEADDR, (char *) & value, sizeof (int));
break;
case ENET_SOCKOPT_RCVBUF:
result = setsockopt (socket, SOL_SOCKET, SO_RCVBUF, (char *) & value, sizeof (int));
break;
case ENET_SOCKOPT_SNDBUF:
result = setsockopt (socket, SOL_SOCKET, SO_SNDBUF, (char *) & value, sizeof (int));
break;
case ENET_SOCKOPT_RCVTIMEO:
result = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) & value, sizeof (int));
break;
case ENET_SOCKOPT_SNDTIMEO:
result = setsockopt (socket, SOL_SOCKET, SO_SNDTIMEO, (char *) & value, sizeof (int));
break;
default:
break;
}
return result == SOCKET_ERROR ? -1 : 0;
}
int
enet_socket_connect (ENetSocket socket, const ENetAddress * address)
{
struct sockaddr_in sin;
memset (& sin, 0, sizeof (struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);
sin.sin_addr.s_addr = address -> host;
return connect (socket, (struct sockaddr *) & sin, sizeof (struct sockaddr_in)) == SOCKET_ERROR ? -1 : 0;
}
ENetSocket
enet_socket_accept (ENetSocket socket, ENetAddress * address)
{
SOCKET result;
struct sockaddr_in sin;
int sinLength = sizeof (struct sockaddr_in);
result = accept (socket,
address != NULL ? (struct sockaddr *) & sin : NULL,
address != NULL ? & sinLength : NULL);
if (result == INVALID_SOCKET)
return ENET_SOCKET_NULL;
if (address != NULL)
{
address -> host = (enet_uint32) sin.sin_addr.s_addr;
address -> port = ENET_NET_TO_HOST_16 (sin.sin_port);
}
return result;
}
void
enet_socket_destroy (ENetSocket socket)
{
closesocket (socket);
}
int
enet_socket_send (ENetSocket socket,
const ENetAddress * address,
const ENetBuffer * buffers,
size_t bufferCount)
{
struct sockaddr_in sin;
DWORD sentLength;
if (address != NULL)
{
memset (& sin, 0, sizeof (struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);
sin.sin_addr.s_addr = address -> host;
}
if (WSASendTo (socket,
(LPWSABUF) buffers,
(DWORD) bufferCount,
& sentLength,
0,
address != NULL ? (struct sockaddr *) & sin : NULL,
address != NULL ? sizeof (struct sockaddr_in) : 0,
NULL,
NULL) == SOCKET_ERROR)
{
if (WSAGetLastError () == WSAEWOULDBLOCK)
return 0;
return -1;
}
return (int) sentLength;
}
int
enet_socket_receive (ENetSocket socket,
ENetAddress * address,
ENetBuffer * buffers,
size_t bufferCount)
{
INT sinLength = sizeof (struct sockaddr_in);
DWORD flags = 0,
recvLength;
struct sockaddr_in sin;
if (WSARecvFrom (socket,
(LPWSABUF) buffers,
(DWORD) bufferCount,
& recvLength,
& flags,
address != NULL ? (struct sockaddr *) & sin : NULL,
address != NULL ? & sinLength : NULL,
NULL,
NULL) == SOCKET_ERROR)
{
switch (WSAGetLastError ())
{
case WSAEWOULDBLOCK:
case WSAECONNRESET:
return 0;
}
return -1;
}
if (flags & MSG_PARTIAL)
return -1;
if (address != NULL)
{
address -> host = (enet_uint32) sin.sin_addr.s_addr;
address -> port = ENET_NET_TO_HOST_16 (sin.sin_port);
}
return (int) recvLength;
}
int
enet_socketset_select (ENetSocket maxSocket, ENetSocketSet * readSet, ENetSocketSet * writeSet, enet_uint32 timeout)
{
struct timeval timeVal;
timeVal.tv_sec = timeout / 1000;
timeVal.tv_usec = (timeout % 1000) * 1000;
return select (maxSocket + 1, readSet, writeSet, NULL, & timeVal);
}
int
enet_socket_wait (ENetSocket socket, enet_uint32 * condition, enet_uint32 timeout)
{
fd_set readSet, writeSet;
struct timeval timeVal;
int selectCount;
timeVal.tv_sec = timeout / 1000;
timeVal.tv_usec = (timeout % 1000) * 1000;
FD_ZERO (& readSet);
FD_ZERO (& writeSet);
if (* condition & ENET_SOCKET_WAIT_SEND)
FD_SET (socket, & writeSet);
if (* condition & ENET_SOCKET_WAIT_RECEIVE)
FD_SET (socket, & readSet);
selectCount = select (socket + 1, & readSet, & writeSet, NULL, & timeVal);
if (selectCount < 0)
return -1;
* condition = ENET_SOCKET_WAIT_NONE;
if (selectCount == 0)
return 0;
if (FD_ISSET (socket, & writeSet))
* condition |= ENET_SOCKET_WAIT_SEND;
if (FD_ISSET (socket, & readSet))
* condition |= ENET_SOCKET_WAIT_RECEIVE;
return 0;
}
#endif
|
the_stack_data/76236.c | /*
* main.c
*
* Created on: 14-12-2014
* Author: jacek
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <openssl/md5.h>
#define ILOSC_HASEL 150
#define ILOSC_SLOWNIK 350000
/*
Struktura przeznaczona do komunikacji między wątkami,
a także przechowująca zwerifykowane klucze
mutex - mutex
wyniki - tablica zweryfikowanych kluczy
nput - zmienna informujaca o ilosci znalezionych kluczy
*/
struct {
pthread_mutex_t mutex;
char wyniki[ILOSC_HASEL][33], wyn[ILOSC_HASEL][33];
int nput;
} shared = { PTHREAD_MUTEX_INITIALIZER };
char tablica[ILOSC_SLOWNIK+1][33]; // Tablica słownika
//char *tablica[33];
char tablicaMD5[ILOSC_HASEL][33]; // Tablica kluczów do sprawdzenia
void *Producent1(void *), *Producent2(void *),
*Producent3(void *), *Producent4(void *),
*Producent5(void *), *Producent6(void *),
*Konsument(void *); // Deklaracja wątków producenta i konsumenta
// Wątek główny/nadzorujący main
int main(){
// tablica = (char*) malloc(ILOSC_SLOWNIK * sizeof(*tablica));
FILE *plik_MD5; // otwierany plik haseł
FILE *plik; // otwierany plik słownika
char w_slownika[30]; // wyraz w słowniku
int i = 0;
char nazwa_pliku[20]; // nazwa pobieranego pliku haseł
char mdString[33]; // zmienna przechowująca jeden klucz
pthread_t produce[6], consume; // deklaracja wątków
printf("Podaj nazwe pliku z haslami: ");
scanf("%s", nazwa_pliku);
plik_MD5 = fopen(nazwa_pliku,"r"); // otwieranie pliku z hasłami
if (plik_MD5 == NULL)
{
printf("Blad otwarcia pliku\n");
return 1;
}
while(!feof(plik_MD5)) // czytaj dopóki nie ma końca pliku
{
fscanf(plik_MD5, "%s", mdString);
strcpy(tablicaMD5[i], mdString); // kopiuj string do tablicy globalnej
i++;
}
fclose(plik_MD5); // zamknięcie pliku z hasłami
i = 0;
plik = fopen("dictionary.txt","r"); // otwarcie pliku słownika
if (plik == NULL)
{
printf("Blad otwarcia pliku\n");
return 2;
}
while(!feof(plik)) // dopóki plik się nie kończy czytaj
{
fscanf(plik, "%s", w_slownika);
strcpy(tablica[i], w_slownika);
i++;
if(i == ILOSC_SLOWNIK) break;
}
fclose(plik); // zamknięcie pliku słownika
pthread_create(&consume, NULL, Konsument, NULL); // rozpoczęcie wątku konsumenta
pthread_create(&produce[0], NULL, Producent1, NULL); // rozpoczęcie wątku producenta1
pthread_create(&produce[1], NULL, Producent2, NULL); // rozpoczęcie wątku producenta2
pthread_create(&produce[2], NULL, Producent3, NULL); // rozpoczęcie wątku producenta3
pthread_create(&produce[3], NULL, Producent4, NULL); // rozpoczęcie wątku producenta4
pthread_create(&produce[4], NULL, Producent5, NULL); // rozpoczęcie wątku producenta5
pthread_create(&produce[5], NULL, Producent6, NULL); // rozpoczęcie wątku producenta6
pthread_join(produce[0], NULL); // oczekiwanie na zakończenie wątku producentów
pthread_join(produce[1], NULL);
pthread_join(produce[2], NULL);
pthread_join(produce[3], NULL);
pthread_join(produce[4], NULL);
pthread_join(produce[5], NULL);
pthread_join(consume, NULL); // oczekiwanie na zakończenie wątku konsumenta
return 0;
}
/*
Wątki producenta
*/
/*
Producent 4 - hasło+liczba
*/
void *Producent4(void *arg){
int i = 0, j, k, liczba;
char liczba_str[33]; // liczba w stringu
char tablica_i[33];
char polaczany[66]; // połączone hasło
unsigned char digest[16]; // zmienne do transformacji stringa na klucz MD5
char mdString[33], pom[33];
while(1){ // nieskończona pętla
for(i = 0; i < ILOSC_SLOWNIK; i++){ // dla każdego hasła w słowniku
strcpy(tablica_i, tablica[i]);
for(j = 0; j < strlen(tablica_i); j++) // zamień wszystkie litery na małe
tablica_i[j] = tolower(tablica_i[j]);
strcpy(polaczany, tablica_i);
sprintf(liczba_str, "%i", liczba); // dodaj do hasła liczbę
strcat(polaczany, liczba_str);
MD5_CTX ctx; // zmienna MD5
MD5_Init(&ctx); // inicjalizacja generowania MD5
MD5_Update(&ctx, polaczany, strlen(polaczany));
MD5_Final(digest, &ctx); // wygenerowanie MD5
for(k = 0; k < 16; k++){
sprintf(&mdString[k*2], "%02x", (unsigned int)digest[k]); // zamiana wygenerowanej funkcji na ciąg znaków
}
strcpy(pom,polaczany);
strcpy(polaczany, mdString);
for(k = 0; k < ILOSC_HASEL; k++){
if(strcmp(polaczany, tablicaMD5[k]) == 0){
printf("Znaleziono takie same klucze dla pozycji %i!\n", k);
strcpy(shared.wyniki[shared.nput], tablicaMD5[k]); // skopiowanie otrzymanego wyniku do tablicy
strcpy(shared.wyn[shared.nput], pom);
shared.nput++; // zwiększenie ilości znalezionych wyników
// return(NULL); // zamknięcie działania producenta
}
}
}
liczba++;
}
}
/*
Producent 5 - Hasło+liczba
*/
void *Producent5(void *arg){
int i = 0, j, k, liczba;
char liczba_str[33];
char tablica_i[33];
char polaczany[66];
unsigned char digest[16];
char mdString[33],pom[33];
while(1){
for(i = 0; i < ILOSC_SLOWNIK; i++){
strcpy(tablica_i, tablica[i]);
tablica_i[0] = toupper(tablica_i[0]);
for(j = 1; j < strlen(tablica_i); j++)
tablica_i[j] = tolower(tablica_i[j]);
strcpy(polaczany, tablica_i);
sprintf(liczba_str, "%i", liczba);
strcat(polaczany, liczba_str);
MD5_CTX ctx; // zmienna MD5
MD5_Init(&ctx); // inicjalizacja generowania MD5
MD5_Update(&ctx, polaczany, strlen(polaczany));
MD5_Final(digest, &ctx); // wygenerowanie MD5
for(k = 0; k < 16; k++){
sprintf(&mdString[k*2], "%02x", (unsigned int)digest[k]); // zamiana wygenerowanej funkcji na ciąg znaków
}
strcpy(pom,polaczany);
strcpy(polaczany, mdString);
for(k = 0; k < ILOSC_HASEL; k++){
if(strcmp(polaczany, tablicaMD5[k]) == 0){
printf("Znaleziono takie same klucze dla pozycji %i!\n", k);
strcpy(shared.wyniki[shared.nput], tablicaMD5[k]); // skopiowanie otrzymanego wyniku do tablicy
strcpy(shared.wyn[shared.nput],pom);
shared.nput++; // zwiększenie ilości znalezionych wyników
// return(NULL); // zamknięcie działania producenta
}
}
}
liczba++;
}
}
/*
Producent 6 - HASŁO+liczba
*/
void *Producent6(void *arg){
int i = 0, j, k, liczba;
char liczba_str[33];
char tablica_i[33];
char polaczany[66];
unsigned char digest[16];
char mdString[33],pom[33];
while(1){
for(i = 0; i < ILOSC_SLOWNIK; i++){
strcpy(tablica_i, tablica[i]);
for(j = 0; j < strlen(tablica_i); j++)
tablica_i[j] = toupper(tablica_i[j]);
strcpy(polaczany, tablica_i);
sprintf(liczba_str, "%i", liczba);
strcat(polaczany, liczba_str);
MD5_CTX ctx; // zmienna MD5
MD5_Init(&ctx); // inicjalizacja generowania MD5
MD5_Update(&ctx, polaczany, strlen(polaczany));
MD5_Final(digest, &ctx); // wygenerowanie MD5
for(k = 0; k < 16; k++){
sprintf(&mdString[k*2], "%02x", (unsigned int)digest[k]); // zamiana wygenerowanej funkcji na ciąg znaków
}
strcpy(pom,polaczany);
strcpy(polaczany, mdString);
for(k = 0; k < ILOSC_HASEL; k++){
if(strcmp(polaczany, tablicaMD5[k]) == 0){
printf("Znaleziono takie same klucze dla pozycji %i!\n", k);
strcpy(shared.wyniki[shared.nput], tablicaMD5[k]); // skopiowanie otrzymanego wyniku do tablicy
strcpy(shared.wyn[shared.nput], pom);
shared.nput++; // zwiększenie ilości znalezionych wyników
// return(NULL); // zamknięcie działania producenta
}
}
}
liczba++;
}
}
/*
Producent 1 - Hasło1Hasło
*/
void *Producent1(void *arg){
int i = 0, j, k;
char tablica_i[33];
char tablica_j[33];
char polaczany[66]; // połączone hasło
unsigned char digest[16]; // zmienne do transformacji stringa na klucz MD5
char mdString[33], pom[33];
for(i = 0; i < ILOSC_SLOWNIK; i++){
strcpy(tablica_i, tablica[i]);
for(j = 0; j < ILOSC_SLOWNIK; j++){
strcpy(tablica_j, tablica[j]);
tablica_i[0] = toupper(tablica_i[0]);
tablica_j[0] = toupper(tablica_j[0]);
strcpy(polaczany, tablica_i);
strcat(polaczany, "1");
strcat(polaczany, tablica_j);
MD5_CTX ctx; // zmienna MD5
MD5_Init(&ctx); // inicjalizacja generowania MD5
MD5_Update(&ctx, polaczany, strlen(polaczany));
MD5_Final(digest, &ctx); // wygenerowanie MD5
for(k = 0; k < 16; k++){
sprintf(&mdString[k*2], "%02x", (unsigned int)digest[k]); // zamiana wygenerowanej funkcji na ciąg znaków
}
strcpy(pom,polaczany);
strcpy(polaczany, mdString);
for(k = 0; k < ILOSC_HASEL; k++){
if(strcmp(polaczany, tablicaMD5[k]) == 0){
printf("Znaleziono takie same klucze dla pozycji %i!\n", k);
strcpy(shared.wyniki[shared.nput], tablicaMD5[k]); // skopiowanie otrzymanego wyniku do tablicy
strcpy(shared.wyn[shared.nput], pom);
shared.nput++; // zwiększenie ilości znalezionych wyników
// return(NULL); // zamknięcie działania producenta
}
}
}
}
}
/*
Producent 2 - hasło#hasło
*/
void *Producent2(void *arg){
int i = 0, j, k;
char tablica_i[33];
char tablica_j[33];
char polaczany[66];
unsigned char digest[16];
char mdString[33],pom[33];
for(i = 0; i < ILOSC_SLOWNIK; i++){
strcpy(tablica_i, tablica[i]);
for(j = 0; j < ILOSC_SLOWNIK; j++){
strcpy(tablica_j, tablica[j]);
tablica_i[0] = tolower(tablica_i[0]);
tablica_j[0] = tolower(tablica_j[0]);
strcpy(polaczany, tablica_i);
strcat(polaczany, "#");
strcat(polaczany, tablica_j);
MD5_CTX ctx; // zmienna MD5
MD5_Init(&ctx); // inicjalizacja generowania MD5
MD5_Update(&ctx, polaczany, strlen(polaczany));
MD5_Final(digest, &ctx); // wygenerowanie MD5
for(k = 0; k < 16; k++){
sprintf(&mdString[k*2], "%02x", (unsigned int)digest[k]); // zamiana wygenerowanej funkcji na ciąg znaków
}
strcpy(pom,polaczany);
strcpy(polaczany, mdString);
for(k = 0; k < ILOSC_HASEL; k++){
if(strcmp(polaczany, tablicaMD5[k]) == 0){
printf("Znaleziono takie same klucze dla pozycji %i!\n", k);
strcpy(shared.wyniki[shared.nput], tablicaMD5[k]); // skopiowanie otrzymanego wyniku do tablicy
strcpy(shared.wyn[shared.nput], pom);
shared.nput++; // zwiększenie ilości znalezionych wyników
// return(NULL); // zamknięcie działania producenta
}
}
}
}
}
/*
Producent 3 - HasłoHasło
*/
void *Producent3(void *arg){
int i = 0, j, k;
char tablica_i[33];
char tablica_j[33];
char polaczany[66];
unsigned char digest[16];
char mdString[33],pom[33];
for(i = 0; i < ILOSC_SLOWNIK; i++){
strcpy(tablica_i, tablica[i]);
for(j = 0; j < ILOSC_SLOWNIK; j++){
strcpy(tablica_j, tablica[j]);
tablica_i[0] = toupper(tablica_i[0]);
tablica_j[0] = toupper(tablica_j[0]);
strcpy(polaczany, tablica_i);
strcat(polaczany, tablica_j);
MD5_CTX ctx; // zmienna MD5
MD5_Init(&ctx); // inicjalizacja generowania MD5
MD5_Update(&ctx, polaczany, strlen(polaczany));
MD5_Final(digest, &ctx); // wygenerowanie MD5
for(k = 0; k < 16; k++){
sprintf(&mdString[k*2], "%02x", (unsigned int)digest[k]); // zamiana wygenerowanej funkcji na ciąg znaków
}
strcpy(pom,polaczany);
strcpy(polaczany, mdString);
for(k = 0; k < ILOSC_HASEL; k++){
if(strcmp(polaczany, tablicaMD5[k]) == 0){
printf("Znaleziono takie same klucze dla pozycji %i!\n", k);
strcpy(shared.wyniki[shared.nput], tablicaMD5[k]); // skopiowanie otrzymanego wyniku do tablicy
strcpy(shared.wyn[shared.nput], pom);
shared.nput++; // zwiększenie ilości znalezionych wyników
// return(NULL); // zamknięcie działania producenta
}
}
}
}
}
/*
Funkcja mutexowa używana do czekania na pozytywny wynik
*/
void consume_wait(int i){
for ( ; ; ) {
pthread_mutex_lock(&shared.mutex);
if (i < shared.nput) {
pthread_mutex_unlock(&shared.mutex);
return;
}
pthread_mutex_unlock(&shared.mutex);
}
}
/*
Funkcja sygnału SIGHUP używana do wyświetlenia wyników
*/
void sygnal(int sig)
{
int i;
printf("\n\nUzyskane wyniki:\n");
for (i = 0; i < shared.nput; i++)
printf("%i: %s\n", i, shared.wyniki[i]);
printf("\n\n");
}
/*
Funkcja konsumenta
*/
void *Konsument(void *arg){
struct sigaction syg; // deklaracja sygnału
syg.sa_handler = sygnal;
sigemptyset(&syg.sa_mask);
syg.sa_flags = 0;
sigaction(SIGHUP, &syg, NULL); // funkcja odpowiedzi na sygnał
int i;
for (i = 0; i < ILOSC_HASEL; i++) {
consume_wait(i); // poczekaj na pozytywny wynik
if (shared.wyniki[i] != "") {
printf("Wyniki[%i] = %s\n", i, shared.wyniki[i]); // wyświetl wynik
printf("Oryginalne haslo[%i] = %s\n", i, shared.wyn[i]);
}}
return(NULL);
}
|
the_stack_data/170452295.c | #include <stdio.h>
/* lista 8
Faça um programa em C par ler e contabilizar os votos de 2 candidatos:
Canditado 1 e Candidato 2. Após a leitura do voto,
deve-se perguntar se deseja continuar(s/n) .
O programa só termina quando o usuário não desejar mais continuar.
Ao final, o programa deve informar a percentagem de votos do candidato 1 e candidato 2.
*/
int main()
{
float votoCand1=0, votoCand2=0;
int voto;
char continuar;
do{
printf("\nEntre com voto");
printf("\n1 - Dilma");
printf("\n2 - Aecio");
printf("\nOpção: ");
scanf("%d", &voto);
if(voto == 1)
votoCand1++;
else if (voto == 2)
votoCand2++;
printf("\nDeseja continuar(s/n)? ");
scanf(" %c", &continuar);
}while(continuar == 's' || continuar == 'S');
printf("\nPercentagem de votos do candidato 1 = %.2f%%",
(votoCand1/(votoCand1+votoCand2))*100 );
printf("\nPercentagem de votos do candidato 2 = %.2f%%",
(votoCand2/(votoCand1+votoCand2))*100 );
return 0;
} |
the_stack_data/7949847.c | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
typedef scalar_t__ tree ;
typedef enum tree_code { ____Placeholder_tree_code } tree_code ;
struct TYPE_2__ {scalar_t__ (* merge_type_attributes ) (scalar_t__,scalar_t__) ;} ;
/* Variables and functions */
scalar_t__ ARITHMETIC_TYPE_P (scalar_t__) ;
int COMPLEX_TYPE ;
scalar_t__ ENUMERAL_TYPE ;
int REAL_TYPE ;
scalar_t__ TREE_CODE (scalar_t__) ;
scalar_t__ TREE_TYPE (scalar_t__) ;
scalar_t__ TYPE_IS_SIZETYPE (scalar_t__) ;
scalar_t__ TYPE_MAIN_VARIANT (scalar_t__) ;
scalar_t__ TYPE_PRECISION (scalar_t__) ;
scalar_t__ TYPE_UNSIGNED (scalar_t__) ;
scalar_t__ VECTOR_TYPE ;
scalar_t__ build_complex_type (scalar_t__) ;
scalar_t__ build_type_attribute_variant (scalar_t__,scalar_t__) ;
scalar_t__ double_type_node ;
scalar_t__ float_type_node ;
int /*<<< orphan*/ gcc_assert (int) ;
scalar_t__ long_double_type_node ;
scalar_t__ long_integer_type_node ;
scalar_t__ long_long_integer_type_node ;
scalar_t__ long_long_unsigned_type_node ;
scalar_t__ long_unsigned_type_node ;
scalar_t__ same_type_p (scalar_t__,scalar_t__) ;
scalar_t__ stub1 (scalar_t__,scalar_t__) ;
TYPE_1__ targetm ;
scalar_t__ type_promotes_to (scalar_t__) ;
tree
type_after_usual_arithmetic_conversions (tree t1, tree t2)
{
enum tree_code code1 = TREE_CODE (t1);
enum tree_code code2 = TREE_CODE (t2);
tree attributes;
/* FIXME: Attributes. */
gcc_assert (ARITHMETIC_TYPE_P (t1)
|| TREE_CODE (t1) == VECTOR_TYPE
|| TREE_CODE (t1) == ENUMERAL_TYPE);
gcc_assert (ARITHMETIC_TYPE_P (t2)
|| TREE_CODE (t2) == VECTOR_TYPE
|| TREE_CODE (t2) == ENUMERAL_TYPE);
/* In what follows, we slightly generalize the rules given in [expr] so
as to deal with `long long' and `complex'. First, merge the
attributes. */
attributes = (*targetm.merge_type_attributes) (t1, t2);
/* If one type is complex, form the common type of the non-complex
components, then make that complex. Use T1 or T2 if it is the
required type. */
if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE)
{
tree subtype1 = code1 == COMPLEX_TYPE ? TREE_TYPE (t1) : t1;
tree subtype2 = code2 == COMPLEX_TYPE ? TREE_TYPE (t2) : t2;
tree subtype
= type_after_usual_arithmetic_conversions (subtype1, subtype2);
if (code1 == COMPLEX_TYPE && TREE_TYPE (t1) == subtype)
return build_type_attribute_variant (t1, attributes);
else if (code2 == COMPLEX_TYPE && TREE_TYPE (t2) == subtype)
return build_type_attribute_variant (t2, attributes);
else
return build_type_attribute_variant (build_complex_type (subtype),
attributes);
}
if (code1 == VECTOR_TYPE)
{
/* When we get here we should have two vectors of the same size.
Just prefer the unsigned one if present. */
if (TYPE_UNSIGNED (t1))
return build_type_attribute_variant (t1, attributes);
else
return build_type_attribute_variant (t2, attributes);
}
/* If only one is real, use it as the result. */
if (code1 == REAL_TYPE && code2 != REAL_TYPE)
return build_type_attribute_variant (t1, attributes);
if (code2 == REAL_TYPE && code1 != REAL_TYPE)
return build_type_attribute_variant (t2, attributes);
/* Perform the integral promotions. */
if (code1 != REAL_TYPE)
{
t1 = type_promotes_to (t1);
t2 = type_promotes_to (t2);
}
/* Both real or both integers; use the one with greater precision. */
if (TYPE_PRECISION (t1) > TYPE_PRECISION (t2))
return build_type_attribute_variant (t1, attributes);
else if (TYPE_PRECISION (t2) > TYPE_PRECISION (t1))
return build_type_attribute_variant (t2, attributes);
/* The types are the same; no need to do anything fancy. */
if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
return build_type_attribute_variant (t1, attributes);
if (code1 != REAL_TYPE)
{
/* If one is a sizetype, use it so size_binop doesn't blow up. */
if (TYPE_IS_SIZETYPE (t1) > TYPE_IS_SIZETYPE (t2))
return build_type_attribute_variant (t1, attributes);
if (TYPE_IS_SIZETYPE (t2) > TYPE_IS_SIZETYPE (t1))
return build_type_attribute_variant (t2, attributes);
/* If one is unsigned long long, then convert the other to unsigned
long long. */
if (same_type_p (TYPE_MAIN_VARIANT (t1), long_long_unsigned_type_node)
|| same_type_p (TYPE_MAIN_VARIANT (t2), long_long_unsigned_type_node))
return build_type_attribute_variant (long_long_unsigned_type_node,
attributes);
/* If one is a long long, and the other is an unsigned long, and
long long can represent all the values of an unsigned long, then
convert to a long long. Otherwise, convert to an unsigned long
long. Otherwise, if either operand is long long, convert the
other to long long.
Since we're here, we know the TYPE_PRECISION is the same;
therefore converting to long long cannot represent all the values
of an unsigned long, so we choose unsigned long long in that
case. */
if (same_type_p (TYPE_MAIN_VARIANT (t1), long_long_integer_type_node)
|| same_type_p (TYPE_MAIN_VARIANT (t2), long_long_integer_type_node))
{
tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
? long_long_unsigned_type_node
: long_long_integer_type_node);
return build_type_attribute_variant (t, attributes);
}
/* Go through the same procedure, but for longs. */
if (same_type_p (TYPE_MAIN_VARIANT (t1), long_unsigned_type_node)
|| same_type_p (TYPE_MAIN_VARIANT (t2), long_unsigned_type_node))
return build_type_attribute_variant (long_unsigned_type_node,
attributes);
if (same_type_p (TYPE_MAIN_VARIANT (t1), long_integer_type_node)
|| same_type_p (TYPE_MAIN_VARIANT (t2), long_integer_type_node))
{
tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
? long_unsigned_type_node : long_integer_type_node);
return build_type_attribute_variant (t, attributes);
}
/* Otherwise prefer the unsigned one. */
if (TYPE_UNSIGNED (t1))
return build_type_attribute_variant (t1, attributes);
else
return build_type_attribute_variant (t2, attributes);
}
else
{
if (same_type_p (TYPE_MAIN_VARIANT (t1), long_double_type_node)
|| same_type_p (TYPE_MAIN_VARIANT (t2), long_double_type_node))
return build_type_attribute_variant (long_double_type_node,
attributes);
if (same_type_p (TYPE_MAIN_VARIANT (t1), double_type_node)
|| same_type_p (TYPE_MAIN_VARIANT (t2), double_type_node))
return build_type_attribute_variant (double_type_node,
attributes);
if (same_type_p (TYPE_MAIN_VARIANT (t1), float_type_node)
|| same_type_p (TYPE_MAIN_VARIANT (t2), float_type_node))
return build_type_attribute_variant (float_type_node,
attributes);
/* Two floating-point types whose TYPE_MAIN_VARIANTs are none of
the standard C++ floating-point types. Logic earlier in this
function has already eliminated the possibility that
TYPE_PRECISION (t2) != TYPE_PRECISION (t1), so there's no
compelling reason to choose one or the other. */
return build_type_attribute_variant (t1, attributes);
}
} |
the_stack_data/51570.c | /*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
void prune_alias_le_Ok(int x) {
int a[1];
if (x <= x) {
a[0] = 0;
} else {
a[1] = 0;
}
}
void prune_alias_ge_Ok(int x) {
int a[1];
if (x >= x) {
a[0] = 0;
} else {
a[1] = 0;
}
}
void prune_alias_eq_Ok(int x) {
int a[1];
if (x == x) {
a[0] = 0;
} else {
a[1] = 0;
}
}
void prune_alias_lt_Ok(int x) {
int a[1];
if (x < x) {
a[1] = 0;
}
}
void prune_alias_gt_Ok(int x) {
int a[1];
if (x > x) {
a[1] = 0;
}
}
void prune_alias_ne_Ok(int x) {
int a[1];
if (x != x) {
a[1] = 0;
}
}
void prune_alias_not_Ok(int x) {
int a[1];
if (!(x == x)) {
a[1] = 0;
}
if (!(x <= x)) {
a[1] = 0;
}
if (!(x >= x)) {
a[1] = 0;
}
}
void prune_alias_and_Ok(int x) {
int a[1];
if (x == x && x != x) {
a[1] = 0;
}
}
void prune_alias_or_Ok(int x, int y) {
int a[1];
if (x != x || y != y) {
a[1] = 0;
}
}
void prune_alias_exp_Ok(int x) {
int a[1];
if (x + 1 != x + 1) {
a[1] = 0;
}
}
void FP_prune_alias_exp_Ok(int x) {
int a[1];
if (x + 1 != 1 + x) {
a[1] = 0;
}
}
#include <stdlib.h>
void prune_arrblk_ne(int* x) {
int* y = x + 10;
if (x != y) {
x[5] = 1;
}
}
void call_prune_arrblk_ne_Ok() {
int* x = (int*)malloc(sizeof(int) * 10);
prune_arrblk_ne(x);
}
void call_prune_arrblk_ne_Bad() {
int* x = (int*)malloc(sizeof(int) * 5);
prune_arrblk_ne(x);
}
void prune_arrblk_eq(int* x) {
int* y = x + 10;
if (x == y) {
x[5] = 1; /* unreachable */
}
}
void call_prune_arrblk_eq_Ok() {
int* x = (int*)malloc(sizeof(int) * 5);
prune_arrblk_eq(x);
}
void prune_minmax1_Ok(unsigned int x, unsigned int y) {
if (x > 0) {
if (y >= x + 1) {
unsigned int z = y - 1;
}
}
}
void call_prune_minmax1_Ok() { prune_minmax1_Ok(0, 0); }
void prune_minmax2_Ok(unsigned int x, unsigned int y) {
if (x > y) {
unsigned int z = x - y;
}
}
void call_prune_minmax2_Ok() { prune_minmax2_Ok(0, 2); }
void loop_prune_Good(int length, int j) {
int i;
char a[length];
for (i = length - 1; i >= 0; i--) {
if (j >= 0 && j < i) {
/* here we always have i >= 1 */
a[length - i] = 'Z';
}
}
}
void loop_prune2_Good_FP(int length, int j) {
int i;
char a[length];
for (i = length - 1; i >= 0; i--) {
/* need a relational domain */
if (j < i && j >= 0) {
/* here we always have i >= 1 */
a[length - i] = 'Z';
}
}
}
void nested_loop_prune_Good(int length) {
int i, j;
char a[length];
for (i = length - 1; i >= 0; i--) {
for (j = 0; j < i; j++) {
/* here we always have i >= 1 */
a[length - i] = 'Z';
}
}
}
void bad_if_alias(int* x, int* y) {
char a[1];
if (x == y) {
a[1] = 'A';
}
}
void call_bad_if_alias_Bad_AlreadyReported() {
int x;
bad_if_alias(x, x);
}
void call_bad_if_alias_Good() {
int x, y;
bad_if_alias(x, y);
}
void bad_if_not_alias(int* x, int* y) {
char a[1];
if (x != y) {
a[1] = 'B';
}
}
void call_bad_if_not_alias_Good() {
int x;
bad_if_not_alias(x, x);
}
void call_bad_if_not_alias_Bad_AlreadyReported() {
int x, y;
bad_if_not_alias(x, y);
}
int unknown_function();
void latest_prune_join(int* a, int n) {
int x;
if (unknown_function()) {
if (n < 4) {
x = 1;
} else {
x = 0;
}
} else {
if (n < 5) {
x = 1;
} else {
return;
}
}
if (x) {
a[n] = 0;
}
}
void call_latest_prune_join_1_Good() {
int a[5];
latest_prune_join(a, 3);
}
void call_latest_prune_join_2_Good() {
int a[5];
latest_prune_join(a, 10);
}
void call_latest_prune_join_3_Bad() {
int a[2];
latest_prune_join(a, 3);
}
void forget_locs_latest_prune(unsigned int n) {
int x;
int* a[5];
if (n < 5) {
x = 1;
} else {
x = 0;
x = 2;
}
if (x) {
a[n] = 0;
}
}
void call_forget_locs_latest_prune_Bad() { forget_locs_latest_prune(10); }
|
the_stack_data/150140600.c | /*
* !/usr/bin/python
* -*- coding: utf-8 -*-
*
* This file is part of pyunicorn.
* Copyright (C) 2008--2017 Jonathan F. Donges and pyunicorn authors
* URL: <http://www.pik-potsdam.de/members/donges/software>
* License: BSD (3-clause)
*/
// cross_recurrence_plot ======================================================
void _manhattan_distance_matrix_fast(int ntime_x, int ntime_y, int dim,
double *x_embedded, double *y_embedded, float *distance) {
// Calculate the manhattan distance matrix
for (int j = 0; j < ntime_x; j++) {
for (int k = 0; k < ntime_y; k++) {
float sum = 0;
for (int l = 0; l < dim; l++) {
// Use manhattan norm
sum += fabs(x_embedded[j*ntime_x+l] - y_embedded[k*ntime_y+l]);
}
distance[j*ntime_x+k] = sum;
}
}
}
void _euclidean_distance_matrix_fast(int ntime_x, int ntime_y, int dim,
double *x_embedded, double *y_embedded, float *distance) {
// Calculate the euclidean distance matrix
for (int j = 0; j < ntime_x; j++) {
for (int k = 0; k < ntime_y; k++) {
float sum = 0;
for (int l = 0; l < dim; l++) {
// Use euclidean norm
float diff = fabs(x_embedded[j*ntime_x+l] -
y_embedded[k*ntime_y+l]);
sum += diff * diff;
}
distance[j*ntime_x+k] = sqrt(sum);
}
}
}
void _supremum_distance_matrix_fast(int ntime_x, int ntime_y, int dim,
float *x_embedded, float *y_embedded, float *distance) {
float temp_diff, diff;
// Calculate the supremum distance matrix
for (int j = 0; j < ntime_x; j++) {
for (int k = 0; k < ntime_y; k++) {
temp_diff = diff = 0;
for (int l = 0; l < dim; l++) {
// Use supremum norm
temp_diff = fabs(x_embedded[j*ntime_x+l] -
y_embedded[k*ntime_y+l]);
if (temp_diff > diff)
diff = temp_diff;
}
distance[j*ntime_x+k] = diff;
}
}
}
// surrogates =================================================================
void _test_pearson_correlation_fast(double *original_data, double *surrogates,
float *correlation, int n_time, int N, double norm) {
float *p_correlation;
double *p_original, *p_surrogates;
for (int i = 0; i < N; i++) {
// Set pointer to correlation(i,0)
p_correlation = correlation + i*N;
for (int j = 0; j < N; j++) {
if (i != j) {
// Set pointer to original_data(i,0)
p_original = original_data + i*n_time;
// Set pointer to surrogates(j,0)
p_surrogates = surrogates + j*n_time;
for (int k = 0; k < n_time; k++) {
*p_correlation += (*p_original) * (*p_surrogates);
// Set pointer to original_data(i,k+1)
p_original++;
// Set pointer to surrogates(j,k+1)
p_surrogates++;
}
*p_correlation *= norm;
}
p_correlation++;
}
}
}
void _test_mutual_information_fast(int N, int n_time, int n_bins,
double scaling, double range_min, double *original_data,
double *surrogates, int *symbolic_original, int *symbolic_surrogates,
int *hist_original, int *hist_surrogates, int * hist2d, float *mi) {
long i, j, k, l, m, in_bins, jn_bins, in_time, jn_time;
double norm, rescaled, hpl, hpm, plm;
double *p_original, *p_surrogates;
float *p_mi;
long *p_symbolic_original, *p_symbolic_surrogates, *p_hist_original,
*p_hist_surrogates, *p_hist2d;
// Calculate histogram norm
norm = 1.0 / n_time;
// Initialize in_bins, in_time
in_time = in_bins = 0;
for (i = 0; i < N; i++) {
// Set pointer to original_data(i,0)
p_original = original_data + in_time;
// Set pointer to surrogates(i,0)
p_surrogates = surrogates + in_time;
// Set pointer to symbolic_original(i,0)
p_symbolic_original = symbolic_original + in_time;
// Set pointer to symbolic_surrogates(i,0)
p_symbolic_surrogates = symbolic_surrogates + in_time;
for (k = 0; k < n_time; k++) {
// Rescale sample into interval [0,1]
rescaled = scaling * (*p_original - range_min);
// Calculate symbolic trajectories for each time series,
// where the symbols are bin numbers.
if (rescaled < 1.0)
*p_symbolic_original = rescaled * n_bins;
else
*p_symbolic_original = n_bins - 1;
// Calculate 1d-histograms for single time series
// Set pointer to hist_original(i, *p_symbolic_original)
p_hist_original = hist_original + in_bins
+ *p_symbolic_original;
(*p_hist_original)++;
// Rescale sample into interval [0,1]
rescaled = scaling * (*p_surrogates - range_min);
// Calculate symbolic trajectories for each time series,
// where the symbols are bin numbers.
if (rescaled < 1.0)
*p_symbolic_surrogates = rescaled * n_bins;
else
*p_symbolic_surrogates = n_bins - 1;
// Calculate 1d-histograms for single time series
// Set pointer to hist_surrogates(i, *p_symbolic_surrogates)
p_hist_surrogates = hist_surrogates + in_bins
+ *p_symbolic_surrogates;
(*p_hist_surrogates)++;
// Set pointer to original_data(i,k+1)
p_original++;
// Set pointer to surrogates(i,k+1)
p_surrogates++;
// Set pointer to symbolic_original(i,k+1)
p_symbolic_original++;
// Set pointer to symbolic_surrogates(i,k+1)
p_symbolic_surrogates++;
}
in_bins += n_bins;
in_time += n_time;
}
// Initialize in_time, in_bins
in_time = in_bins = 0;
for (i = 0; i < N; i++) {
// Set pointer to mi(i,0)
p_mi = mi + i*N;
// Initialize jn_time = 0;
jn_time = jn_bins = 0;
for (j = 0; j < N; j++) {
// Don't do anything if i = j, this case is not of
// interest here!
if (i != j) {
// Set pointer to symbolic_original(i,0)
p_symbolic_original = symbolic_original + in_time;
// Set pointer to symbolic_surrogates(j,0)
p_symbolic_surrogates = symbolic_surrogates + jn_time;
// Calculate 2d-histogram for one pair of time series
// (i,j).
for (k = 0; k < n_time; k++) {
// Set pointer to hist2d(*p_symbolic_original,
// *p_symbolic_surrogates)
p_hist2d = hist2d + (*p_symbolic_original)*n_bins
+ *p_symbolic_surrogates;
(*p_hist2d)++;
// Set pointer to symbolic_original(i,k+1)
p_symbolic_original++;
// Set pointer to symbolic_surrogates(j,k+1)
p_symbolic_surrogates++;
}
// Calculate mutual information for one pair of time
// series (i,j)
// Set pointer to hist_original(i,0)
p_hist_original = hist_original + in_bins;
for (l = 0; l < n_bins; l++) {
// Set pointer to hist_surrogates(j,0)
p_hist_surrogates = hist_surrogates + jn_bins;
// Set pointer to hist2d(l,0)
p_hist2d = hist2d + l*n_bins;
hpl = (*p_hist_original) * norm;
if (hpl > 0.0) {
for (m = 0; m < n_bins; m++) {
hpm = (*p_hist_surrogates) * norm;
if (hpm > 0.0) {
plm = (*p_hist2d) * norm;
if (plm > 0.0)
*p_mi += plm * log(plm/hpm/hpl);
}
// Set pointer to hist_surrogates(j,m+1)
p_hist_surrogates++;
// Set pointer to hist2d(l,m+1)
p_hist2d++;
}
}
// Set pointer to hist_original(i,l+1)
p_hist_original++;
}
// Reset hist2d to zero in all bins
for (l = 0; l < n_bins; l++) {
// Set pointer to hist2d(l,0)
p_hist2d = hist2d + l*n_bins;
for (m = 0; m < n_bins; m++) {
*p_hist2d = 0;
// Set pointer to hist2d(l,m+1)
p_hist2d++;
}
}
}
// Set pointer to mi(i,j+1)
p_mi++;
jn_time += n_time;
jn_bins += n_bins;
}
in_time += n_time;
in_bins += n_bins;
}
}
|
the_stack_data/64201349.c | /* Use a do-while loop */
#include <stdio.h>
int main(){
char i;
i = 65;
do {
printf("The numeric value of %c is %d.\n", i, i);
i++;
} while (i<72);
return 0;
}
|
the_stack_data/53968.c | #include <stdio.h>
#define MAXLINE 1000
void itob(int base10integer, char string[], int base);
int main()
{
char s[MAXLINE];
itob(-255, s, 16);
printf("%s\n", s);
return 0;
}
void itob(int n, char s[], int b)
{
int i, m;
int negative = n < 0;
i = 0;
do {
m = n % b;
if (m < 0)
m = -m;
// Let's use capital letters if we run out of numbers to represent digits.
if (m > 9)
s[i++] = m + 'A' - 10;
else
s[i++] = m + '0';
} while ((n /= b) != 0);
if (negative)
s[i++] = '-';
s[i] = '\0';
} |
the_stack_data/372741.c | /* ヘッダファイルのインクルード */
#include <stdio.h> /* 標準入出力 */
/* main関数 */
int main(void){
/* 変数の宣言 */
char c; /* 取得文字c */
FILE *fp; /* ファイルポインタfp */
/* test.txtを開く. */
fp = fopen("test.txt", "r"); /* fopenで"test.txt"を"r"で開き, ファイルポインタをfpに格納. */
if (fp == NULL){ /* エラー */
/* エラー処理 */
perror("test.txt"); /* perrorで"test.txt"に関するエラーを出力. */
return -1; /* -1を返して異常終了. */
}
/* 1文字ずつ文字を取得し, 出力していく. */
while ((c = fgetc(fp)) != EOF){ /* fgetcでfpから文字を取得してcに格納, さらにそのcがEOFでない間はループを続ける. */
/* cを出力. */
putchar(c); /* putcharでcを出力. */
}
/* "test.txt"を閉じる. */
fclose(fp); /* fcloseでfpを閉じる. */
/* プログラムの終了 */
return 0; /* 0を返して正常終了. */
}
|
the_stack_data/115255.c | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <assert.h>
// These are symbols that are never used at runtime, or at least don't need to do anything for prototype apps
int sem_init(int a, int b, int c) { return 0; }
int sem_destroy(int x) { return 0; }
int sem_post(int x) { return 0; }
int sem_wait(int x) { return 0; }
int sem_trywait(int x) { return 0; }
int sem_timedwait (int *sem, const struct timespec *abs_timeout) { assert(0); return 0; }
int __errno_location() { return 0; }
void mono_log_close_syslog () { assert(0); }
void mono_log_open_syslog (const char *a, void *b) { assert(0); }
void mono_log_write_syslog (const char *a, int b, int c, const char *d) { assert(0); }
void mono_runtime_setup_stat_profiler () { assert(0); }
int mono_thread_state_init_from_handle (int *tctx, int *info, void *sigctx) { assert(0); return 0; }
|
the_stack_data/132513.c | typedef struct {int a; char b;} T;
int h (T *);
T g (T);
#if COMPILER != 1
h (T *x)
{
if (x->a != 0 || x->b != 1)
abort ();
}
#endif
#if COMPILER != 2
T
g (T x)
{
if (x.a != 13 || x.b != 47)
abort ();
x.a = 0;
x.b = 1;
h (&x);
return x;
}
#endif
#if COMPILER != 1
f ()
{
T x;
x.a = 13;
x.b = 47;
g (x);
if (x.a != 13 || x.b != 47)
abort ();
x = g (x);
if (x.a != 0 || x.b != 1)
abort ();
}
#endif
#if COMPILER != 2
main ()
{
f ();
exit (0);
}
#endif
|
the_stack_data/156393962.c | // Program 5.3A
// Program to generate a table of triangular numbers
#include<stdio.h>
int main( void )
{
int n, triangularNumber;
printf( "TABLE OF TRIANGULAR NUMBERS\n\n" );
printf( " n Sum from 1 to n\n" );
printf( "--- ---------------\n" );
triangularNumber = 0;
for( n = 1; n <= 10; ++n )
{
triangularNumber += n;
printf( "%2i %i\n", n, triangularNumber );
}
return 0;
}
|
the_stack_data/150141588.c | #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#define MAXLINE 512
int main(int argc, char** argv) {
int source_fd;
int dest_fd;
int readn;
int totaln = 0;
char buf[MAXLINE];
if (argc != 3) {
fprintf(stderr, "Usage : %s [source file] [destfile]\n", argv[0]);
return 1;
}
if (!(source_fd = open(argv[1], O_RDONLY))) {
perror("Error");
return 1;
}
if (!(dest_fd = open(argv[2], O_CREAT | O_EXCL | O_WRONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
perror("Error");
return 1;
}
if (errno == EEXIST) {
perror("Error");
close(dest_fd);
return 1;
}
memset(buf, 0x00, MAXLINE);
while ((readn = read(source_fd, buf, MAXLINE)) > 0) {
printf("readn : %d\n", readn);
totaln += write(dest_fd, buf, readn);
memset(buf, 0x00, MAXLINE);
}
printf("Total Copy SIze : %d\n", totaln);
close(dest_fd);
close(source_fd);
return 0;
}
|
the_stack_data/45451430.c |
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t nread;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
exit(EXIT_FAILURE);
}
stream = fopen(argv[1], "r");
if (stream == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while ((nread = getline(&line, &len, stream)) != -1) {
printf("Retrieved line of length %zu:\n", nread);
// fwrite(line, nread, 1, stdout);
}
free(line);
fclose(stream);
exit(EXIT_SUCCESS);
}
|
the_stack_data/264678.c | /*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#) Copyright (c) 1988, 1993 The Regents of the University of California. All rights reserved.
* @(#)chroot.c 8.1 (Berkeley) 6/9/93
* $FreeBSD: src/usr.sbin/chroot/chroot.c,v 1.4.2.1 2002/03/15 22:54:59 mikeh Exp $
* $DragonFly: src/usr.sbin/chroot/chroot.c,v 1.9 2004/12/22 08:59:33 dillon Exp $
*/
#include <sys/types.h>
#include <ctype.h>
#include <err.h>
#include <grp.h>
#include <limits.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void usage(void);
int
main(int argc, char **argv)
{
struct group *gp;
struct passwd *pw;
char *endp, *p;
const char *shell;
const char *user; /* user to switch to before running program */
const char *group; /* group to switch to ... */
char *grouplist; /* group list to switch to ... */
gid_t gid, gidlist[NGROUPS_MAX];
uid_t uid;
int ch, gids;
user = NULL;
group = NULL;
grouplist = NULL;
gid = 0;
uid = 0;
while ((ch = getopt(argc, argv, "G:g:u:")) != -1) {
switch(ch) {
case 'u':
user = optarg;
if (*user == '\0')
usage();
break;
case 'g':
group = optarg;
if (*group == '\0')
usage();
break;
case 'G':
grouplist = optarg;
if (*grouplist == '\0')
usage();
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc < 1)
usage();
if (group != NULL) {
if (isdigit(*group)) {
gid = (gid_t)strtoul(group, &endp, 0);
if (*endp != '\0')
goto getgroup;
} else {
getgroup:
if ((gp = getgrnam(group)) != NULL)
gid = gp->gr_gid;
else
errx(1, "no such group `%s'", group);
}
}
for (gids = 0;
(p = strsep(&grouplist, ",")) != NULL && gids < NGROUPS_MAX; ) {
if (*p == '\0')
continue;
if (isdigit(*p)) {
gidlist[gids] = (gid_t)strtoul(p, &endp, 0);
if (*endp != '\0')
goto getglist;
} else {
getglist:
if ((gp = getgrnam(p)) != NULL)
gidlist[gids] = gp->gr_gid;
else
errx(1, "no such group `%s'", p);
}
gids++;
}
if (p != NULL && gids == NGROUPS_MAX)
errx(1, "too many supplementary groups provided");
if (user != NULL) {
if (isdigit(*user)) {
uid = (uid_t)strtoul(user, &endp, 0);
if (*endp != '\0')
goto getuser;
} else {
getuser:
if ((pw = getpwnam(user)) != NULL)
uid = pw->pw_uid;
else
errx(1, "no such user `%s'", user);
}
}
if (chdir(argv[0]) == -1 || chroot(".") == -1)
err(1, "%s", argv[0]);
if (gids && setgroups(gids, gidlist) == -1)
err(1, "setgroups");
if (group && setgid(gid) == -1)
err(1, "setgid");
if (user && setuid(uid) == -1)
err(1, "setuid");
if (argv[1]) {
execvp(argv[1], &argv[1]);
err(1, "%s", argv[1]);
}
if (!(shell = getenv("SHELL")))
shell = _PATH_BSHELL;
execlp(shell, shell, "-i", NULL);
err(1, "%s", shell);
/* NOTREACHED */
}
static void
usage(void)
{
fprintf(stderr, "usage: chroot [-g group] [-G group,group,...] "
"[-u user] newroot [command]\n");
exit(1);
}
|
the_stack_data/178265043.c | #include <stdio.h>
#include <string.h>
void dollars(char *dst, char const *src) { // src point to the characters to be formatted(assumption: these are all digits)
if(dst == NULL || src == NULL)
return;
int len = strlen(src);
*dst++ = '$';
if(len >= 3) {
int i;
for(i = len - 2; i > 0;) {
*dst++ = *src++;
if(--i > 0 && i % 3 == 0)
*dst++ = ',';
}
}
else
*dst++ = '0';
*dst++ = '.';
*dst++ = len < 2 ? '0' : *src++;
*dst++ = len < 1 ? '0' : *src;
*dst = 0;
}
int main(void) {
char dest[20];
char *src = "12345678";
dollars(dest, src);
printf("%s", dest);
} |
the_stack_data/1152406.c | #include <stdio.h>
int main()
{
int n;
for(n =2; n<101; n+=2)
{
printf("%d \n", n);
}
}
|
the_stack_data/175141967.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int global = 0;
char * display_argv(int argc, char ** argv);
int main(int argc, char ** argv) {
char * free_this = NULL;
// All this extra complication just to cram all of argv into a string.
printf("main() called with %s; the value of global = %d\n",
free_this = display_argv(argc, argv), ++global);
// The caller is responsible for freeing the string.
free(free_this);
// Try calling main() recursively (but not infinitely).
if (argc > 1) {
main(argc - 1, argv); // Yeah, yeah...technically it's too long.
}
printf("returning from main(); global = %d\n", global);
return EXIT_SUCCESS;
}
// Return a string containing everything in argv (the caller must free it).
char * display_argv(int argc, char ** argv) {
char * s = NULL;
if (argc < 2) {
char no_arguments[] = "no arguments";
s = malloc(1 + strlen(no_arguments));
if (!s) {
perror("malloc");
exit(EXIT_FAILURE);
}
strcpy(s, no_arguments);
}
else {
s = malloc(1 + strlen(argv[1]));
if (!s) {
perror("malloc");
exit(EXIT_SUCCESS);
}
strcpy(s, argv[1]);
// All this extra complication just to avoid a single wasted space.
for (int i=2; i<argc; i++) {
s = realloc(s, 1 + strlen(s) + 1 + strlen(argv[i]));
if (!s) {
perror("realloc");
exit(EXIT_FAILURE);
}
strcat(s, " ");
strcat(s, argv[i]);
}
}
return s;
}
|
the_stack_data/237641960.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Definition for singly-linked list. */
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int carry_num = 0;
int first = 1;
struct ListNode *res = NULL;
struct ListNode *p = NULL;
struct ListNode *prev = p;
while (l1 != NULL || l2 != NULL || carry_num) {
int sum = 0;
int last_carry = carry_num;
if (l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->val;
l2 = l2->next;
}
if (sum >= 10) {
sum -= 10;
carry_num = 1;
} else {
carry_num = 0;
}
p = malloc(sizeof(*p));
if (first) {
res = p;
first = 0;
}
p->val = sum + last_carry;
if (p->val >= 10) {
p->val -= 10;
carry_num = 1;
}
p->next = NULL;
if (prev != NULL) {
prev->next = p;
}
prev = p;
}
return res;
}
static struct ListNode *node_build(const char *digits)
{
struct ListNode *res, *p, *prev;
int first = 1;
int len = strlen(digits);
const char *c = digits + len - 1;
prev = NULL;
while (len-- > 0) {
p = malloc(sizeof(*p));
if (first) {
first = 0;
res = p;
}
p->val = *c-- - '0';
p->next = NULL;
if (prev != NULL) {
prev->next = p;
}
prev = p;
}
return res;
}
static void show(struct ListNode *ln)
{
int sum = 0, factor = 1;
while (ln != NULL) {
sum += ln->val * factor;
factor *= 10;
ln = ln->next;
}
printf("%d\n", sum);
}
int main(int argc, char **argv)
{
struct ListNode *l1 = node_build(argv[1]);
struct ListNode *l2 = node_build(argv[2]);
struct ListNode *res = addTwoNumbers(l1, l2);
show(l1);
show(l2);
show(res);
return 0;
}
|
the_stack_data/24266.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strdel.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vrybalko <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/28 12:52:31 by vrybalko #+# #+# */
/* Updated: 2016/11/28 13:00:20 by vrybalko ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
void ft_strdel(char **ap)
{
if (ap)
{
if (*ap != NULL)
free(*ap);
*ap = NULL;
}
}
|
the_stack_data/69231.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* itoa( int value, char* str, int base )
{
char * rc;
char * ptr;
char * low;
// Check for supported base.
if ( base < 2 || base > 36 )
{
*str = '\0';
return str;
}
rc = ptr = str;
// Set '-' for negative decimals.
if ( value < 0 )
{
*ptr++ = '-';
}
// Remember where the numbers start.
low = ptr;
// The actual conversion.
do
{
// Modulo is negative for negative value. This trick makes abs() unnecessary.
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + value % base];
value /= base;
} while ( value );
// Terminating the string.
*ptr-- = '\0';
// Invert the numbers.
while ( low < ptr )
{
char tmp = *low;
*low++ = *ptr;
*ptr-- = tmp;
}
return rc;
}
|
the_stack_data/786630.c | /*
* Challenge 704 : binary search
* Search the target in the sequential array
*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
/* Input 1 : sequential array
* Input 2 : array size
* Input 3 : target to search
* Output : the index of the target if exist;
* else -1 .
*
* Notions: Must be carefully wiht the boundary
*/
int search(int* nums, int numsSize, int target){
int left,right,mid;
left = 0;
right = numsSize-1;
while(left <= right)
{
mid = left+(right-left)/2;
if ( target == nums[mid] )
{
return mid;
}
else if ( nums[mid] < target )
{
left = mid+1;
}
else if ( nums[mid] > target )
{
right = mid-1;
}
}
return -1;
}
// Test code
int array[] = {1,3,5,7,9,11,12,14,16,18,20,22};
int index = search(array,12,11);
printf("%d\n",index);
return 0;
} |
the_stack_data/61074731.c | //
// Created by ulysses on 4/3/17.
//
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(void){
int list[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(list) / sizeof(list[0]);
printf("Displaying input:");
for (int i = 0; i < length; i++) {
printf("%d\r", list[i]);
sleep(1);
fflush(stdout);
}
printf("\n");
return 0;
}
|
the_stack_data/89777.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#define MAP_SIZE 0x10000
#define AUDIO_REG_BASE 0x1fe10000
#define GPIO_EN 0x500
#define GPIO_OUT 0x510
#define GPIO_IN 0x520
//控制GPIO39
#define GPIO_PIN 55
int main(int argc, char **argv)
{
int i;
int dev_fd, offset, gpio_move;
dev_fd = open("/dev/mem", O_RDWR | O_SYNC);
// int GPIO_PIN = aoti(argv[1]);
if (dev_fd < 0)
{
printf("open(/dev/mem) failed.");
return -1;
}
unsigned char *map_base=(unsigned char * )mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, dev_fd, AUDIO_REG_BASE );
printf("%x \n", *(volatile unsigned int *)(map_base + GPIO_EN)); //打印该寄存器地址的value
printf("%x \n", *(volatile unsigned int *)(map_base + GPIO_OUT)); //打印该寄存器地址的value
if(GPIO_PIN > 31) {
offset = 4;
gpio_move = GPIO_PIN - 32;
} else {
offset = 0;
gpio_move = GPIO_PIN;
}
*(volatile unsigned int *)(map_base + GPIO_EN + offset) &= ~(1<<gpio_move); //GPIO输出使能
for(i=0;i<5000;i++) {
*(volatile unsigned int *)(map_base + GPIO_OUT + offset) |= (1<<gpio_move); //输出高
usleep(370);
*(volatile unsigned int *)(map_base + GPIO_OUT + offset) &= ~(1<<gpio_move); //输出底
usleep(370);
}
munmap(map_base,MAP_SIZE);//解除映射关系
if(dev_fd)
close(dev_fd);
return 0;
} |
the_stack_data/237643433.c | #include <stdio.h>
#include <assert.h>
void print(long* array, int len, int lower, int upper)
{
printf("len: %d, lower: %d, upper: %d\n", len, lower, upper);
int i;
for(i = lower; i < upper; i++)
{
printf("%d:%ld ", i, array[i]);
}
printf("\n");
}
int getIndexOf(long* array, int len, long timestamp)
{
printf("Looking for: %ld\n", timestamp);
long first = array[0];
if(first >= timestamp)
return 0;
long last = array[len - 1];
if(last < timestamp)
return len;
int lower = 0;
int upper = len;
int range = upper - lower;
while(range > 2)
{
print(array, len, lower, upper);
int half = range / 2;
int index = lower + half;
long cur = array[index];
if(timestamp > cur)
lower = index;
else if(timestamp < cur)
upper = index + 1;
else
return index;
range = upper - lower;
}
int i;
for(i = lower; i < upper; i++)
{
long cur = array[i];
if(cur >= timestamp)
{
printf("ret: %d\n", i);
return i;
}
}
printf("ret: %d\n", len);
return len;
}
int main (int argc, const char * argv[])
{
long array[] =
{
100, // 0
140, // 1
2000, // 2
2001, // 3
2202, // 4
3000, // 5
4000, // 6
5510, // 7
5560, // 8
6787 // 9
};
int len = sizeof(array) / sizeof(long);
assert(getIndexOf(array, len, 3003) == 6);
assert(getIndexOf(array, len, 3000) == 5);
assert(getIndexOf(array, len, 2999) == 5);
assert(getIndexOf(array, len, 1) == 0);
assert(getIndexOf(array, len, 9000) == 10);
long array1[] =
{
100 // 0
};
int len1 = sizeof(array1) / sizeof(long);
assert(getIndexOf(array1, len1, 1) == 0);
assert(getIndexOf(array1, len1, 100) == 0);
assert(getIndexOf(array1, len1, 200) == 1);
long array2[] =
{
100, // 0
140 // 1
};
int len2 = sizeof(array2) / sizeof(long);
assert(getIndexOf(array2, len2, 1) == 0);
assert(getIndexOf(array2, len2, 100) == 0);
assert(getIndexOf(array2, len2, 120) == 1);
assert(getIndexOf(array2, len2, 140) == 1);
assert(getIndexOf(array2, len2, 150) == 2);
long array3[] =
{
100,
200,
300
};
int len3 = sizeof(array3) / sizeof(long);
assert(getIndexOf(array3, len3, 1) == 0);
assert(getIndexOf(array3, len3, 100) == 0);
assert(getIndexOf(array3, len3, 101) == 1);
assert(getIndexOf(array3, len3, 200) == 1);
assert(getIndexOf(array3, len3, 201) == 2);
assert(getIndexOf(array3, len3, 300) == 2);
assert(getIndexOf(array3, len3, 301) == 3);
long array3x[] =
{
100,
200,
200
};
int len3x = sizeof(array3x) / sizeof(long);
assert(getIndexOf(array3x, len3x, 1) == 0);
assert(getIndexOf(array3x, len3x, 100) == 0);
assert(getIndexOf(array3x, len3x, 101) == 1);
assert(getIndexOf(array3x, len3x, 200) == 1);
assert(getIndexOf(array3x, len3x, 201) == 3);
return 0;
}
|
the_stack_data/175143434.c | /* $NetBSD: ccoshl.c,v 1.1 2014/10/10 00:48:18 christos Exp $ */
/*-
* Copyright (c) 2007 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software written by Stephen L. Moshier.
* It is redistributed by the NetBSD Foundation by permission of the author.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <complex.h>
#include "math.h"
long double complex
ccoshl(long double complex z)
{
long double complex w;
long double x, y;
x = creall(z);
y = cimagl(z);
w = coshl(x) * cosl(y) + (sinhl(x) * sinl(y)) * I;
return w;
}
|
the_stack_data/690709.c | #include <stdio.h>
int main(int argc, char** argv) {
int (* badfunc) ();
badfunc = puts;
(*badfunc)("hello, nice to meet you.");
return 0;
}
|
the_stack_data/130840.c | #include <stdio.h>
struct node
{
int info;
int *next;
};
typedef struct node node1;
void initlist(int *avail,int *list,node1 *a,int n)
{
int i;
*list =-1;
*avail=0;
for(i=0;i<n-1;i++)
{
a[i].next=i+1;
}
a[n-1].next=-1;
}
int emptystack(int list)
{
if(list==-1)
return 1 ;
else
return 0 ;
}
int fullstack(int avail)
{
if(avail==-1)
return 1;
else
return 0 ;
}
void addlist(int *list,int *avail,node1 *a,int x)
{
int p,q,back;
p=*avail;
*avail=a[*avail].next;
a[p].info=x;
if(*list==-1)
{
a[p].next=*list;
*list=p;
}
else if(x<a[*list].info)
{
a[p].next=*list;
*list=p;
}
else
{
q=*list;
back=*list;
while(q!=-1&& a[q].info<x)
{
back=q;
q=a[q].next;
}
a[p].next=a[back].next;
a[back].next=p;
}
}
void deletlist(int *list,int *avail,node1 *a,int x)
{
int p,q,back;
if(*list==-1)
{
printf("\nlist is empty\n");
}
else
{
p=*list;
back=*list;
while(p!=-1&&a[p].info!=x)
{
back=p;
p=a[p].next;
}
if(p==-1)
printf("\nValue is not found\n");
else
{
printf("\n%d is deleted\n",x );
a[back].next=a[p].next;
a[p].next=*avail;
*avail=p;
}
}
}
int searchlist(node1 *a,int list,int x)
{
while(a[list].info!=x && list!=-1)
{
list=a[list].next;
}
if(list==-1)
return 0;
else
return 1;
}
void traverselist(node1 *a,int list)
{
while(list!=-1)
{
printf("%d\t",a[list].info);
list=a[list].next;
}
printf("\n");
}
int main()
{
node1 a[10];
int avail,list,n=10,x,p,choice;
initlist(&avail,&list,a,n);
printf("linked list implementing stack\n");
do
{
printf("The stack operations are :\n1)addlist\t2)deletlist\n3)searchlist\t4)traverselist\t5)exit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{case 1:
if(!fullstack(avail))
{
printf("\nenter a number to push in stack\n");
scanf("%d",&x);
addlist(&list,&avail,a,x);
}
else
printf("\nstack is full\n");
break;
case 2:
printf("enter a value to delete\n");
scanf("%d",&x);
deletlist(&list,&avail,a,x);
break;
case 3:
printf("\nenter a value to search\n");
scanf("%d",&x);
if(searchlist(a,list,x))
printf("\nValue found\n");
else
printf("\nValue not found\n");
break;
case 4:
traverselist(a,list);
break;
case 5:
printf("\n");
break;
default:
printf("\nenter a valid choice!\n");
break;
}
}while(choice!=5);
return 0;
} |
the_stack_data/170453056.c | /*
* Copyright 2004-2016 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Since GNU environments like to define their own
* non-portable strerror_r, we need a separate
* source file that does not define _GNU_SOURCE
* in order to get the portable one.
*/
// squelch warning on Mac OS X
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#define _POSIX_C_SOURCE 20112L
#define _XOPEN_SOURCE 600
#undef _GNU_SOURCE
#include <string.h>
#include <errno.h>
#define HAS_STRERROR_R
int sys_xsi_strerror_r(int errnum, char* buf, size_t buflen);
int sys_xsi_strerror_r(int errnum, char* buf, size_t buflen)
{
#ifdef HAS_STRERROR_R
return strerror_r(errnum, buf, buflen);
#else
char* msg = strerror(errnum);
if( strlen(msg) + 1 < buflen ) {
strcpy(buf, msg);
return 0;
}
return ERANGE;
#endif
}
#if 0
// Squelch the warning about not including the chplrt; not necessary here
#include "chplrt.h"
#endif
|
the_stack_data/158202.c | /*
* Copyright (C) 2017, Galois, Inc.
* This sotware is distributed under a standard, three-clause BSD license.
* Please see the file LICENSE, distributed with this software, for specific
* terms and conditions.
*/
#include <netdb.h>
int h_errno;
int *__h_errno_location()
{
return &h_errno;
}
|
the_stack_data/1009568.c | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
int main() {
int pid = fork();
if( pid == 0 ) {
int fd = open("quotes.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR );
dup2(fd, 1);
close(fd);
execl("boba", "boba", NULL);
printf(" this only happens on failure\n" );
} else {
wait(NULL);
}
return 0;
} |
the_stack_data/11929.c | #include<stdio.h>
void Bubblesort(int a[], int n){
int i,j,temp;
for(i=0; i<n; i++){
for(j=i+1; j<n; j++) {
if(a[i]>a[j]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
int main() {
int i, n, key, low, high, mid, a[20];
printf("\n Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the array elements: ");
for(i = 0; i < n; i++)
scanf("%d",&a[i]);
Bubblesort(a,n);
printf("Enter the key element: ");
scanf("%d", &key);
low = 0;
high = n - 1;
while(high >= low){
mid = (low + high) / 2;
if(key == a[mid])
break;
else{
if(key > a[mid])
low = mid + 1;
else
high = mid - 1;
}
}
if(key == a[mid])
printf("The key element is found at location %d", mid + 1);
else
printf("the key element is not found");
return 0;
}
|
the_stack_data/243893291.c | #include <stdio.h>
#include <string.h>
static const char* compression_methods = "none fastlz"
#if defined(FA_ZLIB_ENABLE)
" deflate"
#endif
#if defined(FA_LZMA_ENABLE)
" lzma2"
#endif
;
void commandHelp(char* command)
{
fprintf(stderr, "\n");
if (command == NULL)
{
fprintf(stderr, "farc <command> ...\n");
fprintf(stderr, "command = create, help, list, cat\n\n");
return;
}
else if (!strcmp("help", command))
{
fprintf(stderr, "Help is available for the following commands:\n\n");
fprintf(stderr, "\tcreate (short: c)\n");
fprintf(stderr, "\tlist (short: l)\n");
fprintf(stderr, "\n");
return;
}
else if (!strcmp("create", command) || !strcmp("c", command))
{
fprintf(stderr, "farc crecte|c [<options>] <archive> [@<spec>] [<path> ...]\n\n");
fprintf(stderr, "Create a new file archive.\n\n");
fprintf(stderr, "Options are:\n");
fprintf(stderr, "\t-z <compression> Select compression method: %s (default: none) (global/spec)\n", compression_methods);
fprintf(stderr, "\t-s Optimize layout for optical media (align access to block boundaries) (global)\n");
fprintf(stderr, "\t-v Enabled verbose output (global)\n");
fprintf(stderr, "\n<archive> = Archive file to create\n");
fprintf(stderr, "<spec> = File spec to read files description from (files are gathered relative to spec path)\n");
fprintf(stderr, "<path> ... = Paths to load files from (files are gathered relative to path root)\n");
fprintf(stderr, "\nSpec file format:\n");
fprintf(stderr, "\"<file path>\" <options>\n");
fprintf(stderr, "\n");
return;
}
else if (!strcmp("list", command) || !strcmp("l", command))
{
fprintf(stderr, "farc list|l <archive> ...\n\n");
fprintf(stderr, "List contents of one or more archives.\n\n");
return;
}
else if (!strcmp("cat", command))
{
fprintf(stderr, "farc cat <archive> <file> ...\n\n");
fprintf(stderr, "Pipe contents of one or more files to standard output\n\n");
return;
}
fprintf(stderr, "Unknown help topic.\n\n");
}
|
the_stack_data/118889220.c | #include <stdio.h>
#include <math.h>
void printFormated(float num)
{
if ((int) round(num * 100) % 10 == 0)
printf("%.1f\n", num);
else
printf("%.2f\n", num);
}
int main()
{
char forma; scanf("%c", &forma);
if (forma == 'Q')
{
float tamanho; scanf("%f", &tamanho);
printFormated(tamanho * tamanho); // Área
printFormated(tamanho * 4); // Perímetro
}
else if (forma == 'R')
{
float altura, largura; scanf("%f\n%f", &altura, &largura);
printFormated(altura * largura); // Área
printFormated((altura * 2) + (largura * 2)); // Perímetro
}
else if (forma == 'C')
{
float raio; scanf("%f", &raio);
printFormated(3.14 * raio * raio); // Área
printFormated(2 * 3.14 * raio); // Comprimento
}
else
printf("Nenhuma figura selecionada\n");
return(0);
}
|
the_stack_data/1021238.c | /* { dg-do compile } */
/* { dg-options "-fwrapv -fdump-tree-gimple" } */
int f (int i)
{
return (i - 2) > i;
}
int g (int i)
{
return (i + 2) < i;
}
int h (double i)
{
return (i + 2.0) <= i;
}
/* { dg-final { scan-tree-dump-times " = 0" 0 "gimple" } } */
|
the_stack_data/1186987.c | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sched.h>
int main(int argc, char **argv){
struct sched_param param;
int options = sched_getscheduler(getpid());
switch(options){
case SCHED_FIFO: printf("FIFO \n"); break;
case SCHED_RR: printf("RR \n");break;
case SCHED_OTHER: printf("Other \n"); break;
default: printf("Somthing went wrong \n"); break;
}
sched_getparam(getpid(),¶m);
printf("prio :%i\n",param.sched_priority);
int max = sched_get_priority_max(options);
int min = sched_get_priority_min(options);
printf("max priority %i\n", max);
printf("min priority %i\n",min);
return 0;
}
|
the_stack_data/154829037.c |
/**
* 测试argc、argv是啥?
* C代码运行 (终端)
* gcc -o 01_argc 01_argc.c
* ./01_argc -h 127.0.0.1 -p 6379
*/
#include "stdio.h"
int main(int argc, char **argv){
for (int i = 0; i < argc; ++i) {
printf("传入的参数依次为:%s\n", argv[i]);
}
return 0;
}
|
the_stack_data/243892119.c | #include <stdio.h>
void foo(int a ){
printf("got %d\n", a);
}
void test(int a,int b){
while(a>0){
if(b==0){printf("b<a\n");return;}
a--;
b--;
}
if(b==0){printf("b==a\n");return;}
printf("b>a\n");
return;
}
int main()
{
int a,b;
printf("Enter something:\n");
scanf("%d", &a);
printf("Enter something else: \n");
scanf("%d", &b);
if(a > 0 && a < 50){
if(b > 0 && b < 50){
foo(a);
foo(b);
test(a,b);
}
}
return 0;
}
|
the_stack_data/843140.c | /*
* Copyright (C) 2006 Aleksey Cheusov
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee. Permission to modify the code and to distribute modified
* code is also granted without any restrictions.
*/
#include <assert.h>
#include <wchar.h>
#include <wctype.h>
int
wcscasecmp(const wchar_t *s1, const wchar_t *s2)
{
assert(s1 != NULL);
assert(s2 != NULL);
for (;;) {
int lc1 = towlower(*s1);
int lc2 = towlower(*s2);
int diff = lc1 - lc2;
if (diff != 0)
return diff;
if (!lc1)
return 0;
++s1;
++s2;
}
}
|
the_stack_data/86761.c | #include<stdlib.h>
#include<stdio.h>
#include<string.h>
char *stroka;
int *count;
int result=0;
int *cnt;
int **ar;
char *ConcatStr(char *a, char *b){
int length1=strlen(a),length2=strlen(b);
int i,j,k,len=0,len1=0;
i=length1-1;
int z=length1-1;
k=0;
int lengthNEW=length1+length2-len1;
char c[lengthNEW+1];
for(i=0;i<lengthNEW+1;i++) c[i]=0;
*c='\0';
for(j=0;j<length1;j++){
if((a[i]==b[k])&&(i<=length1-1)){
while((a[i]==b[k])&&(i<=length1-1)){
len++;
k++;
i++;
}
}
if(len>len1) len1=len;
len=0;
k=0;
z--;
i=z;
}
for(i=0;i<length1;i++) c[i]=a[i];
int len3=length2-len1;
for(i=0;i<len3;i++) c[length1+i]=b[len1+i];
stroka=c;
return &stroka;
}
void permut(void *base, char *tek, int n, int test, int *count,size_t width){
int i,j,length;
length=strlen(tek);
char tek2[100];
char *cc;
cc='\0';
strcpy(tek2,tek);
if(test==n) if((length<result)||(result==0)) result=length;
for(i=0;i<n;i++){
if(count[i]==0){
count[i]=1;
permut(base,ConcatStr(tek2,base+width*i), n, test+1, count,width);
count[i]=0;
}
}
}
int main(){
int n,i,j,k;
scanf("%d\n",&n);
char array[n][50];
for(i=0;i<n;i++) gets(array[i]);
int base;
stroka='\0';
char first[1];
first[0]='\0';
count = (int*)malloc(n * sizeof(int));
for(i=0;i<n;i++) count[i]=0;
permut(array,first,n,0,count,50);
free(count);
printf("%d\n",result);
return 0;
}
|
the_stack_data/420147.c |
char AVSVC[512]; // services list to kill (also used by ProcessInactiveServices)
void InitAVSVC()
{
// Windows Security Center
// Windows Defender
// Microsoft Security Essentials (Microsoft Antimalware Service)
// Microsoft Security Essentials (Microsoft Network Inspection)
strcpy(AVSVC,"|wscsvc|WinDefend|MsMpSvc|NisSrv|");
#ifdef dbgdbg
adddeb("InitAVSVC: %s",AVSVC);
#endif
}
|
the_stack_data/148358.c | /* BEGIN_ICS_COPYRIGHT2 ****************************************
Copyright (c) 2015-2017, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
** END_ICS_COPYRIGHT2 ****************************************/
|
the_stack_data/165765082.c | int XXX(int* nums, int numsSize, int target){
int left=0;
int right=numsSize-1;
int ans=numsSize;
int pivot=left+(right-left)/2;
while(left<right)
{
if(nums[pivot]<target){
left=pivot+1;
}
else{
ans=pivot;
right=pivot-1;
}
}
return ans;
}
|
the_stack_data/66227.c | //
#include <omp.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
//
typedef float f32;
typedef double f64;
typedef unsigned long long u64;
//
typedef struct particle_s {
f32 x, y, z;
f32 vx, vy, vz;
} particle_t;
//
void init(particle_t *p, u64 n)
{
for (u64 i = 0; i < n; i++)
{
//
u64 r1 = (u64)rand();
u64 r2 = (u64)rand();
f32 sign = (r1 > r2) ? 1 : -1;
//
p[i].x = sign * (f32)rand() / (f32)RAND_MAX;
p[i].y = (f32)rand() / (f32)RAND_MAX;
p[i].z = sign * (f32)rand() / (f32)RAND_MAX;
//
p[i].vx = (f32)rand() / (f32)RAND_MAX;
p[i].vy = sign * (f32)rand() / (f32)RAND_MAX;
p[i].vz = (f32)rand() / (f32)RAND_MAX;
}
}
//
void move_particles(particle_t *p, const f32 dt, u64 n)
{
//
const f32 softening = 1e-20;
//
for (u64 i = 0; i < n; i++)
{
//
f32 fx = 0.0;
f32 fy = 0.0;
f32 fz = 0.0;
//23 floating-point operations
for (u64 j = 0; j < n; j++)
{
//Newton's law
const f32 dx = p[j].x - p[i].x; //1
//printf("dx = %f\n",dx);
const f32 dy = p[j].y - p[i].y; //2
//printf("dy = %f\n",dy);
const f32 dz = p[j].z - p[i].z; //3
//printf("dz = %f\n",dz);
const f32 d_2 = (dx * dx) + (dy * dy) + (dz * dz) + softening; //9
const f32 d_3_over_2 = pow(d_2, 3.0 / 2.0); //11
// printf("%f ",sqrt(d_2));
//Net force
fx += dx / d_3_over_2; //13
fy += dy / d_3_over_2; //15
fz += dz / d_3_over_2; //17
}
//
p[i].vx += dt * fx; //19
p[i].vy += dt * fy; //21
p[i].vz += dt * fz; //23
}
//3 floating-point operations
for (u64 i = 0; i < n; i++)
{
p[i].x += dt * p[i].vx;
p[i].y += dt * p[i].vy;
p[i].z += dt * p[i].vz;
// printf("%f %f %f\n",p[i].x,p[i].y,p[i].z);
}
}
//
int main(int argc, char **argv)
{
//srand(0);
//
const u64 n = (argc > 1) ? atoll(argv[1]) : 16384;
const u64 steps= 10;
const f32 dt = 0.01;
//
f64 rate = 0.0, drate = 0.0;
//Steps to skip for warm up
const u64 warmup = 3;
//
particle_t *p = malloc(sizeof(particle_t) * n);
//
init(p, n);
const u64 s = sizeof(particle_t) * n;
printf("\n\033[1mTotal memory size:\033[0m %llu B, %llu KiB, %llu MiB\n\n", s, s >> 10, s >> 20);
//
printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout);
//
for (u64 i = 0; i < steps; i++)
{
//Measure
const f64 start = omp_get_wtime();
move_particles(p, dt, n);
const f64 end = omp_get_wtime();
//Number of interactions/iterations
const f32 h1 = (f32)(n) * (f32)(n - 1);
//GFLOPS
const f32 h2 = (23.0 * h1 + 6.0 * (f32)n) * 1e-9;
if (i >= warmup)
{
rate += h2 / (end - start);
drate += (h2 * h2) / ((end - start) * (end - start));
}
//
printf("%5llu %10.3e %10.3e %8.1f %s\n",
i,
(end - start),
h1 / (end - start),
h2 / (end - start),
(i < warmup) ? "*" : "");
fflush(stdout);
}
//
rate /= (f64)(steps - warmup);
drate = sqrt(drate / (f64)(steps - warmup) - (rate * rate));
printf("-----------------------------------------------------\n");
printf("\033[1m%s %4s \033[42m%10.1lf +- %.1lf GFLOP/s\033[0m\n",
"Average performance:", "", rate, drate);
printf("-----------------------------------------------------\n");
//
free(p);
//
return 0;
}
|
the_stack_data/187644046.c | #include <stdint.h>
#include <stdio.h>
char p[256];
char q[256];
int secure(uint8_t k) {
#pragma distribution parameter "k <- DiscreteDistribution(supp = 0:255)"
// uint8_t k;
// scanf("%hhu", &k);
uint8_t t = 0;
uint8_t reg1 = p[t];
uint8_t reg2 = 0;
if (k <= 127)
/*load*/ reg2 = q[255 - t];
else
/*load*/ reg2 = q[t - 128];
/*add */ reg1 = reg1 + reg2;
/*store*/ p[t] = reg1;
return 0;
}
|
the_stack_data/126704184.c | #include <stdio.h>
int main() {
double a,b, med;
scanf("%lf %lf", &a,&b);
med = (a * 3.5 + b * 7.5)/11;
printf("MEDIA = %.5lf\n", med);
return 0;
} |
the_stack_data/41561.c | #include <stdint.h>
#include <stdio.h>
void all_tests (void);
int main(void)
{
#ifdef USE_OLD_VERSION_TO_MAKE_A_REFERENCE_FILE
uint32_t ER[2];
void startup_x86_determiniser (uint32_t * ER);
startup_x86_determiniser (ER);
#endif
printf ("start\n");
all_tests ();
printf ("stop\n");
return 0;
}
|
the_stack_data/95449912.c | #include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
#define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
int main(void)
{
int i;
for (i = 0; i < 256; i++)
if (XOR(islower(i), ISLOWER(i)) || toupper(i) != TOUPPER(i)) {
fprintf(stderr, "error for %02X\n", i);
exit(2);
}
return 0;
}
|
the_stack_data/168893327.c | /*******************************************************************/
/** MAC 438 - Programação Concorrente */
/** IME-USP - Primeiro Semestre de 2016 */
/** Prof. Marcel Parolin Jackowski */
/** */
/** Segundo Exercício-Programa */
/** Arquivo: main.c */
/** */
/** Wagner Ferreira Alves 7577319 */
/** Rafael Marinaro Verona 7577323 */
/** 24/05/2016 */
/*******************************************************************/
#include <stdio.h> /* printf */
#include <stdlib.h> /* EXIT_SUCCESS, EXIT_FAILURE, atoi, malloc, NULL, rand, srand */
#include <pthread.h> /* pthread_t, pthread_create, pthread_join, pthread_mutex_t */
#include <time.h> /* time_t, time, nanosleep, struct timespec */
/* Conversão de milissegundos para nanossegundos: 1 ms = 1000000 ns */
#define MILI_PARA_NANO 1000000
pthread_mutex_t mutex;
int n, p, t, r, s;
int *filaDeAlunos;
int inicioDaFila, fimDaFila; //inicio = primeiro espaço ocupado, fim = primeiro espaço livre
int alunosNaFesta, alunosQueJaParticiparam;
int geraNumeroAleatorioDeZeroA(int limite) {
return (rand() % limite);
}
void esperaEmMilissegundos(long ms) {
struct timespec tempo;
tempo.tv_sec = (time_t) (ms / 1000);
tempo.tv_nsec = (long) (ms - tempo.tv_sec * 1000) * MILI_PARA_NANO;
nanosleep(&tempo, NULL);
}
void *aluno(void *_id) {
int id = *((int*)_id); /* valor apontado por _id é o id que queremos */
/* Define o tempo Tt := tempo até chegar, 0 <= Tt <= t */
int tempoAteChegar = geraNumeroAleatorioDeZeroA(t);
/* Define o tempo Tr := tempo que ficará na festa 0 <= Tr <= r */
int tempoDeFesta = geraNumeroAleatorioDeZeroA(r);
/* Espera Tt, faz a thread dormir por 'tempoAteChegar' milissegundos*/
esperaEmMilissegundos(tempoAteChegar);
/* Avisa que está na porta */
printf("Aluno %d na porta.\n", id);
/* Coloca o aluno na fila de alunos para entrar */
filaDeAlunos[fimDaFila++] = id;
/* Verifica se é o primeiro da fila */
while(filaDeAlunos[inicioDaFila] != id) {
}
/* Espera até a porta estar disponível */
pthread_mutex_lock(&mutex);
/* Avisa que está na festa */
printf("Aluno %d na festa.\n", id);
/* Retira da fila */
inicioDaFila++;
/* Libera a porta */
pthread_mutex_unlock(&mutex);
/* Incrementa o número de alunos na sala */
alunosNaFesta++;
/* Espera Tr */
esperaEmMilissegundos(tempoDeFesta);
/* Avisa que foi embora */
printf("Aluno %d vai embora.\n", id);
/* Decrementa o número de alunos na sala */
alunosNaFesta--;
/* Incrementa o número de alunos que já participaram da festa */
alunosQueJaParticiparam++;
}
void *seguranca(void *param) {
/* Define o tempo Tt := tempo até chegar, 0 <= Tt <= t */
int tempoAteChegar = geraNumeroAleatorioDeZeroA(t);
int tempoEntreRondas;
/* Espera Tt */
esperaEmMilissegundos(tempoAteChegar);
printf("Segurança em ronda\n");
/* Enquanto o número de alunos que já participaram da festa < n */
while (alunosQueJaParticiparam <= n) {
/* Avisa que está na porta */
pthread_mutex_lock(&mutex);
printf("Segurança na porta\n");
/* Se o número de alunos na sala = 0 */
if (alunosNaFesta == 0) {
/* Avisa que vai inspecionar a sala */
printf("Segurança inspeciona a sala.\n");
if (alunosQueJaParticiparam == n) {
pthread_mutex_unlock(&mutex);
break;
}
}
/* Senão Se o número de alunos na sala >= p */
else if (alunosNaFesta >= p) {
/* Avisa que vai expulsar os alunos */
printf("Segurança expulsa alunos.\n");
/* Espera até que o número de alunos na sala seja 0 */
while(alunosNaFesta > 0) {}
}
/* Avisa que está na ronda */
printf("Segurança em ronda\n");
/* Desbloqueia a entrada */
pthread_mutex_unlock(&mutex);
/* Define o tempo 0 <= Ts <= S, o tempo de ronda */
tempoEntreRondas = geraNumeroAleatorioDeZeroA(s);
/* Espera Ts */
esperaEmMilissegundos(tempoEntreRondas);
}
}
void mostraUso() {
printf("Uso:\n");
printf(" ./ep2 <convidados> <minimo-alunos> <intervalo> <tempo-festa> <tempo-ronda>\n");
printf("Onde:\n");
printf(" <convidados>: numero total de convidados para a festa\n");
printf(" <minimo-alunos>: numero minimo de alunos na festa para o seguranca esvaziar a sala\n");
printf(" <intervalo>: intervalo maximo de tempo dentre chegadas de convidados em ms\n");
printf(" <tempo-festa>: tempo maximo de participacao na festa para cada aluno em ms\n");
printf(" <tempo-ronda>: tempo maximo de ronda do seguranca em ms\n");
}
int main(int argc, char const *argv[])
{
/* Verifica se o usuário digitou 5 parâmetros */
if (argc != 6) {
mostraUso();
exit(EXIT_FAILURE);
}
/* Atribuição dos parâmetros */
n = atoi(argv[1]); /* <convidados> */
p = atoi(argv[2]); /* <minimo-alunos> */
t = atoi(argv[3]); /* <intervalo> */
r = atoi(argv[4]); /* <tempo-festa> */
s = atoi(argv[5]); /* <tempo-ronda> */
srand (time(NULL));
alunosNaFesta = alunosQueJaParticiparam = 0;
/* Verifica se os parâmetros são valores válidos */
if (t < 0 || r < 0 || s < 0) {
printf("Atenção! Os valores de <intervalo>, <tempo-festa> e <tempo-ronda> não devem ser negativos\n");
mostraUso();
exit(EXIT_FAILURE);
}
/* Cria vetor de threads para representar os alunos */
pthread_t *threadsAlunos = (pthread_t*) malloc(n * sizeof(pthread_t));
/* Cria uma thread para representar o segurança */
pthread_t threadSeguranca;
/* Inicializa uma fila para representar a ordem de chegada dos alunos */
filaDeAlunos = malloc(n * sizeof(int));
if (filaDeAlunos == NULL) {
printf("Falha ao alocar memória\n");
exit(EXIT_FAILURE);
}
inicioDaFila = fimDaFila = 0;
/* Variáveis para índice, valores de retorno e id do aluno passado à thread */
int i, falhou, *idAluno;
/* Inicialização do Mutex */
falhou = pthread_mutex_init(&mutex, NULL);
if (falhou) {
printf("Ocorreu um erro ao inicializar o mutex\n");
exit(EXIT_FAILURE);
}
/* Inicialização das theads dos alunos */
for (i = 1; i <= n; i++)
{
/* alocando novo ponteiro para um inteiro, a ser passado para a thread do aluno */
idAluno = (int*) malloc(sizeof(int*));
*idAluno = i;
falhou = pthread_create(&(threadsAlunos[i]), /* pthread_t* tid */
NULL, /* const pthread_attr_t* attr */
aluno, /* void* (*start_routine)(void *) */
idAluno); /* void *arg. */
if (falhou) {
printf("Ocorreu um erro ao criar as threads dos alunos!\n");
exit(EXIT_FAILURE);
}
}
/* Inicialização da thread do segurança */
falhou = pthread_create(&threadSeguranca, /* pthread_t* tid */
NULL, /* const pthread_attr_t* attr */
seguranca, /* void* (*start_routine)(void *) */
NULL); /* void *arg. */
if (falhou) {
printf("Ocorreu um erro ao criar a thread do segurança!\n");
exit(EXIT_FAILURE);
}
/* Espera as threads dos alunos e do segurança terminarem */
for (i = 0; i < n; i++) {
pthread_join(threadsAlunos[i], NULL);
}
pthread_join(threadSeguranca, NULL);
/* Termina a festa */
printf("Término de festa!\n");
exit(EXIT_SUCCESS);
}
|
the_stack_data/231393297.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putstr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vyastrub <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/06 12:58:20 by vyastrub #+# #+# */
/* Updated: 2016/12/06 13:11:11 by vyastrub ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_putendl(char const *s)
{
if (s)
while (*s != '\0')
write(1, s++, 1);
write(1, "\n", 1);
}
|
the_stack_data/104087.c | #include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char ch;
int len = 0;
printf("Enter a message: ");
ch = getchar();
while(ch != '\n')
{
len++;
ch = getchar();
}
printf("Your message was %d character(s) long.\n", len);
return 0;
}
|
the_stack_data/703471.c | int main(){
int a = 5;
a = a *4;
return a;
}
|
the_stack_data/48575254.c | #include <stdio.h>
int main(int ac, char * av[])
{
char buffer[1024];
while(1)
{
scanf("%s.%s", buffer, buffer + 512);
printf("%s %s\n", buffer, buffer + 512);
}
return 0;
}
|
the_stack_data/122449.c | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pthread.h>
#define CALL(x) if (counter++ && !(x)) error(#x, __LINE__, counter)
int counter = 2;
char *quit_cmd = "QUIT\r\n";
char *exit_cmd = "EXIT\r\n";
char *draw_cmd = "DRAW\r\n";
char *ok_ans = "OK\r\n";
char *err_ans = "ERR\r\n";
int listen_sock = 0;
void error(char *action, int line, int retc)
{
fprintf(stderr, "'%s' in line #%d failed - server terminated (%d)\n", action, line, errno);
exit(retc);
}
void *serve_client(void *data)
{
int conn_sock = *((int *)data);
char buff[16];
pthread_t self = pthread_self();
srand(self);
for (;;) {
int readin = read(conn_sock, buff, sizeof(buff) - 1);
buff[readin] = '\0';
if (!strcmp(buff, draw_cmd)) {
char answer[100];
sprintf(answer, "OK %d\r\n", rand() % 10000);
write(conn_sock, answer, strlen(answer));
printf("thread %lxd: drawn\n", self);
}
else if (!strcmp(buff, quit_cmd)) {
write(conn_sock, ok_ans, strlen(ok_ans));
close(conn_sock);
printf("thread %lxd: quitted\n", self);
break;
}
else if (!strcmp(buff, exit_cmd)) {
write(conn_sock, ok_ans, strlen(ok_ans));
close(conn_sock);
close(listen_sock);
printf("thread %lxd: exited\n", self);
exit(0);
}
else {
write(conn_sock, err_ans, strlen(err_ans));
printf("thread %lxd: bad command: %s\n", self, buff);
}
}
return NULL;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage %s service_no\n", argv[0]);
return 1;
}
int port = 0;
CALL(sscanf(argv[1], "%d", &port) == 1 && port >= 1 && port <= 65535);
struct protoent *pent;
CALL((pent = getprotobyname("tcp")) != NULL);
CALL((listen_sock = socket(AF_INET, SOCK_STREAM, pent->p_proto)) > 0);
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(servaddr.sin_zero, 0, 8);
int opt_on = 1;
CALL(setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt_on, sizeof(opt_on)) == 0);
CALL(bind(listen_sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) == 0);
CALL(listen(listen_sock, 5) == 0);
for (;;) {
struct sockaddr_in cliaddr;
int conn_sock = 0;
socklen_t cliaddrlen = sizeof(cliaddr);
for (;;) {
CALL((conn_sock = accept(listen_sock, (struct sockaddr *)&cliaddr, &cliaddrlen)) > 0);
printf("client: %s:%d\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
int *newsock = malloc(sizeof(int));
pthread_t newthrd;
*newsock = conn_sock;
pthread_create(&newthrd, NULL, serve_client, newsock);
}
}
} |
the_stack_data/90765157.c | // REQUIRES: x86-registered-target
// REQUIRES: powerpc-registered-target
// UNSUPPORTED: darwin
//
// Generate all the types of files we can bundle.
//
// RUN: %clang -O0 -target %itanium_abi_triple %s -E -o %t.i
// RUN: %clangxx -O0 -target %itanium_abi_triple -x c++ %s -E -o %t.ii
// RUN: %clang -O0 -target %itanium_abi_triple %s -S -emit-llvm -o %t.ll
// RUN: %clang -O0 -target %itanium_abi_triple %s -c -emit-llvm -o %t.bc
// RUN: %clang -O0 -target %itanium_abi_triple %s -S -o %t.s
// RUN: %clang -O0 -target %itanium_abi_triple %s -c -o %t.o
// RUN: %clang -O0 -target %itanium_abi_triple %s -emit-ast -o %t.ast
//
// Generate an empty file to help with the checks of empty files.
//
// RUN: touch %t.empty
//
// Generate a couple of files to bundle with.
//
// RUN: echo 'Content of device file 1' > %t.tgt1
// RUN: echo 'Content of device file 2' > %t.tgt2
//
// Check help message.
//
// RUN: clang-offload-bundler --help | FileCheck %s --check-prefix CK-HELP
// CK-HELP: {{.*}}OVERVIEW: A tool to bundle several input files of the specified type <type>
// CK-HELP: {{.*}}referring to the same source file but different targets into a single
// CK-HELP: {{.*}}one. The resulting file can also be unbundled into different files by
// CK-HELP: {{.*}}this tool if -unbundle is provided.
// CK-HELP: {{.*}}USAGE: clang-offload-bundler [options]
// CK-HELP: {{.*}}-inputs=<string> - [<input file>,...]
// CK-HELP: {{.*}}-outputs=<string> - [<output file>,...]
// CK-HELP: {{.*}}-targets=<string> - [<offload kind>-<target triple>,...]
// CK-HELP: {{.*}}-type=<string> - Type of the files to be bundled/unbundled.
// CK-HELP: {{.*}}Current supported types are:
// CK-HELP: {{.*}}i {{.*}}- cpp-output
// CK-HELP: {{.*}}ii {{.*}}- c++-cpp-output
// CK-HELP: {{.*}}ll {{.*}}- llvm
// CK-HELP: {{.*}}bc {{.*}}- llvm-bc
// CK-HELP: {{.*}}s {{.*}}- assembler
// CK-HELP: {{.*}}o {{.*}}- object
// CK-HELP: {{.*}}gch {{.*}}- precompiled-header
// CK-HELP: {{.*}}ast {{.*}}- clang AST file
// CK-HELP: {{.*}}-unbundle {{.*}}- Unbundle bundled file into several output files.
//
// Check errors.
//
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i -unbundle 2>&1 | FileCheck %s --check-prefix CK-ERR1
// CK-ERR1: error: only one input file supported in unbundling mode
// CK-ERR1: error: number of output files and targets should match in unbundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR2
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR2
// CK-ERR2: error: number of input files and targets should match in bundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR3
// CK-ERR3: error: only one output file supported in bundling mode
// CK-ERR3: error: number of input files and targets should match in bundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i -unbundle 2>&1 | FileCheck %s --check-prefix CK-ERR4
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.i,%t.tgt1 -inputs=%t.bundle.i -unbundle 2>&1 | FileCheck %s --check-prefix CK-ERR4
// CK-ERR4: error: number of output files and targets should match in unbundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2.notexist -outputs=%t.bundle.i 2>&1 | FileCheck %s -DFILE=%t.tgt2.notexist --check-prefix CK-ERR5
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i.notexist -unbundle 2>&1 | FileCheck %s -DFILE=%t.bundle.i.notexist --check-prefix CK-ERR5
// CK-ERR5: error: '[[FILE]]': {{N|n}}o such file or directory
// RUN: not clang-offload-bundler -type=invalid -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s -DTYPE=invalid --check-prefix CK-ERR6
// CK-ERR6: error: '[[TYPE]]': invalid file type specified
// RUN: not clang-offload-bundler 2>&1 | FileCheck %s --check-prefix CK-ERR7
// CK-ERR7-DAG: clang-offload-bundler: for the --type option: must be specified at least once!
// CK-ERR7-DAG: clang-offload-bundler: for the --inputs option: must be specified at least once!
// CK-ERR7-DAG: clang-offload-bundler: for the --outputs option: must be specified at least once!
// CK-ERR7-DAG: clang-offload-bundler: for the --targets option: must be specified at least once!
// RUN: not clang-offload-bundler -type=i -targets=hxst-powerpcxxle-ibm-linux-gnu,openxp-pxxerpc64le-ibm-linux-gnu,xpenmp-x86_xx-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR8
// CK-ERR8: error: invalid target 'hxst-powerpcxxle-ibm-linux-gnu', unknown offloading kind 'hxst', unknown target triple 'powerpcxxle-ibm-linux-gnu'
// CK-ERR8: error: invalid target 'openxp-pxxerpc64le-ibm-linux-gnu', unknown offloading kind 'openxp', unknown target triple 'pxxerpc64le-ibm-linux-gnu'
// CK-ERR8: error: invalid target 'xpenmp-x86_xx-pc-linux-gnu', unknown offloading kind 'xpenmp', unknown target triple 'x86_xx-pc-linux-gnu'
// RUN: not clang-offload-bundler -type=i -targets=openmp-powerpc64le-linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR9A
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR9B
// CK-ERR9A: error: expecting exactly one host target but got 0
// CK-ERR9B: error: expecting exactly one host target but got 2
//
// Check text bundle. This is a readable format, so we check for the format we expect to find.
//
// RUN: clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.i
// RUN: clang-offload-bundler -type=ii -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.ii,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.ii
// RUN: clang-offload-bundler -type=ll -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.ll,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.ll
// RUN: clang-offload-bundler -type=s -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.s,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.s
// RUN: clang-offload-bundler -type=s -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -inputs=%t.tgt1,%t.s,%t.tgt2 -outputs=%t.bundle3.unordered.s
// RUN: FileCheck %s --input-file %t.bundle3.i --check-prefix CK-TEXTI
// RUN: FileCheck %s --input-file %t.bundle3.ii --check-prefix CK-TEXTI
// RUN: FileCheck %s --input-file %t.bundle3.ll --check-prefix CK-TEXTLL
// RUN: FileCheck %s --input-file %t.bundle3.s --check-prefix CK-TEXTS
// RUN: FileCheck %s --input-file %t.bundle3.unordered.s --check-prefix CK-TEXTS-UNORDERED
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____START__ host-[[HOST:.+]]
// CK-TEXTI: int A = 0;
// CK-TEXTI: test_func(void)
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____END__ host-[[HOST]]
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____START__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTI: Content of device file 1
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____END__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-pc-linux-gnu
// CK-TEXTI: Content of device file 2
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-pc-linux-gnu
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____START__ host-[[HOST:.+]]
// CK-TEXTLL: @A = {{.*}}global i32 0
// CK-TEXTLL: define {{.*}}@test_func()
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____END__ host-[[HOST]]
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____START__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTLL: Content of device file 1
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____END__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-pc-linux-gnu
// CK-TEXTLL: Content of device file 2
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-pc-linux-gnu
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____START__ host-[[HOST:.+]]
// CK-TEXTS: .globl {{.*}}test_func
// CK-TEXTS: .globl {{.*}}A
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____END__ host-[[HOST]]
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____START__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTS: Content of device file 1
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____END__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-pc-linux-gnu
// CK-TEXTS: Content of device file 2
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-pc-linux-gnu
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____START__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTS-UNORDERED: Content of device file 1
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____END__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____START__ host-[[HOST:.+]]
// CK-TEXTS-UNORDERED: .globl {{.*}}test_func
// CK-TEXTS-UNORDERED: .globl {{.*}}A
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____END__ host-[[HOST]]
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-pc-linux-gnu
// CK-TEXTS-UNORDERED: Content of device file 2
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-pc-linux-gnu
//
// Check text unbundle. Check if we get the exact same content that we bundled before for each file.
//
// RUN: clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.i,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.i -unbundle
// RUN: diff %t.i %t.res.i
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=i -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.i -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: clang-offload-bundler -type=ii -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.ii,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.ii -unbundle
// RUN: diff %t.ii %t.res.ii
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ii -targets=openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt2 -inputs=%t.bundle3.ii -unbundle
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ll -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.ll,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.ll -unbundle
// RUN: diff %t.ll %t.res.ll
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ll -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.ll -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: clang-offload-bundler -type=s -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.s,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.s -unbundle
// RUN: diff %t.s %t.res.s
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=s -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.s,%t.res.tgt2 -inputs=%t.bundle3.s -unbundle
// RUN: diff %t.s %t.res.s
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=s -targets=openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt2 -inputs=%t.bundle3.s -unbundle
// RUN: diff %t.tgt2 %t.res.tgt2
// Check if we can unbundle a file with no magic strings.
// RUN: clang-offload-bundler -type=s -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.s,%t.res.tgt1,%t.res.tgt2 -inputs=%t.s -unbundle
// RUN: diff %t.s %t.res.s
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// RUN: clang-offload-bundler -type=s -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.s,%t.res.tgt2 -inputs=%t.s -unbundle
// RUN: diff %t.s %t.res.s
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// Check that bindler prints an error if given host bundle does not exist in the fat binary.
// RUN: not clang-offload-bundler -type=s -targets=host-x86_64-xxx-linux-gnu,openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.s,%t.res.tgt1 -inputs=%t.bundle3.s -unbundle 2>&1 | FileCheck %s --check-prefix CK-NO-HOST-BUNDLE
// CK-NO-HOST-BUNDLE: error: Can't find bundle for the host target
//
// Check binary bundle/unbundle. The content that we have before bundling must be the same we have after unbundling.
//
// RUN: clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.bc,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.bc
// RUN: clang-offload-bundler -type=gch -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.ast,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.gch
// RUN: clang-offload-bundler -type=ast -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.ast,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.ast
// RUN: clang-offload-bundler -type=ast -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -inputs=%t.tgt1,%t.ast,%t.tgt2 -outputs=%t.bundle3.unordered.ast
// RUN: clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.bc,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.bc -unbundle
// RUN: diff %t.bc %t.res.bc
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=bc -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.bc -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: clang-offload-bundler -type=gch -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.gch,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.gch -unbundle
// RUN: diff %t.ast %t.res.gch
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=gch -targets=openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt2 -inputs=%t.bundle3.gch -unbundle
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ast -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.ast,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.ast -unbundle
// RUN: diff %t.ast %t.res.ast
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ast -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.ast,%t.res.tgt2 -inputs=%t.bundle3.ast -unbundle
// RUN: diff %t.ast %t.res.ast
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ast -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.ast,%t.res.tgt2 -inputs=%t.bundle3.unordered.ast -unbundle
// RUN: diff %t.ast %t.res.ast
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ast -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.ast -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// Check if we can unbundle a file with no magic strings.
// RUN: clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.bc,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bc -unbundle
// RUN: diff %t.bc %t.res.bc
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// RUN: clang-offload-bundler -type=bc -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.bc,%t.res.tgt2 -inputs=%t.bc -unbundle
// RUN: diff %t.bc %t.res.bc
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// Check that we do not have to unbundle all available bundles from the fat binary.
// RUN: clang-offload-bundler -type=ast -targets=host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.ast,%t.res.tgt2 -inputs=%t.bundle3.unordered.ast -unbundle
// RUN: diff %t.ast %t.res.ast
// RUN: diff %t.tgt2 %t.res.tgt2
//
// Check object bundle/unbundle. The content should be bundled into an ELF
// section (we are using a PowerPC little-endian host which uses ELF). We
// have an already bundled file to check the unbundle and do a dry run on the
// bundling as it cannot be tested in all host platforms that will run these
// tests.
//
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.o -### 2>&1 \
// RUN: | FileCheck %s -DHOST=%itanium_abi_triple -DINOBJ1=%t.o -DINOBJ2=%t.tgt1 -DINOBJ3=%t.tgt2 -DOUTOBJ=%t.bundle3.o --check-prefix CK-OBJ-CMD
// CK-OBJ-CMD: llvm-objcopy{{(.exe)?}}" "--add-section=__CLANG_OFFLOAD_BUNDLE__host-[[HOST]]=[[INOBJ1]]" "--add-section=__CLANG_OFFLOAD_BUNDLE__openmp-powerpc64le-ibm-linux-gnu=[[INOBJ2]]" "--add-section=__CLANG_OFFLOAD_BUNDLE__openmp-x86_64-pc-linux-gnu=[[INOBJ3]]" "[[INOBJ1]]" "[[TEMPOBJ:.*]]"
// CK-OBJ-CMD: llvm-objcopy{{(.exe)?}}" "--set-section-flags=__CLANG_OFFLOAD_BUNDLE__host-[[HOST]]=readonly,exclude" "--set-section-flags=__CLANG_OFFLOAD_BUNDLE__openmp-powerpc64le-ibm-linux-gnu=readonly,exclude" "--set-section-flags=__CLANG_OFFLOAD_BUNDLE__openmp-x86_64-pc-linux-gnu=readonly,exclude" "[[TEMPOBJ]]" "[[OUTOBJ]]"
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.o
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.o,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.o -unbundle
// RUN: diff %t.o %t.res.o
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=o -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.o,%t.res.tgt2 -inputs=%t.bundle3.o -unbundle
// RUN: diff %t.o %t.res.o
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=o -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.o -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// Check if we can unbundle a file with no magic strings.
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.o,%t.res.tgt1,%t.res.tgt2 -inputs=%t.o -unbundle
// RUN: diff %t.o %t.res.o
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// RUN: clang-offload-bundler -type=o -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.o,%t.res.tgt2 -inputs=%t.o -unbundle
// RUN: diff %t.o %t.res.o
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// Some code so that we can create a binary out of this file.
int A = 0;
void test_func(void) {
++A;
}
|
the_stack_data/162644449.c | #include <stdio.h>
int main(int argc, char *argv[])
{
//read any text file from currect directory
char const *const fileName = "std1.txt";
FILE *file = fopen(fileName, "r");
if (!file)
{
printf("\n Unable to open : %s ", fileName);
return -1;
}
char line[500];
while (fgets(line, sizeof(line), file))
{
printf("%s", line);
}
fclose(file);
return 0;
} |
the_stack_data/43832.c | /* crypto/seed/seed_cbc.c -*- mode:C; c-file-style: "eay" -*- */
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
*/
#include <openssl/seed.h>
#include <openssl/modes.h>
void SEED_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const SEED_KEY_SCHEDULE *ks,
unsigned char ivec[SEED_BLOCK_SIZE], int enc)
{
if (enc)
CRYPTO_cbc128_encrypt(in, out, len, ks, ivec,
(block128_f) SEED_encrypt);
else
CRYPTO_cbc128_decrypt(in, out, len, ks, ivec,
(block128_f) SEED_decrypt);
}
|
the_stack_data/159515397.c |
#if LV_BUILD_TEST
#include "lv_test_init.h"
#include "lv_test_indev.h"
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#define HOR_RES 800
#define VER_RES 480
static void hal_init(void);
static void dummy_flush_cb(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p);
lv_indev_t * lv_test_mouse_indev;
lv_indev_t * lv_test_keypad_indev;
lv_indev_t * lv_test_encoder_indev;
lv_color_t test_fb[HOR_RES * VER_RES];
static lv_color_t disp_buf1[HOR_RES * VER_RES];
void lv_test_init(void)
{
lv_init();
hal_init();
}
void lv_test_deinit(void)
{
lv_mem_deinit();
}
static void * open_cb(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode)
{
(void) drv;
(void) mode;
FILE * fp = fopen(path, "rb"); // only reading is supported
return fp;
}
static lv_fs_res_t close_cb(lv_fs_drv_t * drv, void * file_p)
{
(void) drv;
fclose(file_p);
return LV_FS_RES_OK;
}
static lv_fs_res_t read_cb(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br)
{
(void) drv;
*br = fread(buf, 1, btr, file_p);
return (*br <= 0) ? LV_FS_RES_UNKNOWN : LV_FS_RES_OK;
}
static lv_fs_res_t seek_cb(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t w)
{
(void) drv;
uint32_t w2;
switch(w) {
case LV_FS_SEEK_SET:
w2 = SEEK_SET;
break;
case LV_FS_SEEK_CUR:
w2 = SEEK_CUR;
break;
case LV_FS_SEEK_END:
w2 = SEEK_END;
break;
default:
w2 = SEEK_SET;
}
fseek (file_p, pos, w2);
return LV_FS_RES_OK;
}
static lv_fs_res_t tell_cb(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p)
{
(void) drv;
*pos_p = ftell(file_p);
return LV_FS_RES_OK;
}
static void hal_init(void)
{
static lv_disp_draw_buf_t draw_buf;
lv_disp_draw_buf_init(&draw_buf, disp_buf1, NULL, HOR_RES * VER_RES);
static lv_disp_drv_t disp_drv;
lv_disp_drv_init(&disp_drv);
disp_drv.draw_buf = &draw_buf;
disp_drv.flush_cb = dummy_flush_cb;
disp_drv.hor_res = HOR_RES;
disp_drv.ver_res = VER_RES;
lv_disp_drv_register(&disp_drv);
static lv_indev_drv_t indev_mouse_drv;
lv_indev_drv_init(&indev_mouse_drv);
indev_mouse_drv.type = LV_INDEV_TYPE_POINTER;
indev_mouse_drv.read_cb = lv_test_mouse_read_cb;
lv_test_mouse_indev = lv_indev_drv_register(&indev_mouse_drv);
static lv_indev_drv_t indev_keypad_drv;
lv_indev_drv_init(&indev_keypad_drv);
indev_keypad_drv.type = LV_INDEV_TYPE_KEYPAD;
indev_keypad_drv.read_cb = lv_test_keypad_read_cb;
lv_test_keypad_indev = lv_indev_drv_register(&indev_keypad_drv);
static lv_indev_drv_t indev_encoder_drv;
lv_indev_drv_init(&indev_encoder_drv);
indev_encoder_drv.type = LV_INDEV_TYPE_ENCODER;
indev_encoder_drv.read_cb = lv_test_encoder_read_cb;
lv_test_encoder_indev = lv_indev_drv_register(&indev_encoder_drv);
static lv_fs_drv_t drv;
lv_fs_drv_init(&drv); /*Basic initialization*/
drv.letter = 'F'; /*An uppercase letter to identify the drive*/
drv.open_cb = open_cb; /*Callback to open a file*/
drv.close_cb = close_cb; /*Callback to close a file*/
drv.read_cb = read_cb; /*Callback to read a file*/
drv.seek_cb = seek_cb; /*Callback to seek in a file (Move cursor)*/
drv.tell_cb = tell_cb; /*Callback to tell the cursor position*/
lv_fs_drv_register(&drv); /*Finally register the drive*/
}
static void dummy_flush_cb(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
LV_UNUSED(area);
LV_UNUSED(color_p);
memcpy(test_fb, color_p, lv_area_get_size(area) * sizeof(lv_color_t));
lv_disp_flush_ready(disp_drv);
}
uint32_t custom_tick_get(void)
{
static uint64_t start_ms = 0;
if(start_ms == 0) {
struct timeval tv_start;
gettimeofday(&tv_start, NULL);
start_ms = (tv_start.tv_sec * 1000000 + tv_start.tv_usec) / 1000;
}
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
uint64_t now_ms;
now_ms = (tv_now.tv_sec * 1000000 + tv_now.tv_usec) / 1000;
uint32_t time_ms = now_ms - start_ms;
return time_ms;
}
#endif
|
the_stack_data/753839.c | /* $OpenBSD: reallocarray.c,v 1.3 2015/09/13 08:31:47 guenther Exp $ */
/*
* Copyright (c) 2008 Otto Moerbeek <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
/*
* This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
* if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
*/
#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
void *
reallocarray(void *optr, size_t nmemb, size_t size)
{
if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
nmemb > 0 && SIZE_MAX / nmemb < size) {
errno = ENOMEM;
return NULL;
}
return realloc(optr, size * nmemb);
}
DEF_WEAK(reallocarray);
|
the_stack_data/454492.c | #include <stdlib.h>
#include <string.h>
int strStr(char *haystack, char *needle) {
// Initialize pointers to characters in the strings
char *haystackCurr;
char *needleCurr;
// Calculate the length of each string
int len = strlen(haystack) - strlen(needle);
// Iterate through each starting character of the haystack
for (int startIndex = 0; startIndex <= len; startIndex++) {
haystackCurr = haystack + startIndex;
needleCurr = needle;
// While the characters match, continue incrementing
while (*needleCurr && *haystackCurr == *needleCurr) {
haystackCurr++;
needleCurr++;
}
// If the end of the needle is reached, then we have a match
if (*needleCurr == NULL) {
return startIndex;
}
}
return -1;
} |
the_stack_data/920624.c | #include <stdio.h>
#include <stdlib.h>
void *readFile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp != NULL) {
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
void *buffer = malloc(size);
fread(buffer, size, 1, fp);
fflush(fp);
fclose(fp);
return buffer;
}
return NULL;
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("usage: filereader <filename>\n");
return -1;
}
void *ptr = readFile(argv[1]);
printf("%s\n", ptr);
free(ptr);
return 0;
}
|
the_stack_data/4879.c | /*
* Disassembler for Angstrem KP1878BE1 processor.
*
* Copyright (C) 2002 Serge Vakulenko <[email protected]>
*
* This file is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*
* You can redistribute this file and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software Foundation;
* either version 2 of the License, or (at your discretion) any later version.
* See the accompanying file "COPYING.txt" for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <argp.h>
const char *argp_program_version =
"Tesei Disassembler 1.0\n"
"Copyright (C) 2002 Serge Vakulenko\n"
"This program is free software; it comes with ABSOLUTELY NO WARRANTY;\n"
"see the GNU General Public License for more details.";
const char *argp_program_bug_address = "<[email protected]>";
#define TXTSIZE 1024 /* command segment size */
#define DATSIZE 128 /* data segment size */
int debug;
char *infile;
unsigned short text [TXTSIZE];
unsigned char tbusy [TXTSIZE];
struct argp_option argp_options[] = {
{"debug", 'D', 0, 0, "Print debugging information" },
{ 0 }
};
/*
* Parse a single option.
*/
int parse_option (int key, char *arg, struct argp_state *state)
{
switch (key) {
case 'D':
debug = 1;
break;
case ARGP_KEY_END:
if (state->arg_num != 1) /* Not enough arguments. */
argp_usage (state);
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
/*
* Our argp parser.
*/
struct argp argp_parser = {
/* The options we understand. */
argp_options,
/* Function to parse a single option. */
parse_option,
/* A description of the arguments we accept. */
"infile.hex",
/* Program documentation. */
"\nDisassembler for Angstrem Tesei (KP1878BE1) processor"
};
void uerror (char *s, ...)
{
va_list ap;
va_start (ap, s);
if (infile)
fprintf (stderr, "%s: ", infile);
vfprintf (stderr, s, ap);
va_end (ap);
fprintf (stderr, "\n");
exit (1);
}
int hexdig (char *p)
{
unsigned char val = 0;
if (*p >= '0' && *p <= '9') val = (*p - '0') << 4;
else if (*p >= 'A' && *p <= 'F') val = (*p - 'A' + 10) << 4;
else uerror ("bad hex digit");
++p;
if (*p >= '0' && *p <= '9') val += *p - '0';
else if (*p >= 'A' && *p <= 'F') val += *p - 'A' + 10;
else uerror ("bad hex digit");
return val;
}
int gethex (int *len, long *addr, unsigned char *line)
{
char buf [80];
unsigned char sum;
int i, eof;
static int high;
again:
if (! fgets (buf, sizeof (buf), stdin))
uerror ("unexpected EOF");
if (buf[0] != ':')
goto again;
*len = hexdig (buf+1);
if (strlen (buf) < *len * 2 + 11)
uerror ("too short hex line");
*addr = (long) high << 16 | hexdig (buf+3) << 8 | hexdig (buf+5);
eof = hexdig (buf+7);
sum = 0;
for (i=0; i<*len; ++i) {
line [i] = hexdig (buf+9 + i + i);
sum += line [i];
}
sum += eof + *len + (*addr & 0xff) + (*addr >> 8 & 0xff);
if (sum != (unsigned char) - hexdig (buf+9 + *len + *len))
uerror ("bad hex checksum");
if (eof == 4) {
if (*len != 2)
uerror ("invalid hex linear address record length");
high = line[0] << 8 | line[1];
goto again;
}
if (eof == 1)
return 0;
if (eof)
uerror ("unknown hex record");
return 1;
}
void readimage ()
{
int len, i;
long addr;
unsigned char line [16];
while (gethex (&len, &addr, line)) {
if (addr & 1)
uerror ("odd address");
if (len & 1)
uerror ("odd length");
addr /= 2;
if (addr > TXTSIZE)
uerror ("invalid hex address");
for (i=0; i<len; i+=2) {
text [addr] = line [i] | line [i+1] << 8;
tbusy [addr] = 1;
++addr;
}
}
}
void print_reg (FILE *out, unsigned char reg)
{
fprintf (out, "%%%c%d", (reg >> 3) + 'a', reg & 7);
}
void print_command (FILE *out, int line, int addr, int cmd)
{
char *m;
int arg;
if (line > 0)
fprintf (out, " %4d", line);
else
fprintf (out, " ");
fprintf (out, " %04x %04x\t\t\t", addr, cmd);
switch (cmd) {
case 0x0000: fprintf (out, "nop"); goto done;
case 0x0001: fprintf (out, "wait"); goto done;
case 0x0002: fprintf (out, "rst"); goto done;
case 0x0003: fprintf (out, "ijmp"); goto done;
case 0x0004: fprintf (out, "tof"); goto done;
case 0x0005: fprintf (out, "tdc"); goto done;
case 0x0006: fprintf (out, "sksp"); goto done;
case 0x0007: fprintf (out, "ijsr"); goto done;
case 0x0008: fprintf (out, "slp"); goto done;
case 0x000c: fprintf (out, "rts"); goto done;
case 0x000d: fprintf (out, "rti"); goto done;
case 0x000e: fprintf (out, "rtsc\t0"); goto done;
case 0x000f: fprintf (out, "rtsc\t1"); goto done;
case 0x0181: fprintf (out, "stc"); goto done;
case 0x0182: fprintf (out, "stz"); goto done;
case 0x0184: fprintf (out, "stn"); goto done;
case 0x0188: fprintf (out, "stie"); goto done;
case 0x01c1: fprintf (out, "clc"); goto done;
case 0x01c2: fprintf (out, "clz"); goto done;
case 0x01c4: fprintf (out, "cln"); goto done;
case 0x01c8: fprintf (out, "clie"); goto done;
}
switch (cmd >> 4) {
case 0x001:
fprintf (out, "%s\t#%c", (cmd & 8) ? "pop" : "push",
(cmd & 7) + 'a');
goto done;
case 0x002: case 0x003: m = "swap"; goto arg1op;
case 0x004: case 0x005: m = "neg"; goto arg1op;
case 0x006: case 0x007: m = "not"; goto arg1op;
case 0x008: case 0x009: m = "shl"; goto arg1op;
case 0x00a: case 0x00b: m = "shr"; goto arg1op;
case 0x00c: case 0x00d: m = "shra"; goto arg1op;
case 0x00e: case 0x00f: m = "rlc"; goto arg1op;
case 0x010: case 0x011: m = "rrc"; goto arg1op;
case 0x012: case 0x013: m = "adc"; goto arg1op;
case 0x014: case 0x015: m = "sbc"; goto arg1op;
case 0x2c2: case 0x2c3: m = "dec"; goto arg1op;
case 0x302: case 0x303: m = "inc"; goto arg1op;
case 0x400: case 0x401: m = "clr"; goto arg1op;
arg1op: fprintf (out, "%s\t", m);
print_reg (out, cmd & 0x1f);
goto done;
case 0x018: m = "sst"; goto statusop;
case 0x01c: m = "cst";
statusop: fprintf (out, "%s\t0%xh", m, cmd & 0xf);
goto done;
}
switch (cmd >> 12) {
case 0x4:
case 0x5: m = "movl"; goto moveop;
case 0x6:
case 0x7: m = "cmpl";
moveop: fprintf (out, "%s\t", m);
print_reg (out, cmd & 0x1f);
arg = (cmd >> 5) & 0xff;
if (arg > 9)
fprintf (out, ", 0%xh", arg);
else
fprintf (out, ", %d", arg);
goto done;
case 0x8: m = "jmp"; goto jumpop;
case 0x9: m = "jsr"; goto jumpop;
case 0xa: m = "jz"; goto jumpop;
case 0xb: m = "jnz"; goto jumpop;
case 0xc: m = "jns"; goto jumpop;
case 0xd: m = "js"; goto jumpop;
case 0xe: m = "jnc"; goto jumpop;
case 0xf: m = "jc";
jumpop: fprintf (out, "%s", m);
arg = cmd & 0xfff;
if (arg > 9)
fprintf (out, "\t0%xh", arg);
else if (arg)
fprintf (out, "\t%d", arg);
goto done;
}
switch (cmd >> 8) {
case 0x04: case 0x05: case 0x06: case 0x07: m = "mov"; goto movop;
case 0x08: case 0x09: case 0x0a: case 0x0b: m = "cmp"; goto movop;
case 0x0c: case 0x0d: case 0x0e: case 0x0f: m = "sub"; goto movop;
case 0x10: case 0x11: case 0x12: case 0x13: m = "add"; goto movop;
case 0x14: case 0x15: case 0x16: case 0x17: m = "and"; goto movop;
case 0x18: case 0x19: case 0x1a: case 0x1b: m = "or"; goto movop;
case 0x1c: case 0x1d: case 0x1e: case 0x1f: m = "xor";
movop: fprintf (out, "%s\t", m);
print_reg (out, cmd & 0x1f);
fprintf (out, ", ");
print_reg (out, cmd >> 5 & 0x1f);
goto done;
case 0x28: case 0x29: m = "bicl"; goto bitop;
case 0x2a: case 0x2b: m = "bich"; goto bitop;
case 0x34: case 0x35: m = "bttl"; goto bitop;
case 0x36: case 0x37: m = "btth"; goto bitop;
case 0x38: case 0x39: m = "bisl"; goto bitop;
case 0x3a: case 0x3b: m = "bish"; goto bitop;
case 0x3c: case 0x3d: m = "btgl"; goto bitop;
case 0x3e: case 0x3f: m = "btgh";
bitop: fprintf (out, "%s\t", m);
print_reg (out, cmd & 0x1f);
fprintf (out, ", 0%xh", cmd >> 5 & 0xf);
goto done;
case 0x2c: case 0x2d:
case 0x2e: case 0x2f: m = "subl"; goto bit5op;
case 0x30: case 0x31:
case 0x32: case 0x33: m = "addl";
bit5op: fprintf (out, "%s\t", m);
print_reg (out, cmd & 0x1f);
fprintf (out, ", 0%xh", cmd >> 5 & 0x1f);
goto done;
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
fprintf (out, "ldr\t#%c, ", (cmd & 7) + 'a');
arg = (cmd >> 3) & 0xff;
if (arg > 9)
fprintf (out, "0%xh", arg);
else
fprintf (out, "%d", arg);
goto done;
case 0x02:
fprintf (out, "mtpr\t#%c, ", ((cmd >> 5) & 7) + 'a');
print_reg (out, cmd & 0x1f);
goto done;
case 0x03:
fprintf (out, "mfpr\t");
print_reg (out, cmd & 0x1f);
fprintf (out, ", #%c", ((cmd >> 5) & 7) + 'a');
goto done;
}
fprintf (out, "?");
if (cmd >= ' ' && cmd <= '~')
fprintf (out, "\t\t; `%c'", cmd);
done:
fprintf (out, "\n");
}
void disasm ()
{
int i;
for (i=0; i<TXTSIZE; ++i)
if (tbusy [i])
print_command (stdout, 0, i, text [i]);
}
int main (int argc, char **argv)
{
int i;
argp_parse (&argp_parser, argc, argv, 0, &i, 0);
if (! freopen (argv[i], "r", stdin))
uerror ("cannot open");
readimage ();
disasm ();
return 0;
}
|
the_stack_data/6386529.c | #include<stdio.h>
#define M 50
struct state {
char name[50];
int population;
float literacyRate;
float income;
} st[M]; /* array of structure */
int main() {
int i, n, ml, mi, maximumLiteracyRate, maximumIncome;
float rate;
ml = -1;
mi = -1;
maximumLiteracyRate = 0;
maximumIncome = 0;
printf("Enter how many states:");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter state %d details :", i);
printf("\nEnter state name : ");
scanf("%s", &st[i].name);
printf("\nEnter total population : ");
scanf("%ld", &st[i].population);
printf("\nEnter total literary rate : ");
scanf("%f", &rate);
st[i].literacyRate = rate;
printf("\nEnter total income : ");
scanf("%f", &st[i].income);
}
for (i = 0; i < n; i++) {
if (st[i].literacyRate >= maximumLiteracyRate) {
maximumLiteracyRate = st[i].literacyRate;
ml++;
}
if (st[i].income > maximumIncome) {
maximumIncome = st[i].income;
mi++;
}
}
printf("\nState with highest literary rate :%s", st[ml].name);
printf("\nState with highest income :%s", st[mi].name);
return (0);
}
|
the_stack_data/45449353.c | /*
Copyright 1999, Be Incorporated. All Rights Reserved.
This file may be used under the terms of the Be Sample Code License.
*/
struct ext_mime {
char *extension;
char *mime;
};
struct ext_mime mimes[] = {
{ "gz", "application/x-gzip" },
{ "hqx", "application/x-binhex40" },
{ "lha", "application/x-lharc" },
{ "pcl", "application/x-pcl" },
{ "pdf", "application/pdf" },
{ "ps", "application/postscript" },
{ "sit", "application/x-stuff-it" },
{ "tar", "application/x-tar" },
{ "tgz", "application/x-gzip" },
{ "uue", "application/x-uuencode" },
{ "z", "application/x-compress" },
{ "zip", "application/zip" },
{ "zoo", "application/x-zoo" },
{ "aif", "audio/x-aiff" },
{ "aiff", "audio/x-aiff" },
{ "au", "audio/basic" },
{ "mid", "audio/x-midi" },
{ "midi", "audio/x-midi" },
{ "mod", "audio/mod" },
{ "ra", "audio/x-real-audio" },
{ "wav", "audio/x-wav" },
{ "mp3", "audio/x-mpeg" },
{ "bmp", "image/x-bmp" },
{ "fax", "image/g3fax" },
{ "gif", "image/gif" },
{ "iff", "image/x-iff" },
{ "jpg", "image/jpeg" },
{ "jpeg", "image/jpeg" },
{ "pbm", "image/x-portable-bitmap" },
{ "pcx", "image/x-pcx" },
{ "pgm", "image/x-portable-graymap" },
{ "png", "image/png" },
{ "ppm", "image/x-portable-pixmap" },
{ "rgb", "image/x-rgb" },
{ "tga", "image/x-targa" },
{ "tif", "image/tiff" },
{ "tiff", "image/tiff" },
{ "xbm", "image/x-xbitmap" },
{ "txt", "text/plain" },
{ "doc", "text/plain" },
{ "htm", "text/html" },
{ "html", "text/html" },
{ "rtf", "text/rtf" },
{ "c", "text/x-source-code" },
{ "cc", "text/x-source-code" },
{ "c++", "text/x-source-code" },
{ "h", "text/x-source-code" },
{ "hh", "text/x-source-code" },
{ "cxx", "text/x-source-code" },
{ "cpp", "text/x-source-code" },
{ "S", "text/x-source-code" },
{ "java", "text/x-source-code" },
{ "avi", "video/x-msvideo" },
{ "mov", "video/quicktime" },
{ "mpg", "video/mpeg" },
{ "mpeg", "video/mpeg" },
{ 0, 0 }
};
|
the_stack_data/36076331.c | /*
* $Id: wctype_towctrans.c,v 1.3 2006-01-08 12:04:27 obarthel Exp $
*
* :ts=4
*
* Portable ISO 'C' (1994) runtime library for the Amiga computer
* Copyright (c) 2002-2015 by Olaf Barthel <obarthel (at) gmx.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Neither the name of Olaf Barthel nor the names of contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _WCTYPE_HEADERS_H
#include <wctype.h>
#endif /* _WCTYPE_HEADERS_H */
/****************************************************************************/
wint_t
towctrans(wint_t c, wctrans_t desc)
{
(void) c;
(void) desc;
return(0);
}
|
the_stack_data/200142063.c | /*
gcc -std=c17 -lc -lm -pthread -o ../_build/c/numeric_fenv_feholdexcept.exe ./c/numeric_fenv_feholdexcept.c && (cd ../_build/c/;./numeric_fenv_feholdexcept.exe)
https://en.cppreference.com/w/c/numeric/fenv/feholdexcept
*/
#include <stdio.h>
#include <fenv.h>
#include <float.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("current exceptions raised: ");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
printf("\n");
}
double x2 (double x) /* times two */
{
fenv_t curr_excepts;
/* Save and clear current f-p environment. */
feholdexcept(&curr_excepts);
/* Raise inexact and overflow exceptions. */
printf("In x2(): x = %f\n", x=x*2.0);
show_fe_exceptions();
feclearexcept(FE_INEXACT); /* hide inexact exception from caller */
/* Merge caller's exceptions (FE_INVALID) */
/* with remaining x2's exceptions (FE_OVERFLOW). */
feupdateenv(&curr_excepts);
return x;
}
int main(void)
{
feclearexcept(FE_ALL_EXCEPT);
feraiseexcept(FE_INVALID); /* some computation with invalid argument */
show_fe_exceptions();
printf("x2(DBL_MAX) = %f\n", x2(DBL_MAX));
show_fe_exceptions();
return 0;
}
|
the_stack_data/28261571.c | #include <spawn.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ENVIRONMENT variables*/
extern char **environ;
/* ASLR disabling magic constant from Apple LLDB source code
https://opensource.apple.com/source/lldb/lldb-76/tools/darwin-debug/darwin-debug.cpp
*/
#ifndef _POSIX_SPAWN_DISABLE_ASLR
#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
#endif
int main(int argc, char* argv[]) {
pid_t pid;
int status;
char **argv2;
posix_spawnattr_t p_attr;
char *suffix = ".orig";
argv2 = malloc(argc * sizeof(char*));
/* add suffix to executable */
argv2[0] = malloc(strlen(argv[0] + strlen(suffix) + 1));
sprintf(argv2[0], "%s%s", argv[0], suffix);
/* copy all arguments */
for(int i = 1; i < argc; i++) {
argv2[i] = strdup(argv[i]);
}
/* set magic constant to disable ASLR */
posix_spawnattr_init(&p_attr);
posix_spawnattr_setflags(&p_attr, _POSIX_SPAWN_DISABLE_ASLR);
status = posix_spawnp(&pid, argv2[0], NULL, &p_attr, argv, environ);
if(status == 0) {
/* wait for end */
if (waitpid(pid, &status, WUNTRACED) != -1) {
/* normal case, just exit */
if (WIFEXITED(status)) {
/* return original exit code */
return WEXITSTATUS(status);
}
/* abnormal cases */
else if (WIFSIGNALED(status)) {
fprintf(stderr, "%s SIGNALED by signal %d\n", argv2[0], WTERMSIG(status));
return -1;
}
else if (WIFSTOPPED(status)) {
fprintf(stderr, "%s STOPPED by signal %d\n", argv2[0], WSTOPSIG(status));
return -1;
}
else {
fprintf(stderr, "%s waitpid unknown status %d\n", argv2[0], status);
return -1;
}
}
else {
perror("waitpid");
return -1;
}
}
else {
fprintf(stderr, "posix_spawn: %s\n", strerror(status));
return -1;
}
return -1;
} |
the_stack_data/26699619.c | // REQUIRES: x86-registered-target
// REQUIRES: powerpc-registered-target
// UNSUPPORTED: darwin, aix
//
// Generate all the types of files we can bundle.
//
// RUN: %clang -O0 -target %itanium_abi_triple %s -E -o %t.i
// RUN: %clangxx -O0 -target %itanium_abi_triple -x c++ %s -E -o %t.ii
// RUN: %clang -O0 -target %itanium_abi_triple %s -S -emit-llvm -o %t.ll
// RUN: %clang -O0 -target %itanium_abi_triple %s -c -emit-llvm -o %t.bc
// RUN: %clang -O0 -target %itanium_abi_triple %s -S -o %t.s
// RUN: %clang -O0 -target %itanium_abi_triple %s -c -o %t.o
// RUN: %clang -O0 -target %itanium_abi_triple %s -emit-ast -o %t.ast
//
// Generate an empty file to help with the checks of empty files.
//
// RUN: touch %t.empty
//
// Generate a couple of files to bundle with.
//
// RUN: echo 'Content of device file 1' > %t.tgt1
// RUN: echo 'Content of device file 2' > %t.tgt2
//
// Check help message.
//
// RUN: clang-offload-bundler --help | FileCheck %s --check-prefix CK-HELP
// CK-HELP: {{.*}}OVERVIEW: A tool to bundle several input files of the specified type <type>
// CK-HELP: {{.*}}referring to the same source file but different targets into a single
// CK-HELP: {{.*}}one. The resulting file can also be unbundled into different files by
// CK-HELP: {{.*}}this tool if -unbundle is provided.
// CK-HELP: {{.*}}USAGE: clang-offload-bundler [options]
// CK-HELP: {{.*}}-allow-missing-bundles {{.*}}- Create empty files if bundles are missing when unbundling
// CK-HELP: {{.*}}-inputs=<string> - [<input file>,...]
// CK-HELP: {{.*}}-list {{.*}}- List bundle IDs in the bundled file.
// CK-HELP: {{.*}}-outputs=<string> - [<output file>,...]
// CK-HELP: {{.*}}-targets=<string> - [<offload kind>-<target triple>,...]
// CK-HELP: {{.*}}-type=<string> - Type of the files to be bundled/unbundled.
// CK-HELP: {{.*}}Current supported types are:
// CK-HELP: {{.*}}i {{.*}}- cpp-output
// CK-HELP: {{.*}}ii {{.*}}- c++-cpp-output
// CK-HELP: {{.*}}ll {{.*}}- llvm
// CK-HELP: {{.*}}bc {{.*}}- llvm-bc
// CK-HELP: {{.*}}s {{.*}}- assembler
// CK-HELP: {{.*}}o {{.*}}- object
// CK-HELP: {{.*}}a {{.*}}- archive of objects
// CK-HELP: {{.*}}gch {{.*}}- precompiled-header
// CK-HELP: {{.*}}ast {{.*}}- clang AST file
// CK-HELP: {{.*}}-unbundle {{.*}}- Unbundle bundled file into several output files.
//
// Check errors.
//
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i -unbundle 2>&1 | FileCheck %s --check-prefix CK-ERR1
// CK-ERR1: error: only one input file supported in unbundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i -outputs=%t.bundle.i -unbundle 2>&1 | FileCheck %s --check-prefix CK-ERR1A
// CK-ERR1A: error: number of output files and targets should match in unbundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR2
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR2
// CK-ERR2: error: number of input files and targets should match in bundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR3
// CK-ERR3: error: only one output file supported in bundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i -unbundle 2>&1 | FileCheck %s --check-prefix CK-ERR4
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.i,%t.tgt1 -inputs=%t.bundle.i -unbundle 2>&1 | FileCheck %s --check-prefix CK-ERR4
// CK-ERR4: error: number of output files and targets should match in unbundling mode
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2.notexist -outputs=%t.bundle.i 2>&1 | \
// RUN: FileCheck %s -DFILE=%t.tgt2.notexist -DMSG=%errc_ENOENT --check-prefix CK-ERR5
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i.notexist -unbundle 2>&1 | \
// RUN: FileCheck %s -DFILE=%t.bundle.i.notexist -DMSG=%errc_ENOENT --check-prefix CK-ERR5
// CK-ERR5: error: '[[FILE]]': [[MSG]]
// RUN: not clang-offload-bundler -type=invalid -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s -DTYPE=invalid --check-prefix CK-ERR6
// CK-ERR6: error: '[[TYPE]]': invalid file type specified
// RUN: not clang-offload-bundler 2>&1 | FileCheck %s --check-prefix CK-ERR7
// CK-ERR7: clang-offload-bundler: for the --type option: must be specified at least once!
// RUN: not clang-offload-bundler -type=i -inputs=%t.i,%t.tgt1,%t.tgt2 2>&1 | FileCheck %s -check-prefix=CK-ERR7A
// CK-ERR7A: error: for the --outputs option: must be specified at least once!
// RUN: not clang-offload-bundler -type=i -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s -check-prefix=CK-ERR7B
// CK-ERR7B: error: for the --targets option: must be specified at least once!
// RUN: not clang-offload-bundler -type=i -targets=hxst-powerpcxxle-ibm-linux-gnu,openxp-pxxerpc64le-ibm-linux-gnu,xpenmp-x86_xx-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR8
// CK-ERR8: error: invalid target 'hxst-powerpcxxle-ibm-linux-gnu', unknown offloading kind 'hxst', unknown target triple 'powerpcxxle-ibm-linux-gnu'
// RUN: not clang-offload-bundler -type=i -targets=host-powerpc64le-ibm-linux-gnu,openxp-pxxerpc64le-ibm-linux-gnu,xpenmp-x86_xx-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR8A
// CK-ERR8A: error: invalid target 'openxp-pxxerpc64le-ibm-linux-gnu', unknown offloading kind 'openxp', unknown target triple 'pxxerpc64le-ibm-linux-gnu'
// RUN: not clang-offload-bundler -type=i -targets=host-powerpc64le-ibm-linux-gnu,openmp-powerpc64le-ibm-linux-gnu,xpenmp-x86_xx-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR8B
// CK-ERR8B: error: invalid target 'xpenmp-x86_xx-pc-linux-gnu', unknown offloading kind 'xpenmp', unknown target triple 'x86_xx-pc-linux-gnu'
// RUN: not clang-offload-bundler -type=i -targets=openmp-powerpc64le-linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR9A
// CK-ERR9A: error: expecting exactly one host target but got 0
// RUN: not clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR9B
// CK-ERR9B: error: Duplicate targets are not allowed
// RUN: not clang-offload-bundler -type=a -targets=hxst-powerpcxxle-ibm-linux-gnu,openxp-pxxerpc64le-ibm-linux-gnu,xpenmp-x86_xx-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s --check-prefix CK-ERR10A
// CK-ERR10A: error: Archive files are only supported for unbundling
//
// Check text bundle. This is a readable format, so we check for the format we expect to find.
//
// RUN: clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.i
// RUN: clang-offload-bundler -type=ii -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.ii,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.ii
// RUN: clang-offload-bundler -type=ll -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.ll,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.ll
// RUN: clang-offload-bundler -type=s -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.s,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.s
// RUN: clang-offload-bundler -type=s -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -inputs=%t.tgt1,%t.s,%t.tgt2 -outputs=%t.bundle3.unordered.s
// RUN: FileCheck %s --input-file %t.bundle3.i --check-prefix CK-TEXTI
// RUN: FileCheck %s --input-file %t.bundle3.ii --check-prefix CK-TEXTI
// RUN: FileCheck %s --input-file %t.bundle3.ll --check-prefix CK-TEXTLL
// RUN: FileCheck %s --input-file %t.bundle3.s --check-prefix CK-TEXTS
// RUN: FileCheck %s --input-file %t.bundle3.unordered.s --check-prefix CK-TEXTS-UNORDERED
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____START__ host-[[HOST:.+]]
// CK-TEXTI: int A = 0;
// CK-TEXTI: test_func(void)
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____END__ host-[[HOST]]
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____START__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTI: Content of device file 1
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____END__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-pc-linux-gnu
// CK-TEXTI: Content of device file 2
// CK-TEXTI: // __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-pc-linux-gnu
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____START__ host-[[HOST:.+]]
// CK-TEXTLL: @A = {{.*}}global i32 0
// CK-TEXTLL: define {{.*}}@test_func()
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____END__ host-[[HOST]]
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____START__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTLL: Content of device file 1
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____END__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-pc-linux-gnu
// CK-TEXTLL: Content of device file 2
// CK-TEXTLL: ; __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-pc-linux-gnu
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____START__ host-[[HOST:.+]]
// CK-TEXTS: .globl {{.*}}test_func
// CK-TEXTS: .globl {{.*}}A
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____END__ host-[[HOST]]
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____START__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTS: Content of device file 1
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____END__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-pc-linux-gnu
// CK-TEXTS: Content of device file 2
// CK-TEXTS: # __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-pc-linux-gnu
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____START__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTS-UNORDERED: Content of device file 1
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____END__ openmp-powerpc64le-ibm-linux-gnu
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____START__ host-[[HOST:.+]]
// CK-TEXTS-UNORDERED: .globl {{.*}}test_func
// CK-TEXTS-UNORDERED: .globl {{.*}}A
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____END__ host-[[HOST]]
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-pc-linux-gnu
// CK-TEXTS-UNORDERED: Content of device file 2
// CK-TEXTS-UNORDERED: # __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-pc-linux-gnu
//
// Check text unbundle. Check if we get the exact same content that we bundled before for each file.
//
// RUN: clang-offload-bundler -type=i -inputs=%t.bundle3.i -list | FileCheck -check-prefix=CKLST %s
// RUN: clang-offload-bundler -type=i -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.i,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.i -unbundle
// RUN: diff %t.i %t.res.i
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=i -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.i -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: clang-offload-bundler -type=ii -inputs=%t.bundle3.ii -list | FileCheck -check-prefix=CKLST %s
// RUN: clang-offload-bundler -type=ii -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.ii,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.ii -unbundle
// RUN: diff %t.ii %t.res.ii
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ii -targets=openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt2 -inputs=%t.bundle3.ii -unbundle
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ll -inputs=%t.bundle3.ll -list | FileCheck -check-prefix=CKLST %s
// RUN: clang-offload-bundler -type=ll -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.ll,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.ll -unbundle
// RUN: diff %t.ll %t.res.ll
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ll -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.ll -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: clang-offload-bundler -type=s -inputs=%t.bundle3.s -list | FileCheck -check-prefix=CKLST %s
// RUN: clang-offload-bundler -type=s -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.s,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.s -unbundle
// RUN: diff %t.s %t.res.s
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=s -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.s,%t.res.tgt2 -inputs=%t.bundle3.s -unbundle
// RUN: diff %t.s %t.res.s
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=s -targets=openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt2 -inputs=%t.bundle3.s -unbundle
// RUN: diff %t.tgt2 %t.res.tgt2
// Check if we can unbundle a file with no magic strings.
// RUN: clang-offload-bundler -type=s -inputs=%t.s -list | FileCheck -check-prefix=CKLST2 --allow-empty %s
// RUN: clang-offload-bundler -type=s -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.s,%t.res.tgt1,%t.res.tgt2 -inputs=%t.s -unbundle -allow-missing-bundles
// RUN: diff %t.s %t.res.s
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// RUN: clang-offload-bundler -type=s -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.s,%t.res.tgt2 -inputs=%t.s -unbundle -allow-missing-bundles
// RUN: diff %t.s %t.res.s
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// Check that bindler prints an error if given host bundle does not exist in the fat binary.
// RUN: not clang-offload-bundler -type=s -targets=host-x86_64-xxx-linux-gnu,openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.s,%t.res.tgt1 -inputs=%t.bundle3.s -unbundle -allow-missing-bundles 2>&1 | FileCheck %s --check-prefix CK-NO-HOST-BUNDLE
// CK-NO-HOST-BUNDLE: error: Can't find bundle for the host target
//
// Check binary bundle/unbundle. The content that we have before bundling must be the same we have after unbundling.
//
// RUN: clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.bc,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.bc
// RUN: clang-offload-bundler -type=gch -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.ast,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.gch
// RUN: clang-offload-bundler -type=ast -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.ast,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.ast
// RUN: clang-offload-bundler -type=ast -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -inputs=%t.tgt1,%t.ast,%t.tgt2 -outputs=%t.bundle3.unordered.ast
// RUN: clang-offload-bundler -type=bc -inputs=%t.bundle3.bc -list | FileCheck -check-prefix=CKLST %s
// RUN: clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.bc,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.bc -unbundle
// RUN: diff %t.bc %t.res.bc
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=bc -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.bc -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: clang-offload-bundler -type=gch -inputs=%t.bundle3.gch -list | FileCheck -check-prefix=CKLST %s
// RUN: clang-offload-bundler -type=gch -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.gch,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.gch -unbundle
// RUN: diff %t.ast %t.res.gch
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=gch -targets=openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt2 -inputs=%t.bundle3.gch -unbundle
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ast -inputs=%t.bundle3.ast -list | FileCheck -check-prefix=CKLST %s
// RUN: clang-offload-bundler -type=ast -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.ast,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.ast -unbundle
// RUN: diff %t.ast %t.res.ast
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ast -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.ast,%t.res.tgt2 -inputs=%t.bundle3.ast -unbundle
// RUN: diff %t.ast %t.res.ast
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ast -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.ast,%t.res.tgt2 -inputs=%t.bundle3.unordered.ast -unbundle
// RUN: diff %t.ast %t.res.ast
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=ast -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.ast -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// Check if we can unbundle a file with no magic strings.
// RUN: clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.bc,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bc -unbundle -allow-missing-bundles
// RUN: diff %t.bc %t.res.bc
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// RUN: clang-offload-bundler -type=bc -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.bc,%t.res.tgt2 -inputs=%t.bc -unbundle -allow-missing-bundles
// RUN: diff %t.bc %t.res.bc
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// Check that we do not have to unbundle all available bundles from the fat binary.
// RUN: clang-offload-bundler -type=ast -targets=host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.ast,%t.res.tgt2 -inputs=%t.bundle3.unordered.ast -unbundle
// RUN: diff %t.ast %t.res.ast
// RUN: diff %t.tgt2 %t.res.tgt2
//
// Check object bundle/unbundle. The content should be bundled into an ELF
// section (we are using a PowerPC little-endian host which uses ELF). We
// have an already bundled file to check the unbundle and do a dry run on the
// bundling as it cannot be tested in all host platforms that will run these
// tests.
//
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.o -### 2>&1 \
// RUN: | FileCheck %s -DHOST=%itanium_abi_triple -DINOBJ1=%t.o -DINOBJ2=%t.tgt1 -DINOBJ3=%t.tgt2 -DOUTOBJ=%t.bundle3.o --check-prefix CK-OBJ-CMD
// CK-OBJ-CMD: llvm-objcopy{{(.exe)?}}" "--add-section=__CLANG_OFFLOAD_BUNDLE__host-[[HOST]]={{.*}}" "--set-section-flags=__CLANG_OFFLOAD_BUNDLE__host-[[HOST]]=readonly,exclude" "--add-section=__CLANG_OFFLOAD_BUNDLE__openmp-powerpc64le-ibm-linux-gnu=[[INOBJ2]]" "--set-section-flags=__CLANG_OFFLOAD_BUNDLE__openmp-powerpc64le-ibm-linux-gnu=readonly,exclude" "--add-section=__CLANG_OFFLOAD_BUNDLE__openmp-x86_64-pc-linux-gnu=[[INOBJ3]]" "--set-section-flags=__CLANG_OFFLOAD_BUNDLE__openmp-x86_64-pc-linux-gnu=readonly,exclude" "--" "[[INOBJ1]]" "[[OUTOBJ]]"
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.o
// RUN: clang-offload-bundler -type=o -inputs=%t.bundle3.o -list | FileCheck -check-prefix=CKLST %s
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.o,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.o -unbundle
// RUN: diff %t.bundle3.o %t.res.o
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=o -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.o,%t.res.tgt2 -inputs=%t.bundle3.o -unbundle
// RUN: diff %t.bundle3.o %t.res.o
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
// RUN: clang-offload-bundler -type=o -targets=openmp-powerpc64le-ibm-linux-gnu -outputs=%t.res.tgt1 -inputs=%t.bundle3.o -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// Check if we can unbundle a file with no magic strings.
// RUN: clang-offload-bundler -type=o -inputs=%t.o -list | FileCheck -check-prefix=CKLST2 --allow-empty %s
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.o,%t.res.tgt1,%t.res.tgt2 -inputs=%t.o -unbundle -allow-missing-bundles
// RUN: diff %t.o %t.res.o
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
// RUN: clang-offload-bundler -type=o -targets=openmp-powerpc64le-ibm-linux-gnu,host-%itanium_abi_triple,openmp-x86_64-pc-linux-gnu -outputs=%t.res.tgt1,%t.res.o,%t.res.tgt2 -inputs=%t.o -unbundle -allow-missing-bundles
// RUN: diff %t.o %t.res.o
// RUN: diff %t.empty %t.res.tgt1
// RUN: diff %t.empty %t.res.tgt2
//
// Check -bundle-align option
//
// RUN: clang-offload-bundler -bundle-align=4096 -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.bc,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.bc
// RUN: clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -outputs=%t.res.bc,%t.res.tgt1,%t.res.tgt2 -inputs=%t.bundle3.bc -unbundle
// RUN: diff %t.bc %t.res.bc
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
//
// Check error due to missing bundles
//
// RUN: clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,hip-amdgcn-amd-amdhsa--gfx900 -inputs=%t.bc,%t.tgt1 -outputs=%t.hip.bundle.bc
// RUN: not clang-offload-bundler -type=bc -inputs=%t.hip.bundle.bc -outputs=%t.tmp.bc -unbundle \
// RUN: -targets=hip-amdgcn-amd-amdhsa--gfx906 \
// RUN: 2>&1 | FileCheck -check-prefix=MISS1 %s
// RUN: not clang-offload-bundler -type=bc -inputs=%t.hip.bundle.bc -outputs=%t.tmp.bc,%t.tmp2.bc -unbundle \
// RUN: -targets=hip-amdgcn-amd-amdhsa--gfx906,hip-amdgcn-amd-amdhsa--gfx900 \
// RUN: 2>&1 | FileCheck -check-prefix=MISS1 %s
// MISS1: error: Can't find bundles for hip-amdgcn-amd-amdhsa--gfx906
// RUN: not clang-offload-bundler -type=bc -inputs=%t.hip.bundle.bc -outputs=%t.tmp.bc,%t.tmp2.bc -unbundle \
// RUN: -targets=hip-amdgcn-amd-amdhsa--gfx906,hip-amdgcn-amd-amdhsa--gfx803 \
// RUN: 2>&1 | FileCheck -check-prefix=MISS2 %s
// MISS2: error: Can't find bundles for hip-amdgcn-amd-amdhsa--gfx803 and hip-amdgcn-amd-amdhsa--gfx906
// RUN: not clang-offload-bundler -type=bc -inputs=%t.hip.bundle.bc -outputs=%t.tmp.bc,%t.tmp2.bc,%t.tmp3.bc -unbundle \
// RUN: -targets=hip-amdgcn-amd-amdhsa--gfx906,hip-amdgcn-amd-amdhsa--gfx803,hip-amdgcn-amd-amdhsa--gfx1010 \
// RUN: 2>&1 | FileCheck -check-prefix=MISS3 %s
// MISS3: error: Can't find bundles for hip-amdgcn-amd-amdhsa--gfx1010, hip-amdgcn-amd-amdhsa--gfx803, and hip-amdgcn-amd-amdhsa--gfx906
//
// Check error due to duplicate targets
//
// RUN: not clang-offload-bundler -type=bc -targets=host-%itanium_abi_triple,hip-amdgcn-amd-amdhsa--gfx900,hip-amdgcn-amd-amdhsa--gfx900 \
// RUN: -inputs=%t.bc,%t.tgt1,%t.tgt1 -outputs=%t.hip.bundle.bc 2>&1 | FileCheck -check-prefix=DUP %s
// RUN: not clang-offload-bundler -type=bc -inputs=%t.hip.bundle.bc -outputs=%t.tmp.bc,%t.tmp2.bc -unbundle \
// RUN: -targets=hip-amdgcn-amd-amdhsa--gfx906,hip-amdgcn-amd-amdhsa--gfx906 \
// RUN: 2>&1 | FileCheck -check-prefix=DUP %s
// DUP: error: Duplicate targets are not allowed
//
// Check -list option
//
// RUN: clang-offload-bundler -bundle-align=4096 -type=bc -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.bc,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.bc
// RUN: not clang-offload-bundler -type=bc -inputs=%t.bundle3.bc -unbundle -list 2>&1 | FileCheck -check-prefix=CKLST-ERR %s
// CKLST-ERR: error: -unbundle and -list cannot be used together
// RUN: not clang-offload-bundler -type=bc -inputs=%t.bundle3.bc -targets=host-%itanium_abi_triple -list 2>&1 | FileCheck -check-prefix=CKLST-ERR2 %s
// CKLST-ERR2: error: -targets option is invalid for -list
// RUN: not clang-offload-bundler -type=bc -inputs=%t.bundle3.bc -outputs=out.txt -list 2>&1 | FileCheck -check-prefix=CKLST-ERR3 %s
// CKLST-ERR3: error: -outputs option is invalid for -list
// RUN: not clang-offload-bundler -type=bc -inputs=%t.bundle3.bc,%t.bc -list 2>&1 | FileCheck -check-prefix=CKLST-ERR4 %s
// CKLST-ERR4: error: only one input file supported for -list
// CKLST-DAG: host-
// CKLST-DAG: openmp-powerpc64le-ibm-linux-gnu
// CKLST-DAG: openmp-x86_64-pc-linux-gnu
// CKLST2-NOT: host-
// CKLST2-NOT: openmp-powerpc64le-ibm-linux-gnu
// CKLST2-NOT: openmp-x86_64-pc-linux-gnu
//
// Check unbundling archive for HIP.
//
// When the input to clang-offload-bundler is an archive of bundled bitcodes,
// for each target, clang-offload-bundler extracts the bitcode from each
// bundle and archives them. Therefore for each target, the output is an
// archive of unbundled bitcodes.
//
// RUN: clang-offload-bundler -type=bc -targets=hip-amdgcn-amd-amdhsa--gfx900,hip-amdgcn-amd-amdhsa--gfx906 \
// RUN: -inputs=%t.tgt1,%t.tgt2 -outputs=%T/hip_bundle1.bc
// RUN: clang-offload-bundler -type=bc -targets=hip-amdgcn-amd-amdhsa--gfx900,hip-amdgcn-amd-amdhsa--gfx906 \
// RUN: -inputs=%t.tgt1,%t.tgt2 -outputs=%T/hip_bundle2.bc
// RUN: llvm-ar cr %T/hip_archive.a %T/hip_bundle1.bc %T/hip_bundle2.bc
// RUN: clang-offload-bundler -unbundle -type=a -targets=hip-amdgcn-amd-amdhsa--gfx900,hip-amdgcn-amd-amdhsa--gfx906 \
// RUN: -outputs=%T/hip_900.a,%T/hip_906.a -inputs=%T/hip_archive.a
// RUN: llvm-ar t %T/hip_900.a | FileCheck -check-prefix=HIP-AR-900 %s
// RUN: llvm-ar t %T/hip_906.a | FileCheck -check-prefix=HIP-AR-906 %s
// HIP-AR-900-DAG: hip_bundle1-hip-amdgcn-amd-amdhsa--gfx900
// HIP-AR-900-DAG: hip_bundle2-hip-amdgcn-amd-amdhsa--gfx900
// HIP-AR-906-DAG: hip_bundle1-hip-amdgcn-amd-amdhsa--gfx906
// HIP-AR-906-DAG: hip_bundle2-hip-amdgcn-amd-amdhsa--gfx906
//
// Check bundling without host target is allowed for HIP.
//
// RUN: clang-offload-bundler -type=bc -targets=hip-amdgcn-amd-amdhsa--gfx900,hip-amdgcn-amd-amdhsa--gfx906 \
// RUN: -inputs=%t.tgt1,%t.tgt2 -outputs=%t.hip.bundle.bc
// RUN: clang-offload-bundler -type=bc -list -inputs=%t.hip.bundle.bc | FileCheck -check-prefix=NOHOST %s
// RUN: clang-offload-bundler -type=bc -targets=hip-amdgcn-amd-amdhsa--gfx900,hip-amdgcn-amd-amdhsa--gfx906 \
// RUN: -outputs=%t.res.tgt1,%t.res.tgt2 -inputs=%t.hip.bundle.bc -unbundle
// RUN: diff %t.tgt1 %t.res.tgt1
// RUN: diff %t.tgt2 %t.res.tgt2
//
// NOHOST-NOT: host-
// NOHOST-DAG: hip-amdgcn-amd-amdhsa--gfx900
// NOHOST-DAG: hip-amdgcn-amd-amdhsa--gfx906
// Check archive unbundling
//
// Create few code object bundles and archive them to create an input archive
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-amdgcn-amd-amdhsa-gfx906,openmp-amdgcn-amd-amdhsa--gfx908 -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.simple.bundle
// RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-amdgcn-amd-amdhsa--gfx903 -inputs=%t.o,%t.tgt1 -outputs=%t.simple1.bundle
// RUN: llvm-ar cr %t.input-archive.a %t.simple.bundle %t.simple1.bundle
// RUN: clang-offload-bundler -unbundle -type=a -targets=openmp-amdgcn-amd-amdhsa-gfx906,openmp-amdgcn-amd-amdhsa-gfx908 -inputs=%t.input-archive.a -outputs=%t-archive-gfx906-simple.a,%t-archive-gfx908-simple.a
// RUN: llvm-ar t %t-archive-gfx906-simple.a | FileCheck %s -check-prefix=GFX906
// GFX906: simple-openmp-amdgcn-amd-amdhsa-gfx906
// RUN: llvm-ar t %t-archive-gfx908-simple.a | FileCheck %s -check-prefix=GFX908
// GFX908-NOT: {{gfx906}}
// Check for error if no compatible code object is found in the heterogeneous archive library
// RUN: not clang-offload-bundler -unbundle -type=a -targets=openmp-amdgcn-amd-amdhsa-gfx803 -inputs=%t.input-archive.a -outputs=%t-archive-gfx803-incompatible.a 2>&1 | FileCheck %s -check-prefix=INCOMPATIBLEARCHIVE
// INCOMPATIBLEARCHIVE: error: no compatible code object found for the target 'openmp-amdgcn-amd-amdhsa-gfx803' in heterogeneous archive library
// Check creation of empty archive if allow-missing-bundles is present and no compatible code object is found in the heterogeneous archive library
// RUN: clang-offload-bundler -unbundle -type=a -targets=openmp-amdgcn-amd-amdhsa-gfx803 -inputs=%t.input-archive.a -outputs=%t-archive-gfx803-empty.a -allow-missing-bundles
// RUN: cat %t-archive-gfx803-empty.a | FileCheck %s -check-prefix=EMPTYARCHIVE
// EMPTYARCHIVE: !<arch>
// Some code so that we can create a binary out of this file.
int A = 0;
void test_func(void) {
++A;
}
|
the_stack_data/73801.c | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <unistd.h>
#define MAX 256
#define HashT_MAX 10
#define adminPin 123456
const char *filename = "accounts.txt";
const char *tempFilename = "accounts_tmp.txt";
FILE *ftemp;
FILE *fptr;
FILE *fhistory;
/*********************** CONSOLE FUNCTIONS ***********************/
int readLine(char *out){
int len = 0;
if (fgets(out, MAX, stdin) == NULL) return 0;
len = strlen(out);
if (len > 0) out[--len] = '\0';
return len;
}
int readInt(){
char temp[MAX];
int input;
readLine(temp);
sscanf(temp, "%d", &input);
return input;
}
int askInt(){
int input = 0;
input = readInt();
return input;
}
void tolower_str(char *str){
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
}
void pauseKey(){
printf("\nPress ENTER to continue . . . ");
getchar();
}
void clearScreen(){
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
/*********************** NODE STRUCTURE ***********************/
typedef struct _user{
int kartu;
int rekening;
int saldo;
int status;
char nama[MAX];
char pin[7];
int treeKey;
struct _user *next, *prev;
} User;
User *head, *tail, *curr, *node, *tempUser, *tempDirect, *temp_a, *temp_b;
/*********************** NODE FUNCTIONS ***********************/
void createNode(int rekening, int saldo, char nama[], char pin[], int kartu, int status){ //function untuk membuat node baru di linked list
node = (User*) malloc(sizeof(User));
node->next = NULL;
node->prev = NULL;
node->kartu = kartu;
node->rekening = rekening;
node->saldo = saldo;
node->status = status;
strcpy(node->nama, nama);
strcpy(node->pin, pin);
if(head == NULL){
head = node;
head->next = node;
head->prev = node;
tail = node;
}
else{
tail->next = node;
node->prev = tail;
tail = node;
tail->next = head;
head->prev = tail;
}
}
/*********************** QUEUE STRUCTURE ***********************/
typedef struct _queue{
int kartu;
int rekening;
int saldo;
int status;
char nama[MAX];
char pin[7];
struct _queue *next;
} Queue;
Queue *qnode, *qhead, *qtail;
/*********************** QUEUE FUNCTIONS ***********************/
void enqueue(int rekening, int saldo, char nama[], char pin[], int kartu, int status){
qnode = (Queue*) malloc(sizeof(Queue));
qnode->kartu = kartu;
qnode->rekening = rekening;
qnode->saldo = saldo;
qnode->status = status;
strcpy(qnode->nama, nama);
strcpy(qnode->pin, pin);
qnode->next = NULL;
if(qhead == NULL) qhead = qnode;
else qtail->next = qnode;
qtail = qnode;
}
void dequeue(){
Queue *hapus = qhead;
qhead = qhead->next;
free(hapus);
}
int isEmpty(Queue *temphead){
if(temphead == NULL) return 1;
else return 0;
}
/*********************** HASH STRUCTURE ***************************/
typedef struct _hashing{
int kartu;
struct _hashing *next;
} Hashing;
Hashing *head_hash, *HashT[HashT_MAX];
/*********************** HASH FUNCTIONS ***************************/
void insertToChain(int key, Hashing **head){
Hashing *ptr = (*head);
Hashing *node = (Hashing*) malloc(sizeof(Hashing));
node->kartu = key;
node->next = NULL;
if(*head == NULL){
*head = node;
head_hash = node;
} else {
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = node;
}
}
/*********************** TREE STRUCTURE ***************************/
typedef struct _tree{
int key;
struct _tree *left, *right;
} Tree;
/*********************** TREE FUNCTIONS ***************************/
Tree *newNode(int item){ //function untuk membuat node baru pada BST
Tree *temp = (Tree*) malloc(sizeof(Tree));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
Tree *insert(Tree *node, int key){
/* Jika tree null, dibuat nodenya */
if(node == NULL) return newNode(key);
/* Jika tidak null, maka akan turun ke bawah */
if(key < node->key)
node->left = insert(node->left, key);
else if(key > node->key)
node->right = insert(node->right, key);
/* return node jika sudah selesai */
return node;
}
void printTree(int key){
curr = head;
while(1){
if(key == curr->kartu){
printf("Nama Nasabah : %s\n", curr->nama);
printf("Nomor Kartu : %d\n", curr->kartu);
printf("Nomor Rekening : %d\n", curr->rekening);
printf("PIN : %s\n", curr->pin);
printf("Saldo : Rp%d\n", curr->saldo);
printf("Status : %s\n", curr->status ? "Terblokir" : "Normal"); //Untuk melihat apakah data pengguna sudah terblokir atau belum
printf("------------------------------------\n");
}
curr = curr->next;
if(curr == head)
break;
}
}
void preorder(Tree *pnode){
if(pnode == NULL) return;
printTree(pnode->key);
preorder(pnode->left);
preorder(pnode->right);
}
void inorder(Tree *pnode){
if(pnode == NULL) return;
inorder(pnode->left);
printTree(pnode->key);
inorder(pnode->right);
}
void postorder(Tree *pnode){
if(pnode == NULL) return;
postorder(pnode->left);
postorder(pnode->right);
printTree(pnode->key);
}
void replaceData(){ //function untuk mereplace data baru pengguna di accounts.txt
ftemp = fopen(tempFilename, "w");
curr = head;
while(1){
fprintf(ftemp, "nama=%s#kartu=%d#rekening=%d#pin=%s#saldo=%d#blocked=%d\n", curr->nama, curr->kartu, curr->rekening, curr->pin, curr->saldo, curr->status);
curr = curr->next;
if(curr == head)
break;
}
fclose(ftemp);
remove(filename);
rename(tempFilename, filename);
}
void moveData(){ //function untuk memindahkan data dari accounts.txt ke linked list
int rekening = 0, saldo = 0, kartu = 0, status = 0;
char nama[MAX], pin[7];
for(int i = 0; i < HashT_MAX; i++){
HashT[i] = NULL; // Inisialisasi HashTable
}
fptr = fopen(filename, "r");
while(!feof(fptr)){
fscanf(fptr, "nama=%[^#]#kartu=%d#rekening=%d#pin=%[^#]#saldo=%d#blocked=%d ", nama, &kartu, &rekening, pin, &saldo, &status);
if(rekening != 0){
createNode(rekening, saldo, nama, pin, kartu, status);
insertToChain(kartu, &HashT[kartu%10]);
}
}
fclose(fptr);
}
int duplicateNumber(int choice, int temp){ //function untuk mengembalikan nilai integer dari nomor kartu / nomor rekening yang ada di file accounts.txt sesuai dengan parameter choice
int rekening = 0, saldo = 0, kartu = 0, status = 0;
char nama[MAX], pin[7];
fptr = fopen(filename, "r");
while(!feof(fptr)){
fscanf(fptr, "nama=%[^#]#kartu=%d#rekening=%d#pin=%[^#]#saldo=%d#blocked=%d ", nama, &kartu, &rekening, pin, &saldo, &status);
if(choice == 0 && kartu == temp){
fclose(fptr);
return kartu;
}
else if(choice == 1 && rekening == temp){
fclose(fptr);
return rekening;
}
}
fclose(fptr);
return 0;
}
int randomNumber(char request[]){ //function mendapatkan nomor kartu dan nomor rekening acak ketika pengguna mendaftar ke bank
int result = 0, lower, upper;
int temp = 0;
do{
temp = 0;
srand(time(NULL));
if(strcmp(request, "card") == 0){ //Jika string compare me-return value '0' alias true yang artinya parameter string "request" yang diterima sama dengan string pembanding
lower = 10000; //Menentukan batas bawah bilangan
upper = 99999; //Menentukan batas atas bilangan
result = (rand() % (upper - lower + 1)) + lower;
temp = duplicateNumber(0, result);
}
else if (strcmp(request, "rekening") == 0){
lower = 100000000; //Menentukan batas bawah bilangan
upper = 999999999; //Menentukan batas atas bilangan
result = (rand() % (upper - lower + 1)) + lower;
temp = duplicateNumber(1, result);
}
}while(temp == result);
return result; //Kemudian return hasil dari operasi yang ada di variable 'result'
}
//function untuk mencatat setiap transaksi yang nasabah lakukan
void writeHistory(int rekening_tmp, int saldo_tmp, int tipe){
fhistory = fopen(tempUser->nama, "a");
fprintf(fhistory, "rekening=%d#nominal=%d#tipe=%d\n", rekening_tmp, saldo_tmp, tipe);
fclose(fhistory);
}
//function untuk membuat file kosong dengan nama nasabah
void newFile(char *name){
if(access(name, F_OK) != 0){
fhistory = fopen(name, "a");
fclose(fhistory);
}
}
void infoMenu(){
int pilihan = 0;
int rekening_tmp = 0, saldo_tmp = 0, tipe = 0, i = 1;
do{
clearScreen();
printf("===================================\n");
printf(" Menu Info Saldo \n");
printf("===================================\n");
printf("1. Info Saldo Anda\n");
printf("2. Mutasi Rekening\n");
printf("0. Kembali\n");
printf("Pilihan : ");
pilihan = askInt();
if(pilihan >= 1 && pilihan <= 2){
break;
}
}while(pilihan != 0);
switch(pilihan){
case 1:
printf("Rekening Anda : %d\n", tempUser->rekening); //Untuk menampilkan nomor rekening pengguna
printf("Saldo Anda : Rp%d\n", tempUser->saldo); //Untuk menampilkan saldo pengguna
pauseKey();
break;
case 2:
clearScreen();
fhistory = fopen(tempUser->nama, "r");
if(fhistory == NULL){
/*
Jika file nama nasabah tidak ada,
maka artinya nasabah belum pernah melakukan transaksi.
*/
printf("Info : %s belum pernah melakukan transaksi !\n", tempUser->nama);
newFile(tempUser->nama);
}
else{
if(head != NULL){
while(!feof(fhistory)){
fscanf(fhistory, "rekening=%d#nominal=%d#tipe=%d ", &rekening_tmp, &saldo_tmp, &tipe);
if(tipe == 1){ //tipe = 1 untuk Setor Tunai
printf("Transaksi Ke-%d\n", i);
printf("Tipe Transaksi : Setor Tunai\n");
printf("Rekening Anda : %d\n", tempUser->rekening);
printf("Jumlah Setoran : Rp%d\n", saldo_tmp);
}
else if(tipe == 2){ //tipe = 2 untuk Penarikan Tunai
printf("Transaksi Ke-%d\n", i);
printf("Tipe Transaksi : Penarikan Tunai\n");
printf("Rekening Anda : %d\n", tempUser->rekening);
printf("Jumlah Penarikan : Rp%d\n", saldo_tmp);
}
else if(tipe == 3){ //tipe = 3 untuk Transfer
printf("Transaksi Ke-%d\n", i);
printf("Tipe Transaksi : Transfer\n");
printf("Rekening Anda : %d\n", tempUser->rekening);
printf("Rekening Tujuan : %d\n", rekening_tmp);
printf("Jumlah Transfer : Rp%d\n", saldo_tmp);
}
printf("------------------------------------\n");
i++;
}
if(tipe == 0){
printf("Anda belum melakukan transaksi apapun!\n");
} else {
printf("Sukses menampilkan transaksi terakhir Anda\n");
}
}
else {
printf("Belum Ada Nasabah yang Terdaftar !\n");
}
}
fclose(fhistory);
pauseKey();
break;
default:
break;
}
}
void depositMenu(){
int nominal = 0;
clearScreen();
printf("====================================\n");
printf(" Menu Setor Tunai \n");
printf("====================================\n");
printf("Masukkan Nominal Uang : Rp");
nominal = askInt();
tempUser->saldo += nominal; //Saldo pengguna bertambah sesuai nominal yang di input oleh pengguna
replaceData(); //Untuk mereplace data baru pengguna di accounts.txt
writeHistory(tempUser->rekening, nominal, 1); //Untuk menyimpan history hasil transaksi
printf("\nSetor Tunai Berhasil !\n");
pauseKey();
}
void withdrawMenu(){
int pilihan = 0;
int nominal[] = {100000, 500000, 1000000, 1500000, 2000000}; //Menyimpan nominal penarikan tunai ke dalam array
do{
clearScreen();
printf("====================================\n");
printf(" Menu Penarikan Tunai \n");
printf("====================================\n");
printf("1. Rp100.000\n");
printf("2. Rp500.000\n");
printf("3. Rp1.000.000\n");
printf("4. Rp1.500.000\n");
printf("5. Rp2.000.000\n");
printf("0. Kembali\n");
printf("Pilihan : ");
pilihan = askInt();
if(pilihan >= 0 && pilihan <= 5){
switch(pilihan){
case 1:
if(tempUser->saldo >= nominal[pilihan-1]){
tempUser->saldo -= nominal[pilihan-1]; //Saldo pengguna berkurang Rp100.000
writeHistory(tempUser->rekening, nominal[pilihan-1], 2); //Untuk menyimpan history hasil transaksi
printf("Penarikan Tunai Berhasil !\n");
}
else{
printf("Maaf Saldo Anda Tidak Mencukupi !\n");
}
break;
case 2:
if(tempUser->saldo >= nominal[pilihan-1]){
tempUser->saldo -= nominal[pilihan-1]; //Saldo pengguna berkurang Rp500.000
writeHistory(tempUser->rekening, nominal[pilihan-1], 2); //Untuk menyimpan history hasil transaksi
printf("Penarikan Tunai Berhasil !\n");
}
else{
printf("Maaf Saldo Anda Tidak Mencukupi !\n");
}
break;
case 3:
if(tempUser->saldo >= nominal[pilihan-1]){
tempUser->saldo -= nominal[pilihan-1]; //Saldo pengguna berkurang Rp1.000.000
writeHistory(tempUser->rekening, nominal[pilihan-1], 2); //Untuk menyimpan history hasil transaksi
printf("Penarikan Tunai Berhasil !\n");
}
else{
printf("Maaf Saldo Anda Tidak Mencukupi !\n");
}
break;
case 4:
if(tempUser->saldo >= nominal[pilihan-1]){
tempUser->saldo -= nominal[pilihan-1]; //Saldo pengguna berkurang Rp1.500.000
writeHistory(tempUser->rekening, nominal[pilihan-1], 2); //Untuk menyimpan history hasil transaksi
printf("Penarikan Tunai Berhasil !\n");
}
else{
printf("Maaf Saldo Anda Tidak Mencukupi !\n");
}
break;
case 5:
if(tempUser->saldo >= nominal[pilihan-1]){
tempUser->saldo -= nominal[pilihan-1]; //Saldo pengguna berkurang Rp2.000.000
writeHistory(tempUser->rekening, nominal[pilihan-1], 2); //Untuk menyimpan history hasil transaksi
printf("Penarikan Tunai Berhasil !\n");
}
else{
printf("Maaf Saldo Anda Tidak Mencukupi !\n");
}
break;
default:
break;
}
replaceData(); //Untuk mereplace data baru pengguna di accounts.txt
pauseKey();
break;
}
else{
printf("Pilihan Salah !");
pauseKey();
}
}while(pilihan != 0);
}
void transferMenu(){
int rekTujuan = 0, nominal = 0;
clearScreen();
printf("===================================\n");
printf(" Menu Transfer \n");
printf("===================================\n");
if(head != tail){
printf("Masukkan Nomor Rekening Tujuan : ");
rekTujuan = askInt();
tempDirect = head;
while(1){ //Untuk mencari rekening pengguna yang ingin di transfer
if(rekTujuan == tempDirect->rekening && rekTujuan != tempUser->rekening)
break;
tempDirect = tempDirect->next;
if(tempDirect == head)
break;
}
if(rekTujuan == tempDirect->rekening && rekTujuan != tempUser->rekening){ //Jika rekening yang dituju valid, maka proses transfer dilakukan
printf("Masukkan Nominal Saldo : Rp");
nominal = askInt();
tempUser->saldo -= nominal;
tempDirect->saldo += nominal;
replaceData(); //Untuk mereplace data baru di accounts.txt
writeHistory(rekTujuan, nominal, 3); //Untuk menyimpan history hasil transaksi
printf("\nTransfer Berhasil !\n");
pauseKey();
}
else { //Jika rekening pengguna tidak valid, maka tidak akan terjadi proses transfer
printf("\nRekening Tujuan yang Anda Masukkan Tidak Terdaftar !\n");
pauseKey();
}
}
else { //Jika belum ada 2 rekening yang terdaftar di bank, maka tidak akan terjadi proses transfer
printf("Minimal Harus Ada 2 Rekening yang Terdaftar untuk Melakukan Transfer Saldo !\n");
pauseKey();
}
}
void mainMenu(){
int pilihan = 0;
do{
clearScreen();
printf("====================================\n");
printf(" Menu Utama \n");
printf("====================================\n");
printf("1. Info\n");
printf("2. Setor Tunai\n");
printf("3. Tarik Tunai\n");
printf("4. Transfer\n");
printf("0. Kembali\n");
printf("Pilihan : ");
pilihan = askInt();
switch(pilihan){
case 1:
infoMenu();
break;
case 2:
depositMenu();
break;
case 3:
withdrawMenu();
break;
case 4:
transferMenu();
break;
default:
break;
}
}while(pilihan != 0);
}
void swap(User *a, User *b){ //function untuk mengembalikan data yang sudah di sorting ke linked list
char nama[MAX], pin[7];
int kartu = 0, rekening = 0, saldo = 0, status = 0;
strcpy(nama, a->nama);
kartu = a->kartu;
rekening = a->rekening;
strcpy(pin, a->pin);
saldo = a->saldo;
status = a->status;
strcpy(a->nama, b->nama);
a->kartu = b->kartu;
a->rekening = b->rekening;
strcpy(a->pin, b->pin);
a->saldo = b->saldo;
a->status = b->status;
strcpy(b->nama, nama);
b->kartu = kartu;
b->rekening = rekening;
strcpy(b->pin, pin);
b->saldo = saldo;
b->status = status;
}
void sort_saldoTerkecil(){ //function untuk melakukan sorting dari saldo terkecil ke saldo terbesar menggunakan selection sort
int i = 1;
curr = head;
if(head != NULL){
while(curr->next != head){
temp_a = curr->next;
temp_b = curr;
while(1){
if(temp_a->saldo < temp_b->saldo){
temp_b = temp_a;
}
temp_a = temp_a->next;
if(temp_a == head){
break;
}
}
if(curr != temp_b){
swap(curr, temp_b);
}
curr = curr->next;
}
}
}
void sort_saldoTerbesar(){ //function untuk melakukan sorting dari saldo terbesar ke saldo terkecil menggunakan selection sort
int i = 1;
curr = head;
if(head != NULL){
while(curr->next != head){
temp_a = curr->next;
temp_b = curr;
while(1){
if(temp_a->saldo > temp_b->saldo){
temp_b = temp_a;
}
temp_a = temp_a->next;
if(temp_a == head){
break;
}
}
if(curr != temp_b){
swap(curr, temp_b);
}
curr = curr->next;
}
}
}
void daftarNasabah(char request[9]){ //function untuk menampilkan list nasabah yang sudah pernah mendaftar di bank
int i = 1;
clearScreen();
printf("===================================\n");
printf(" List Akun Nasabah \n");
printf("===================================\n");
curr = head;
if(head != NULL){
while(1){
printf("Data Nasabah Ke-%d\n", i);
printf("Nama Nasabah : %s\n", curr->nama);
printf("Nomor Kartu : %d\n", curr->kartu);
printf("Nomor Rekening : %d\n", curr->rekening);
printf("PIN : %s\n", curr->pin);
printf("Saldo : Rp%d\n", curr->saldo);
printf("Status : %s\n", curr->status ? "Terblokir" : "Normal"); //Untuk melihat apakah data pengguna sudah terblokir atau belum
printf("------------------------------------\n");
curr = curr->next;
i++;
if(curr == head)
break;
}
if(strcmp(request, "terbesar") == 0 && head != NULL){
printf("\nDaftar Nasabah berhasil diurutkan berdasarkan saldo terbesar !\n");
}
else if(strcmp(request, "terkecil") == 0&& head != NULL){
printf("\nDaftar Nasabah berhasil diurutkan berdasarkan saldo terkecil !\n");
}
}
else{
printf("Belum Ada Nasabah yang Terdaftar !\n");
}
pauseKey();
}
void listMenu_sorting(){
int pilihan = 0;
do{
clearScreen();
printf("===================================\n");
printf(" List Data Nasabah \n");
printf("===================================\n");
printf("1. Sort Saldo Terbesar\n");
printf("2. Sort Saldo Terkecil\n");
printf("0. Kembali\n");
printf("Pilihan : ");
pilihan = askInt();
switch(pilihan){
case 1:
sort_saldoTerbesar();
daftarNasabah("terbesar"); //Untuk melakukan sorting dan menampilkan dari saldo terbesar ke saldo terkecil
break;
case 2:
sort_saldoTerkecil();
daftarNasabah("terkecil"); //Untuk melakukan sorting dan menampilkan dari saldo terkecil ke saldo terbesar
break;
default:
break;
}
}while(pilihan != 0);
}
void listMenu_tree(){
Tree *root = NULL;
int pilihan = 0;
curr = head;
root = insert(root, curr->kartu);
curr = curr->next;
while(1){
insert(root, curr->kartu);
curr = curr->next;
if(curr == head)
break;
}
do{
clearScreen();
printf("=====================================\n");
printf(" List Data Nasabah (Mode Tree) \n");
printf("=====================================\n");
printf("1. Pre-Order\n");
printf("2. In-Order\n");
printf("3. Post-Order\n");
printf("0. Kembali\n");
printf("Pilihan : ");
pilihan = askInt();
clearScreen();
printf("=====================================\n");
printf(" List Data Nasabah (Mode Tree) \n");
printf("=====================================\n");
switch(pilihan){
case 1:
preorder(root);
pauseKey();
break;
case 2:
inorder(root);
pauseKey();
break;
case 3:
postorder(root);
pauseKey();
break;
default:
break;
}
}while(pilihan != 0);
}
void listMenu(){
int pilihan = 0;
do{
clearScreen();
printf("====================================\n");
printf(" Menu List Data Nasabah \n");
printf("====================================\n");
printf("1. Sorting Mode\n");
printf("2. Tree Mode\n");
printf("0. Kembali\n");
printf("Pilihan : ");
pilihan = askInt();
switch(pilihan){
case 1:
listMenu_sorting();
break;
case 2:
listMenu_tree();
break;
default:
break;
}
}while(pilihan != 0);
}
void list_noKartu(){ //function untuk menampilkan urutan nomor kartu nasabah menggunakan algoritma hashing
clearScreen();
printf("====================================\n");
printf(" Menu List Nomor Kartu Nasabah \n");
printf("====================================\n");
for(int i = 0; i < HashT_MAX; i++){
Hashing *ptr = HashT[i];
printf("[%d] ->", i);
while(ptr != NULL){
printf(" (%d)", ptr->kartu);
ptr = ptr->next;
}
printf("\n");
}
pauseKey();
}
void searchMenu(){ //function untuk mencari data nasabah dengan memasukkan nama nasabah
char searchKey[MAX], temp[MAX];
bool check = false;
clearScreen();
printf("====================================\n");
printf(" Menu Pencarian Nasabah \n");
printf("====================================\n");
printf("Masukkan nama lengkap nasabah : "); readLine(searchKey);
printf("\n");
curr = head;
while(1){
strcpy(temp, curr->nama);
tolower_str(temp);
tolower_str(searchKey);
if(strcmp(searchKey, temp) == 0){
check = true;
break;
}
curr = curr->next;
if(curr == head){
break;
}
}
if(check == true){
printf("Data nasabah yang anda cari :\n");
printf("Nama Nasabah : %s\n", curr->nama);
printf("Nomor Kartu : %d\n", curr->kartu);
printf("Nomor Rekening : %d\n", curr->rekening);
printf("PIN : %s\n", curr->pin);
printf("Saldo : Rp%d\n", curr->saldo);
printf("Status : %s\n", curr->status ? "Terblokir" : "Normal"); //Untuk melihat apakah data pengguna sudah terblokir atau belum
} else {
printf("Data pengguna tidak ditemukan !\n");
}
pauseKey();
}
void verificationMenu(){ //function untuk melakukan verifikasi akun menggunakan algoritma queue
int pilihan;
int tempPin;
clearScreen();
printf("====================================\n");
printf(" Menu Verifikasi Akun \n");
printf("====================================\n");
printf("Masukkan PIN (Administrator) : ");
tempPin = askInt();
if(tempPin == adminPin){
if(!isEmpty(qhead)){
while(!isEmpty(qhead)){
do{
clearScreen();
printf("====================================\n");
printf(" Menu Verifikasi Akun \n");
printf("====================================\n");
printf("Nama Nasabah : %s\n", qhead->nama);
printf("Nomor Kartu : %d\n", qhead->kartu);
printf("Nomor Rekening : %d\n", qhead->rekening);
printf("PIN : %s\n", qhead->pin);
printf("Saldo : Rp%d\n", qhead->saldo);
printf("Status : %s\n", qhead->status ? "Terblokir" : "Normal"); //Untuk melihat apakah data pengguna sudah terblokir atau belum
printf("------------------------------------\n");
printf("1. Verifikasi akun\n");
printf("2. Batalkan akun\n");
printf("0. Kembali\n");
printf("Pilihan : ");
pilihan = askInt();
if(pilihan >= 0 && pilihan <= 2){
switch(pilihan){
case 1:
createNode(qhead->rekening, qhead->saldo, qhead->nama, qhead->pin, qhead->kartu, qhead->status); //Untuk membuat node baru di linked list
insertToChain(qhead->kartu, &HashT[qhead->kartu%10]);
fptr = fopen(filename, "a"); //Untuk mencatat data pengguna di accounts.txt
if(fptr == NULL){
printf("\n Error: %s does not exist!", filename);
}
else{
fprintf(fptr, "nama=%s#kartu=%d#rekening=%d#pin=%s#saldo=%d#blocked=%d\n", node->nama, node->kartu, node->rekening, node->pin, node->saldo, node->status);
}
fclose(fptr);
printf("Verifikasi akun berhasil!\n\n");
printf("Nomor Kartu Nasabah : %d\n", node->kartu);
printf("Nomor Rekening Nasabah : %d\n", node->rekening);
dequeue();
pauseKey();
break;
case 2:
printf("Verifikasi akun dibatalkan!\n");
dequeue();
pauseKey();
break;
default:
break;
}
if(pilihan < 0 || pilihan > 2){
printf("Pilihan Salah !\n");
pauseKey();
}
}
}while(pilihan < 0 || pilihan > 2);
if(pilihan == 0) break;
}
}
else{
printf("Queue masih kosong!\n");
pauseKey();
}
}
else{
printf("\nPIN salah!\n");
pauseKey();
}
}
void registerMenu(){ //function untuk melakukan pendaftaran
int rekening = 0, saldo = 0, kartu = 0, status = 0;
char nama[MAX], pin[MAX];
kartu = randomNumber("card"); //Untuk generate nomor kartu acak
rekening = randomNumber("rekening"); //Untuk generate nomor rekening acak
clearScreen();
printf("====================================\n");
printf(" Menu Pendaftaran Nasabah \n");
printf("====================================\n");
printf("Masukkan Nama Anda : "); readLine(nama);
printf("Masukkan Saldo Awal : Rp");
saldo = askInt();
do{
printf("Masukkan 6 Digit PIN : "); readLine(pin);
}while(strlen(pin) != 6); //Untuk memastikan PIN yang dimasukkan pengguna harus 6 digit
enqueue(rekening, saldo, nama, pin, kartu, status); //Untuk membuat node baru di linked list
printf("-------------------------------------\n");
printf("Akun Anda berhasil dimasukkan ke dalam Queue.\n");
printf("Mohon tunggu hingga admin memverifikasi akun Anda !\n");
pauseKey();
}
void loginMenu(){ //function untuk login
int kartu = 0, tempKartu = 0, num_of_retries = 3, i = 0;
char tempPin[MAX];
bool retry = true, card_exist = false;
Hashing *ptr;
do{
clearScreen();
printf("====================================\n");
printf(" Menu Login \n");
printf("====================================\n");
if(head != NULL){
printf("Masukkan Nomor Kartu Anda : ");
tempKartu = askInt();
printf("Masukkan PIN Anda : ");
readLine(tempPin);
/*
Mencari input nomor kartu di HashTable,
Jika input nomor kartu sesuai dengan yang ada di HashTable,
maka akan keluar dari looping
*/
for(i = 0; i < HashT_MAX; i++){
ptr = HashT[i];
if(ptr == NULL){
ptr = head_hash;
} else {
while(ptr != NULL){
if(tempKartu == ptr->kartu){
card_exist = true;
break;
}
ptr = ptr->next;
}
if(card_exist){
kartu = ptr->kartu;
break;
}
}
}
tempUser = head;
while(1){ //Untuk mencari data pengguna yang login di linked list
if(kartu == tempUser->kartu)
break;
tempUser = tempUser->next;
if(tempUser == head)
break;
}
if(kartu == tempUser->kartu && strcmp(tempPin, tempUser->pin) == 0 && tempUser->status == 0){ //Jika datanya valid maka masuk ke main menu
newFile(tempUser->nama);
mainMenu();
break;
}
else if(tempUser->status == 1){ //Jika datanya sudah terblokir maka keluar dari menu login
retry = false;
break;
}
else if(kartu == tempUser->kartu && strcmp(tempPin, tempUser->pin) != 0 && tempUser->status == 0){ //Untuk melakukan hitung mundur, jika 3x berturut-turut pengguna salah memasukkan PIN maka datanya akan terblokir
num_of_retries--;
if(num_of_retries >= 1){
printf("\nPIN yang Anda masukkan salah !\n");
printf("Sisa percobaan Anda %d kali lagi\n", num_of_retries);
if(num_of_retries == 1){
printf("Jika Anda masih salah dalam memasukkan PIN Anda,\n");
printf("maka akun Anda akan TERBLOKIR !\n");
}
pauseKey();
}
if(num_of_retries == 0){
tempUser->status = 1;
replaceData();
retry = false;
}
}
else{ //Jika data yang pengguna masukkan tidak valid atau tidak ada di linked list maka akan keluar dari menu login
printf("\nData yang anda masukkan tidak terdaftar\n");
pauseKey();
break;
}
}
else{ //Jika tidak ada satupun data di linked list atau pengguna belum pernah melakukan pendaftaran maka akan keluar dari menu login
printf("Tidak Ada Nasabah yang Terdaftar !\n");
pauseKey();
break;
}
}while(retry == true);
if(retry == false){
printf("\nNomor Kartu Anda telah Terblokir!\n");
pauseKey();
}
}
void freeData(bool deleteData){
User *temp;
if(head != NULL){
curr = head->next;
while(curr != NULL && curr != head){
temp = curr;
curr = curr->next;
if(deleteData){
remove(temp->nama);
}
free(temp);
}
if(deleteData){
remove(head->nama);
}
free(head);
head = tail = NULL;
}
}
void clearMenu(bool flag){
if(flag){
int tempPin;
clearScreen();
printf("=====================================\n");
printf(" Menu Hapus Semua Data Nasabah \n");
printf("=====================================\n");
printf("Masukkan PIN (Administrator) : ");
tempPin = askInt();
if(tempPin == adminPin){
clearScreen();
printf("=====================================\n");
printf(" Menu Hapus Semua Data Nasabah \n");
printf("=====================================\n");
freeData(flag);
ftemp = fopen(tempFilename, "w");
fclose(ftemp);
remove(filename);
rename(tempFilename, filename);
printf("Semua Data Nasabah Berhasil Dihapus!\n");
}
else{
printf("\nPIN Salah!\n");
}
}
else{
clearScreen();
freeData(flag);
printf("Terima Kasih Sudah Menggunakan U-Bank !\n");
}
pauseKey();
}
//function untuk mengecek keberadaan dan permission dari file accounts.txt
bool checkFile(){
bool status = true;
if(access(filename, F_OK) != 0){ // Check for file permission
printf(" Error : '%s' does not exist!\n\n", filename);
printf("A new file named '%s' has been created!\n", filename);
FILE *file;
file = fopen(filename, "a");
fclose(file);
pauseKey();
} else {
if(access(filename, R_OK) != 0){
printf(" Error : '%s' file exist, but missing read permission!\n", filename);
pauseKey();
status = false;
}
if(access(filename, W_OK) != 0){
printf(" Error : '%s' file exist, but missing write permission!\n", filename);
pauseKey();
status = false;
}
}
return status;
}
int main(){
int pilihan = 0;
clearScreen();
if(!checkFile()){
return 0;
}
moveData(); //Untuk memindahkan data dari accounts.txt ke linked list sebelum program dimulai
do{
clearScreen();
printf("====================================\n");
printf(" Selamat Datang di U-Bank \n");
printf("====================================\n");
printf("1. Login\n");
printf("2. Register\n");
printf("3. Verifikasi Akun Nasabah (Administrator)\n");
printf("4. List Data Nasabah\n");
printf("5. List Nomor Kartu Nasabah\n");
printf("6. Cari Data Nasabah\n");
printf("7. Hapus Semua Data Nasabah (Administrator)\n");
printf("0. Keluar\n");
printf("Pilihan : ");
pilihan = askInt();
if(pilihan >= 0 && pilihan <= 7){
switch(pilihan){
case 1:
loginMenu();
break;
case 2:
registerMenu();
break;
case 3:
verificationMenu(); // Untuk melakukan verifikasi akun menggunakan algoritma queue
break;
case 4:
listMenu(); // Untuk menampilkan data nasabah yang sudah pernah mendaftar
break;
case 5:
list_noKartu(); // Untuk menampilkan urutan nomor kartu nasabah menggunakan algoritma hashing
break;
case 6:
searchMenu(); // Untuk mencari data nasabah dengan memasukkan nama nasabah
break;
case 7:
clearMenu(true); // Untuk menghapus semua data di linked list dan di accounts.txt
break;
default:
break;
}
}
else{
printf("Pilihan Salah !");
pauseKey();
}
}while(pilihan != 0);
clearMenu(false); //Untuk menghapus semua data di linked list tanpa menghapus data di accounts.txt
return 0;
}
|
the_stack_data/12636877.c | /*
** EPITECH PROJECT, 2017
** my_revstr.c
** File description:
** reverse string
*/
#include <unistd.h>
char my_putchar(char c);
int my_putstr(char const *str);
int my_strlen(char const *str);
char *my_revstr(char *str)
{
char variable;
int a_start;
int a;
a = my_strlen(str);
a_start = a;
a--;
for (int i = 0; i != a_start / 2; i++) {
variable = str[i];
str[i] = str[a];
str[a] = variable;
a--;
}
return (str);
}
|
the_stack_data/15763969.c | /**
* @file bufst.c
* @brief print stdin/stdout/stderr buffer status info
* @author liuyang1 [email protected]
* @version 0.01
* @date 2012-11-13
*/
|
the_stack_data/182953275.c | /* Representation of calling context for argv */
/* This declaration generates a warning in gcc if the function name is
"main". */
int argv03(int argc, char * (*argv)[argc])
{
char *p = (*argv)[1];
return p==p; // To silence gcc
}
|
the_stack_data/465729.c | a, b, c, d, e, f;
g() {
long h, i, j;
e = 0;
if (c || a) {
f &&k();
j = e;
a &&k();
h = d;
} else if (b) {
l();
i = j = e;
}
if (j)
m();
n(i);
n(h);
}
|
the_stack_data/37637710.c | #include <stdio.h>
int main(int argc, char** argv) {
char* x = "Hello, world!";
puts(x);
return 0;
} |
the_stack_data/198581386.c | #include<stdio.h>
main()
{
prinf("Hello World");
}
|
the_stack_data/37636498.c | /**
* This version is stamped on May 10, 2016
*
* Contact:
* Louis-Noel Pouchet <pouchet.ohio-state.edu>
* Tomofumi Yuki <tomofumi.yuki.fr>
*
* Web address: http://polybench.sourceforge.net
*/
/* fdtd-2d.c: this file is part of PolyBench/C */
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
static void init_array(int tmax,
int nx,
int ny,
double ex[1000 + 0][1200 + 0],
double ey[1000 + 0][1200 + 0],
double hz[1000 + 0][1200 + 0],
double _fict_[500 + 0])
{
//int i, j;
for (int i = 0; i < tmax; i++)
_fict_[i] = (double)i;
for (int i = 0; i < nx; i++)
for (int j = 0; j < ny; j++)
{
ex[i][j] = ((double)i * (j + 1)) / nx;
ey[i][j] = ((double)i * (j + 2)) / ny;
hz[i][j] = ((double)i * (j + 3)) / nx;
}
}
static void print_array(int nx,
int ny,
double ex[1000 + 0][1200 + 0],
double ey[1000 + 0][1200 + 0],
double hz[1000 + 0][1200 + 0])
{
int i, j;
fprintf(stderr, "==BEGIN DUMP_ARRAYS==\n");
fprintf(stderr, "begin dump: %s", "ex");
for (i = 0; i < nx; i++)
for (j = 0; j < ny; j++)
{
if ((i * nx + j) % 20 == 0)
fprintf(stderr, "\n");
fprintf(stderr, "%0.2lf ", ex[i][j]);
}
fprintf(stderr, "\nend dump: %s\n", "ex");
fprintf(stderr, "==END DUMP_ARRAYS==\n");
fprintf(stderr, "begin dump: %s", "ey");
for (i = 0; i < nx; i++)
for (j = 0; j < ny; j++)
{
if ((i * nx + j) % 20 == 0)
fprintf(stderr, "\n");
fprintf(stderr, "%0.2lf ", ey[i][j]);
}
fprintf(stderr, "\nend dump: %s\n", "ey");
fprintf(stderr, "begin dump: %s", "hz");
for (i = 0; i < nx; i++)
for (j = 0; j < ny; j++)
{
if ((i * nx + j) % 20 == 0)
fprintf(stderr, "\n");
fprintf(stderr, "%0.2lf ", hz[i][j]);
}
fprintf(stderr, "\nend dump: %s\n", "hz");
}
static void kernel_fdtd2d(int tmax,
int nx,
int ny,
double ex[1000 + 0][1200 + 0],
double ey[1000 + 0][1200 + 0],
double hz[1000 + 0][1200 + 0],
double _fict_[500 + 0])
{
// int t, i, j;
#pragma scop
for (int t = 0; t < tmax; t++)
{
for (int j = 0; j < ny; j++)
ey[0][j] = _fict_[t];
for (int i = 1; i < nx; i++)
for (int j = 0; j < ny; j++)
ey[i][j] = ey[i][j] - 0.5 * (hz[i][j] - hz[i - 1][j]);
for (int i = 0; i < nx; i++)
for (int j = 1; j < ny; j++)
ex[i][j] = ex[i][j] - 0.5 * (hz[i][j] - hz[i][j - 1]);
for (int i = 0; i < nx - 1; i++)
for (int j = 0; j < ny - 1; j++)
hz[i][j] = hz[i][j] - 0.7 * (ex[i][j + 1] - ex[i][j] +
ey[i + 1][j] - ey[i][j]);
}
#pragma endscop
}
int main(int argc, char **argv)
{
int tmax = 500;
int nx = 1000;
int ny = 1200;
double(*ex)[1000 + 0][1200 + 0];
ex = (double(*)[1000 + 0][1200 + 0]) malloc(((1000 + 0) * (1200 + 0)) * sizeof(double));
;
double(*ey)[1000 + 0][1200 + 0];
ey = (double(*)[1000 + 0][1200 + 0]) malloc(((1000 + 0) * (1200 + 0)) * sizeof(double));
;
double(*hz)[1000 + 0][1200 + 0];
hz = (double(*)[1000 + 0][1200 + 0]) malloc(((1000 + 0) * (1200 + 0)) * sizeof(double));
;
double(*_fict_)[500 + 0];
_fict_ = (double(*)[500 + 0]) malloc((500 + 0) * sizeof(double));
;
init_array(tmax, nx, ny,
*ex,
*ey,
*hz,
*_fict_);
kernel_fdtd2d(tmax, nx, ny,
*ex,
*ey,
*hz,
*_fict_);
if (argc > 42)
print_array(nx, ny, *ex, *ey, *hz) ;
//argc=0;argv[0]=0;
//printf("GR: %f",hz[999][1199]);
free((void *)ex);
;
free((void *)ey);
;
free((void *)hz);
;
free((void *)_fict_);
;
return 0;
}
|
the_stack_data/1192029.c | /*
basic 1
*/
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
int fd;
int ret = 0;
int read_pin;
int write_ret;
int write_on ;
int main(int argc, char *argv[])
{
unsigned int i;
unsigned int read_pin_buf;
fd = open("/dev/io_control",O_RDWR);
if(fd < 0)
{
perror("error to open /dev/io_control_dev");
exit(1);
}
int number ;
unsigned int zero = 0 ;
while(1)
{
ret = read(fd, &read_pin,4);
if(ret < 0)
{
perror("error to read\n");
exit(1);
}
read_pin_buf=read_pin;
//printf("read_pin_buf =%d \n " ,read_pin_buf );
//number = read_pin_buf & (zero |(0x1<<7)) ;
//printf("%d" , number );
if(( read_pin_buf & (zero |(0x1<<7))) == 128 )
printf("1");
if((read_pin_buf & (zero |(0x1<<8))) == 256 )
printf("2");
if((read_pin_buf & (zero |(0x1<<9))) == 512)
printf("3");
if((read_pin_buf & (zero |(0x1<<10))) == 1024 )
printf("4");
if((read_pin_buf & (zero |(0x1<<11))) == 2048 )
printf("5");
if((read_pin_buf & (zero |(0x1<<4))) == 16 )
printf("6");
if((read_pin_buf & (zero |(0x1<<5))) == 32 )
printf("7");
if((read_pin_buf & (zero |(0x1<<6))) == 64 )
printf("8");
printf("qq\n");
sleep(1) ;
/*
switch(read_pin_buf)
{
case 4:
case 5:
case 6:
number = read_pin_buf +1 ;
write_on = number +7 ;
write_ret = write(fd , &write_on , 4) ;
if(write_ret < 0)
{
printf("open led error!\n");
exit(1) ;
}
break;
case 7:
case 8:
case 9:
case 10:
case 11:
number = read_pin_buf -7 ;
write_on = number + 7 ;
write_ret = write(fd , &write_on , 4);
if(write_ret < 0)
{
printf("open led error!\n ");
exit(1) ;
}
break;
default:
write_on = 15 ;
write_ret = write(fd , &write_on , 4);
if(write_ret < 0)
{
printf("led error!\n");
exit(1);
}
break;
}
*/
/*
for(i=4;i<10;i++)
{
if(read_pin_buf==i && (i>6))
printf("read the PIN: PI%d-(key%d)\n",i,i-7);
if(read_pin_buf==i && (i<=6))
printf("read the PIN: PI%d-(key%d)\n",i,i+1);
}
if(read_pin_buf==10)
printf("read the PIN: PG9-(key3)\n");
if(read_pin_buf==11)
printf("read the PIN: PG11-(key4)\n");
*/
}
close(fd);
return 0;
}
|
the_stack_data/92328212.c | /*
** test.c for my_put_nbr in /home/daniel_b/Piscine_C_J03
**
** Made by Erwan DANIEL
** Login <[email protected]>
**
** Started on Thu Oct 2 01:37:20 2014 Erwan DANIEL
** Last update Sun Feb 1 19:39:37 2015 DANIEL Erwan
*/
int get_next(int number)
{
char c;
c = (number % 10) + 0x30;
if (number < 10)
{
write(1, &c, 1);
return;
}
number = number / 10;
get_next(number);
write(1, &c, 1);
return (0);
}
int my_put_nbr(int nb)
{
if (nb < 0)
{
write(1, "-", 1);
get_next(nb * -1);
}
else
get_next(nb);
return (0);
}
|
the_stack_data/181392345.c | #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define M 1024
#define K 1024
#define N 1024
#define SIZE 1024
#define NUM_THREADS 32
#define TILE_WIDTH 32
int A[M][K];
int B[K][N];
int C[M][N];
int goldenC[M][N];
pthread_t tid[SIZE / TILE_WIDTH][SIZE / TILE_WIDTH]; //Thread ID
pthread_attr_t attr[SIZE / TILE_WIDTH][SIZE / TILE_WIDTH]; //Set of thread attributes
struct v
{
int i; /* row */
int j; /* column */
};
void *worker(void *arg);
int main(int argc, char *argv[])
{
int i, j, k;
struct timespec t_start, t_end;
double elapsedTime;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
A[i][j] = rand() % SIZE;
B[i][j] = rand() % SIZE;
}
}
// start time
clock_gettime(CLOCK_REALTIME, &t_start);
for (i = 0; i < SIZE / TILE_WIDTH; i++)
{
for (j = 0; j < SIZE / TILE_WIDTH; j++)
{
struct v *dataid = (struct v *)malloc(sizeof(struct v));
dataid->i = i;
dataid->j = j;
pthread_create(&tid[i][j], NULL, worker, (void *)dataid);
//printf("%d %d\n", dataid->i, dataid->j);
}
}
for (i = 0; i < SIZE / TILE_WIDTH; ++i)
{
for (j = 0; j < SIZE / TILE_WIDTH; j++)
{
pthread_join(tid[i][j], NULL);
}
}
// stop time
clock_gettime(CLOCK_REALTIME, &t_end);
// compute and print the elapsed time in millisec
elapsedTime = (t_end.tv_sec - t_start.tv_sec) * 1000.0;
elapsedTime += (t_end.tv_nsec - t_start.tv_nsec) / 1000000.0;
printf("Parallel elapsedTime: %lf ms\n", elapsedTime);
//Print out the resulting matrix
// start time
clock_gettime(CLOCK_REALTIME, &t_start);
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
for (k = 0; k < K; k++)
{
goldenC[i][j] += A[i][k] * B[k][j];
}
}
}
// stop time
clock_gettime(CLOCK_REALTIME, &t_end);
// compute and print the elapsed time in millisec
elapsedTime = (t_end.tv_sec - t_start.tv_sec) * 1000.0;
elapsedTime += (t_end.tv_nsec - t_start.tv_nsec) / 1000000.0;
printf("Sequential elapsedTime: %lf ms\n", elapsedTime);
int pass = 1;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
if (goldenC[i][j] != C[i][j])
{
// printf("%d %d\n", i, j);
pass = 0;
break;
}
}
}
if (pass == 1)
printf("Test pass!\n");
return 0;
}
void *worker(void *arg)
{
int i, j, k, tid, portion_size, row_start, row_end, column_start, column_end;
double sum;
struct v *data = (struct v *)arg;
//tid = *(int *)(arg); // get the thread ID assigned sequentially.
portion_size = TILE_WIDTH;
row_start = data->i * portion_size;
row_end = (data->i + 1) * portion_size;
column_start = data->j * portion_size;
column_end = (data->j + 1) * portion_size;
//printf("%d %d %d %d %d %d\n", data->i, data->j, row_start, row_end, column_start, column_end);
for (i = row_start; i < row_end; i++)
{ // hold row index of 'matrix1'
for (j = column_start; j < column_end; j++)
{ // hold column index of 'matrix2'
sum = 0; // hold value of a cell
/* one pass to sum the multiplications of corresponding cells
in the row vector and column vector. */
for (k = 0; k < SIZE; ++k)
{
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}
} |
the_stack_data/23449.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2015 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* This program is intended to be a simple dummy program for gdb to read. */
#include <unistd.h>
int
main (void)
{
return 0;
}
|
the_stack_data/142832.c | #include <stdio.h>
int main()
{
char str[100];
printf("enter string :- ");
scanf("%s",str);
int i=0;
int j=1;
int count=1;
while(str[i]!='\0'){
if(str[i]==str[j]){
count++;
j++;
}
else{
printf("%d%c ",count,str[i]);
i=j;
j++;
count=1;
}
}
return 0;
}
|
the_stack_data/104828902.c | /**
* Hei Platform Library
* Copyright (C) 2017-2021 Mark E Sowden <[email protected]>
* This software is licensed under MIT. See LICENSE for more details.
*/
#include <ctype.h>
int pl_strisalnum( const char *s ) {
for ( int i = 0; s[ i ] != '\0'; ++i ) {
if ( isalnum( s[ i ] ) ) {
return i;
}
}
return -1;
}
int pl_strnisalnum( const char *s, unsigned int n ) {
for ( unsigned int i = 0; i < n; ++i ) {
if ( s[ i ] == '\0' ) {
break;
}
if ( isalnum( s[ i ] ) ) {
return i;
}
}
return -1;
} |
the_stack_data/11076155.c | #include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
char NEWLINE = '\n';
int readWhile(int fd, char* buffer, int length) {
char symbol;
int symbolsRead = 0;
int i;
for (i = 0; i < length; ++i) {
symbolsRead = read(fd, &symbol, 1);
// cant read anymore
if (symbolsRead == 0) {
return symbolsRead;
}
buffer[i] = symbol;
// newline found
if (symbol == NEWLINE) {
break;
}
// length reached
if (i + 1 == length) {
buffer[i + 1] = '\n';
}
}
return i + 1;
}
void fold(char* filename, int lineSize) {
int fd = 0;
if (filename) {
fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
}
int symbols = 0;
char buffer[1024] = "";
while((symbols = readWhile(fd, buffer, lineSize)) > 0) {
write(1, buffer, symbols);
}
if (filename) {
close(fd);
}
}
int main(int argc, char** argv) {
int lineSize = 80;
bool filePassed = false;
// handle all options first
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
// if argument is "-w" option
if (argv[i][1] == 'w') {
lineSize = atoi(argv[i] + 2);
if (lineSize == 0) {
// wrong line size
printf("Invalid number of columns.");
}
} else {
// unknown param
}
}
}
// handle file arguments
for (int i = 1; i < argc; ++i) {
if (argv[i][0] != '-') {
filePassed = true;
fold(argv[i], lineSize);
}
}
if (!filePassed) {
fold(NULL, lineSize);
}
return EXIT_SUCCESS;
}
|
the_stack_data/49358.c | #include <stdlib.h>
struct fptr
{
int (*p_fptr)(int, int);
};
int plus(int a, int b) {
return a+b;
}
int minus(int a, int b) {
return a-b;
}
void foo(int x)
{
struct fptr a_fptr;
if(x>1)
{
a_fptr.p_fptr=plus;
x=a_fptr.p_fptr(1,x);
a_fptr.p_fptr=minus;
}else
{
a_fptr.p_fptr=minus;
}
x=a_fptr.p_fptr(1,x);
}
// 19 : plus
// 25 : minus |
the_stack_data/1079849.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/ppm.c"
#else
static int libppm_(Main_load)(lua_State *L)
{
const char *filename = luaL_checkstring(L, 1);
FILE* fp = fopen ( filename, "r" );
if ( !fp ) {
luaL_error(L, "cannot open file <%s> for reading", filename);
}
long W,H,C;
char p,n;
int D, bps, bpc;
// magic number
p = (char)getc(fp);
if ( p != 'P' ) {
W = H = 0;
fclose(fp);
luaL_error(L, "corrupted file");
}
n = (char)getc(fp);
// Dimensions
W = ppm_get_long(fp);
H = ppm_get_long(fp);
// Max color value
D = ppm_get_long(fp);
// Either 8 or 16 bits per pixel
bps = 8;
if (D > 255) {
bps = 16;
}
bpc = bps / 8;
//printf("Loading PPM\nMAGIC: %c%c\nWidth: %ld, Height: %ld\nChannels: %d, Bits-per-pixel: %d\n", p, n, W, H, D, bps);
// load data
int ok = 1;
size_t s;
unsigned char *r = NULL;
if ( n=='6' ) {
C = 3;
s = W*H*C*bpc;
r = malloc(s);
if (fread ( r, 1, s, fp ) < s) ok = 0;
} else if ( n=='5' ) {
C = 1;
s = W*H*C*bpc;
r = malloc(s);
if (fread ( r, 1, s, fp ) < s) ok = 0;
} else if ( n=='3' ) {
int c,i;
C = 3;
s = W*H*C;
r = malloc(s);
for (i=0; i<s; i++) {
if (fscanf ( fp, "%d", &c ) != 1) { ok = 0; break; }
r[i] = 255*c / D;
}
} else if ( n=='2' ) {
int c,i;
C = 1;
s = W*H*C;
r = malloc(s);
for (i=0; i<s; i++) {
if (fscanf ( fp, "%d", &c ) != 1) { ok = 0; break; }
r[i] = 255*c / D;
}
} else {
W=H=C=0;
fclose ( fp );
luaL_error(L, "unsupported magic number: P%c", n);
}
if (!ok) {
fclose ( fp );
luaL_error(L, "corrupted file or read error");
}
// export tensor
THTensor *tensor = THTensor_(newWithSize3d)(C,H,W);
real *data = THTensor_(data)(tensor);
long i,k,j=0;
int val;
for (i=0; i<W*H; i++) {
for (k=0; k<C; k++) {
if (bpc == 1) {
data[k*H*W+i] = (real)r[j++];
} else if (bpc == 2) {
val = r[j] | (r[j+1] << 8);
j += 2;
data[k*H*W+i] = (real)val;
}
}
}
// cleanup
free(r);
fclose(fp);
// return loaded image
luaT_pushudata(L, tensor, torch_Tensor);
return 1;
}
int libppm_(Main_save)(lua_State *L) {
// get args
const char *filename = luaL_checkstring(L, 1);
THTensor *tensor = luaT_checkudata(L, 2, torch_Tensor);
THTensor *tensorc = THTensor_(newContiguous)(tensor);
real *data = THTensor_(data)(tensorc);
// dimensions
long C,H,W,N;
if (tensorc->nDimension == 3) {
C = tensorc->size[0];
H = tensorc->size[1];
W = tensorc->size[2];
} else if (tensorc->nDimension == 2) {
C = 1;
H = tensorc->size[0];
W = tensorc->size[1];
} else {
C=W=H=0;
luaL_error(L, "can only export tensor with geometry: HxW or 1xHxW or 3xHxW");
}
N = C*H*W;
// convert to chars
unsigned char *bytes = (unsigned char*)malloc(N);
long i,k,j=0;
for (i=0; i<W*H; i++) {
for (k=0; k<C; k++) {
bytes[j++] = (unsigned char)data[k*H*W+i];
}
}
// open file
FILE* fp = fopen(filename, "w");
if ( !fp ) {
luaL_error(L, "cannot open file <%s> for writing", filename);
}
// write 3 or 1 channel(s) header
if (C == 3) {
fprintf(fp, "P6\n%ld %ld\n%d\n", W, H, 255);
} else {
fprintf(fp, "P5\n%ld %ld\n%d\n", W, H, 255);
}
// write data
fwrite(bytes, 1, N, fp);
// cleanup
THTensor_(free)(tensorc);
free(bytes);
fclose (fp);
// return result
return 1;
}
static const luaL_Reg libppm_(Main__)[] =
{
{"load", libppm_(Main_load)},
{"save", libppm_(Main_save)},
{NULL, NULL}
};
DLL_EXPORT int libppm_(Main_init)(lua_State *L)
{
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, libppm_(Main__), "libppm");
return 1;
}
#endif
|
the_stack_data/854635.c | /*
* Copyright (C) 2018 bzt (bztsrc@github)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/**
* minimal sprintf implementation
*/
unsigned int vsprintf(char *dst, char *fmt, __builtin_va_list args) {
long int arg;
int len, sign, i;
char *p, *orig = dst, tmpstr[19];
// failsafes
if (dst == (void *)0 || fmt == (void *)0) {
return 0;
}
// main loop
arg = 0;
while (*fmt) {
// argument access
if (*fmt == '%') {
fmt++;
// literal %
if (*fmt == '%') {
goto put;
}
len = 0;
// size modifier
while (*fmt >= '0' && *fmt <= '9') {
len *= 10;
len += *fmt - '0';
fmt++;
}
// skip long modifier
if (*fmt == 'l') {
fmt++;
}
// character
if (*fmt == 'c') {
arg = __builtin_va_arg(args, int);
*dst++ = (char)arg;
fmt++;
continue;
} else
// decimal number
if (*fmt == 'd') {
arg = __builtin_va_arg(args, int);
// check input
sign = 0;
if ((int)arg < 0) {
arg *= -1;
sign++;
}
if (arg > 99999999999999999L) {
arg = 99999999999999999L;
}
// convert to string
i = 18;
tmpstr[i] = 0;
do {
tmpstr[--i] = '0' + (arg % 10);
arg /= 10;
} while (arg != 0 && i > 0);
if (sign) {
tmpstr[--i] = '-';
}
// padding, only space
if (len > 0 && len < 18) {
while (i > 18 - len) {
tmpstr[--i] = ' ';
}
}
p = &tmpstr[i];
goto copystring;
} else
// hex number
if (*fmt == 'x') {
arg = __builtin_va_arg(args, long int);
// convert to string
i = 16;
tmpstr[i] = 0;
do {
char n = arg & 0xf;
// 0-9 => '0'-'9', 10-15 => 'A'-'F'
tmpstr[--i] = n + (n > 9 ? 0x37 : 0x30);
arg >>= 4;
} while (arg != 0 && i > 0);
// padding, only leading zeros
if (len > 0 && len <= 16) {
while (i > 16 - len) {
tmpstr[--i] = '0';
}
}
p = &tmpstr[i];
goto copystring;
} else
// string
if (*fmt == 's') {
p = __builtin_va_arg(args, char *);
copystring:
if (p == (void *)0) {
p = "(null)";
}
while (*p) {
*dst++ = *p++;
}
}
} else {
put:
*dst++ = *fmt;
}
fmt++;
}
*dst = 0;
// number of bytes written
return dst - orig;
}
/**
* Variable length arguments
*/
unsigned int sprintf(char *dst, char *fmt, ...) {
__builtin_va_list args;
__builtin_va_start(args, fmt);
return vsprintf(dst, fmt, args);
} |
the_stack_data/22012018.c | #include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef long long ll;
int i, top;
char ch, c[1000];
int chk() {
top--;
for (i = 0;i < top / 2;i++)
if (c[i] != c[top - i])
return 0;
return 1;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin);
freopen("1.out", "w", stdout);
freopen("1.err", "w", stderr);
#endif
while (~scanf("%c", &ch)) {
if (ch == '\n') {
if (chk())
printf("Y\n");
else
printf("N\n");
bzero(c, top + 1);
top = 0;
}
if (isalpha(ch))
c[top++] = tolower(ch);
}
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
fclose(stderr);
#endif
return 0;
} |
the_stack_data/140561.c | char a[2]={'\\','c'};
int main(void)
{
return a[0]++;
} |
the_stack_data/300733.c | /* Copyright (c) 2009 Joerg Wunsch
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id: malloc-8.c 2151 2010-06-09 20:49:06Z joerg_wunsch $ */
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#ifdef __AVR__
#include "../../libc/stdlib/stdlib_private.h"
#endif
/*
* Basic malloc() test:
*
* Two lists are maintained simultaneously, both featuring a different
* payload size to trigger memory fragmentation issues. A single
* linked list is regularly appended to, and deleted from in a
* semi-random manner. In parallel, a double linked list is
* maintained in ascending order of its payload values, gets new nodes
* inserted, and nodes removed from close to the end. After a number
* of runs (500), the random sequence is replayed, and the remaining
* list entries are removed, again, in the same semi-random order they
* have been created with. All successful append/insert and remove
* operations are accounted. At the end, the number of all
* append/insert operations and delete operations must match for each
* of the lists, and malloc's internal free list is monitored for only
* consisting of a single large block (representing all the dynamic
* memory that has been freed up again).
*/
#define N 500
struct list1
{
struct list1 *next;
uint16_t payload;
};
struct list2
{
struct list2 *next, *prev;
int32_t payload;
};
struct list1 *l1head, *l1tail;
struct list2 *l2head, *l2tail;
bool l1append(uint16_t payload)
{
struct list1 *ele = malloc(sizeof(struct list1));
if (ele == NULL)
return false;
ele->payload = payload;
ele->next = NULL;
if (l1tail == NULL)
{
l1head = l1tail = ele;
return true;
}
l1tail->next = ele;
l1tail = ele;
return true;
}
struct list1 *l1find(uint16_t payload)
{
if (l1head == NULL)
return NULL;
struct list1 *ele = l1head;
while (ele != NULL && ele->payload != payload)
ele = ele->next;
return ele;
}
void l1delete(struct list1 *ele)
{
struct list1 *e = l1head;
struct list1 *f = NULL;
if (ele == NULL)
return;
while (e != NULL && e != ele)
{
f = e;
e = e->next;
}
if (e == NULL)
exit(33);
if (f == NULL)
{
/* First element matched, new head. */
l1head = e->next;
if (l1tail == ele)
/* No member left. */
l1tail = NULL;
}
else
{
f->next = ele->next;
if (l1tail == ele)
/* New tail. */
l1tail = f;
}
free(ele);
}
bool l2insert(int32_t payload)
{
struct list2 *ele = malloc(sizeof(struct list2));
if (ele == NULL)
return false;
ele->payload = payload;
ele->next = ele->prev = NULL;
if (l2head == NULL && l2tail == NULL)
{
l2head = l2tail = ele;
return true;
}
struct list2 *p = l2head;
while (p != NULL && p->payload < ele->payload)
p = p->next;
if (p == NULL)
{
/* new tail */
l2tail->next = ele;
ele->prev = l2tail;
l2tail = ele;
return true;
}
/* insert here */
ele->prev = p->prev;
ele->next = p;
if (p->prev != NULL)
p->prev->next = ele;
else
/* new head */
l2head = ele;
p->prev = ele;
return true;
}
void l2delete(struct list2 *ele)
{
struct list2 *p = l2head;
if (ele == NULL)
return;
while (p != NULL && p != ele)
p = p->next;
if (p == NULL)
exit(34);
if (p->prev != NULL)
p->prev->next = p->next;
else
l2head = p->next;
if (p->next != NULL)
p->next->prev = p->prev;
else
l2tail = p->prev;
free(ele);
}
struct list2 *l2find_3rd_last(void)
{
uint8_t i;
struct list2 *ele;
if (l2tail == NULL)
return NULL;
for (i = 0, ele = l2tail; i < 3; ele = ele->prev)
{
if (ele->prev == NULL)
break;
}
return ele;
}
#ifdef __AVR__
void fill_mem(void) __attribute__((section(".init3"),naked));
void fill_mem(void)
{
extern uint8_t __bss_end;
uint8_t *p = &__bss_end;
do
*p++ = 0xa5;
while (p < (uint8_t *)RAMEND);
}
#else
size_t __malloc_margin;
#endif
uint16_t stats[4];
#define RAND_START_VALUE 4242
int
main(void)
{
uint16_t i;
int32_t r;
uint8_t x;
int32_t v;
__malloc_margin = 32;
srandom(RAND_START_VALUE);
for (i = 0; i < N; i++)
{
r = random();
x = r & 0x0f;
v = ((int32_t)x << 28) | ((int32_t)x << 24) |
((int32_t)x << 20) | ((int32_t)x << 16) |
((int32_t)x << 12) | ((int32_t)x << 8) |
((int32_t)x << 4) | (int32_t)x;
if (r & 0x10)
{
if (l1append(v))
stats[0]++;
}
else if (r & 0x20)
{
struct list1 *p = l1find(v);
if (p != NULL)
{
stats[1]++;
l1delete(p);
}
}
if (r & 0x40)
{
if (l2insert(v))
stats[2]++;
}
else if (r & 0x80)
{
struct list2 *p = l2find_3rd_last();
if (p != NULL)
{
stats[3]++;
l2delete(p);
}
}
}
srandom(RAND_START_VALUE); /* repeat random sequence */
while (l1head != NULL || l2head != NULL)
{
r = random();
x = r & 0x0f;
v = ((int32_t)x << 28) | ((int32_t)x << 24) |
((int32_t)x << 20) | ((int32_t)x << 16) |
((int32_t)x << 12) | ((int32_t)x << 8) |
((int32_t)x << 4) | (int32_t)x;
if (r & 0x10)
{
struct list1 *p = l1find(v);
if (p != NULL)
{
stats[1]++;
l1delete(p);
}
}
else if (r & 0x40)
{
struct list2 *p = l2find_3rd_last();
if (p != NULL)
{
stats[3]++;
l2delete(p);
}
}
}
if (stats[0] != stats[1] || stats[2] != stats[3])
exit(1);
#ifdef __AVR__
if (__flp != NULL)
exit(2);
#endif
return 0;
}
|
Subsets and Splits