language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | /*
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
Write a function:
int solution(int A[], int N);
that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
For example, given array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the function should return 7, as explained in the example above.
Write an efficient algorithm for the following assumptions:
N is an odd integer within the range [1..1,000,000];
each element of array A is an integer within the range [1..1,000,000,000];
all but one of the values in A occur an even number of times.
*/
int solution(int A[], int N) {
// write your code in C99 (gcc 6.2.0)
int single_elem = 0;
int i;
for(i = 0; i < N; i++) {
//explanation:
//A^A = 0
//A^0 = A
single_elem ^= A[i];
}
return single_elem;
}
|
C | //10,ֵСֵ
#include <stdio.h>
#define LEN 10
int main()
{
int nCount = 0;
float nMin = 0;
float nMax = 0;
float nBox[LEN] = { 0 };
puts("Enter 10 numbers");
for (; nCount < 10; nCount++)
{
scanf_s("%f", &nBox[nCount]);
}
nMax = nMin = nBox[0];
for (nCount = 0; nCount < 10; nCount++)
{
(nMax > nBox[nCount]) ?( nMax = nMax):( nMax = nBox[nCount]);
}
printf("The max of number is %f\r\n", nMax);
for (nCount = 0; nCount < 10; nCount++)
{
(nMin < nBox[nCount]) ? (nMin = nMin) : (nMin = nBox[nCount]);
}
printf("The min of number is %f\r\n", nMin);
return 0;
} |
C | #include "holberton.h"
/**
* _pow - Returns the value of x raised to the y of power
* @x: Base number
* @y: Exponent
*
* Return: int
*/
unsigned int _pow(int x, unsigned int y)
{
unsigned int res = 1, i;
for (i = 0; i < y; i++)
{
res = res * x;
}
return (res);
}
/**
* binary_to_uint - converts a binary number to an unsigned int
* @b: Pointer to string
*
* Return: The converted number, or 0 if some char is not 0 or 1 and is b is NU
*/
unsigned int binary_to_uint(const char *b)
{
unsigned int res = 0, len = 0;
int i;
while (b[len] != '\0')
{
if (b[len] != '1' && b[len] != '0')
return (0);
len++;
}
if (b == '\0')
return (0);
i = len - 1;
len = 0;
for (; i >= 0; --i)
{
if (b[i] == '1')
{
res = res + _pow(2, len);
}
len++;
}
return (res);
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
static int num_signal=0;
void signal_handler(int sig){
if(sig==10){//SIGUSR1
printf("\n prints %d sigint \n",num_signal);
}
if(sig==2){//SIGINT
num_signal++;
}
}
int main(){
printf("server pid: %d\n", getpid());
while(1){
signal(SIGUSR1,signal_handler);
signal(SIGINT,signal_handler);
}
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr,i;
ptr = calloc(5, sizeof(int));
for(i=0;i<5;i++)
*(ptr + i) = i;
for(i=0;i<5;i++)
printf("%d\t",*(ptr+i));
free(ptr);
}
|
C | // src/next_mday_days.c
#include <stdio.h> /* printf */
#include <time.h> /* struct tm */
#include "_private.h" /* mth_days */
int next_mday_days(int tgt_mday, const struct tm* lc)
// Days to end of current month
{
D && printf("next_mday_days()\n");
D && printf(" On tm_year:%d tm_mon:%d\n",lc->tm_year,lc->tm_mon);
int curr_mth_days = mth_days(lc->tm_year+1900, lc->tm_mon+1);
D && printf(" tgt_mday:%d curr_mth_days:%d curr_mday:%d\n",
tgt_mday, curr_mth_days, lc->tm_mday);
int days = (tgt_mday + curr_mth_days - lc->tm_mday) % curr_mth_days;
D && printf(" Days to next mday is: %d\n", days);
return days;
}
int next_next_mday_days(int tgt_mday, const struct tm* lc)
// Days to next, next day of month
{
D && printf("next_next_mday_days()\n");
int next_days = next_mday_days(tgt_mday, lc);
int curr_mth_days = mth_days(lc->tm_year+1900, lc->tm_mon+1);
int next_mth_days = mth_days(lc->tm_year+1900, lc->tm_mon+2);
D && printf(" On tgt_mday:%d curr_mday:%d next_days:%d\n",
tgt_mday, lc->tm_mday, next_days);
D && printf(" curr_mth_days:%d next_mth_days:%d\n",
curr_mth_days, next_mth_days);
if (tgt_mday >= lc->tm_mday)
return next_days + curr_mth_days;
else
return next_days + next_mth_days;
}
|
C | //COPYRIGHT @KOLMOGROV
#include <stdio.h>
#include <mpi.h>
#include "err.h"
#define low (-100)
#define high 100
#define h 1
double func(double x)
{
return 4/(1+x*x);
}
int main(int argc, char *argv[])
{
int rank, size,errc;
double sum=0, inter,area;
errc=MPI_Init(&argc,&argv);
MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
handle(errc);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
inter=(INT_MAX)/size;
double i=low+rank*inter;
while(i<(low+(rank+1)*inter))
{
sum+=func(i)*h;
i=i+h;
}
MPI_Reduce(&sum,&area,1,MPI_DOUBLE, MPI_SUM,0,MPI_COMM_WORLD);
if(rank==0)
{
printf("Area is= %g\n",area);
printf("pi is= %g\n",area/4);
}
MPI_Finalize();
return 0;
} |
C | #include <stdio.h>
#define TAM 100
float media_ponderada(float n1, float n2);
int main() {
int i, N;
float nota1[TAM], nota2[TAM], mediadoaluno[TAM];
float mediageral;
char ch1;
printf("\n***** Faz a média de N alunos *****");
printf("\n\nEntre com a quantidade de alunos na turma - no máximo 100: ");
scanf("%d",&N);
mediageral = 0.0;
for(i=0; i < N; i++) {
printf("\n\nEntre com a nota 1 do aluno %d: ", i+1);
scanf("%f", ¬a1[i]);
printf("Entre com a nota 2 do aluno %d: ", i+1);
scanf("%f", ¬a2[i]);
mediadoaluno[i] = media_ponderada(nota1[i], nota2[i]);
if( mediadoaluno[i] >= 6.0 )
printf("Aprovado - Média = %.1f", mediadoaluno[i]);
else
printf("Reprovado - Média = %.1f", mediadoaluno[i]);
mediageral = mediageral + mediadoaluno[i];
}
mediageral = mediageral/N;
printf("\n\nA média geral da turma é: %.1f", mediageral);
printf("\n");
while (1) {
printf("\nDeseja consultar as notas e a média de algum aluno?");
printf("\nSe sim, tecle <ENTER>, senão tecle \'q\': ");
getchar();
scanf("%c",&ch1);
if( ch1 == 'q' )
break;
printf("\nEntre com o numero do aluno: ");
scanf("%d", &i);
printf("Os resultados do aluno %d são: \nNota1 = %.1f - Nota2 = %.1f - Média = %.1f\n", i, nota1[i-1], nota2[i-1], mediadoaluno[i-1]);
}
printf("\n\n");
return 0;
}
float media_ponderada(float n1, float n2) {
float m;
m = (2.0*n1 + 3.0*n2)/5.0;
return m;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hashtable_country.h"
#include "hashtable_virus.h"
HashtableCountry* hash_country_create(int hashNodes) {
int i;
HashtableCountry* ht = malloc(sizeof (HashtableCountry));
ht->hash_nodes = hashNodes;
ht->nodes = (HashtableCountryNode**) malloc(hashNodes * sizeof (HashtableCountryNode*)); //create hashtable for countries
for (i = 0; i < hashNodes; i++) {
ht->nodes[i] = NULL;
}
return ht;
}
void hash_country_destroy(HashtableCountry* ht) {
int i;
for (i = 0; i < ht->hash_nodes; i++) {
HashtableCountryNode* temp = ht->nodes[i];
while (temp != NULL) {
ht->nodes[i] = temp->next;
free(temp->countryName);
free(temp);
temp = ht->nodes[i];
}
}
free(ht->nodes);
free(ht);
}
HashtableCountryNode* hash_country_search(HashtableCountry* ht, char* countryName) {
int pos = hash_function((unsigned char*) countryName, ht->hash_nodes);
HashtableCountryNode* temp = ht->nodes[pos];
while (temp != NULL) {
if (!strcmp(temp->countryName, countryName))
return temp;
temp = temp->next;
}
return temp;
}
HashtableCountryNode* hash_country_insert(HashtableCountry* ht, char* countryName) {
int pos = hash_function((unsigned char*) countryName, ht->hash_nodes);
HashtableCountryNode* new;
new = (HashtableCountryNode*) malloc(sizeof (HashtableCountryNode));
new->countryName = (char*) malloc(strlen(countryName) + 1);
strcpy(new->countryName, countryName);
new->next = ht->nodes[pos];
ht->nodes[pos] = new;
return new;
}
void hash_country_delete(HashtableCountry* ht, char* countryName) {
int pos = hash_function((unsigned char*) countryName, ht->hash_nodes);
HashtableCountryNode* temp = ht->nodes[pos], *temp2;
int first = 1; // flag to check if we are in first node
while (temp != NULL) {
if (!strcmp(temp->countryName, countryName)) {
if (first)
ht->nodes[pos] = temp->next;
else
temp2->next = temp->next;
free(temp->countryName);
free(temp);
return;
}
temp2 = temp;
temp = temp->next;
first = 0;
}
}
HashtableCountryNode** hash_country_to_array(HashtableCountry* ht, int* len) {
int i, j;
HashtableCountryNode* temp;
*len = 0;
for (i = 0; i < ht->hash_nodes; i++) {
temp = ht->nodes[i];
while (temp != NULL) {
(*len)++;
temp = temp->next;
}
}
HashtableCountryNode** table = malloc(sizeof (HashtableCountryNode*)*(*len));
int counter = 0;
for (i = 0; i < ht->hash_nodes; i++) {
temp = ht->nodes[i];
while (temp != NULL) {
table[counter++] = temp;
temp = temp->next;
}
}
for (i = 0; i < *len - 1; i++) { //sort array alphabetically
for (j = i+1; j < *len; j++) {
if(strcmp(table[i]->countryName,table[j]->countryName)>0){
temp = table[i];
table[i] = table[j];
table[j] = temp;
}
}
}
return table;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int array1[], array2[], array3[], array4[], size, choice;
void load_array(int array[], int size);
void print_array(int array[], int size);
float average_array(int array[], int size);
int main() {
printf("Average 4 arrays\n");
printf("Insert size of arrays: ");
scanf("%d", &size);
load_array(array1, size);
load_array(array2, size);
load_array(array3, size);
load_array(array4, size);
printf("First Array\n");
print_array(array1, size);
printf("Second Array\n");
print_array(array2, size);
printf("Third Array\n");
print_array(array3, size);
printf("Fourth Array\n");
print_array(array4, size);
printf("Average of 1st array is: %.2f\n", average_array(array1, size));
printf("Average of 2nd array is: %.2f\n", average_array(array2, size));
printf("Average of 3rd array is: %.2f\n", average_array(array3, size));
printf("Average of 4th array is: %.2f\n", average_array(array4, size));
return 0;
}
void load_array(int array[], int size){
printf("============ Menu =============== \n");
printf("1. Manual insert (to keyboard) \n");
printf("2. Random insert (values generated to random function)\n");
printf("Your choice: ");
scanf("%d", &choice);
if (choice == 1) {
for (int index = 0; index < size; index++) {
printf("Insert element at position [%d]: ", index);
scanf("%d", &array[index]);
}
} else {
if (choice == 2) {
srand(time(0));
for (int index = 0; index < size; index++)
array[index] = 1 + rand() % 100;
}
system("clear");
}
}
void print_array(int array[], int size){
printf("=================================\n");
for (int index = 0; index < size; index++)
printf("Element at position [%d] is %d\n", index, array[index]);
}
float average_array(int array[], int size) {
int sum = 0;
for (int index = 0; index < size; index++)
sum = sum + array[index];
return (float) sum / size;
} |
C | #include "common_header.h"
#include "server_header.h"
char* server_ip,* server_port,* listen_port;
typedef struct tagWEB_CLIENT
{
int tag_id;
int ptt_socket;
int recv_data_socket;
int send_data_socket;
char ptt_to_recv_buf[8*1024+1];
size_t ptt_to_recv_buf_h;
size_t ptt_to_recv_buf_t;
char send_to_ptt_buf[8*1024+1];
size_t send_to_ptt_buf_h;
size_t send_to_ptt_buf_t;
} WEB_CLIENT;
const int grecv_Content_Length = 100*1024*1024;
int total_recv_data_len = 0;
int gsend_Content_Length = -1;
int total_send_data_len = 0;
char ptt_to_recv_buf[8*1024+1];
size_t ptt_to_recv_buf_h = 0;
size_t ptt_to_recv_buf_t = 0;
char send_to_ptt_buf[8*1024+1];
size_t send_to_ptt_buf_h = 0;
size_t send_to_ptt_buf_t = 0;
int ptt_socket = -1, recv_data_socket = -1, send_data_socket = -1;
int main(int argc, char **argv)
{
if(argc < 4)
{
printf("./server server_ip server_port local_listen_port\r\n");
exit(-1);
}
server_ip = argv[1];
server_port = argv[2];
listen_port = argv[3];
int listen_socket;
// create listen_socket
if((listen_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("create listen_sock");
exit(-1);
}
struct sockaddr_in server;
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(listen_port));
server.sin_addr.s_addr = INADDR_ANY;
// bind listen_socket
if((bind(listen_socket, (struct sockaddr *)&server, sizeof(server))) == -1)
{
perror("bind listen_sock");
exit(-1);
}
#define MAX_CLIENTS 1
// listen listen_socket
if((listen(listen_socket, MAX_CLIENTS)) == -1)
{
perror("listen listen_sock");
exit(-1);
}
// prepare select multiplexing
fd_set readfds, oldrfds;
fd_set writefds, oldwfds;
int request_socket;
int result;
int request_timeout;
FD_ZERO(&oldrfds);
FD_ZERO(&oldwfds);
FD_SET(listen_socket, &oldrfds);
request_timeout = request_socket = -1;
// wait timeout initial
struct timeval wait;
for(;;)
{
memcpy(&readfds, &oldrfds, sizeof(readfds));
memcpy(&writefds, &oldwfds, sizeof(writefds));
printf("------------------\r\n");
printf("Waiting select....\r\n");
fflush(stdout);
wait.tv_sec = 1;
wait.tv_usec = 0;
// add timeout
if ( (select(10, &readfds, &writefds, NULL, &wait)) < 0)
{
perror("select()");
break;
}
// reading ptt_socket
if((ptt_socket != -1) && (FD_ISSET(ptt_socket, &readfds)))
{
printf("Reading ptt_socket(%d)...\r\n\r\n", ptt_socket);
// check if buffer is not full
if(ptt_to_recv_buf_h != (ptt_to_recv_buf_t+1)%sizeof(ptt_to_recv_buf))
{
result = recv_from_socket_to_circle_buf(ptt_socket, &ptt_to_recv_buf_h, &ptt_to_recv_buf_t, ptt_to_recv_buf, sizeof(ptt_to_recv_buf));
if(result <= 0)
{
// do something, it will skip following recv&send socket
close(ptt_socket);
close(recv_data_socket);
close(send_data_socket);
ptt_socket = -1;
recv_data_socket = -1;
send_data_socket = -1;
FD_ZERO(&oldrfds);
FD_ZERO(&oldwfds);
FD_SET(listen_socket, &oldrfds);
request_socket = -1;
if(result < 0)
{
printf("Line:%d in %s :\t", __LINE__, __FILE__);
printf("ptt_socket error.\r\n");
}
printf("ptt_socket is closed.\r\n");
continue;
}
else
{
printf("ptt_socket to ptt_to_recv_buf [%d]\r\n", result);
}
}
// buffer is not empty
if((recv_data_socket != -1) && (ptt_to_recv_buf_h != ptt_to_recv_buf_t))
{
FD_SET(recv_data_socket, &oldwfds);
}
}
// reading send_data_socket
if((send_data_socket != -1) && (FD_ISSET(send_data_socket, &readfds)))
{
printf("Reading send_data_socket(%d)...\r\n\r\n", send_data_socket);
// check if buffer is not full
if(send_to_ptt_buf_h != (send_to_ptt_buf_t+1)%sizeof(send_to_ptt_buf))
{
result = recv_from_socket_to_circle_buf(send_data_socket, &send_to_ptt_buf_h, &send_to_ptt_buf_t, send_to_ptt_buf, sizeof(send_to_ptt_buf));
if(result <= 0)
{
// do something
FD_CLR(send_data_socket, &oldrfds);
close(send_data_socket);
send_data_socket = -1;
if(result < 0)
{
printf("Line:%d in %s :\t", __LINE__, __FILE__);
printf("send_data_socket error.\r\n");
}
printf("send_data_socket is closed.\r\n");
}
else
{
total_send_data_len = total_send_data_len + result;
printf("send_data_socket to send_to_ptt_buf [%d][%d][c:%d]\r\n", result, total_send_data_len, gsend_Content_Length);
if(total_send_data_len == gsend_Content_Length)
{
FD_CLR(send_data_socket, &oldrfds);
close(send_data_socket);
send_data_socket = -1;
printf("send_data_socket is full and closed.\r\n");
}
}
}
// buffer is not empty
if((ptt_socket != -1) && (send_to_ptt_buf_h != send_to_ptt_buf_t))
{
FD_SET(ptt_socket, &oldwfds);
}
}
// reading recv_data_socket
if((recv_data_socket != -1) && (FD_ISSET(recv_data_socket, &readfds)))
{
printf("Reading recv_data_socket(%d)...\r\n\r\n", recv_data_socket);
char buf[10240];
result = recv(recv_data_socket, buf, sizeof(buf), 0);
if(result <= 0)
{
FD_CLR(recv_data_socket, &oldrfds);
FD_CLR(recv_data_socket, &oldwfds);
close(recv_data_socket);
recv_data_socket = -1;
if(result < 0)
{
printf("Line:%d in %s :\t", __LINE__, __FILE__);
printf("errno:%d\r\n", errno);
}
printf("recv_data_socket is closed.\r\n");
}
else
{
buf[result] = 0;
printf("Line:%d in %s :\t", __LINE__, __FILE__);
printf("Unknown Exception\r\n");
printf("%s\r\n", buf);
}
}
// writing ptt_socket
if((ptt_socket != -1) && (FD_ISSET(ptt_socket, &writefds)))
{
printf("Writing ptt_socket(%d)...\r\n\r\n", ptt_socket);
// check if buffer is not empty
if(send_to_ptt_buf_h != send_to_ptt_buf_t)
{
result = send_from_circle_buf_to_socket(ptt_socket, &send_to_ptt_buf_h, &send_to_ptt_buf_t, send_to_ptt_buf, sizeof(send_to_ptt_buf), sizeof(send_to_ptt_buf));
if(result <= 0)
{
// do something
close(ptt_socket);
close(recv_data_socket);
close(send_data_socket);
ptt_socket = -1;
recv_data_socket = -1;
send_data_socket = -1;
FD_ZERO(&oldrfds);
FD_ZERO(&oldwfds);
FD_SET(listen_socket, &oldrfds);
request_socket = -1;
if(result < 0)
{
printf("Line:%d in %s :\t", __LINE__, __FILE__);
printf("ptt_socket error.\r\n");
}
printf("ptt_socket is closed.\r\n");
// skip following code because the disconnection
continue;
}
else
{
printf("send_to_ptt_buf to ptt_socket [%d]\r\n", result);
}
}
// buffer is empty
if((ptt_socket != -1) && (send_to_ptt_buf_h == send_to_ptt_buf_t))
{
FD_CLR(ptt_socket, &oldwfds);
}
}
// writing recv_data_socket
if((recv_data_socket != -1) && (FD_ISSET(recv_data_socket, &writefds)))
{
printf("Writing recv_data_socket(%d)...\r\n\r\n", recv_data_socket);
// check if buffer is empty
if(ptt_to_recv_buf_h != ptt_to_recv_buf_t)
{
size_t limit_len;
limit_len = (grecv_Content_Length - total_recv_data_len);
result = send_from_circle_buf_to_socket(recv_data_socket, &ptt_to_recv_buf_h, &ptt_to_recv_buf_t, ptt_to_recv_buf, sizeof(ptt_to_recv_buf), limit_len);
if(result <= 0)
{
// do something
FD_CLR(recv_data_socket, &oldrfds);
FD_CLR(recv_data_socket, &oldwfds);
close(recv_data_socket);
recv_data_socket = -1;
if(result < 0)
{
printf("Line:%d in %s :\t", __LINE__, __FILE__);
printf("recv_data_socket error.\r\n");
}
printf("recv_data_socket is closed.\r\n");
}
else
{
total_recv_data_len = total_recv_data_len + result;
printf("ptt_to_recv_buf to recv_data_socket [%d][%d][%d]\r\n", result, total_recv_data_len, grecv_Content_Length);
if(total_recv_data_len == grecv_Content_Length)
{
FD_CLR(recv_data_socket, &oldrfds);
FD_CLR(recv_data_socket, &oldwfds);
close(recv_data_socket);
recv_data_socket = -1;
printf("recv_data_socket is full.\r\n");
}
}
}
// buffer is empty
if((recv_data_socket != -1) && (ptt_to_recv_buf_h == ptt_to_recv_buf_t))
{
FD_CLR(recv_data_socket, &oldwfds);
}
}
// reading request_socket or listen_socket
if(request_socket != -1)
{
// reading request_socket
if(FD_ISSET(request_socket, &readfds))
{
printf("Reading request_socket(%d)...\r\n\r\n", request_socket);
REQUEST_TYPE erequest_type = Wrapper_Request_Connection_Reader(request_socket, &gsend_Content_Length);
switch(erequest_type)
{
// OPEN SERVER CONNECTION
case OPEN_SERVER_CONNECTION:
printf("OPEN_SERVER_CONNECTION:%d\r\n", ptt_socket);
// CONNECT TO PTT
if((ptt_socket != -1) && (send_data_socket != -1) && (recv_data_socket != -1))
{
// repeat to request ptt connection
/*
FD_CLR(ptt_socket, &oldrfds);
FD_CLR(ptt_socket, &oldwfds);
close(ptt_socket);
printf("close ptt_socket(%d).\r\n", ptt_socket);
ptt_socket = -1;
ptt_to_recv_buf_h = 0;
ptt_to_recv_buf_t = 0;
send_to_ptt_buf_h = 0;
send_to_ptt_buf_t = 0;
*/
Wrapper_Response_Open_Server_Connection_NOTOK(request_socket);
}
else
{
if(ptt_socket != -1)
{
FD_CLR(ptt_socket, &oldrfds);
FD_CLR(ptt_socket, &oldwfds);
close(ptt_socket);
printf("LINE:%d close ptt_socket(%d).\r\n", __LINE__, ptt_socket);
ptt_socket = -1;
}
// clear buffer
ptt_to_recv_buf_h = 0;
ptt_to_recv_buf_t = 0;
send_to_ptt_buf_h = 0;
send_to_ptt_buf_t = 0;
if(CONNECT_TO_PTT(&ptt_socket) == -1)
{
// response header to request_socket
// close request_socket
printf("Connect to PTT : fail.\r\n");
close(ptt_socket);
ptt_socket = -1;
Wrapper_Response_Open_Server_Connection_NOTOK(request_socket);
}
else
{
// ASSIGN A TAG_ID from USER_LIST
// response header to request_socket
// close request_socket
printf("Connect to PTT : ok.\r\n");
FD_SET(ptt_socket, &oldrfds);
Wrapper_Response_Open_Server_Connection_OK(request_socket);
printf("Create ptt_socket(%d)\r\n", ptt_socket);
}
}
break;
// OPEN RECV DATA CONNECTION
case OPEN_RECV_DATA_CONNECTION:
printf("OPEN_RECV_DATA_CONNECTION:%d\r\n", recv_data_socket);
if(ptt_socket != -1)
{
if(recv_data_socket != -1)
{
Wrapper_Response_Open_Recv_Data_Connection_NOTOK(request_socket);
/*
FD_CLR(recv_data_socket, &oldrfds);
close(recv_data_socket);
printf("close recv_data_socket(%d).\r\n", recv_data_socket);
recv_data_socket = -1;
*/
}
else
{
// request socket transfer into recv socket
recv_data_socket = request_socket;
FD_SET(recv_data_socket, &oldrfds);
if(ptt_to_recv_buf_h != ptt_to_recv_buf_t)
{
FD_SET(recv_data_socket, &oldwfds);
}
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
Wrapper_Response_Open_Recv_Data_Connection_OK(recv_data_socket);
total_recv_data_len = 0;
printf("Create recv_data_socket(%d)\r\n", recv_data_socket);
}
}
else
{
Wrapper_Response_Open_Recv_Data_Connection_NOTOK(request_socket);
/*
FD_CLR(request_socket, &oldrfds);
close(request_socket);
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
*/
}
break;
// SEND DATA CONNECTION
case OPEN_SEND_DATA_CONNECTION:
printf("OPEN_SEND_DATA_CONNECTION:%d\r\n", send_data_socket);
if(ptt_socket == -1)
{
FD_CLR(request_socket, &oldrfds);
close(request_socket);
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
}
else
{
if(send_data_socket != -1)
{
FD_CLR(request_socket, &oldrfds);
close(request_socket);
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
}
else
{
send_data_socket = request_socket;
total_send_data_len = 0;
FD_SET(send_data_socket, &oldrfds);
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
printf("Create send_data_socket(%d)\r\n", send_data_socket);
}
}
break;
// Delete ALL CONNECTION
case CLOSE_ALL_CONNECTION:
printf("CLOSE_ALL_CONNECTION\r\n");
close(ptt_socket);
close(recv_data_socket);
close(send_data_socket);
ptt_socket = -1;
recv_data_socket = -1;
send_data_socket = -1;
FD_ZERO(&oldrfds);
FD_ZERO(&oldwfds);
FD_SET(listen_socket, &oldrfds);
request_socket = -1;
break;
break;
case CLOSE_REQUEST_SOCKET:
printf("CLOSE_REQUEST_SOCKET:%d\r\n", request_socket);
FD_CLR(request_socket, &oldrfds);
close(request_socket);
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
break;
case UNKNOWN_REQUEST:
printf("UNKNOWN_REQUEST\r\n");
FD_CLR(request_socket, &oldrfds);
close(request_socket);
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
break;
default:
printf("Unknown Exception\r\n");
FD_CLR(request_socket, &oldrfds);
close(request_socket);
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
break;
}
}
else
{
// update request_timeout
request_timeout--;
if(request_timeout < 0)
{
FD_CLR(request_socket, &oldrfds);
close(request_socket);
request_socket = -1;
FD_SET(listen_socket, &oldrfds);
}
}
}
else
{
if(FD_ISSET(listen_socket, &readfds))
{
printf("Reading listen_socket(%d)...\r\n\r\n", listen_socket);
struct sockaddr_in client_sockaddr;
int client_sockaddr_len = sizeof(struct sockaddr_in);
if((request_socket = accept(listen_socket, (struct sockaddr *)&client_sockaddr, &client_sockaddr_len)) == -1)
{
perror("accept");
}
printf("New Client from IP %s and port %d\r\n", inet_ntoa(client_sockaddr.sin_addr), ntohs(client_sockaddr.sin_port));
FD_SET(request_socket, &oldrfds);
FD_CLR(listen_socket, &oldrfds);
printf("Create request_socket(%d)\r\n", request_socket);
request_timeout = 5;
}
}
}
return 0;
}
|
C | #include "common.h"
#include "memory.h"
#include <string.h>
#define VMEM_ADDR 0xa0000
#define SCR_SIZE (320 * 200)
#define NR_PT ((SCR_SIZE + PT_SIZE - 1) / PT_SIZE) // number of page tables to cover the vmem
PDE *get_updir();
//PTE ptable[1024] align_to_page;
extern PTE kptable[];
void create_video_mapping()
{
/* create an identical mapping from virtual memory area
* [0xa0000, 0xa0000 + SCR_SIZE) to physical memeory area
* [0xa0000, 0xa0000 + SCR_SIZE) for user program. You may define
* some page tables to create this mapping.
*/
PDE *pdir = get_updir();
PTE *vmptable = (PTE *)va_to_pa(kptable);
pdir[0].val = make_pde(vmptable);
vmptable += 0xa0;
for(uint32_t i = 0xa0; i <= 0xaf; ++i)
{
vmptable->val = make_pte(i << 12);
++vmptable;
}
}
void video_mapping_write_test()
{
int i;
uint32_t *buf = (void *)VMEM_ADDR;
for (i = 0; i < SCR_SIZE / 4; i++)
{
buf[i] = i;
}
}
void video_mapping_read_test()
{
int i;
uint32_t *buf = (void *)VMEM_ADDR;
for (i = 0; i < SCR_SIZE / 4; i++)
{
assert(buf[i] == i);
}
}
void video_mapping_clear()
{
memset((void *)VMEM_ADDR, 0, SCR_SIZE);
}
|
C | /*
* menu.c
*
* Created on: Jun 12, 2020
* Author: catalina
*/
#include <stdio.h>
#include <stdlib.h>
#include "menu.h"
#include "utn.h"
//menu opciones principal
int menu()
{
int option;
system("clear");
printf(" ***** M E N U P A N D E M I A *****\n\n\n");
printf(" (1) Cargar archivo (modo texto).\n\n");
printf(" (2) Imprimir lista pandemia\n\n");
printf(" (3) Asignar recuperados infectados y muertos\n\n");
printf(" (4) Filtrar \n\n");
printf(" (5) Ordenar por infectados\n\n");
printf(" (6) Pais mas castigado\n\n");
printf(" (7) Salir\n\n\n");
utn_getEntero(&option, 3, "Ingrese opcion: ", "Error, no es una opcion valida\n", 1, 7);
return option;
}
//menu filtrar
int menuFiltrar()
{
int option;
system("clear");
printf("***** F I L T R A R P O R G R A V E D A D *****\n\n");
printf(" 1. Paises exitosos\n");
printf(" 2. Paises en el horno\n");
printf(" 3. Salir\n\n");
utn_getEntero(&option, 3, "Ingrese opcion: ", "Error, no es una opcion valida\n", 1, 3);
return option;
}
|
C | #ifndef control_funtion_h
#define control_funtion_h
#include <math.h>
/*please fill this controller function
* input:
* des_pos -> desired position
* des_vel -> desired velocity
* des_acc -> desired acceleration
* des_yaw -> desired yaw angle
* now_pos -> now psition
* now_vel -> body velocity
* Kp -> P gain for position loop
* Kd -> P gain for velocity loop
* Mass -> quality of the quadrotor
*
* output:
* rpy -> target attitude for autopilot
* target_thrust -> target thrust of the quadrotor
* */
void SO3Control_function( const double des_pos[3],
const double des_vel[3],
const double des_acc[3],
const double des_yaw,
const double now_pos[3],
const double now_vel[3],
const double now_yaw,
const double Kp[3],
const double Kd[3],
const double Mass,
const double Gravity,
double rpy[3],
double &target_thrust
)
{
target_thrust=Mass*(Gravity+Kd[2]*(des_vel[2]-now_vel[2])+Kp[2]*(des_pos[2]-now_pos[2]));
double rdd_des = Kd[0]*(des_vel[0]-now_vel[0])+Kp[0]*(des_pos[0]-now_pos[0]);
double pdd_des = Kd[1]*(des_vel[1]-now_vel[1])+Kp[1]*(des_pos[1]-now_pos[1]);
rpy[0]=1/Gravity*(rdd_des*sin(des_yaw)-pdd_des*cos(des_yaw));
rpy[1]=1/Gravity*(rdd_des*cos(des_yaw)+pdd_des*sin(des_yaw));
rpy[2]=des_yaw;
}
#endif
|
C | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[]) {
char cwd[256];
char fullname[1024];
if(argc < 2) {
fprintf(stderr, "usage: %s name\n", argv[0]);
return -1;
}
printf("cwd = %s\n", getcwd(cwd, sizeof(cwd)));
snprintf(fullname, sizeof(fullname), "%s/%s", cwd, argv[1]);
printf("fullname = %s\n", fullname);
if(fchmodat(AT_FDCWD, fullname, 0644, AT_SYMLINK_NOFOLLOW) < 0)
perror("fchmodat");
return 0;
}
|
C | #ifndef __ARR_H__
#define __ARR_H__
typedef struct _arr_t {
int *arr;
int arr_len;
int num_entries;
} arr_t;
int alloc_arr(arr_t *a, int arr_len);
int free_arr(arr_t *a);
int arr_contains(arr_t *a, int e);
int arr_add(arr_t *a, int e);
#endif |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* hex_dump.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amaindro <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/15 00:54:06 by amaindro #+# #+# */
/* Updated: 2017/08/01 01:40:37 by amaindro ### ########.fr */
/* */
/* ************************************************************************** */
#include "malloc2.h"
static void chunk_dump(t_chunk *chunk)
{
char *ptr;
while (chunk != NULL)
{
if (!chunk->is_free)
{
ft_putaddr((unsigned long long int)chunk, 'a');
ptr = (char*)((unsigned long long int)chunk + sizeof(t_chunk));
while (ptr < (char*)((unsigned long long int)chunk + chunk->size))
{
ft_putchar(' ');
ft_putaddr((unsigned char)*ptr, 'a');
ptr++;
}
ft_putchar('\n');
}
chunk = chunk->next;
}
}
static void chunk_char_dump(t_chunk *chunk)
{
char *ptr;
while (chunk != NULL)
{
if (!chunk->is_free)
{
ft_putaddr((unsigned long long int)chunk, 'a');
ptr = (char*)((unsigned long long int)chunk + sizeof(t_chunk));
ft_putchar(' ');
while (ptr < (char*)((unsigned long long int)chunk + chunk->size))
{
if (ft_isprint(*ptr))
ft_putchar(*ptr);
else
ft_putchar('.');
ptr++;
}
ft_putchar('\n');
}
chunk = chunk->next;
}
}
void char_dump(void)
{
chunk_char_dump(chunk_array[0]);
chunk_char_dump(chunk_array[1]);
chunk_char_dump(chunk_array[2]);
}
void hex_dump(void)
{
chunk_dump(chunk_array[0]);
chunk_dump(chunk_array[1]);
chunk_dump(chunk_array[2]);
}
|
C | #include <stdio.h>
#define XOPEN_SOURCE
#include <stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/ioctl.h>
/* Chown the slave to the calling user. */
extern int grantpt (int __fd) __THROW;
/* Release an internal lock so the slave can be opened.
Call after grantpt(). */
extern int unlockpt (int __fd) __THROW;
/* Return the pathname of the pseudo terminal slave associated with
the master FD is open on, or NULL on errors.
The returned storage is good until the next call to this function. */
extern char *ptsname (int __fd) __THROW __wur;
char buf[1]={'\0'}; //创建缓冲区,这里只需要大小为1字节
int main() {
//创建master、slave对并解锁slave字符设备文件
int mfd = open("/dev/ptmx", O_RDWR);
grantpt(mfd);
unlockpt(mfd);
//查询并在控制台打印slave文件位置
fprintf(stderr,"%s\n",ptsname(mfd));
int pid=fork();//分为两个进程
if(pid) {
//父进程从master读字节,并写入标准输出中
while(1) {
printf("mfd:%d\n", mfd);
if(read(mfd,buf,1)>0)
write(1,buf,1);
else
sleep(1);
}
} else {
//子进程从标准输入读字节,并写入master中
while(1) {
printf("mfd:%d\n", mfd);
if(read(0,buf,1)>0)
write(mfd,buf,1);
else
sleep(1);
}
}
return 0;
}
|
C | #include<stdio.h>
#include<math.h>
void main()
{
int a,b,c,d,e;
float y;
printf("enter the numbers:");
scanf("%d%d",&a,&b);
printf("enter the line no.:");
scanf("%d%d%d",&c,&d,&e);
y=((a*c+b*d+e)/sqrt(c*c+d*d));
printf("\n%f",y);
}
|
C | /* maxTweeter.c
*
* input:
* One program arguement, filepath to a CSV file.
*
*
* restrictions:
* Max line length will not exceed 1024 characters.
* Length of file will not exceed 20,000 lines.
* Header for Name may be surrounded by quotes, but then all names must also be surrounded by quotes.
* Tweet field will not contain any commas.
* goals:
* Program correctness on input files.
* Program stability: should not crash on any input, including invalid files.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//DEBUG_MODE: 0=disabled, 1=enabled.
#define DEBUG_MODE 0
#define MAX_LINE_LENGTH 1024
#define MAX_FILE_LINES 20000
#define NAME "name"
#define NAME_QUOTES "\"name\""
#define FAILURE_EXIT exit(1)
#define dprintf(args ...) if(DEBUG_MODE) fprintf(stderr, args)
struct columnProperties{
char name[MAX_LINE_LENGTH];
int quotes;
};
struct nameCount{
char name[MAX_LINE_LENGTH];
int count;
int taken;//0=false : 1=true
};
FILE* fileStream;
struct columnProperties column[MAX_LINE_LENGTH];
struct nameCount names[MAX_FILE_LINES];
char lineBuffer[MAX_LINE_LENGTH];
int total_names;
int name_index;
int name_quotes;
int last_column_index;
char* filePath;
//Prints the 10 names that had the highest count in the input file.
void print10Names(){
int i;
int listSize;
if(total_names > 10){
listSize = 10;
}else{
listSize = total_names;
}
for(i = 0; i < listSize; i++){
printf("%s: %d\n", names[i].name, names[i].count);
}
return;
}
//Comparison function for the use of qsort.
int comparator(const void* p1, const void* p2){
int r = ((struct nameCount*)p1)->count;
int l = ((struct nameCount*)p2)->count;
return (l - r);
}
//Uses qsort to sort the datastructure names from greatest to least.
void sortStructure(){
int size = sizeof(names) / sizeof(names[0]);
qsort((void*)names, size, sizeof(names[0]), comparator);
}
//Removes surrounding immediate quotes from a string.
char* removeQuotes(char* string){
size_t length = strlen(string);
if(length > 0){
string++;
}
if(length > 1){
string[length-2] = '\0';
}
return string;
}
//Returns the last char in a string/buffer.
char lastChar(char* c){
if(c == NULL || *c == '\0'){
return 0;
}
return c[strlen(c)-1];
}
//Checks element for quote matching.
//Returns 0 for absent, 1 for present. FAILURE_EXIT on mismatch.
int checkFirstLast(const char* string){
size_t stringLength = strlen(string);
int out;
dprintf("Checking string: %s\n", string);
if(string[0] == '"'){
if(string[stringLength-1] != '"'){
dprintf("Field inconsistancy...Quote invalidation...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}else{
out = 1;
}
}else{
if(string[stringLength-1] == '"'){
dprintf("Field inconsistancy...Quote invalidation...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}else{
out = 0;
}
}
dprintf("out = %d\n", out);
return out;
}
//Increment the count of the name in the name structure.
//If not present, add it and initialize.
void incrementNameCount(char* name){
dprintf("IncrementNameCount enter: name=%s\n", name);
int index;
int found = 0;
for(index = 0; found == 0 && index < MAX_FILE_LINES; index++ ){
if(!strcmp(name, names[index].name) || names[index].taken == 0){
found = 1;
break;
}
dprintf("index = %d\n", index);
}
if(found){
if(names[index].taken == 0){
strcpy(names[index].name, name);
names[index].count = 1;
names[index].taken = 1;
total_names++;
}else{
names[index].count++;
}
return;
}else{
//Believed to be dead code, there should always be room in...
//...the names structure with the upper bound being MAX_FILE_LINES.
dprintf("No room to add name to database...\n");
fclose(fileStream);
FAILURE_EXIT;
}
}
//Checks the header for validity, checks for name/"name" field.
//Keeps track of which fields require surrounding quotes.
void headerChecker(){
dprintf("Entered headerChecker...\n");
int nameCount = 0;
int count = 0;
int breakLoop = 0;
char* element;
char* workingElement = NULL;
if(fgets(lineBuffer, MAX_LINE_LENGTH, fileStream) == NULL){
dprintf("File contains no content...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
if(lastChar(lineBuffer)!= '\n'){
dprintf("Line does not end with a \\n char...line length exceeds maxiumum...");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
element = strtok(lineBuffer, ",");
while(element != NULL)
{
if(lastChar(element) == '\n'){
break;
}
strcpy(column[count].name, element);
if(checkFirstLast(element)){
column[count].quotes = 1;
}else{
column[count].quotes = 0;
}
if(!strcmp(element, NAME)){
nameCount++;
name_quotes = 0;
name_index = count;
}
if(!strcmp(element, NAME_QUOTES)){
nameCount++;
name_quotes = 1;
name_index = count;
}
dprintf("Element %d name = %s\n", count, column[count].name);
dprintf("Element %d quotes = %d\n", count, column[count].quotes);
count++;
element = strtok(NULL, ",");
}
if(element == NULL){
dprintf("Invalid header... line overflow\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
//Recalculates the last string field and if it uses quotes, removing the '\n' character.
if(lastChar(element) == '\n'){
dprintf("Enter exception area, removing \\n\n");
element[strlen(element) -1] = '\0';
//column[count].name[strlen(column[count].name) -1] = '\0';
strcpy(column[count].name, element);
//column[count].quotes = checkFirstLast(column[count].name);
if(checkFirstLast(element)){
column[count].quotes = 1;
}else{
column[count].quotes = 0;
}
//Checks for name field.
if(!strcmp(column[count].name, NAME)){
nameCount++;
name_quotes = 0;
name_index = count;
}
if(!strcmp(column[count].name, NAME_QUOTES)){
nameCount++;
name_quotes = 1;
name_index = count;
}
dprintf("Element %d name = %s\n", count, column[count].name);
dprintf("Element %d quotes = %d\n", count, column[count].quotes);
}else{
dprintf("Invalid header... how did we get here?\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
//Records the last column index for future reference in parsing lines.
last_column_index = count;
dprintf("Last Column Index = %d\n", last_column_index);
//If no valid column "name" or name.
if(nameCount != 1){
dprintf("Invalid header... no name field.\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
dprintf("Name field found in column %d, Contains quotes?:%d\n", name_index, name_quotes);
for(int i = 0; i <= last_column_index; i++){
dprintf("field:%s | index:%d | quotes:%d\n", column[i].name, i, column[i].quotes);
}
}
//Scans each line, checking that the field is valid to the requirements of its column.
//If field belongs to the name/"name" column, increment the field with incrementNameCount(field).
int lineChecker(){
int lineCount = 1;
int index;
char* element;
char* workingElement = NULL;
while(fgets(lineBuffer, MAX_LINE_LENGTH, fileStream) != NULL && lineCount < MAX_FILE_LINES){
element = strtok(lineBuffer, ",");
for(index = 0; index < last_column_index; index++){
dprintf("Checking index = %d\n", index);
if(!element){
dprintf("Row does not line with header1...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
if(column[index].quotes != checkFirstLast(element)){
dprintf("Quote mismatch of element1...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
if(index == name_index)
{
if(name_quotes){
incrementNameCount(removeQuotes(element));
}else{
incrementNameCount(element);
}
}
element = strtok(NULL, ",");
}
if(!element){
dprintf("Row does not line with header2...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
if(lastChar(element) != '\n'){
dprintf("Row does not line with header3...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
element[strlen(element)-1] = '\0';
if(column[index].quotes != checkFirstLast(element)){
dprintf("Quote mismatch of element2...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
if(index == name_index)
{
if(name_quotes){
incrementNameCount(removeQuotes(element));
}else{
incrementNameCount(element);
}
}
dprintf("LineCount = %d\n", lineCount);
lineCount++;
}
if(lineBuffer != NULL && lineCount == MAX_FILE_LINES){
dprintf("LineBuffer = %s\n", lineBuffer);
dprintf("Exceeded maximum number of lines in file...\n");
printf("Invalid Input Format.\n");
fclose(fileStream);
FAILURE_EXIT;
}
}
//Checks for file at provided filePath.
//If found, opens and stores in fileStream global var.
//Else, exit with failure state.
void fileChecker(char* filePath){
fileStream = fopen(filePath, "r");
if(!fileStream){
dprintf("File with provided path not found...\n");
printf("File not found.\n");
FAILURE_EXIT;
}else{
dprintf("File with provided path found and opened...\n");
}
return;
}
int main(int argc, char **argv){
total_names = 0;
//Checks correct number of passed arguements.
if( argc < 2){
dprintf("No file path provided...\n");
printf("Invalid number of arguements.\n");
FAILURE_EXIT;
}
if( argc > 2){
dprintf("Too many arguements...\n");
printf("Invalid number of arguements.\n");
FAILURE_EXIT;
}
filePath = malloc(sizeof(char) * strlen(argv[1]));
if(!filePath){
dprintf("Failed to allocate memory...\n");
printf("Memory allocation failure.\n");
FAILURE_EXIT;
}
//Save filePath arguement to filePath global variable.
strcpy(filePath, argv[1]);
//Checks validity of filePath.
fileChecker(filePath);
//free(filePath);
//Checks validity of header of file.
headerChecker();
//Parses line-by-line, validating and collecting name data.
lineChecker();
//Sorts name data structure.
sortStructure();
//Outputs 10 names with most occurances.
print10Names();
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include "graphics.h"
#include "genlib.h"
#include "conio.h"
#include <windows.h>
#include <olectl.h>
#include <stdio.h>
#include <mmsystem.h>
#include <wingdi.h>
#include <ole2.h>
#include <ocidl.h>
#include <winuser.h>
#include "unsize_array.h"
typedef struct STRUCT_MAZE{
int map[10][10];
int out_X;
int out_Y;
}MAZE;
void search_maze(int x,int y,MAZE *maze,link_array *try_path,link_array *success_path);
link_array *write_into_link(int x,int y,link_array *node);
void move(int x,int y,MAZE *maze,link_array *try_path,link_array *success_path);
link_array *copy(link_array *success_path,link_array *try_path);
int count_step(link_array *p);
void Main()
{
InitGraphics();
InitConsole();
MAZE model={.map={
{0,0,0,0,0,0},
{0,2,1,1,0,0},
{0,1,0,1,1,0},
{0,1,1,0,1,0},
{0,1,0,1,1,0},
{0,1,0,1,1,0},
{0,1,1,0,1,0},
{0,1,1,1,1,0},
{0,0,0,0,0,0}
}
};
MAZE *maze;
maze = (MAZE*)malloc(sizeof(MAZE));
*maze = model;
maze->out_X = 7;
maze->out_Y = 4;
link_array *success_path,*try_path;
success_path = create_link();
try_path = create_link();
search_maze(1,1,maze,try_path,success_path);
if (success_path->next->data[0] == -1)
printf("NO PATH!");
else
{
print_path(success_path,maze);
draw(maze, success_path);
}
}
void search_maze(int x,int y,MAZE *maze,link_array *try_path,link_array *success_path)
{
int i;
for (i = 0;i < 4;i++)
switch (i)
{
case 0:
move(x+1,y,maze,try_path,success_path);
break;
case 1:
move(x,y+1,maze,try_path,success_path);
break;
case 2:
move(x,y-1,maze,try_path,success_path);
break;
case 3:
move(x-1,y,maze,try_path,success_path);
break;
}
}
void move(int x,int y,MAZE *maze,link_array *try_path,link_array *success_path)
{
if (maze->map[x][y] == 1)
{
maze->map[x][y] = 2;
try_path = write_into_link(x,y,try_path);
if ((x) == maze->out_X && y == maze->out_Y)
{
maze->map[x][y] = 1;
success_path = copy(success_path,try_path);
return;
}
else
{
search_maze(x, y,maze,try_path, success_path);
maze->map[x][y] = 1;
}
}
}
link_array *write_into_link(int x,int y,link_array *node)
{
//printf("x=%d,y=%d",x,y);
link_array *next_node;
if (node->next->data[0] != -1)
{
node->next->data[0] = x;
node->next->data[1] = y;
return node->next;
}
else
{
next_node = (link_array*)malloc(sizeof(link_array));
next_node->data[0] = x;
next_node->data[1] = y;
next_node->next = node->next;
node->next = next_node;
}
return next_node;
}
link_array *copy(link_array *success_path,link_array *try_path)
{
int out_x = try_path->data[0],out_y = try_path->data[1];
int success_path_steps, try_path_steps;
link_array *success_p = success_path;
//turn to head
link_array *try_p = try_path->next->next;
//turn to node after head
link_array *tansition;
success_path_steps = count_step(success_path);
try_path_steps = count_step(try_path);
if (success_path_steps > try_path_steps || success_path_steps == 0)
{
do
{
if (success_p->next->data[0] == -1)
{
tansition = (link_array*)malloc(sizeof(link_array));
tansition->next = success_p->next;
success_p->next = tansition;
}
else
tansition = success_p->next;
tansition->data[0] = try_p->data[0];
tansition->data[1] = try_p->data[1];
success_p = success_p->next;
try_p = try_p->next;
}
while(try_p != try_path->next);
}
return success_path;//head
}
int count_step(link_array *head)
{
int step=0;
link_array *p = head;
do
{
p = p->next;
step++;
}
while(p != head);
return step-1;
}
|
C | #ifndef CHELL_LINEEDIT_H
#define CHELL_LINEEDIT_H
#include <stdio.h>
/**
* Resets the terminal formatting entirely.
*/
#define RSTT "\x1B[0m"
/**
* Color choices.
* The codes sets the foreground color to the indicated color.
*/
#define BLKT "\x1B[30m"
#define REDT "\x1B[31m"
#define GRNT "\x1B[32m"
#define YELT "\x1B[33m"
#define BLUT "\x1B[34m"
#define WHTT "\x1B[97m"
/**
* Text formatting.
* BFTT allows for bold text.
*/
#define BFTT "\x1B[1m"
#define clearline() printf("%c[2K\r", 27)
#define cursorpos(x) printf("\r\033[%luC", (x))
/**
* Reads a line from the stdin interactively until a newline has been found.
* Note that the returned string needs to be freed.
*
* @param prompt A prompt to keep at the beginning of the input line.
* @param promptlen The length of the prompt as seen on the screen,
* excluding any escape characters such as colors.
* @result A string with the read line from stdin.
*/
char* ch_readline(const char *, size_t);
#endif
|
C | //Function call and pointer
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void main()
{
int a=3, b=5;
swap(&a, &b);
}
|
C | #include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(int argc, string key[])
{
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
else for (int k = 0; k < 26; k += 1)//go through each letter of key
{
if (64 < (int) key[1][k] && (int) key [1][k] < 123)//if within letter range
{
if (90 < (int) key [1][k] && (int) key[1][k] < 97)//but in that small non letter region
{
printf("Key must contain 26 characters.\n");//reject
return 1;
}
else if (97 < (int) key[1][k] && (int) key [1][k] < 123)//if lowercase
{
key[1][k] -= 32;//change to caps
}
}
else//otherwise error
{
printf("Key must contain 26 characters.\n");
return 1;//
}
int count = 0;
for (int d = 0; d < 26; d += 1)//then compare against each letter of key
{
if (key[1][k] == key[1][d] || key[1][k] == key[1][d] + 32)
{
count += 1;
}
}
if (count >= 2)//if duplicate letters
{
printf("Key must contain 26 characters.\n");
return 1;//
}
}
//if key is all ok then
string plaintext = get_string("plaintext: ");
printf("ciphertext: ");
for (int p = 0; p < strlen(plaintext); p += 1)//go through each char of plaintext
{
if (64 < (int) plaintext[p] && (int) plaintext[p] < 91)//if plaintext char is uppercase
{
printf("%c", key [1] [(int) plaintext[p] - 65]);//print from key
}
else if (96 < (int) plaintext[p] && (int) plaintext[p] < 123)//if plaintext char is lowercase
{
printf("%c", key [1] [(int) plaintext[p] - 97] + 32);//print from key but convert to lowercase first
}
else
{
printf("%c", plaintext [p]);//if not just print that char
}
}
printf("\n");
return 0;
}
|
C | #include <stdio.h>
int main()
{
int x= 10;
printf("Value of x is %d\n", x);
printf("Adress of x is %p\n", &x);
return 0;
}
|
C | #include<stdio.h>
#include<string.h>
void search(char txt[], char pat[])
{
int l1, l2, i, j;
l1 = strlen(txt);
l2 = strlen(pat);
for (i = 0; i <= l1 - l2; i++) {
for (j = 0; j < l2; j++) {
if (txt[i + j] != pat[j]) {
break;
}
}
if (j == l2) {
printf("Pattern found at index %d \n", i);
}
}
}
int main()
{
char txt[100];
char pat[100];
scanf("%s", txt);
scanf("%s", pat);
search(txt,pat);
return 0;
}
|
C | #include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int n;
char name[10];
}
node;
int main(void)
{
node test[5];
for (int i = 0; i < 5; i++)
{
test[i].n = i*3;
fprintf(stdout, "enter string.\n");
char *user = get_string();
strcpy(test[i].name, user);
}
fprintf(stdout, "printing result...\n");
for (int i = 0; i < 5; i++)
{
fprintf(stdout, "no. %i: n is %i and name is %s\n", i, test[i].n, test[i].name);
}
} |
C | #pragma comment(copyright, " © Copyright Rocket Software, Inc. 2017, 2020 ")
#include <stdlib.h>
/* TODO: figure out how to wrap new, new[], delete, and delete[],
* if necessary.
*/
/* To somewhat convince ourselves that, this isn't introducing
* memory leaks, maybe wrap free as well, then keep track of
* the 0->1 allocations and frees of the corresponding addresses.
* Might not cover all possible cases, but I think it would
* work for the most common use cases.
*/
/* On Linux, Windows, and OS X, malloc(0) returns a
* non-NULL, freeable pointer.
*/
void *zos_compat_malloc_wrapper(size_t size) {
if (size == 0) {
size = 1;
}
return malloc(size);
}
/* calloc(0, _) and calloc(_, 0) behaves in line
* with malloc(0) on linux, probably other platforms too.
*/
void *zos_compat_calloc_wrapper(size_t num, size_t size) {
if (num == 0) {
num = 1;
}
if (size == 0) {
size = 1;
}
return calloc(num, size);
}
/* On linux, with sole regard to return values, realloc acts as if
* it were defined as such:
* realloc(ptr, size)
* | ptr == NULL = malloc(val)
* | size == 0 = free(val)
* | otherwise = malloc(val)
*/
void *zos_compat_realloc_wrapper(void *ptr, size_t size) {
if (ptr == NULL && size == 0) {
size = 1;
}
return realloc(ptr, size);
}
/* While at the moment the following wrapper does nothing, it's
* included to provide a stable forward compatible ABI, in case
* we ever want to do something involving tracing allocations.
* I mean, we've already wrapped most of the allocation functions,
* might as well properly take advantage of that fact by doing the
* rest.
*/
void zos_compat_free_wrapper(void *ptr) {
free(ptr);
}
|
C | #include <stdio.h>
#include <stdlib.h>
typedef struct lianbiao
{
int a;
struct lianbiao *next;
}lb;
lb* myinput()
{
lb *head,*p,*pp;
printf("请输入int型数据,以0结束.\n");
head=p=(lb *)calloc(sizeof(lb),1);
while(1)
{
pp=(lb *)calloc(sizeof(lb),1);
scanf("%d",&pp->a);
if(pp->a==0)
{
p->next=NULL;
return head;
}
p->next=pp;
p=pp;
}
}
void myoutput(lb *head)
{
head=head->next;
while(1)
{
if(head!=NULL)
{
printf("%d ",head->a);
head=head->next;
}
else break;
}
printf("\n");
return;
}
void chuli(lb *head)
{
int num;
lb *p,*pp,*tmp1,*tmp2;
tmp=p=head->next;
num=p->a;
while(1)
{
p=p->next;
if(p!=NULL)
{
if(p->a <= num)
{
pp=p;
head->next=p;
tmp=
}
}
}
}
main()
{
lb *head;
head=myinput();
myoutput(head);
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#if defined (__GNU__)
#define PACKED __attribute__((packed))
#else
#define PACKED
#endif
typedef struct PACKED {
int barrelID;
int battery;
int temperature;
int humidity;
int pressure;
int roll;
int pitch;
int yaw;
} queuedData;
typedef struct {
queuedData * data;
void * next;
} node;
typedef struct {
node * head;
node * tail;
} queue;
node * createNode (queuedData * data) {
node * newNode;
newNode = (node *) malloc (sizeof(node)); // Create node
// We must allocate memory for the struct this Node is pointing!
// Otherwise we will have a segmentation fault
newNode->data = (queuedData *) malloc(sizeof(queuedData));
memcpy(newNode->data, data, sizeof(queuedData)); // Fill with provided data
//memcpy(data, data, sizeof(queuedData)); // Fill with provided data
newNode->next = NULL;
return newNode;
}
void initQueue(queue * q) {
q -> head = NULL;
q -> tail = NULL;
}
void queueInsert(queue * q, node * n) {
node * head;
node * next;
if (q -> head == NULL) {
q -> head = n;
q -> tail = n;
}
else {
q -> tail -> next = n; // Update tail's next
q -> tail = n; // replace tail
}
/* Iterating through the queue to insert a new record
involves O(n) while just inserting to tail is O(1)
next = (node *) q -> head;
while (1) { //Iterating through queue
if (next -> next == NULL) {
next -> next = n;
break;
} else {
next = (node *) next->next;
}
} */
}
void queueRemove(queue * q, queuedData * retrievedData) {
node * node_ptr;
queuedData * node_data_ptr;
if (q->head == NULL) {
printf("Fail. Queue is empty\n\r");
}
else {
memcpy(retrievedData, q->head->data, sizeof(queuedData));
//memcpy(retrievedNode, q -> head, sizeof(node)); // Copy to provided pointer
node_ptr = q->head;
node_data_ptr = q->head->data; // IMPORTANT, not only free up node's memory but also node's data
q->head = (node *) q->head->next; // Update head
free(node_ptr);
free(node_data_ptr);
}
}
int main () {
queue beaconQueue;
initQueue(&beaconQueue);
queuedData data = {
.barrelID = 2,
.battery = 89,
.temperature = 29,
.humidity = 30,
.pressure = 800000,
.roll = 180,
.pitch = 90,
.yaw = 45,
};
queueInsert(&beaconQueue, createNode(&data));
queuedData data2 = {
.barrelID = 61,
.battery = 70,
.temperature = 35,
.humidity = 45,
.pressure = 800400,
.roll = 18,
.pitch = 95,
.yaw = 95,
};
queueInsert(&beaconQueue, createNode(&data2));
queuedData data3 = {
.barrelID = 161,
.battery = 170,
.temperature = 135,
.humidity = 145,
.pressure = 80400,
.roll = 118,
.pitch = 195,
.yaw = 195,
};
queueInsert(&beaconQueue, createNode(&data3));
queuedData retrievedData;
while (beaconQueue.head != NULL) {
queueRemove(&beaconQueue, &retrievedData);
printf("Barrel ID: %d\n\r", retrievedData.barrelID);
}
queuedData data4 = {
.barrelID = 161,
.battery = 170,
.temperature = 135,
.humidity = 145,
.pressure = 80400,
.roll = 118,
.pitch = 195,
.yaw = 195,
};
queueInsert(&beaconQueue, createNode(&data4));
queuedData data5 = {
.barrelID = 61,
.battery = 70,
.temperature = 35,
.humidity = 45,
.pressure = 800400,
.roll = 18,
.pitch = 95,
.yaw = 95,
};
queueInsert(&beaconQueue, createNode(&data5));
queuedData data6 = {
.barrelID = 2,
.battery = 89,
.temperature = 29,
.humidity = 30,
.pressure = 800000,
.roll = 180,
.pitch = 90,
.yaw = 45,
};
queueInsert(&beaconQueue, createNode(&data6));
while (beaconQueue.head != NULL) {
queueRemove(&beaconQueue, &retrievedData);
printf("Barrel ID: %d\n\r", retrievedData.barrelID);
}
/*
queueRemove(&beaconQueue, &retrievedNode);
printf("Barrel ID: %d\n\r", retrievedNode.data->barrelID);
queueRemove(&beaconQueue, &retrievedNode);
printf("Barrel ID: %d\n\r", retrievedNode.data->barrelID);
queueRemove(&beaconQueue, &retrievedNode);
printf("Barrel ID: %d\n\r", retrievedNode.data->barrelID);
*/
printf("Hello World\n");
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split_whitespaces.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tamigore <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/09/16 20:07:41 by tamigore #+# #+# */
/* Updated: 2018/09/18 14:02:29 by tamigore ### ########.fr */
/* */
/* ************************************************************************** */
#define SPACE(x) (str[x] == ' '||str[x] == '\n'||str[x] == '\t'||str[x] == '\0')
#define CHAR(x) ((x > 32 && x < 127) ? 1 : 0)
#include <stdlib.h>
#include <stdio.h>
int ft_count_words(char *str)
{
int i;
int len;
i = 0;
len = 0;
while (str[i] != '\0')
{
if (CHAR(str[i]) == 1)
{
len++;
while (CHAR(str[i]) == 1 && str[i] != '\0')
i++;
}
else
i++;
}
return (len);
}
int ft_size_tab(int *x, char *str)
{
int i;
int nb;
i = *x;
nb = 0;
while (SPACE(i))
i++;
if (CHAR(str[i]) == 1)
{
while (CHAR(str[i]) == 1)
{
i++;
nb++;
}
*x = i;
return (nb);
}
i++;
return (0);
}
char **ft_fill_tab(char **tab, char *str, int len)
{
int x;
int y;
int n;
x = 0;
n = 0;
while (x < len)
{
while (SPACE(n))
n++;
if (CHAR(str[n]) == 1)
{
y = 0;
while (CHAR(str[n]) == 1)
tab[x][y++] = str[n++];
}
tab[x][y] = '\0';
x++;
n++;
}
return (tab);
}
char **ft_split_whitespaces(char *str)
{
char **tab;
int len;
int i;
int nb;
int index;
i = 0;
len = 0;
index = 0;
len = ft_count_words(str);
if (!(tab = (char **)malloc(sizeof(char *) * (len + 1))))
return (0);
while (i < len)
{
nb = ft_size_tab(&index, str);
if (!(tab[i] = (char *)malloc(sizeof(char) * (nb + 1))))
return (0);
i++;
}
tab = ft_fill_tab(tab, str, len);
tab[len] = 0;
return (tab);
}
|
C | /*
* funcServer.c
*
* Created on: Dec 5, 2012
* Author: rosyid
*/
#include "funcServer.h"
static void init_fs() {
memset(&(fs.hints), 0, sizeof(fs.hints));
fs.hints.ai_family = AF_INET;
fs.hints.ai_socktype = SOCK_STREAM;
fs.hints.ai_flags = AI_PASSIVE;
}
static void ftps_listen() {
char* addr_serv;
int x = 1;
getaddrinfo(NULL, FTPPORT, &(fs.hints), &(fs.srv_info));
fs.socket_fd = socket(fs.srv_info->ai_family, fs.srv_info->ai_socktype, fs.srv_info->ai_protocol);
setsockopt(fs.socket_fd, SOL_SOCKET, SO_REUSEADDR, &x, fs.srv_info->ai_addrlen);
bind(fs.socket_fd, fs.srv_info->ai_addr, fs.srv_info->ai_addrlen);
listen(fs.socket_fd, BACKLOG);
addr_serv = inet_ntoa((*(struct sockaddr_in*)fs.srv_info->ai_addr).sin_addr);
printf("Server STARTED!\nHOST:%s\n", addr_serv);
}
static void sigchild_handler(int x) {
while(waitpid(-1, NULL, WNOHANG) > 0);
}
static void ftps_accept() {
char* client_addr_str;
unsigned int client_addrlen;
fs.sa.sa_handler = sigchild_handler;
sigemptyset(&(fs.sa.sa_mask));
fs.sa.sa_flags = SA_RESTART;
sigaction(SIGCHLD, &fs.sa, NULL);
connection_id = 0;
while(1) {
client_addrlen = sizeof(fs.client_addr);
fs.accsocket_fd = accept(fs.socket_fd, (struct sockaddr*) &(fs.client_addr), &client_addrlen);
client_addr_str = inet_ntoa(((struct sockaddr_in*) &fs.client_addr)->sin_addr);
connection_id++;
printf("Catch connection from %s\n", client_addr_str);
printf("ID Connection : %d\n", connection_id);
//buat proses baru untuk menghandle client baru
if(!fork()) {
close(fs.socket_fd);
ftps_handle_conn(client_addr_str);
close(fs.accsocket_fd);
printf("Connection to %s (%d) closed\n", client_addr_str, connection_id);
exit(0);
}
close(fs.accsocket_fd);
}
}
static int ftps_retrieve(char *path) {
char err[MEDIUMBUFFSIZE];
char msg[SMALLBUFFSIZE];
printf("Retrieve file : %s (%d)\n", path, connection_id);
if(ftp_file_exist(path, err) == -1) {
printf("-- FAILED [%s]\n", err);
sprintf(msg, "%s", SR501);
send(fs.accsocket_fd, msg, SMALLBUFFSIZE, 0);
return ST_ERROR;
}
strcpy(msg, SR150);
send(fs.accsocket_fd, msg, SMALLBUFFSIZE, 0);
int last_byte = recv(fs.accsocket_fd, msg, SMALLBUFFSIZE, 0);
msg[last_byte] = '\0';
if(!strcmp(msg, "READY")) {
printf("-- Client ready to receive file\n");
strcpy(msg, SR250);
send(fs.accsocket_fd, msg, SMALLBUFFSIZE, 0);
printf("-- File transfer STARTED\n");
ftp_send_file_partitioned(path, fs.accsocket_fd);
printf("-- File transfer FINISHED\n");
strcpy(msg, SR250);
send(fs.accsocket_fd, msg, SMALLBUFFSIZE, 0);
}
return ST_RETR;
}
static int ftps_store(char *filename) {
char message[STDBUFFSIZE];
printf("Store file : %s (%d)\n", filename, connection_id);
strcpy(message, SR150);
send(fs.accsocket_fd, message, SMALLBUFFSIZE, 0);
int last_byte = recv(fs.accsocket_fd, message, SMALLBUFFSIZE, 0);
message[last_byte] = '\0';
if(!strcmp(message, "READY")) {
printf("-- Client ready to send file\n");
strcpy(message, SR250);
send(fs.accsocket_fd, message, SMALLBUFFSIZE, 0);
printf("-- File transfer STARTED\n");
ftp_retrieve_file_partitioned(filename, fs.accsocket_fd);
printf("-- File transfer END\n");
strcpy(message, SR250);
send(fs.accsocket_fd, message, SMALLBUFFSIZE, 0);
}
return ST_STOR;
}
static int ftps_quit(const char *client_addr) {
char msg[STDBUFFSIZE];
sprintf(msg, SR200, " [Connection to %s CLOSED!]\n", client_addr);
send(fs.accsocket_fd, msg, sizeof(msg), 0);
return ST_QUIT;
}
static int ftps_list(char *path) {
struct dirent **list;
char msg[BIGBUFFSIZE];
int i, n;
if(path == NULL) {
path = getcwd(NULL, STDBUFFSIZE);
}
printf("List on %s directory (%d)\n", path, connection_id);
n = scandir(path, &list, NULL, alphasort);
if(n < 0) {
printf("-- FAILED\n");
strcpy(msg, SR501);
send(fs.accsocket_fd, msg, SMALLBUFFSIZE, 0);
return ST_ERROR;
}
printf("-- SUCCESS\n");
strcpy(msg, SR150);
send(fs.accsocket_fd, msg, SMALLBUFFSIZE, 0);
memset(&msg, 0, BIGBUFFSIZE);
sprintf(msg, "CWD: %s\n", getcwd(NULL, STDBUFFSIZE));
sprintf(msg, "%sPATH: %s\n", msg, path);
for(i = 0; i < n; i++) {
if(list[i]->d_type == DT_DIR) {
sprintf(msg, "%s%s (dir)\n", msg, list[i]->d_name);
} else {
sprintf(msg, "%s%s\n", msg, list[i]->d_name);
}
free(list[i]);
}
free(list);
//printf("--%s\n", msg);
send(fs.accsocket_fd, msg, BIGBUFFSIZE, 0);
return ST_LIST;
}
static int ftps_cwd(char *path) {
char msg[STDBUFFSIZE];
printf("CWD: %s from (%d)\n", path, connection_id);
if(chdir(path) == -1) {
strcpy(msg, SR501);
printf("-- FAILED\n");
} else {
strcpy(msg, SR200);
printf("-- SUCCESS\n");
}
send(fs.accsocket_fd, msg, STDBUFFSIZE, 0);
return ST_CWD;
}
static void ftps_parse_msg(char *client_msg, const char *client_addr, int *loop_status) {
char ** arr_msg;
ftp_tokenizer(client_msg, &arr_msg, ' ', 20);
if(!strcmp(arr_msg[0], CMD_RETR)) {
ftps_retrieve(arr_msg[1]);
} else if(!strcmp(arr_msg[0], CMD_STOR)) {
ftps_store(arr_msg[1]);
} else if(!strcmp(arr_msg[0], CMD_QUIT)) {
ftps_quit(client_addr);
} else if(!strcmp(arr_msg[0], CMD_LIST)) {
ftps_list(arr_msg[1]);
} else if(!strcmp(arr_msg[0], CMD_CWD)) {
ftps_cwd(arr_msg[1]);
}
free(arr_msg);
return;
}
static void ftps_handle_conn(const char *client_addr) {
char msg[STDBUFFSIZE];
char client_msg[STDBUFFSIZE];
int loop = 1;
int last_byte;
sprintf(msg, SR200, "| [Server connected to %s]\n", client_addr);
send(fs.accsocket_fd, msg, sizeof(msg), 0);
while(loop) {
last_byte = recv(fs.accsocket_fd, client_msg, STDBUFFSIZE, 0);
client_msg[last_byte] = '\0';
ftps_parse_msg(client_msg, client_addr, &loop);
printf("\n");
}
}
int ftps_server_main(int argc, char **argv) {
char* cwd;
cwd = ftp_getcwd(argc, argv);
printf("FTelePortation Server\n");
printf("CWD: %s\n", cwd);
init_fs();
ftps_listen();
ftps_accept();
}
|
C | /**
* @file
* @brief A driver for the solenoid.
*/
/**
* @brief Initializes the solenoid.
*/
void solenoid_init();
/**
* @brief Sets the solenoid.
*/
void solenoid_set();
/**
* @brief Clears the solenoid.
*/
void solenoid_clear();
/**
* @brief Checks if the solenoid is set.
*
* @return A boolean corresponding to if the solenoid is set or not.
*/
int solenoid_is_set();
/**
* @brief Fires the solenoid.
*/
void solenoid_fire();
|
C | /**
* Nombre: ejercicio8.c
* Autores: Jose Ignacio Gomez, Óscar Gómez
* Fecha: 10-03-2017
* Grupo: 2202
* Pareja: 5
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include <time.h>
#define NUM_PROC 4 /*!< Ńumero de iteraciones*/
int son_pid; /*!< Variable para almacenar el pid del proceso hijo*/
int root_pid; /*!<Variable para almacenar el pid del proceso root*/
int status; /*!< Variable de estado para los wait*/
time_t tiempo; /*!< Variables necesarias para trabajar con tiempos*/
struct tm *tlocal;
char output[128]; /*!< Variable donde almacenaremos la fecha y hora*/
int main(int argc, char const *argv[]) {
int numproc, vueltas, v = 0;
int i;
int padre = 0; /*!< Indica si un proceso tiene hijos (1) o no (0)*/
int pid = 0; /*!< Fijamos pid a 0 para que efectúe un fork()
en la primera iteración del bucle*/
void manejador_USR1();
void manejador_TERM();
void manejador_FIN();
if(argc < 3 || argc > 3) {
printf("Prueba con: ./ejercicio8 <numero_procesos> <numero_vueltas>\n");
return 1;
}
numproc = atoi(argv[1]);
vueltas = atoi(argv[2]);
root_pid = getpid(); /*Guardamos el pid del proceso raíz*/
for(i = 0; i < numproc; i++){
if(pid == 0){/*Para generar árboles en serie
sólo harán forks los hijos*/
if((pid = fork()) < 0) {
perror("Error de fork");
exit(EXIT_FAILURE);
}
else if(i == numproc - 1 && pid == 0){ /*Si es el último proceso,
gestiona la primera señal*/
son_pid = root_pid; /*El último proceso mandará señales al root*/
sleep(5);
kill(son_pid, SIGUSR1);
break;
}
else if (pid > 0) {
padre = 1;
son_pid = pid;
break;
}
}
else{
padre = 1;
son_pid = pid; /*El pid obtenido en el fork será el pid del hijo*/
break;
}
}
/*Ahora vamos a gestionar el envío circular de señales*/
while(v <= vueltas){
/*Armamos la llegada de señales*/
if(signal(SIGUSR1, manejador_USR1) == SIG_ERR){
perror("signal");
exit(EXIT_FAILURE);
}
if(signal(SIGTERM, manejador_TERM) == SIG_ERR){
perror("signal");
exit(EXIT_FAILURE);
}
pause(); /*Los procesos esperan la llegada de una señal*/
v++;
}
/*Ahora el root iniciará una cadena de llamadas a TERM*/
if(getpid() != root_pid) {
pause(); /*Espera la llegada de una señal SIGTERM*/
}
else {
kill(son_pid, SIGTERM);
if(signal(SIGTERM, manejador_FIN) == SIG_ERR){
perror("signal");
exit(EXIT_FAILURE);
}
pause(); /*Espera la llegada de una señal SIGTERM, pero la
ignorará para ejecutar el código siguiente*/
}
/*A continuación, el root debería ser el único capaz de llegar hasta
aquí, por lo que realizará un wait y morirá*/
printf("Muere PID=%d\n", getpid());
wait(&status);
exit(EXIT_SUCCESS);
return 0;
}
/**
* Manejador para la señal USR1
* @author Jose Ignacio Gomez, Óscar Gómez
* @date 16-03-2017
* @param int signal
*/
void manejador_USR1(int signal){
tiempo = time(0);
tlocal = localtime(&tiempo);
strftime(output, 128, "%d/%m/%y %H:%M:%S", tlocal);
printf("Hola PID=%d, time= %s\n", getpid(), output);
sleep(2);
kill(son_pid, SIGUSR1);
}
/**
* Manejador para la señal TERM
* @author Jose Ignacio Gomez, Óscar Gómez
* @date 16-03-2017
* @param int signal
*/
void manejador_TERM(int signal){
sleep(1);
kill(son_pid, SIGTERM);
printf("Muere PID=%d\n", getpid());
wait(&status);
exit(EXIT_SUCCESS);
}
/**
* Manejador para la señal TERM del proceso root
* @author Jose Ignacio Gomez, Óscar Gómez
* @date 16-03-2017
* @param int signal
*/
void manejador_FIN(int signal) {
printf("Muere PID=%d\n", getpid());
wait(&status);
exit(EXIT_SUCCESS);
} |
C | #include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "member.h"
#define MIN_ID 0
// Struct Decleration
struct Member_t{
int member_id;
char* member_name;
};
// Function Implementations
Member memberCreate(const int member_id, const char* member_name)
{
assert(member_name != NULL || member_id >= MIN_ID);
Member member = malloc(sizeof(*member));
if(member == NULL)
{
return NULL;
}
member->member_id = member_id;
char* member_name_copy = malloc(sizeof(char)*(strlen(member_name) + 1));
if(member_name_copy == NULL)
{
memberDestroy(member);
return NULL;
}
strcpy(member_name_copy, member_name);
member->member_name = member_name_copy;
return member;
}
void memberDestroy(Member member)
{
free(member->member_name);
free(member);
}
int* memberGetId(Member member)
{
assert(member != NULL);
return &member->member_id;
}
char* memberGetName(Member member)
{
assert(member != NULL);
return member->member_name;
}
bool memberEqual(Member member1, Member member2)
{
assert(member1 != NULL || member2 != NULL);
return member1->member_id == member2->member_id;
}
Member memberCopy(Member member)
{
Member member_copy = memberCreate(member->member_id, member->member_name);
if(member_copy == NULL)
{
return NULL;
}
return member_copy;
} |
C | #include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define K 1024
#define WRITELEN (128 * K)
int main(void)
{
int result = -1; /*创建管道结果*/
int fd[2], nbytes; /*文件描述符,字符个数*/
pid_t pid; /*PID*/
char string[WRITELEN] = "Hello Miclefeng pipe";
char readbuffer[10 * K]; /*读缓冲区*/
int *write_fd = &fd[1]; /*文件描述符1,用于写*/
int *read_fd = &fd[0]; /*文件描述符0,用于读*/
result = pipe(fd);
if (-1 == result) {
printf("建立管道失败\n");
return -1;
}
pid = fork(); /*分叉程序*/
if (-1 == pid) {
printf("Fork 进程失败\n");
return -1;
}
if (0 == pid) {
/*子进程,关闭读管道*/
close(*read_fd);
int write_size = WRITELEN;
result = 0;
while (write_size >= 0) {
result = write(*write_fd, string, write_size); /*写入管道数据*/
printf("\n=====> 写入 %d 个数据 <=====\n\n", result);
if (result > 0) {
write_size -= result; /*写入的长度*/
printf("写入%d个数据,剩余%d个数据\n", result, write_size);
} else {
sleep(10);
break;
}
}
return 0;
} else {
/*父进程,关闭写管道*/
close(*write_fd);
while (1) {
nbytes = read(*read_fd, readbuffer, sizeof(readbuffer)); /*读取数据*/
if (nbytes <= 0) {
printf("没有数据写入了\n");
break;
}
printf("接收到%d个数据,内容为:'%s'\n", nbytes, readbuffer);
}
return 0;
}
}
|
C | #ifndef __GRADER_H
#define __GRADER_H
#include <stdio.h>
#include <string.h>
#include <printf.h>
#include <stdlib.h>
#include <setjmp.h>
////////////////////////////////////////////////////////////////
// Color macros
#define TEST_COLOR "35;1"
#define RESET_COLOR "0"
#define PASSED_COLOR "32"
#define FAILED_COLOR "31;1"
#define WARN_COLOR "34;1"
#ifndef NO_COLOR
# define COLOR(__c, __s) ESCAPE(__c) __s ESCAPE(RESET)
# define ESCAPE(__s) "\x1B[" __s##_COLOR "m"
#else
# define COLOR(__c, __s) __s
# define ESCAPE(__s)
#endif
#ifndef PRINTF_BUFFER_SIZE
# define PRINTF_BUFFER_SIZE 4096
#endif
#ifndef STACK_LIMIT
# define STACK_LIMIT (1 * 1024 * 1024)
#endif
#define DESCRIBE(__call, ...)\
({ LAST_CALL(__VA_ARGS__); __call ;})
////////////////////////////////////////////////////////////////
// Assertions
////////////////////////////////////////////////////////////////
// Asserting x == y
//
// ASSERT_EXACT (format, expected_val, actual_val)
// ASSERT_EXACT_MSG(format, message, expected_val, actual_val)
// ASSERT_MSG (message, expected_val, actual_val)
//
// format is the formatting string used to print the values
// message is the string that will be printed in front of the message
// ASSERT_MSG just prints the message and not the values
# define ASSERT_EXACT(__fmt, __expected, __actual) \
ASSERT_EXACT_MSG(__fmt, #__actual, __expected, __actual)
#undef ASSERT_EXACT
# define ASSERT_EXACT(__fmt, __expected, __actual) \
do { \
if ((__expected) != (__actual)) \
FAILED("%s: expecting '"__fmt"', but found '"__fmt"'", last_call_buffer, __expected, __actual);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_EXACT_MSG(__fmt, __expr, __expected, __actual) \
do { \
if ((__expected) != (__actual)) \
FAILED(__expr ": expecting '"__fmt"', but found '"__fmt"'", __expected, __actual);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_EXACT_DESCRIBED(__fmt, __expected, __actual, __args_fmt, ...) \
do { \
if ((__expected) != (__actual)) \
FAILED("Expecting '"__fmt"', but found '"__fmt"'.\nCalled by: "__args_fmt, __expected, __actual, __VA_ARGS__);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_MSG(__msg, __expected, __actual) \
do { \
if ((__expected) != (__actual)) { \
FAILED(__msg); \
} else { \
ASSERT_PASSED(); \
} \
} while (0)
////////////////////////////////////////////////////////////////
// Asserting x~= y
//
// ASSERT_FP(format, expected_val, actual_val, precision)
//
// assertion for floating point values, asserting equality up to a
// precision in absolute value
# define ASSERT_FP(__fmt, __expected, __actual, __prec) \
do { \
if (fabs((__expected) - (__actual)) > (__prec)) \
FAILED("Expecting '"__fmt"', but found '"__fmt"'", __expected, __actual);\
else \
ASSERT_PASSED(); \
} while (0)
////////////////////////////////////////////////////////////////
// Dedicated assertions for specific types
# define ASSERT_INT(__expected, __actual) \
ASSERT_EXACT("%d", __expected, __actual)
# define ASSERT_INT_MSG(__expected, __actual, __argsfmt, ...) \
ASSERT_EXACT_DESCRIBED("%d", __expected, __actual, __argsfmt, __VA_ARGS__)
# define ASSERT_UINT(__expected, __actual) \
ASSERT_EXACT("%u", __expected, __actual)
# define ASSERT_UINT_MSG(__expected, __actual, __argsfmt, ...) \
ASSERT_EXACT_DESCRIBED("%u", __expected, __actual, __argsfmt, __VA_ARGS__)
# define ASSERT_LONG(__expected, __actual) \
ASSERT_EXACT("%ld", __expected, __actual)
# define ASSERT_ULONG(__expected, __actual) \
ASSERT_EXACT("%lu", __expected, __actual)
# define ASSERT_FLOAT(__expected, __actual, __prec) \
ASSERT_FP("%f", __expected, __actual, __prec)
# define ASSERT_DOUBLE(__expected, __actual, __prec) \
ASSERT_FP("%lf", __expected, __actual, __prec)
# define ASSERT_PTR(__expected, __actual) \
ASSERT_EXACT("%p", __expected, __actual)
# define ASSERT_PTR_MSG(__expected, __actual, __argsfmt, ...) \
ASSERT_EXACT_DESCRIBED("%p", __expected, __actual, __argsfmt, __VA_ARGS__)
# define ASSERT_NULL(__actual) \
ASSERT_EXACT("%p", NULL, __actual)
# define ASSERT_NULL_MSG(__actual, __argsfmt, ...) \
ASSERT_EXACT_DESCRIBED("%p", NULL, __actual, __argsfmt, __VA_ARGS__)
# define ASSERT_STRUCT(__struct_comparator, __expected, __actual) \
do { \
if (!(((__expected) == (__actual)) || (__struct_comparator((__expected), (__actual)))))\
FAILED("Expecting: %-@ but found: %-@\nCalled by: %s", 1, (__expected), 1, (__actual), last_call_buffer);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_STRUCT_MSG(__struct_comparator, __expected, __actual, __args_fmt, ...) \
do { \
if (!(((__expected) == (__actual)) || (__struct_comparator((__expected), (__actual)))))\
FAILED("Expecting: %-@ but found: %-@\nCalled by: "__args_fmt, 1, (__expected), 1, (__actual), __VA_ARGS__);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_ARRAY_MSG(__size, __expected, __actual, __fmt, __args_fmt, ...) \
do { \
int __idx = array_compare(compare_memory, __expected, __actual, __size, sizeof(__expected[0])); \
if (__idx != -1) \
FAILED("Expecting\n"__fmt" but found\n"__fmt" at index %d.\nCalled by: "__args_fmt, \
__expected[__idx], __actual[__idx], __idx, __VA_ARGS__);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_ARRAY_STRUCT_MSG(__size, __expected, __actual, __fmt, __args_fmt, ...) \
do { \
int __idx = array_compare(compare_memory, __expected, __actual, __size, sizeof(__expected[0])); \
if (__idx != -1) \
FAILED("Expecting: "__fmt" but found: "__fmt" at index %d.\nCalled by: "__args_fmt, \
1, &__expected[__idx], 1, &__actual[__idx], __idx, __VA_ARGS__);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_NOT_NULL(__actual) \
do { \
if (NULL == (__actual)) \
FAILED("'"#__actual"', expecting not NULL");\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_NOT_NULL_MSG(__actual, __args_fmt, ...) \
do { \
if (NULL == (__actual)) \
FAILED("'"#__actual"', expecting not NULL: "__args_fmt, __VA_ARGS__); \
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_BOOL(__expected, __actual) \
ASSERT_EXACT_MSG("%d", #__actual, ((__expected) == 0), ((__actual) == 0))
# define ASSERT_BOOL_MSG(__expected, __actual, __argsfmt, ...) \
ASSERT_EXACT_DESCRIBED("%d", ((__expected) == 0), ((__actual) == 0), __argsfmt, __VA_ARGS__)
# define ASSERT_TRUE(__actual) \
ASSERT_BOOL(1, __actual)
# define ASSERT_TRUE_MSG(__actual, __argsfmt, ...) \
ASSERT_BOOL_MSG(1, __actual, __argsfmt, __VA_ARGS__)
# define ASSERT_FALSE(__actual) \
ASSERT_BOOL(0, __actual)
# define ASSERT_FALSE_MSG(__actual, __argsfmt, ...) \
ASSERT_BOOL_MSG(0, __actual, __argsfmt, __VA_ARGS__)
# define ASSERT_STRING(__expected, __actual) \
do { \
if (memcmp(__expected, __actual, strlen(__expected) + 1)) \
FAILED("Expecting\n'%s', but found\n'%s'", __expected, __actual);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_STRING_MSG(__expected, __actual, __args_fmt, ...) \
do { \
if (memcmp(__expected, __actual, strlen(__expected) + 1)) \
FAILED("Expecting\n'%s', but found\n'%s'.\nCalled by: "__args_fmt, __expected, __actual, __VA_ARGS__);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_CHAR(__expected, __actual) \
do { \
if (__expected != __actual) \
FAILED("Expecting '%c' (code %hhd), but found '%c' (code %hhd)", __expected, __expected, __actual, __actual); \
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_VALID_PTR(__actual) \
do { \
if (invalid_stack_pointer(__actual)) \
FAILED("Expecting valid pointer, but pointer (%p) is above in stack.", __actual);\
else \
ASSERT_PASSED(); \
} while (0)
# define ASSERT_VALID_PTR_MSG(__actual, __args_fmt, ...) \
do { \
if (invalid_stack_pointer(__actual)) \
FAILED("Expecting valid pointer, but pointer (%p) is above in stack.\ Called by: "__args_fmt, __actual, __VA_ARGS__);\
else \
ASSERT_PASSED(); \
} while (0)
////////////////////////////////////////////////////////////////
// Asserting if a function is recursive or not
//
// ASSERT_NOT_RECURSIVE(function_name, args)
// ASSERT_RECURSIVE(stack_depth, function_name, args)
//
// Ex. : ASSERT_RECURSIVE(4, fibo_rec, 4) asserts that fibo_rec(4)
// makes 4 recursive calls.
#define TRACE_CALL(__var, __fun, ...) \
trace_function(__fun); \
__fun(__VA_ARGS__); \
struct call_info __var = trace_function(NULL)
#define ASSERT_NOT_RECURSIVE(__fun, ...) \
do { \
TRACE_CALL(_call_info, __fun, __VA_ARGS__); \
ASSERT_MSG(#__fun "() should not be recursive.", 1, _call_info.stack_depth); \
} while(0)
#define ASSERT_RECURSIVE(__stack_depth, __fun, ...) \
do { \
TRACE_CALL(_call_info, __fun, __VA_ARGS__); \
ASSERT_MSG(#__fun "() should be recursive.", __stack_depth, _call_info.stack_depth); \
} while(0)
////////////////////////////////////////////////////////////////
// Asserting that a function has been implemented
//
// ASSERT_IMPLEMENTED(function_name)
#define ASSERT_PASSED() assert_passed()
#define ASSERT_IMPLEMENTED(__fun) \
do { \
if (((void*)__fun) == NULL || ((void*)__fun) == ((void*)__##__fun)) \
FAILED("Not implemented: %s", #__fun); \
else \
ASSERT_PASSED(); \
} while(0)
#define ASSERT_IMPLEMENTED_SILENT(__fun) \
do { \
if (((void*)__fun) == NULL || ((void*)__fun) == ((void*)__##__fun)) {\
assert_failed(); \
return EXIT_FAILURE; \
} else \
ASSERT_PASSED(); \
} while(0)
////////////////////////////////////////////////////////////////
// Asserting that a call triggers an assertion or exit() with
// some values.
// These macro should never be nested (nor interleaved).
//
// ASSERT_RAISES(call)
// ASSERT_EXIT_WITH(status, call)
#define ASSERT_RAISES(__call) \
START_BARRIER(trap) \
__call ; \
FAILED(#__call " should raise an assertion."); \
RESCUE_BARRIER \
if (user_has_asserted()) \
ASSERT_PASSED(); \
else \
FAILED(#__call " should raise an assertion (not an exit)."); \
END_BARRIER
#define ASSERT_NO_RAISES(__call) \
START_BARRIER(trap) \
__call ; \
ASSERT_PASSED(); \
RESCUE_BARRIER \
FAILED(#__call " should not raise an assertion (nor exit)."); \
END_BARRIER
#define ASSERT_EXIT_WITH(__code, __call) \
START_BARRIER(trap) \
__call ; \
FAILED(#__call " should exit with status %d (exit not called).", __code); \
RESCUE_BARRIER \
trap = (trap > 0)?(trap - 1):(trap+1); \
if (user_has_asserted()) \
FAILED(#__call " should exit with status %d not an assertion.", __code); \
else if (__code != trap) \
FAILED(#__call " should exit with status %d not %d.", __code, trap); \
else \
ASSERT_PASSED(); \
END_BARRIER
////////////////////////////////////////////////////////////////
// Assertions on memory allocation
//
// __BEGIN_MEMORY_CHECKING__
// __END_MEMORY_CHECKING__
//
// Define a block where the memory protection mechanisms are
// enabled. At the end, the memory balance is checked with
// ASSERT_MEMORY_BALANCED.
// Ex. :
// __BEGIN_MEMORY_CHECKING__
// struct fifo * f = __fifo__empty();
// // the fifo and the link should have been allocated
// ASSERT_INT(2, (int) get_a_stats().allocated);
// __END_MEMORY_CHECKING__
#define __BEGIN_MEMORY_CHECKING__ \
do { \
struct a_stats _m_ck_pt = get_a_stats();\
enable_malloc_protector(); \
#define __END_MEMORY_CHECKING__ \
disable_malloc_protector(); \
ASSERT_MEMORY_BALANCED(_m_ck_pt); \
}while(0);
// ASSERT_MEMORY_BALANCED(checkpoint)
//
// checkpoint must have been called with get_a_stats() before. Then
// the macro compares the memory stats between checkpoint and the
// current point, and tests for memory leaks and invalid free(s).
#define ALLOCATED(__s) \
((__s).allocated - (__s).freed)
#define ASSERT_MEMORY_BALANCED(__saved_stats) \
do { \
struct a_stats __stats = get_a_stats(); \
long leaks = ALLOCATED(__stats) - ALLOCATED(__saved_stats); \
long faults = __stats.fault - __saved_stats.fault; \
if (leaks) \
FAILED(COLOR(FAILED, "Memory leak")": %ld block%s", \
leaks, leaks == 1 ? "": "s"); \
if (faults) \
FAILED(COLOR(FAILED, "Invalid free")" on %ld pointer%s", \
faults, faults == 1 ? "" : "s"); \
if (leaks == 0 && faults == 0) \
ASSERT_PASSED(); \
} while (0)
// FREE_ALL
//
// Calls free_all() to free all pointers handled by the malloc
// library. Warning : this does not work for all malloc handlers.
#define FREE_ALL() \
do { \
enable_malloc_protector(); \
free_all(); \
disable_malloc_protector(); \
} while(0)
////////////////////////////////////////////////////////////////
// FAILED(printf_like_args ...)
//
// Prints an error message to stderr and exits
#ifdef __APPLE__
# define XPRINTF(__file, ...) \
fxprintf(__file, domain, NULL, __VA_ARGS__)
# define LAST_CALL(...) \
sxprintf(last_call_buffer, PRINTF_BUFFER_SIZE, domain, NULL, __VA_ARGS__)
extern printf_domain_t domain;
#else
# define XPRINTF(__file, ...) \
fprintf(__file, __VA_ARGS__)
# define LAST_CALL(...) \
snprintf(last_call_buffer, PRINTF_BUFFER_SIZE, __VA_ARGS__)
#endif
#define MSG(...) \
do { \
XPRINTF(stderr, COLOR(WARN, "In %s: "), __func__);\
XPRINTF(stderr, __VA_ARGS__); \
XPRINTF(stderr, "\n"); \
fflush(stderr); \
} while (0)
#define FAILED(...) \
do { \
MSG(__VA_ARGS__); \
assert_failed(); \
return EXIT_FAILURE;\
} while (0)
////////////////////////////////////////////////////////////////
// Test macro helpers
//
// TEST(message, function_name, function_args ...)
//
// Generate a struct test with a better syntax.
// Ex. : TEST("allocating a fifo", test_allocate_fifo, NULL),
#define ASIZE(__sym) (sizeof(__sym)/sizeof(__sym[0]))
#define TEST(__name, __fun, __data) \
{__name, (testfun_t)__fun, ASIZE(__data), &__data}
////////////////////////////////////////////////////////////////
// TEST_CASES(test_name, struct_definition, list_of_cases ...)
// TEST_FUNCTION(function_name) // where test_name == function_name
// TEST_FUNCTION_WITH(test_name, function_name)
// END_TEST_FUNCTION
//
// The first macro defins a list of test cases for the function that
// will be defined within the block TEST_FUNCTION
// ... END_TEST_FUNCTION. Within this block, one can access 'len' the
// number of test cases and values[] the test cases array.
//
// Ex. : (filling an array with even values 0 2 4 6 8 ...)
//
// TEST_CASES(fill_even, { int l ;})
// { 0 }, { 1 }, { 5 }
// END_TEST_CASES
// TEST_FUNCTION(fill_even)
// for (int i = 0 ; i < len ; i++) {
// int result[] = { -1, -1, -1, -1, -1, -1};
// int l = values[i].l;
// fill_even(l, result);
// for (int j = 0; j < l; j ++) {
// ASSERT_INT(2 * j, result[j]);
// }
// }
// END_TEST_FUNCTION
//
// In order to test some code but with another test name, use the
// TEST_FUNCTION_WITH macro. In fact, every test should refer to some
// code written by the students. For example :
//
// TEST_FUNCTION_WITH(fill_even_boundary_check, fill_even)
// ...
// END_TEST_FUNCTION
#define TEST_CASES(__name, __type) \
struct __name __type test_ ## __name ## _values[] = {
#define END_TEST_CASES \
};
#define NO_TEST_CASE(__name) \
struct __name {int no;} test_ ## __name ## _values[] = {{ 0 }};
#define TEST_FUNCTION_GENERIC(__name) \
int test_ ## __name (int len, struct __name values[]) { \
#define TEST_FUNCTION(__name) \
TEST_FUNCTION_GENERIC(__name) \
ASSERT_IMPLEMENTED_SILENT(__name);
#define TEST_FUNCTION_WITH(__name, __fun) \
TEST_FUNCTION_GENERIC(__name) \
ASSERT_IMPLEMENTED_SILENT(__fun);
#define END_TEST_FUNCTION \
return EXIT_SUCCESS; \
}
// PAD_BUFFER(buffer, size)
#define PAD_BUFFER(__buffer) \
memset(__buffer, 0x5a, ASIZE(__buffer) - 1); \
(__buffer)[ASIZE(__buffer) - 1] = 0
////////////////////////////////////////////////////////////////
// PRINT_RENDERER(struct_name,var_name,string,fields...)
// Configures a printer for a given struct name.
// The var_name must be the one used inside the fields.
//
// Ex. :
//
// PRINT_RENDERER(iris, i, "{ %s, %d, %d, %d, %d }",
// iris_gender[i->gender],
// i->sepal_length, i->sepal_width,
// i->petal_length, i->petal_width);
//
// Then the renderer can be used with something like :
//
// ASSERT_STRING_MSG(expected, actual, "print_iris(%-@)", 1, &exemples[i]);
//
// The "1" is the size of the array to display. The `-` disable the `{}` around
// items. Some exemples are given in 'iris' and 'planning'.
struct print_renderer {
size_t type_size;
const char *(*get_format)(const struct printf_info * info);
int (*render)(FILE *stream, const char *fmt, const void * item);
};
void struct_renderer(const struct print_renderer render);
void struct_renderer_alt(const struct print_renderer render);
#define PRINT_RENDERER(__struct, __var, __patern, ...) \
static const char* array_##__struct ##_fmt(const struct printf_info *info) { \
return ", "__patern; \
} \
static int array_##__struct(FILE *stream, const char *fmt, const struct __struct * __var) { \
return fprintf(stream, fmt, __VA_ARGS__); \
} \
static const struct print_renderer render_ ## __struct = {sizeof(struct __struct), array_##__struct##_fmt, (int (*)(FILE *, const char* , const void *))array_##__struct}
#define DEFINE_STRUCT_COMPARATOR(__struct) \
static int compare_##__struct( \
const struct __struct *p1, const struct __struct *p2) { \
return !memcmp(p1, p2, sizeof(struct point_t)); \
}
////////////////////////////////////////////////////////////////
// EXERCICE(message, list_of_test_function_names ...)
//
// Builds a test suite containing all the tests in the list and
// execute them one by one.
#define TNAME(x, n) TEST(x ":" #n, test_ ## n, test_ ## n ## _values),
#define FE_1(WHAT, X, Y) WHAT(X, Y)
#define FE_2(WHAT, X, Y, ...) WHAT(X, Y) FE_1(WHAT, X, __VA_ARGS__)
#define FE_3(WHAT, X, Y, ...) WHAT(X, Y) FE_2(WHAT, X, __VA_ARGS__)
#define FE_4(WHAT, X, Y, ...) WHAT(X, Y) FE_3(WHAT, X, __VA_ARGS__)
#define FE_5(WHAT, X, Y, ...) WHAT(X, Y) FE_4(WHAT, X, __VA_ARGS__)
#define FE_6(WHAT, X, Y, ...) WHAT(X, Y) FE_5(WHAT, X, __VA_ARGS__)
#define FE_7(WHAT, X, Y, ...) WHAT(X, Y) FE_6(WHAT, X, __VA_ARGS__)
#define FE_8(WHAT, X, Y, ...) WHAT(X, Y) FE_7(WHAT, X, __VA_ARGS__)
#define FE_9(WHAT, X, Y, ...) WHAT(X, Y) FE_8(WHAT, X, __VA_ARGS__)
#define FE_10(WHAT, X, Y, ...) WHAT(X, Y) FE_9(WHAT, X, __VA_ARGS__)
#define FE_11(WHAT, X, Y, ...) WHAT(X, Y) FE_10(WHAT, X, __VA_ARGS__)
#define FE_12(WHAT, X, Y, ...) WHAT(X, Y) FE_11(WHAT, X, __VA_ARGS__)
#define FE_13(WHAT, X, Y, ...) WHAT(X, Y) FE_12(WHAT, X, __VA_ARGS__)
#define FE_14(WHAT, X, Y, ...) WHAT(X, Y) FE_13(WHAT, X, __VA_ARGS__)
#define FE_15(WHAT, X, Y, ...) WHAT(X, Y) FE_14(WHAT, X, __VA_ARGS__)
#define FE_16(WHAT, X, Y, ...) WHAT(X, Y) FE_15(WHAT, X, __VA_ARGS__)
#define FE_17(WHAT, X, Y, ...) WHAT(X, Y) FE_16(WHAT, X, __VA_ARGS__)
#define FE_18(WHAT, X, Y, ...) WHAT(X, Y) FE_17(WHAT, X, __VA_ARGS__)
#define FE_19(WHAT, X, Y, ...) WHAT(X, Y) FE_18(WHAT, X, __VA_ARGS__)
#define FE_20(WHAT, X, Y, ...) WHAT(X, Y) FE_19(WHAT, X, __VA_ARGS__)
#define FE_21(WHAT, X, Y, ...) WHAT(X, Y) FE_20(WHAT, X, __VA_ARGS__)
#define FE_22(WHAT, X, Y, ...) WHAT(X, Y) FE_21(WHAT, X, __VA_ARGS__)
#define FE_23(WHAT, X, Y, ...) WHAT(X, Y) FE_22(WHAT, X, __VA_ARGS__)
#define FE_24(WHAT, X, Y, ...) WHAT(X, Y) FE_23(WHAT, X, __VA_ARGS__)
#define FE_25(WHAT, X, Y, ...) WHAT(X, Y) FE_24(WHAT, X, __VA_ARGS__)
#define FE_26(WHAT, X, Y, ...) WHAT(X, Y) FE_25(WHAT, X, __VA_ARGS__)
#define FE_27(WHAT, X, Y, ...) WHAT(X, Y) FE_26(WHAT, X, __VA_ARGS__)
#define FE_28(WHAT, X, Y, ...) WHAT(X, Y) FE_27(WHAT, X, __VA_ARGS__)
#define FE_29(WHAT, X, Y, ...) WHAT(X, Y) FE_28(WHAT, X, __VA_ARGS__)
#define FE_30(WHAT, X, Y, ...) WHAT(X, Y) FE_29(WHAT, X, __VA_ARGS__)
#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,\
_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,NAME,...) NAME
#define FOR_EACH(action, arg, ...) \
GET_MACRO(__VA_ARGS__,\
FE_30,FE_29,FE_28,FE_27,FE_26,FE_25,FE_24,FE_23,FE_22,FE_21,\
FE_20,FE_19,FE_18,FE_17,FE_16,FE_15,FE_14,FE_13,FE_12,FE_11,\
FE_10,FE_9,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1)(action, arg, __VA_ARGS__)
#define PP_NARG(...) \
PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) \
PP_ARG_N(__VA_ARGS__)
#define PP_ARG_N( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63, N, ...) N
#define PP_RSEQ_N() \
63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9, 8, 7, 6, 5, 4, 3, 2, 1, 0
#define EXERCICE(_name, ...) \
const struct test exercice [] = { \
FOR_EACH(TNAME, _name, __VA_ARGS__) \
{ .name= NULL} \
};
////////////////////////////////////////////////////////////////
// WEAK_DEFINE(function_name, return_type, args_types ...) { block }
//
// Defines a function named function_name that can be used within the
// code and the tests. The goal is for the student to be able to use
// the function even if he has not implemented it. If not implemented,
// the weak function will return false with ASSERT_IMPLEMENTED. To use
// the function in the tests, it suffices to prefix it with '__'.
#define WEAK_DEFINE_RELAY(__x) #__x
#ifdef __APPLE__
# ifdef ANSWER
# define PROVIDED_FUNCTION(__name, __ret, ...) \
extern __ret __name(__VA_ARGS__); \
static __ret __##__name(__VA_ARGS__) {
# define WEAK_DEFINE(__name, __ret, ...) \
extern __ret __name(__VA_ARGS__); \
static __ret __##__name(__VA_ARGS__)
# else
# define PROVIDED_FUNCTION(__name, __ret, ...) \
static __ret __##__name(__VA_ARGS__) {exit(1);} \
static __ret __name(__VA_ARGS__) {
# define WEAK_DEFINE(__name, __ret, ...) \
static __ret __##__name(__VA_ARGS__) {exit(1);} \
static __ret __name(__VA_ARGS__)
# endif
#else
# define PROVIDED_FUNCTION(__name, __ret, ...) \
extern __ret __name(__VA_ARGS__) \
__attribute__ ((weak, alias(WEAK_DEFINE_RELAY(__##__name)))); \
static __ret __##__name(__VA_ARGS__) {
# define WEAK_DEFINE(__name, __ret, ...) \
extern __ret __name(__VA_ARGS__) \
__attribute__ ((weak, alias(WEAK_DEFINE_RELAY(__##__name)))); \
static __ret __##__name(__VA_ARGS__)
#endif
#define END_PROVIDED_FUNCTION }
////////////////////////////////////////////////////////////////
// End of macros
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Public interface
// Test function
typedef int (* const testfun_t) (int, const void*);
// Struct for the tests
struct test {
const char *name; // test name
const testfun_t fun; // test function
int len; // length of the parameters
const void *param; // parameters
};
// Call statistics
struct call_info {
unsigned count;
unsigned stack_depth;
};
// Allocation statistics
struct a_stats {
unsigned long allocated, freed, reallocated;
unsigned long fault;
};
// Get allocation statistics
struct a_stats get_a_stats();
void enable_malloc_protector();
void disable_malloc_protector();
void free_all();
size_t pointer_info(void*);
// Get call info (for recursion etc..)
struct call_info trace_function(void *sym);
// Main entry point
int grader(const struct test tests[], int argc, char **argv);
void list_tests(const struct test tests[]);
struct printer {
void (*header)();
void (*result)(const struct test*, int);
void (*summary)();
};
const struct test *find_test(const struct test test[], const char *name);
int run_test(const struct test *test, const struct printer *print);
int run_test_group(const struct test test[], const struct printer *print);
void assert_passed();
void assert_failed();
// User assert support
// !! Remark that END_BARRIER should be followed by a semi-column, while not the others
//
#define START_BARRIER(__trap) \
do { \
int __trap; \
reset_user_assert(); \
jmp_buf _barrier; \
if (!(__trap = setjmp(_barrier))) { \
register_barrier(_barrier);
#define RESCUE_BARRIER \
} else {
#define END_BARRIER \
} \
release_barrier(); \
} while(0)
int user_has_asserted();
void reset_user_assert();
void release_barrier();
void register_barrier(jmp_buf checkpoint);
int invalid_stack_pointer(const void *sentinel_addr);
// Grab printf feature
// Note: the size of the buffer is controled by
// -DPRINTF_BUFFER_SIZE=4096
// which has to be set while compiling grader.c (in libexam)
void start_grab_printf();
char* end_grab_printf();
enum grader_mode_t { MAIN, TEST, GRADE };
enum grader_mode_t get_grader_mode();
// Renderers
//void print_test_result(const struct test *test, int status);
//void print_raw_test_result(const struct test *test, int status);
// Helpers
int normalize(int v); // force positive values to 1 and negative to -1.
int as_bool(int v); // force true to 1.
int compare_memory(const void* v1, const void* v2, size_t size);
// Compare two arrays and return the differing index or -1 if none
int array_compare(int (*comparator)(const void*, const void*, size_t),
const void *a1, const void *a2, size_t n, size_t item_size);
extern char last_call_buffer[PRINTF_BUFFER_SIZE];
#endif // __GRADER_H
|
C | #ifndef _SINGLE_LIST_H
#define _SINGLE_LIST_H
struct node;
typedef struct node * pNode;
typedef pNode sList;
struct node
{
int value;
pNode next;
};
pNode sListSearch(sList l, int v);
void sListDelete(sList l);
void sListAppend(sList l, int v, pNode p);
void sListRemove(sList l, int v);
void sListPrint(sList l);
#endif //_SINGLE_LIST_H
|
C | #include<stdio.h>
int main()
{
double h;
scanf("%lf", &h);
if(h >= 4)
{
printf("He can be a excellent programmer.");
}
else if(h >= 3)
{
printf("He can be a good programmer.");
}
else if(h > 2)
{
printf("He can be a normal programmer.");
}
else
{
printf("He can not be a programmer.");
}
return 0;
}
|
C | #include <stdlib.h>
#include <string.h>
void * destroy(char** args) {
int i = 0;
while(args[i]) free(args[i++]);
free(args);
return NULL;
}
void * recallocarray(void * ptr, size_t nmemb, size_t size, size_t oldLen) {
void * temp = calloc(nmemb, size);
memcpy(temp, ptr, oldLen * size);
free(ptr);
return temp;
}
|
C | #include "monty.h"
/**
* exe_operation - function that executes opcodes
* @op_command: opcode commamd
* @head: pointer to head
* @line_number: line number
*
* Return: void
*/
void exe_operation(char *op_command, stack_t **head, unsigned int line_number)
{
int i;
instruction_t all_ops[] = {
{"push", do_push},
{"pall", do_pall},
{"pint", do_pint},
{"pop", do_pop},
{"add", do_add},
{"sub", do_sub},
{"mul", do_mul},
{"div", do_div},
{"mod", do_mod},
{"swap", do_swap},
{"nop", do_nop},
{"pchar", do_pchar},
{"rotl", do_rotl},
{"rotr", do_rotr},
{"pstr", do_pstr},
{NULL, NULL}
};
for (i = 0; all_ops[i].opcode; i++)
{
if (strcmp(op_command, all_ops[i].opcode) == 0)
{
all_ops[i].f(head, line_number);
return;
}
}
if (op_command[0] != '#' && strlen(op_command) != 0)
{
dprintf(STDERR_FILENO, "L%u: unknown instruction %s\n", line_number,
op_command);
free_fp_line();
exit(EXIT_FAILURE);
}
}
|
C | //
// Created by Chao Yang on 2019-04-22.
//
#include "util.h"
#include <stddef.h>
uint32_t
bytes_to_u32(uintptr_t addr) {
uint32_t u32 = 0;
for(int i = 0; i < 4; i++) {
uint8_t* ptr = (void*)(addr + i);
u32 |= ((*ptr) << (i * 8));
}
return u32;
}
uint64_t
bytes_to_u64(uintptr_t addr) {
uint64_t u64 = 0;
uint8_t* ptr;
for(size_t i = 0; i < 8; i++) {
ptr = (void*)(addr + i);
u64 |= ((*ptr) << (i << 3));
}
return u64;
} |
C | #include "common.h"
void convert_to_data(uint64_t value, int size, unsigned char * data) {
for (int i = 0; i < size; i++) {
data[i] = 0;
data[i] = value >> ((size - i - 1) * 8) & 255;
}
}
uint64_t convert_from_data(int size, unsigned char * data) {
uint64_t value = 0;
for (int i = 0; i < size; i++) {
value |= data[i] << ((size - i - 1) * 8);
}
return value;
}
|
C | #include <stdlib.h>
#include <sys/resource.h>
#include "png.h"
int main(int argc, char** argv) {
void writeImage(FILE *file, png_bytepp data, int width, int height) {
png_structp p = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
png_infop info = png_create_info_struct(p);
setjmp(png_jmpbuf(p));
png_init_io(p, file);
png_set_rows(p, info, data);
png_set_IHDR(p, info, width, height,
8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_ADAM7,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_write_png(p, info, 0, png_voidp_NULL);
png_destroy_write_struct(&p, &info);
}
void write_png(int width, int height) {
png_bytepp getData(png_bytepp rows, png_bytep image) {
for (int i = 0; i < height; ++i) {
rows[i] = image + width * 3 * i;
for (int j = 0; j < width; ++j) {
void setData(png_bytep dest, int x, int y) {
int horiz = y > 3 && y < 6;
int vert = x > 4 && x < 7;
dest[0] = (vert || horiz) * 255;
dest[1] = (vert || horiz) * 255;
dest[2] = !(vert || horiz) * 255;
}
setData(rows[i] + j * 3, j * 16 / width, i * 10 / height);
}
}
return rows;
}
png_bytep rows[height];
png_byte image[width * 3 * height];
writeImage(stdout, getData(rows, image), width, height);
}
int height = 400;
if (argc > 1) {
sscanf(argv[1], "%d", &height);
}
if (height > 1200) {
struct rlimit rl;
getrlimit(RLIMIT_STACK, &rl);
int rlim_cur = rl.rlim_cur;
printf("%d\n", rlim_cur);
rl.rlim_cur = 8720000 * 8;
setrlimit(RLIMIT_STACK, &rl);
}
write_png(height / 10 * 16, height);
}
|
C | #include <stdio.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
struct s {
int one;
char two;
};
/*
* This function is intended to simulate a function that is passed a
* value for which it needs to get the struct that the value is a member
* of.
*/
void something(char* value) {
struct s* sp = container_of(value, struct s, two);
printf("struct for two:%p\n", sp);
printf("sp.two: %c\n", sp->two);
}
int main(int argc, char** argv) {
// the following is a gnu extension called brace-group within expression
// where the compiler will evaluate the complete block and use the last
// value in the block:
int nr = ( { int x = 10; x + 4; } );
printf("nr:%d\n", nr);
// Notice that this is used in the container_of macro, it returns the
// value from the last statement.
//
int x = 1;
typeof(x) y = 2;
printf("%d %d\n", x, y);
int* p = &((struct s*)0)->one;
char* p2 = &((struct s*)0)->two;
printf("%p\n", p);
printf("%p\n", p2);
struct s s1;
struct s* sp = container_of(&s1.two, struct s, two);
struct s s2 = {1, 'a'};
printf("s=%p\n", &s2);
printf("s.two=%c\n", s2.two);
something(&s2.two);
return 0;
}
|
C | /*
gcc -std=c17 -lc -lm -pthread -o ../_build/c/string_wide_iswblank.exe ./c/string_wide_iswblank.c && (cd ../_build/c/;./string_wide_iswblank.exe)
https://en.cppreference.com/w/c/string/wide/iswblank
*/
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u3000'; // Ideographic space (' ')
printf("in the default locale, iswblank(%#x) = %d\n", c, !!iswblank(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswblank(%#x) = %d\n", c, !!iswblank(c));
}
|
C | #include <stdio.h>
#include <unistd.h>
int main()
{
// Iteratively double i
for (int i = 1;; i *= 2)
{
printf("%i\n", i);
sleep(1);
}
return 0;
} |
C | #include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
#include "arpa/inet.h"
#include "sys/socket.h"
//定义监听端口
#define PORT 8080
/**
* 处理浏览器请求
* 参数 *sock 客户端套接字地址
*/
void requestHandling(void *sock);
//发送数据
void sendData(void *sock, char *filename);
//显示html
void catHTML(void *sock, char *filename);
//显示图片
void catJPEG(void *sock, char *filename);
//定义错误处理句柄
void errorHandling(char *message);
int main(int argc, char *argv[]){
//保存创建的服务器端套接字
int serv_sock;
//保存接受请求的客户端套接字
int clnt_sock;
//缓冲区
char buf[1024];
//保存服务器套接字地址信息
struct sockaddr_in serv_addr;
//保存客户端套接字地址信息
struct sockaddr_in clnt_addr;
//套接字地址变量的大小
socklen_t clnt_addr_size;
//发送给客户端的固定内容
char status[] = "HTTP/1.0 200 OK\r\n";
char header[] = "Server: A Simple Web Server\r\nContent-Type: text/html\r\n\r\n";
char body[] = "<html><head><title>A Simple Web Server</title><head><body><h1>This is my first Web server</h1></body></html>";
//创建一个服务器套接字
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
if(-1 == serv_sock){
errorHandling("Socket error()");
}
//配置套接字IP和端口信息
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(PORT);
//绑定服务器套接字
if (-1 == bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
errorHandling("bind() error");
}
//监听服务器套接字
if(-1 == listen(serv_sock, 5)){
errorHandling("listen() error");
}
//接受客户端的请求
clnt_addr_size = sizeof(clnt_addr);
clnt_sock = accept(serv_sock,(struct sockaddr *) &clnt_addr, &clnt_addr_size);
if (-1 ==clnt_sock) {
errorHandling("accept() error");
}
//读取客户端请求
read(clnt_sock, buf, sizeof(buf) -1);
printf("%s\n", buf);
//向客户端套接字发送信息
write(clnt_sock, status, sizeof(status));
write(clnt_sock, header, sizeof(header));
write(clnt_sock, body, sizeof(body));
//关闭套接字
close(clnt_sock);
close(serv_sock);
return 0;
}
//错误处理函数
void errorHandling(char *message){
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#define SIZE 8
typedef int data_t;
typedef struct list{
data_t data[SIZE]; //保存数据的空间
int last; //保存最后一个有效元素的下标
}list_t;
/*返回创建好的 空顺序表 的地址*/
list_t *creat_list()
{
list_t *p;
p = malloc(sizeof(list_t));//申请空间
p->last = -1; //初始化 结构内部相应内容
return p;
}
/*
* p: 顺序表的地址
* index:插入的下标位置
* data:插入的数据
*
* return:成功返回0 ;失败返回-1
* */
int ins_index_list(list_t *p,int index,data_t data)
{
//1.将插入位置的数据向下移动
// 1.1 移动最后一个 到下一个位置 data[last + 1] = data[last];
// 1.2 移动倒数第二个
// 1.3 。。。。
//
//2.写入数据到对应位置
//3. last ++
int i;
if(SIZE - 1 == p->last) // 如果容器满 直接退出
return -1;
if(index < 0 || index > p->last + 1)
return -2;
for(i = p->last;i >= index;i --){
p->data[i + 1] = p->data[i];
}
p->data[index] = data;
p->last ++; // (*p).last
return 0;
}
int del_index_list(list_t *p,int index)
{
//1.移动删除位置之下的数据
// 1.1 index + 1 位置的数据到 index
// 1.2 index + 2 index + 1
// ....
//2.last --
int i;
if(-1 == p->last) //如果为空,则退出
return -1;
if(index < 0 || index > p->last)
return -2;
for(i = index;i < p->last;i ++){
p->data[i] = p->data[i + 1];
}
p->last --; //p->last // (*p).last
return 0;
}
void print_list(list_t *p)
{
int i;
for(i = 0;i <= p->last;i ++){// 打印数据集合里的内容
printf("%d ",p->data[i]);
}
printf("\n");
printf("last:%d\n",p->last);//打印
//最后一个元素位置
return ;
}
int main(int argc, const char *argv[])
{
list_t *p;
list_t *p1;
int i;
p = creat_list();
p1 = creat_list();
for(i = 6;i >= 0;i --){
ins_index_list(p,0,i);
}
print_list(p);
del_index_list(p,7);
print_list(p);
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "utone.h"
typedef struct {
ut_fof *fof;
ut_ftbl *sine;
ut_ftbl *win;
} UserData;
void process(ut_data *ut, void *udata) {
UserData *ud = udata;
UTFLOAT osc = 0, fof = 0;
ut_fof_compute(ut, ud->fof, &osc, &fof);
ut->out[0] = fof;
}
int main() {
srand(1234567);
UserData ud;
ut_data *ut;
ut_create(&ut);
ut_ftbl_create(ut, &ud.sine, 2048);
ut_ftbl_create(ut, &ud.win, 1024);
ut_fof_create(&ud.fof);
ut_gen_sine(ut, ud.sine);
ut_gen_composite(ut, ud.win, "0.5 0.5 270 0.5");
ut_fof_init(ut, ud.fof, ud.sine, ud.win, 100, 0);
ut->len = 44100 * 10;
ut_process(ut, &ud, process);
ut_fof_destroy(&ud.fof);
ut_ftbl_destroy(&ud.sine);
ut_ftbl_destroy(&ud.win);
ut_destroy(&ut);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <regex.h>
void SolveMaze(char *maze, int width, int height) {
int dir, count;
int x, y;
int dx, dy;
int forward;
/* Remove the entry and exit. */
maze[0 * width + 1] = 1;
maze[(height - 1) * width + (width - 2)] = 1;
forward = 1;
dir = 0;
count = 0;
x = 1;
y = 1;
while(x != width - 2 || y != height - 2) {
dx = 0; dy = 0;
switch(dir) {
case 0: dx = 1; break;
case 1: dy = 1; break;
case 2: dx = -1; break;
default: dy = -1; break;
}
if( (forward && maze[(y + dy) * width + (x + dx)] == 0)
|| (!forward && maze[(y + dy) * width + (x + dx)] == 2)) {
maze[y * width + x] = forward ? 2 : 3;
x += dx;
y += dy;
forward = 1;
count = 0;
dir = 0;
} else {
dir = (dir + 1) % 4;
count += 1;
if(count > 3) {
forward = 0;
count = 0;
}
}
}
/* Replace the entry and exit. */
maze[(height - 2) * width + (width - 2)] = 2;
maze[(height - 1) * width + (width - 2)] = 2;
}
int main(int argc, char *argv[]) {
int width, height;
char *maze;
/* Open file */
FILE *fp = fopen(argv[1] , "r");
/* Get maze width and height */
height = 0;
width = fp.regex();
if(!width || !height){
printf("error: illegal size /n");
exit(EXIT_FAILURE);
}
/* Get maze */
maze = (char*)"";
if(maze == NULL) {
printf("error: maze not found");
exit(EXIT_FAILURE);
}
/* Solve maze */
SolveMaze(maze, width, height);
/* Clean up. */
fclose(fp);
free(maze);
free(width);
free(height);
exit(EXIT_SUCCESS);
} |
C | #include<stdio.h>
//declaration of structure
struct node
{
int info;
struct node *next;
};
//create function
struct node *create()
{
struct node *root,*newnode,*temp,*prev;
root=NULL;
int n;
printf("enter no(-999 to stop) = ");
scanf("%d",&n);
while(n!=-999)
{
newnode=(struct node*)malloc(sizeof(struct node));
newnode->info=n;
newnode->next=NULL;
if(root==NULL)
root=newnode;
else
prev->next=newnode;
prev=newnode;
printf("enter no(-999 to stop) = ");
scanf("%d",&n);
}
return (root);
}
//display function
void display(struct node *s)
{
while(s!=NULL)
{
printf("%d\t",s->info);
s=s->next;
}
printf("\n");
}
//max function
int max(struct node *s)
{
int max=0;
while(s!=NULL)
{
if(max<=s->info)
max=s->info;
s=s->next;
}
return max;
}
//length function
int len(struct node *s)
{
int l=0;
while(s!=NULL)
{
l++;
s=s->next;
}
return l;
}
//search function
void search(struct node *s,int x)
{
int c=0,l=0;
while(s!=NULL)
{
c++;
if(s->info==x)
{
l++;
printf("%d\t",c);
}
s=s->next;
}
if(l==0)
printf("-1\n");
else
printf("\n");
}
//replace function
void replace(struct node *s,int x,int y)
{
while(s!=NULL)
{
if(s->info==x)
{
s->info=y;
}
s=s->next;
}
}
//sorting
void sort(struct node *s)
{
struct node *r;
int temp;
while(s!=NULL)
{
r=s;
while(r!=NULL)
{
if(s->info>=r->info)
{
temp=r->info;
r->info=s->info;
s->info=temp;
}
r=r->next;
}
s=s->next;
}
}
//reverse
struct node* reverse(struct node *s)
{
struct node *save,*prev,*current;
current=s;
prev=NULL;
while(current!=NULL)
{
save=current->next;
current->next=prev;
prev=current;
current=save;
}
return(prev);
}
//merge two list
struct node* merge(struct node *s1,struct node *s2)
{
struct node *newnode,*prev,*root;
root=NULL;
while(s1!=NULL)
{
newnode=(struct node *)malloc(sizeof(struct node));
newnode->info=s1->info;
newnode->next=NULL;
if(root==NULL)
root=newnode;
else
prev->next=newnode;
prev=newnode;
s1=s1->next;
}
while(s2!=NULL)
{
newnode=(struct node *)malloc(sizeof(struct node));
newnode->info=s2->info;
newnode->next=NULL;
prev->next=newnode;
prev=newnode;
s2=s2->next;
}
return(root);
}
//main function
void main()
{
struct node *start,*s1,*s2,*s3;
int c,maximum,l,x,y;
start=create();
read:
printf("enter choice \n 1 to display list \n 2 to display max \n 3 to find length of list \n 4 to search a number in list \n 5 to replace number in list \n 6 to sort list \n 7 to reverse list \n 8 to merge two list \n 0 to exit \n");
scanf("%d",&c);
switch(c)
{
case 0:
break;
case 1:
display(start);goto read;
case 2:
maximum=max(start);
printf("maximum in list = %d\n",maximum);
goto read;
case 3:
l=len(start);
printf("length of list = %d\n",l);
goto read;
case 4:
printf("enter number to search = ");
scanf("%d",&x);
search(start,x);
goto read;
case 5:
printf("enter number to be replaced = ");
scanf("%d",&x);
printf("enter new number = ");
scanf("%d",&y);
replace(start,x,y);
goto read;
case 6:
sort(start);
goto read;
case 7:
start=reverse(start);
goto read;
case 8:
s1=create();
s2=create();
s3=merge(s1,s2);
display(s3);
goto read;
default:
printf("entered choice is wrong\n");
goto read;
}
}
|
C | #include <stdio.h>
#include "sfs.h"
struct workspace {
unsigned int task_no;
};
void common_task(void)
{
struct workspace *ws;
ws = SFS_work();
printf("task%d!\n",ws->task_no);
}
void regist_task1(void)
{
struct workspace *ws;
ws = SFS_work();
ws->task_no = 1;
SFS_change("TASK1", 0, common_task);
}
void regist_task2(void)
{
struct workspace *ws;
ws = SFS_work();
ws->task_no = 2;
SFS_change("TASK2", 0, common_task);
}
int main(void)
{
int loop=5;
SFS_initialize();
SFS_fork("Regist TASK1",0,regist_task1);
SFS_fork("Regist TASK2",0,regist_task2);
while(loop--)
SFS_dispatch();
return 0;
}
|
C | #include <stdio.h>
int med3(int a, int b, int c)
{
if (a >= b)
{
if(b >= c) return b;
else if (a <= c) return a;
else return c;
}
else if (a > c) return a;
else if (b > c) return c;
else return b;
}
int main(void)
{
int a, b, c;
printf("Get a median among three integers.\n");
printf("a : "); scanf("%d", &a);
printf("b : "); scanf("%d", &b);
printf("c : "); scanf("%d", &c);
printf("The median is %d.\n", med3(a, b, c));
return 0;
}
|
C | #include <stdio.h>
#include <Windows.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
//öͣλ
enum role { manager = 1, technician, saler, salemanager };//ö: Ա Ա ۾
//Աṹ
struct employee
{
int number;
char name[15];
int age;
char sex[5];
char department[10];//
enum role role;//λ
double salary;//
int worktime;//ʱ
double salesvolume;//۶
struct employee *next;
struct employee *last;
};
//////////////////////////////////////////////////
void welcomePage();//ӭ
void logo();//
void main_menu(struct employee *S);//˵
struct employee * readfile();//ļ
void writefile(struct employee *S);//дļ
void search_employee(struct employee *S);//ҹ
struct employee * change_employee(struct employee *p);//Ĺ
void out_employee(struct employee *S);//ҳǰ
void out_salary_employee(struct employee *S);//ͳƺйϢ
struct employee * add_employee(struct employee *S);//ӹ
struct employee * delete_employee(struct employee *S);//ɾ
void out_one_employee(struct employee *S);//ԱϢϢ
void out_one_salary_employee(struct employee *S);//ԱϢйϢ
int count_salemanager(struct employee *S, char department[10]);//жijǷ۾
double calculate_departmentSalesValue(struct employee *S, char department[10]);//ij۶
void list_page(struct employee * S);//ҳ
void list_out(struct employee * S);//ܷҳʾ
void page(struct employee * S);//ҳҳ
void sort_Salary(struct employee * S);//
void statistics(struct employee *S);//ͳƹ
struct employee * sta_salary(struct employee *S);//ͳƹ
//////////////////////////////////////////////////
int main();
|
C | #pragma once
//Basic set of indexeds for bool Keys array
// this enum spans from 0 to 73, so make sure to use KEYS_SIZE for the size of the array
#define KEYS_SIZE 74
enum KEYS{
KEY_A,
KEY_B,
KEY_C,
KEY_D,
KEY_E,
KEY_F,
KEY_G,
KEY_H,
KEY_I,
KEY_J,
KEY_K,
KEY_L,
KEY_M,
KEY_N,
KEY_O,
KEY_P,
KEY_Q,
KEY_R,
KEY_S,
KEY_T,
KEY_U,
KEY_V,
KEY_W,
KEY_X,
KEY_Y,
KEY_Z,
KEY_0,
KEY_1,
KEY_2,
KEY_3,
KEY_4,
KEY_5,
KEY_6,
KEY_7,
KEY_8,
KEY_9,
KEY_F1,
KEY_F2,
KEY_F3,
KEY_F4,
KEY_F5,
KEY_F6,
KEY_F7,
KEY_F8,
KEY_F9,
KEY_F10,
KEY_F11,
KEY_F12,
KEY_ESCAPE,
KEY_TILDE,
KEY_MINUS,
KEY_EQUALS,
KEY_BACKSPACE,
KEY_TAB,
KEY_OPENBRACE,
KEY_CLOSEBRACE,
KEY_ENTER,
KEY_SEMICOLON,
KEY_QUOTE,
KEY_BACKSLASH,
KEY_COMMA,
KEY_FULLSTOP,
KEY_SLASH,
KEY_SPACE,
KEY_INSERT,
KEY_DELETE,
KEY_HOME,
KEY_END,
KEY_PGUP,
KEY_PGDN,
KEY_LEFT,
KEY_RIGHT,
KEY_UP,
KEY_DOWN,
}; |
C | #include <stdio.h>
#include <stdlib.h>
struct passenger {
int floor;
int time;
};
struct passenger passengers[101];
int cmp_passenger(const void *left, const void *right)
{
struct passenger *l = (struct passenger *)left;
struct passenger *r = (struct passenger *)right;
return l->floor - r->floor;
}
int main()
{
int n, s;
scanf("%d %d", &n, &s);
for (int i = 0; i < n; i++) {
scanf("%d %d", &passengers[i].floor, &passengers[i].time);
}
qsort(passengers, n, sizeof(struct passenger), cmp_passenger);
int cur_floor = s, cur_time = 0;
for (int i = 0; i < n; i++) {
int delta = cur_floor - passengers[i].floor;
cur_time += delta;
cur_floor = passengers[i].floor;
if (cur_time < passengers[i].time) {
cur_time = passengers[i].time;
}
}
cur_time += cur_floor;
printf("%d\n", cur_time);
return 0;
}
|
C | #include <stdio.h>
int main() {
float result;
int addidition = 3 + 1;
//The result of our calculation*
result = (float)(addidition) / 5;
printf("The value of 4/5 is %f\n", result);
return 0;
}
|
C | //#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
typedef struct cache_entry_t {
char* filename;
struct cache_entry_t* next;
} cache_entry;
typedef struct cache_t {
cache_entry* file_cache;
signed short int cache_size;
} cache;
void cache_insert(cache* cache, char* filename);
void cache_remove(cache* cache, char* filename);
int contains_entry(cache* cache, char* filename);
void show_cache_entries(cache* cache);
int write_cache_updates(cache* cache);
|
C | #ifndef TOKEN_H_
#define TOKEN_H_
#include "common.h"
#define TOKEN_KINDS \
TOKEN_KIND(Error, "error") \
TOKEN_KIND(None, "none") \
TOKEN_KIND(Comment, "Comment") \
TOKEN_KIND(Eof, "EOF") \
TOKEN_KIND(IntLiteral, "integer literal") \
TOKEN_KIND(FloatLiteral, "float literal") \
TOKEN_KIND(StrLiteral, "string literal") \
TOKEN_KIND(CharLiteral, "character literal") \
TOKEN_KIND(Identifier, "identifier") \
TOKEN_KIND(OpenParen, "(") \
TOKEN_KIND(CloseParen, ")") \
TOKEN_KIND(OpenBrace, "[") \
TOKEN_KIND(CloseBrace, "]") \
TOKEN_KIND(OpenBracket, "{") \
TOKEN_KIND(CloseBracket, "}") \
TOKEN_KIND(Period, ".") \
TOKEN_KIND(PeriodPeriod, "..") \
TOKEN_KIND(Comma, ",") \
TOKEN_KIND(Colon, ":") \
TOKEN_KIND(Semicolon, ";") \
TOKEN_KIND(ColonColon, "::") \
TOKEN_KIND(Dollar, "$") \
TOKEN_KIND(At, "@") \
TOKEN_KIND(Plus, "+") \
TOKEN_KIND(Minus, "-") \
TOKEN_KIND(Slash, "/") \
TOKEN_KIND(Percent, "%") \
TOKEN_KIND(Astrick, "*") \
TOKEN_KIND(AstrickAstrick, "**") \
TOKEN_KIND(LessLess, "<<") \
TOKEN_KIND(GreaterGreater, ">>") \
TOKEN_KIND(Ampersand, "&") \
TOKEN_KIND(Pipe, "|") \
TOKEN_KIND(Carrot, "^") \
TOKEN_KIND(Tilde, "~") \
TOKEN_KIND(Bang, "!") \
TOKEN_KIND(Less, "<") \
TOKEN_KIND(Greater, ">") \
TOKEN_KIND(LessEqual, "<=") \
TOKEN_KIND(GreaterEqual, ">=") \
TOKEN_KIND(EqualEqual, "==") \
TOKEN_KIND(BangEqual, "!=") \
TOKEN_KIND(Equal, "=") \
TOKEN_KIND(PlusEqual, "+=") \
TOKEN_KIND(MinusEqual, "-=") \
TOKEN_KIND(AstrickEqual, "*=") \
TOKEN_KIND(SlashEqual, "/=") \
TOKEN_KIND(PercentEqual, "%=") \
TOKEN_KIND(AstrickAstrickEqual, "**=") \
TOKEN_KIND(LessLessEqual, "<<=") \
TOKEN_KIND(GreaterGreaterEqual, ">>=") \
TOKEN_KIND(CarrotEqual, "^=") \
TOKEN_KIND(AmpersandEqual, "&=") \
TOKEN_KIND(PipeEqual, "|=") \
TOKEN_KIND(Underscore, "_") \
TOKEN_KIND(If, "if") \
TOKEN_KIND(Else, "else") \
TOKEN_KIND(Let, "let") \
TOKEN_KIND(Mut, "mut") \
TOKEN_KIND(Fn, "fn") \
TOKEN_KIND(Type, "type") \
TOKEN_KIND(Struct, "struct") \
TOKEN_KIND(Enum, "enum") \
TOKEN_KIND(Break, "break") \
TOKEN_KIND(Continue, "continue") \
TOKEN_KIND(Return, "return") \
TOKEN_KIND(While, "while") \
TOKEN_KIND(For, "for") \
TOKEN_KIND(Match, "match") \
TOKEN_KIND(Sizeof, "sizeof") \
TOKEN_KIND(Alignof, "alignof") \
TOKEN_KIND(When, "when") \
TOKEN_KIND(Use, "use") \
TOKEN_KIND(And, "and") \
TOKEN_KIND(Or, "or") \
TOKEN_KIND(In, "in") \
TOKEN_KIND(True, "true") \
TOKEN_KIND(False, "false")
typedef enum TokenKind {
#define TOKEN_KIND(name, ...) Tkn_##name,
TOKEN_KINDS
#undef TOKEN_KIND
Num_Tokens
} TokenKind;
typedef enum ExpectedType {
NoType,
I8,
I16,
I32,
I64,
U8,
U16,
U32,
U64,
F32,
F64,
} ExpectedType;
typedef struct Token {
union {
i64 value_i64;
f64 value_float;
char value_char;
struct {
char* value;
u32 len;
} value_string;
} literal;
// this is only used for numberic literals
// it stores the original string value.
const char* string; // this will be set explicitly
u32 string_len;
TokenKind kind;
ExpectedType type;
u64 line;
u64 column;
u64 span;
u64 index;
} Token;
Token new_token(TokenKind kind, u64 line, u64 column, u64 span, u64 index);
Token new_integer_token(u64 value, u64 line, u64 column, u64 span, u64 index);
Token new_float_token(f32 value, u64 line, u64 column, u64 span, u64 index);
Token new_string_token(const char* value, u32 len, u64 line, u64 column, u64 span, u64 index);
Token new_identifier_token(const char* value, u32 len, u64 line, u64 column, u64 span, u64 index);
Token new_char_token(char value, u64 line, u64 column, u64 span, u64 index);
Token new_integer_token_type(u64 value, u64 line, u64 column, u64 span, u64 index, ExpectedType type);
Token new_float_token_type(f32 value, u64 line, u64 column, u64 span, u64 index, ExpectedType type);
Token new_char_token_type(char value, u64 line, u64 column, u64 span, u64 index, ExpectedType type);
void set_string(Token* token, const char* value);
const char* get_token_string(Token* token);
i64 get_integer(Token* token);
f32 get_float32(Token* token);
f64 get_float64(Token* token);
const char* get_string(Token* token);
const char** all_token_strings();
bool is_literal(Token* token);
bool is_identifier(Token* token);
bool is_operator(Token* token);
bool is_assignment(Token* token);
typedef enum Assoc {
Left,
Right
} Assoc;
u32 precedence(Token* token);
Assoc associative(Token* token);
TokenKind find_keyword(const char* str);
#endif
|
C | //Lăbău Cristea Andrei Liviu 314 CB
#include "utils.h"
Resource* get_page_resources(const char *URL_Name, int *n) {
int i, j, name_len, url_name_len = strlen(URL_Name);
unsigned int resource_nr = 0;
uint32_t size = 0;
if(URL_Name == NULL) {
return NULL;
}
for(i = 0; i < url_name_len; i++) {
resource_nr += URL_Name[i];
}
resource_nr %= 13;
Resource *result = (Resource *)calloc(resource_nr, sizeof(Resource));
*n = resource_nr;
for(i = 0; i < resource_nr; i++) {
sprintf(result[i].name, "%s-(%d)", URL_Name, i);
size = 0;
name_len = strlen(result[i].name);
for(j = 0; j < name_len; j++) {
size += result[i].name[j];
}
/* Some randomness */
size ^= size << 3;
size += size >> 5;
size ^= size << 4;
size += size >> 17;
size ^= size << 25;
size += size >> 6;
/* 100MB Maximum size */
result[i].dimension = size % 104857601;
result[i].currently_downloaded = 0;
}
return result;
}
/* Seteaza bandwith */
void setBand(TBrowser* brws, unsigned long bandwidth) {
brws -> bandwidth = bandwidth;
}
/* Initializeaza o structura pagina web */
TWebPage* AlocPage(char* url) {
int n = 0;
Resource* resources = get_page_resources(url, &n);
if(!resources) {
printf("ERROR: Can't get page resources.\n");
return NULL;
}
TWebPage* page = calloc(1,sizeof(TWebPage));
if(!page) {
return NULL;
}
strcpy(page -> url, url);
page -> num_res = n;
page -> resources = calloc(n, sizeof(Resource));
if(!page -> resources) {
return NULL;
}
memcpy(page -> resources, resources, n * sizeof(Resource));
return page;
}
/* Initializeaza o structura tab */
Tab* AlocTab() {
Tab* tab = calloc(1,sizeof(Tab));
if(!tab) {
return NULL;
}
tab -> current_page = calloc(1, sizeof(TWebPage));
tab -> back_stack = InitS(sizeof(TWebPage));
tab -> forward_stack = InitS(sizeof(TWebPage));
return tab;
}
/* Initializeaza structura browser */
TBrowser* OpenBrowser() {
TBrowser* browser = calloc(1, sizeof(TBrowser));
if(!browser) {
return NULL;
}
Tab* tab = AlocTab();
TLista* L = &(browser -> tabs);
InsertSf(L, tab);
browser -> current_tab = *L;
browser -> bandwidth = 1024;
browser -> time = 0;
browser -> historyQ = InitQ(21 * sizeof(char));
browser -> priorDownQ = InitQ(sizeof(Resource));
browser -> finishDownQ = InitQ(sizeof(Resource));
return browser;
}
/* Deschidere tab */
int OpenTab(TBrowser* brws) {
Tab* tab = AlocTab(); // se aloca un tab
TLista L = brws -> tabs;
InsertSf(&L, tab); // insereaza in lista de taburi
if(!L) {
return 0;
}
TLista p = L;
for(; p -> urm != NULL; p = p -> urm);
brws -> current_tab = p; // seteaza tabul curent
return 1;
}
/* Inchidere tab */
void DelTab(TBrowser* brws) {
TLista L = brws -> tabs;
TLista p = L, ant = NULL;
for(; p -> urm != NULL; ant = p, p = p -> urm);
if(p == brws -> current_tab) {
brws -> current_tab = ant;
}
ant -> urm = NULL;
free(p);
}
/* Schimba tabul curent */
void ChangeTab(TBrowser* brws, int index) {
TLista L = brws -> tabs;
TLista p = L;
int k = 0;
while (k < index) {
p = p -> urm;
k++;
}
brws -> current_tab = p;
}
/* Afiseaza url-ul paginii curente de pe un tab */
void DispTab(void* x, FILE* f) {
TWebPage* page = calloc(1, sizeof(TWebPage));
if(!page) {
exit(1);
}
memcpy(page, ((Tab*)x) -> current_page, sizeof(TWebPage));
if(!strcmp(page->url, "")) {
fprintf(f, "empty)\n");
}
else {
fprintf(f, "%s)\n", page -> url);
}
}
/* Afiseaza taburi deschise
* L = lista taburi
*/
void PrintOpenTabs(TLista L, void (*DispEl)(void* x, FILE* f), FILE* f) {
int nrTab = 0;
TLista p = L;
for(; p != NULL; p = p -> urm) {
fprintf(f, "(%d: ", nrTab);
DispEl(p -> info, f);
nrTab++;
}
}
/* Accesare adresa */
void Goto(TBrowser* brws, char* url) {
IntrQ(brws -> historyQ, url); // istoric global
TWebPage* page = AlocPage(url);
TLista tabCell = brws -> current_tab;
Tab* tab = (Tab*)tabCell -> info;
if(tab -> current_page) {
Push(tab -> back_stack, tab -> current_page); //
}
ResetS(tab -> forward_stack); // reset stiva
memcpy(tab -> current_page, page, sizeof(TWebPage));
}
/* Accesarea paginii anterioare */
int Back(TBrowser* brws, FILE* f) {
Tab* tab = (Tab*)brws -> current_tab -> info;
TWebPage* aux = calloc(1, sizeof(TWebPage));
if(!aux) {
return 0;
}
if(!VIDAST(tab -> back_stack)) {
Push(tab -> forward_stack, tab -> current_page);
Pop(tab -> back_stack, aux);
memcpy(tab -> current_page, aux, sizeof(TWebPage));
}
else {
fprintf(f, "can't go back, no pages in stack\n");
}
return 1;
}
/* Accesarea paginii urmatoare */
int Forward(TBrowser* brws, FILE* f) {
Tab* tab = (Tab*)brws -> current_tab -> info;
TWebPage* aux = calloc(1, sizeof(TWebPage));
if(!aux) {
return 0;
}
if(!VIDAST(tab -> forward_stack)) {
Push(tab -> back_stack, tab -> current_page);
Pop(tab -> forward_stack, aux);
memcpy(tab -> current_page, aux, sizeof(TWebPage));
}
else {
fprintf(f, "can't go forward, no pages in stack\n");
}
return 1;
}
/* Afiseaza un element de tip char */
void afisChar(void* el, FILE* f) {
fprintf(f, "%s\n", (char*)el);
}
/* Afisez coada istoricului global */
void AfisQ(TQueue* q, void (*afisEl)(void* x, FILE* f), FILE* f ) {
TQueue* aux = InitQ(21 * sizeof(char));
while(!VIDAQ(q)) { // daca am elemente in coada
void* elem = calloc(21, sizeof(char));
if(!elem) {
exit(1);
}
ExtrQ(q, elem); // extragere primul element
afisChar(elem, f); // afisare
IntrQ(aux, elem); // introducere in coada aux.
}
while(!VIDAQ(aux)) { // refacere coada initiala
void* elem = calloc(21, sizeof(char));
if(!elem) {
exit(1);
}
ExtrQ(aux, elem);
IntrQ(q, elem);
}
DistrQ(aux); // distruge lista initiala
}
/* Sterge primele nrEntries intrari din istoricul global */
void DelHistory(TQueue* q, int nrEntries) {
if(nrEntries == 0) {
ResetQ(q);
}
else {
int k = 0;
while(k < nrEntries) {
void* aux = calloc(21, sizeof(char));
if(!aux) {
exit(1);
}
ExtrQ(q, aux);
free(aux);
k++;
}
}
}
/* Afiseaza lista de resurse descarcarcabile ale unei pagini */
void AfisDownloads(TWebPage* page, FILE* f) {
Resource* res = page -> resources;
if(res) {
int nrRes = page -> num_res;
int i;
for(i = 0; i < nrRes; i++) {
fprintf(f, "[%d - ", i);
fprintf(f, "\"%s\" : ", res[i].name);
fprintf(f, "%ld]\n", res[i].dimension);
}
}
}
/* Descarca resursa cu indexul specificat */
int DownloadRes(TBrowser* brws, int index, FILE* f) {
TLista tabCell = brws -> current_tab;
Tab* tab = (Tab*)tabCell -> info;
TWebPage* page = tab -> current_page;
Resource* resource = calloc(1, sizeof(Resource));
if(!resource) {
return 0;
}
if(!page -> resources) {
return 0;
}
memcpy(resource, &page -> resources[index], sizeof(Resource));
unsigned long priority;
priority = resource -> dimension - resource -> currently_downloaded;
AQ auxQ = InitQ(sizeof(Resource));
if(VIDAQ(brws -> priorDownQ)) { // daca coada e goala
IntrQ(brws -> priorDownQ, resource); // introduc in varf
}
else {
int in = 0;
int ok = 1;
while(!VIDAQ(brws -> priorDownQ)) { // daca coada nu e goala
Resource* aux = calloc(1, sizeof(Resource));
if(!aux) {
return 0;
}
ExtrQ(brws -> priorDownQ, aux); // verific prioritatea
if(aux -> dimension - aux -> currently_downloaded < priority) {
IntrQ(auxQ, aux);
}
else {
in = 1;
if(ok == 1) { // resursa inca nu a fost adaugata
IntrQ(auxQ, resource); // adaug resursa
ok = 0;
}
IntrQ(auxQ, aux);
}
if(VIDAQ(brws -> priorDownQ) && in == 0) {
IntrQ(auxQ, resource); // resursa inca nu a fost adaugata
}
}
while(!VIDAQ(auxQ)) { // refac coada initiala
Resource* aux = calloc(1, sizeof(Resource));
if(!aux) {
return 0;
}
ExtrQ(auxQ, aux);
IntrQ(brws -> priorDownQ, aux);
}
DistrQ(auxQ); // eliberez coada auxiliara
}
return 1;
}
/* Simuleaza trecerea unei secunde la comanda goto */
void ModifyDown(AQ q, unsigned long bandwidth) {
AQ auxQ = InitQ(sizeof(Resource));
Resource* aux = calloc(1, sizeof(Resource));
if(!aux) {
exit(1);
}
ExtrQ(q, aux);
aux -> currently_downloaded += bandwidth; // actualizez cantitatea
IntrQ(auxQ, aux);
while(!VIDAQ(q)) { // introduc toate celelalte
Resource* aux2 = calloc(1, sizeof(Resource));
if(!aux) {
exit(1);
}
ExtrQ(q, aux2);
IntrQ(auxQ, aux2);
}
while(!VIDAQ(auxQ)) { // refac coada
Resource* aux2 = calloc(1, sizeof(Resource));
ExtrQ(auxQ, aux2);
IntrQ(q, aux2);
}
DistrQ(auxQ);
}
/* Afiseaza istoricul descarcarilor nefinalizate*/
void DispDownHistory(AQ q, FILE* f) {
TQueue* aux = InitQ(sizeof(Resource));
while(!VIDAQ(q)) {
Resource* elem = calloc(1, sizeof(Resource));
if(!elem) {
exit(1);
}
ExtrQ(q, elem); // extrag cate un element pentru afisare
unsigned long priority;
priority = elem -> dimension - elem -> currently_downloaded;
fprintf(f, "[\"%s\" : ", elem -> name);
fprintf(f, "%ld/%ld]\n", priority, elem -> dimension);
IntrQ(aux, elem); // intorduc in coada aux
}
while(!VIDAQ(aux)) { // refac coada initiala
Resource* elem = calloc(1, sizeof(Resource));
if(!elem) {
exit(1);
}
ExtrQ(aux, elem);
IntrQ(q, elem);
}
DistrQ(aux); // distrug coada auxiliara
}
/* Afiseaza istoricul descarcarilor finalizate */
void DispCompletedDown(AQ q, FILE* f) {
AQ aux = InitQ(sizeof(Resource));
while(!VIDAQ(q)) {
Resource* elem = calloc(1, sizeof(Resource));
if(!elem) {
exit(1);
}
ExtrQ(q, elem); // extrag cate un element pentru afisare
fprintf(f, "[\"%s\" : completed]\n", elem -> name);
IntrQ(aux, elem); // intorduc in coada aux
}
while(!VIDAQ(aux)) { // refac coada initiala
Resource* elem = calloc(1, sizeof(Resource));
if(!elem) {
exit(1);
}
ExtrQ(aux, elem);
IntrQ(q, elem);
}
}
void Wait(AQ downQ, AQ finishQ, unsigned long load) {
AQ auxQ1 = InitQ(sizeof(Resource));
while(!VIDAQ(downQ)) { // am elemente in coada
Resource* elem = calloc(1, sizeof(Resource));
if(!elem) {
exit(1);
}
ExtrQ(downQ, elem); // extrag cate un element
unsigned long remaining = elem -> dimension - elem -> currently_downloaded;
if(remaining > load) { // caz 1
elem -> currently_downloaded += load;
load = 0; // actualizez load
IntrQ(auxQ1, elem);
}
else if(remaining == load) { // caz 2
elem -> currently_downloaded += load; // actualizez load
load = 0;
IntrQ(finishQ, elem);
}
else if(remaining < load) { // caz 3
elem -> currently_downloaded += remaining;
load -= remaining; // actualizez load
IntrQ(finishQ, elem);
}
}
while(!VIDAQ(auxQ1)) { // refac coada initiala
Resource* elem = calloc(1, sizeof(Resource));
if(!elem) {
exit(1);
}
ExtrQ(auxQ1, elem);
IntrQ(downQ, elem);
}
DistrQ(auxQ1);
} |
C | #include<stdio.h>
int s(int *[]);
int main()
{
int a[5]={4,3,7,1,2};
int *b[5];
for (int i=0;i<5;i++)
{
b[i]=&a[i];
}
printf("before: \n");
for (int j=0;j<5;j++)
{
printf("A[%d] : %d\n",j,a[j]);
}
s(b);
printf("after:\n");
for (int j=0;j<5;j++)
{
printf("A[%d] : %d\n",j,a[j]);
}
}
int s(int *x[])
{
int i=4;
int temp;
for(int j=0;j<4;j++)
{
for(int z=0;z<i;z++)
{
if(*x[z]>*x[z+1])
{
temp=*x[z];
*x[z]=*x[z+1];
*x[z+1]=temp;
}
}
i--;
}
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int calculo_potencia(int base, int potencia);
int main(){
int base, potencia;
printf("Digite um valor para base (k) e o valor da potencia(n):\n");
scanf("%d %d", &base, &potencia);
calculo_potencia(base,potencia);
printf("%d", calculo_potencia(base,potencia));
}
int calculo_potencia(int base, int potencia){
if(potencia == 0){
return 1;
} else {
return (base * pow(base, potencia - 1));
}
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int SListDateType;
typedef struct SListNode
{
struct SListNode* _pNext;
SListDateType _data;
}SListNode;
SListNode* BuySListNode(SListDateType data)
{
SListNode* pNewNode = (SListNode*)malloc(sizeof(SListNode));
if (pNewNode == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
pNewNode->_data = data;
pNewNode->_pNext = NULL;
return pNewNode;
}
void SListPushBack(SListNode** pHead, SListDateType data)
{
//β
assert(pHead);
SListNode* pNewNode = BuySListNode(data);
if (*pHead == NULL)
*pHead = pNewNode;
else
{
SListNode* pCur = *pHead;
while (pCur->_pNext)
pCur = pCur->_pNext;
pCur->_pNext = pNewNode;
}
}
void PrintSList(SListNode* pHead)
{
SListNode* pCur = pHead;
while (pCur)
{
printf("%d->", pCur->_data);
pCur = pCur->_pNext;
}
printf("NULL\n");
}
SListNode* RemoveALL(SListNode** pHead, SListDateType data)
{
assert(pHead != NULL);
if (*pHead == NULL)
return NULL;
SListNode* cur = *pHead;
SListNode* new = NULL;
SListNode* new_tmp = NULL;
while (cur != NULL)
{
if (cur->_data != data)
{
if (new_tmp == NULL)
new_tmp = new = cur;
else
{
new_tmp->_pNext = cur;
new_tmp = cur;
}
}
cur = cur->_pNext;
}
new_tmp->_pNext = NULL;
return new;
}
SListNode* Reverse(SListNode** pHead)
{
assert(pHead != NULL);
if (*pHead == NULL)
return NULL;
if ((*pHead)->_pNext == NULL)
return *pHead;
SListNode* new = NULL;
SListNode* cur = *pHead;
while (cur != NULL)
{
SListNode* next = cur->_pNext;
cur->_pNext = new;
new = cur;
cur = next;
}
return new;
}
SListNode* FindMid(SListNode* pHead)
{
SListNode* fast = pHead;
SListNode* slow = pHead;
while (fast != NULL && fast->_pNext != NULL)
{
fast = fast->_pNext->_pNext;
slow = slow->_pNext;
}
return slow;
}
SListNode* FindK(SListNode* pHead, int k)
{
if (pHead == NULL)
return NULL;
SListNode* fast = pHead;
SListNode* slow = pHead;
int num = 0;
while (fast != NULL && num < k)
{
fast = fast->_pNext;
++num;
}
if(num < k)
return NULL;
else
{
while (fast != NULL)
{
fast = fast->_pNext;
slow = slow->_pNext;
}
return slow;
}
}
SListNode* cat(SListNode** l1, SListNode** l2)
{
assert(l1 != NULL && l2 != NULL);
SListNode* new = NULL;
SListNode* c1 = *l1;
SListNode* c2 = *l2;
SListNode* new_tmp = NULL;
while (c1 != NULL && c2 != NULL)
{
if (c1->_data <= c2->_data)
{
if (new_tmp != NULL)
{
new_tmp->_pNext = c1;
new_tmp = c1;
}
else
new = new_tmp = c1;
c1 = c1->_pNext;
}
else
{
if (new_tmp != NULL)
{
new_tmp->_pNext = c2;
new_tmp = c2;
}
else
new = new_tmp = c2;
c2 = c2->_pNext;
}
}
if (c1 == NULL)
new_tmp->_pNext = c2;
else
new_tmp->_pNext = c1;
return new;
}
SListNode* fenge(SListNode** pHead, SListDateType data)
{
assert(pHead != NULL);
SListNode* cur = *pHead;
SListNode* min = NULL;
SListNode* min_tmp = NULL;
SListNode* max = NULL;
SListNode* max_tmp = NULL;
while (cur != NULL)
{
if(cur->_data<=data)
{
if (min_tmp == NULL)
min = min_tmp = cur;
else
{
min_tmp->_pNext = cur;
min_tmp = cur;
}
}
else
{
if (max_tmp == NULL)
max = max_tmp = cur;
else
{
max_tmp->_pNext = cur;
max_tmp = cur;
}
}
cur = cur->_pNext;
}
if (min_tmp == NULL)//ûСdata
return max;
if (max_tmp->_pNext != NULL)
//һdataĩ
//滹һСdata,nextΪ
//ͳһ
max_tmp->_pNext = NULL;
min_tmp->_pNext = max;
return min;
}
SListNode* DelateDuplacation(SListNode** pHead)
{
//,ͬʱ,,p1,p2
//Ҫͷp1,Ҫһֱp1ǰڵ
assert(pHead != NULL);
if (*pHead == NULL)
return NULL;
SListNode* fake = (SListNode*)malloc(sizeof(SListNode));//(ٽڵ)
fake->_pNext = *pHead;
SListNode* pre = fake;
SListNode* p1 = *pHead;
SListNode* p2 = (*pHead)->_pNext;
while (p2 != NULL)
{
if (p1->_data != p2->_data)
{
pre = p1;
p1 = p2;
p2 = p2->_pNext;
}
else
{
while (p2 != NULL && p2->_data == p1->_data)
p2 = p2->_pNext;
while (p1 != p2)
{
SListNode* cur = p1;
p1 = p1->_pNext;
free(cur);
}
pre->_pNext = p2;
if(p2!=NULL)
p2 = p2->_pNext;
}
}
(*pHead) = fake->_pNext;
free(fake);
return *pHead;
}
int main()
{
SListNode* pHead = NULL;
SListNode* l2 = NULL;
SListPushBack(&pHead, 2);
SListPushBack(&pHead, 2);
SListPushBack(&pHead, 1);
SListPushBack(&pHead, 3);
SListPushBack(&pHead, 3);
PrintSList(pHead);
SListNode* new = IsMidNode(&pHead);
PrintSList(new);
system("pause");
}
Node* Copy(Node* head)
//ֿ
//һ,ֻƽڵvaluenext,½ڵϽڵ
//ڶ,randomĸ
//,
{
Node* cur_head = head;
while (cur_head != NULL)
{
Node* newnode = (Node*)malloc(Node);
newnode->value = cur_head->value;
newnode->next = cur_head->next;
cur_head->next = newnode;
cur_head = newnode->next;
}
cur_head = head;
while (cur_head != NULL)
{
Node* newnode = cur_head->next;
if (cur_head->random == NULL)
newnode->random = cur_head->random;
else
{
newnode->random = cur_head->random->next;
}
cur_head = cur_head->next->next;
}
cur_head = head;
while (cur_head != NULL)
{
Node* newnode = cur_head->next;
cur_head->next = newnode->next;
newnode->next = cur_head->next->next;
cur_head = cur_head->next;
}
} |
C | #include <stdio.h>
int main() {
/* Izlaz */
if (padavine=='d' || padavine=='D') {
printf("Ne odgovara niti jedan grad.");
} else if (padavine=='n' || padavine=='N') {
if (temperatura>-5 && temperatura<30) {
printf("Elma i Anja mogu u Sarajevo.");
}
else if (temperatura<5) {
printf("Anja i Una mogu u Sarajevo");
}
else if (temperatura>20) {
printf("Anja i Una mogu u Sarajevo");
}
else if (temperatura>-5 && temperatura<5) {
printf("Drugarice idu u Sarajevo");
}
}
return 0;
}
|
C | /*
* test_crypto.c
*
* Performs a simple encryption-decryption
* of random data from /dev/urandom with the
* use of the cryptodev device.
*
* Stefanos Gerangelos <[email protected]>
* Vangelis Koukis <[email protected]>
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <crypto/cryptodev.h>
#define DATA_SIZE 256
#define BLOCK_SIZE 16
#define KEY_SIZE 16 /* AES128 */
/* Insist until all of the data has been read */
ssize_t insist_read(int fd, void *buf, size_t cnt)
{
ssize_t ret;
size_t orig_cnt = cnt;
while (cnt > 0) {
ret = read(fd, buf, cnt);
if (ret < 0)
return ret;
buf += ret;
cnt -= ret;
}
return orig_cnt;
}
static int fill_urandom_buf(unsigned char *buf, size_t cnt)
{
int crypto_fd;
int ret = -1;
crypto_fd = open("/dev/urandom", O_RDONLY);
if (crypto_fd < 0)
return crypto_fd;
ret = insist_read(crypto_fd, buf, cnt);
close(crypto_fd);
return ret;
}
static int test_crypto(int cfd)
{
int i = -1;
struct session_op sess;
struct crypt_op cryp;
struct {
unsigned char in[DATA_SIZE],
encrypted[DATA_SIZE],
decrypted[DATA_SIZE],
iv[BLOCK_SIZE],
key[KEY_SIZE];
} data;
memset(&sess, 0, sizeof(sess));
memset(&cryp, 0, sizeof(cryp));
/*
* Use random values for the encryption key,
* the initialization vector (IV), and the
* data to be encrypted
*/
if (fill_urandom_buf(data.in, DATA_SIZE) < 0) {
perror("getting data from /dev/urandom\n");
return 1;
}
if (fill_urandom_buf(data.iv, BLOCK_SIZE) < 0) {
perror("getting data from /dev/urandom\n");
return 1;
}
if (fill_urandom_buf(data.key, KEY_SIZE) < 0) {
perror("getting data from /dev/urandom\n");
return 1;
}
printf("\nOriginal data:\n");
for (i = 0; i < DATA_SIZE; i++)
printf("%x", data.in[i]);
printf("\n");
/*
* Get crypto session for AES128
*/
sess.cipher = CRYPTO_AES_CBC;
sess.keylen = KEY_SIZE;
sess.key = data.key;
if (ioctl(cfd, CIOCGSESSION, &sess)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
/*
* Encrypt data.in to data.encrypted
*/
cryp.ses = sess.ses;
cryp.len = sizeof(data.in);
cryp.src = data.in;
cryp.dst = data.encrypted;
cryp.iv = data.iv;
cryp.op = COP_ENCRYPT;
if (ioctl(cfd, CIOCCRYPT, &cryp)) {
perror("ioctl(CIOCCRYPT)");
return 1;
}
printf("\nEncrypted data:\n");
for (i = 0; i < DATA_SIZE; i++) {
printf("%x", data.encrypted[i]);
}
printf("\n");
/*
* Decrypt data.encrypted to data.decrypted
*/
cryp.src = data.encrypted;
cryp.dst = data.decrypted;
cryp.op = COP_DECRYPT;
if (ioctl(cfd, CIOCCRYPT, &cryp)) {
perror("ioctl(CIOCCRYPT)");
return 1;
}
printf("\nDecrypted data:\n");
for (i = 0; i < DATA_SIZE; i++) {
printf("%x", data.decrypted[i]);
}
printf("\n");
/* Verify the result */
if (memcmp(data.in, data.decrypted, sizeof(data.in)) != 0) {
fprintf(stderr, "\nFAIL: Decrypted and original data differ.\n");
return 1;
} else
fprintf(stderr, "\nTest passed.\n");
/* Finish crypto session */
if (ioctl(cfd, CIOCFSESSION, &sess.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
return 0;
}
int main(void)
{
int fd;
fd = open("/dev/cryptodev0", O_RDWR);
if (fd < 0) {
perror("open(/dev/crypto)");
return 1;
}
if (test_crypto(fd) < 0) {
return 1;
}
if (close(fd) < 0) {
perror("close(fd)");
return 1;
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_type.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dheredat <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/22 14:46:10 by dheredat #+# #+# */
/* Updated: 2020/09/02 22:07:56 by dheredat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/asm.h"
/*
** Описание p[5]
** + 0 - Имя
** + 1 - Комментарий чемпиона
** + 2 - пустая строка
** + 3 - Начало метки
** + 4 - Инструкция
*/
static int is_name(char *str)
{
size_t i;
i = 0;
while (i < ft_strlen(NAME_CMD_STRING) &&
str[i] && str[i] == NAME_CMD_STRING[i])
i++;
if (str[i] && (str[i] != ' ' && str[i] != '\t' && str[i] != '"'))
return (0);
return (i == ft_strlen(NAME_CMD_STRING) ? 1 : 0);
}
static int is_comment(char *str)
{
size_t i;
i = 0;
while (i < ft_strlen(COMMENT_CMD_STRING) &&
str[i] && str[i] == COMMENT_CMD_STRING[i])
i++;
if (str[i] && (str[i] != ' ' && str[i] != '\t' && str[i] != '"'))
return (0);
return (i == ft_strlen(COMMENT_CMD_STRING) ? 1 : 0);
}
static int is_namecomm(char *str)
{
if (is_name(str))
return (0);
else if (is_comment(str))
return (1);
else
return (-1);
}
static int is_labelinst(char *str)
{
if (is_label(str))
return (3);
else if (is_inst(str) > 0)
return (4);
else
return (-1);
}
int get_type(char **str, int bytes, int fd, t_hero **hero)
{
int type;
char *s;
if (!*str && bytes == -2)
quit(EN_MALLOC, NULL, NULL);
if (!(s = ft_str_white_trim(*str)))
{
ft_strdel(&s);
return (2);
}
if ((ft_strlen(s) == 1 && *s == '\n')
|| s[0] == COMMENT_CHAR || s[0] == ALT_COMMENT_CHAR)
{
ft_strdel(&s);
ft_strdel(str);
return (2);
}
ft_strdel(str);
if (((type = is_namecomm(s)) != -1))
if (check_namecomm(&s, type, fd, hero) >= 0)
return (type);
if ((type = is_labelinst(s)) > 0)
return (parse_instruct(s, type, fd, hero));
ft_strdel(&s);
return (-1);
}
|
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
int Cmd_Argc () ;
char* Cmd_Argv (int) ;
int /*<<< orphan*/ Com_Printf (char*) ;
int /*<<< orphan*/ Cvar_Set2 (char*,char*,int /*<<< orphan*/ ) ;
int MAX_STRING_TOKENS ;
int /*<<< orphan*/ qfalse ;
int /*<<< orphan*/ strcat (char*,char*) ;
int strlen (char*) ;
void Cvar_Set_f( void ) {
int i, c, l, len;
char combined[MAX_STRING_TOKENS];
c = Cmd_Argc();
if ( c < 3 ) {
Com_Printf ("usage: set <variable> <value>\n");
return;
}
combined[0] = 0;
l = 0;
for ( i = 2 ; i < c ; i++ ) {
len = strlen ( Cmd_Argv( i ) + 1 );
if ( l + len >= MAX_STRING_TOKENS - 2 ) {
break;
}
strcat( combined, Cmd_Argv( i ) );
if ( i != c-1 ) {
strcat( combined, " " );
}
l += len;
}
Cvar_Set2 (Cmd_Argv(1), combined, qfalse);
} |
C | #include "stdlib.h"
#define ATEXIT_MAX (8)
typedef void (*AtexitFunc)(void);
static AtexitFunc __atexit_funcs[ATEXIT_MAX];
static int __atexit_count;
int atexit(void (*func)(void)) {
int count = __atexit_count;
if (count >= ATEXIT_MAX)
return 1;
__atexit_funcs[count] = func;
++__atexit_count;
return 0;
}
void __atexit_call(void) {
for (AtexitFunc *p = &__atexit_funcs[__atexit_count]; p > __atexit_funcs; )
(*(--p))();
}
|
C | /* Program name: prime3.c
Author : Atish Jain
IDE: C-Free 5.0
Task : Program to check whether the given no is prime or not - Logic 3 */
# include <stdio.h>
main()
{
int no,d=2,count=0;
char isprime='y';
printf("Enter a no....:");
scanf("%d",&no);
while(d<(no/2))
{
count++;
if(no%d==0)
{
isprime='n';
break;
}
d++;
}
if(isprime=='y')
printf("%d is Prime....",no);
else
printf("%d is Not Prime....",no);
printf("\n\nNo of Repetitions are:%d",count);
printf("\n");
} |
C | #include <stdio.h>
int main () {
printf("%d\n",exame(5));
}
int exame (int n) {
int a;
int b = 1;
int current = 2;
for (int i = 2; i < n; i++) {
a = b;
b = current;
current = (1 + b) / a;
}
return current;
} |
C | //
// main.c
// 计算位数
//
// Created by edz on 2020/8/3.
// Copyright © 2020 edz. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
int num, count=0;
printf("Enter a number: ");
scanf("%d", &num);
do {
num = num / 10 ;
count++;
} while (num !=0);
printf("%d\n",count);
return 0;
}
|
C | # include <string.h>
# include <stdio.h>
# include "openAddressingOperations.h"
/* Returns the number of probes as a metric of efficiency. */
long openAddressTable_Insert (OpenAddressTable *oaTable, void *elem) {
long h, i, k, slotKey;
char *slot;
/* Put the elem key into a long variable. */
k = keyCopy((char*)elem + oaTable->keyOffset, oaTable->keySize);
for (i = 0; i < oaTable->m; ++i) {
/* Get the hash for the given key and probe number. */
h = oaTable->hfunc(k, oaTable->m, i);
slot = (char*)(oaTable->table) + (oaTable->elemSize * h);
slotKey = keyCopy(slot + oaTable->keyOffset, oaTable->keySize);
if ((slotKey == oaTable->emptyFlag) || (slotKey == oaTable->deletedFlag)) {
memcpy(slot, elem, oaTable->elemSize);
return i;
}
}
return TABLE_FULL;
}
long openAddressTable_Search (OpenAddressTable *oaTable, void *key) {
long h, i, k, m, slotKey;
char *slot;
k = keyCopy(key, oaTable->keySize);
m = oaTable->m;
for (i = 0; i < m; ++i) {
h = oaTable->hfunc(k, m, i);
slot = (char*)(oaTable->table) + (oaTable->elemSize * h);
slotKey = keyCopy(slot + oaTable->keyOffset, oaTable->keySize);
if (slotKey == k) {
return h;
} else if (slotKey == oaTable->deletedFlag) {
continue;
} else if (slotKey == oaTable->emptyFlag) {
break;
}
}
return NOT_FOUND;
}
void openAddressTable_Delete (OpenAddressTable *oaTable, void *elem) {
long slotNum;
void *slot;
size_t keyOffset = oaTable->keyOffset;
slotNum = openAddressTable_Search(oaTable, ((char*)elem) + oaTable->keyOffset);
if(slotNum != NOT_FOUND) {
slot = (char*)(oaTable->table) + (slotNum * oaTable->elemSize);
memcpy(slot + keyOffset, &(oaTable->deletedFlag), oaTable->keySize);
}
}
/* Endian independent copying of key of size lte sizeof(long) into a long. */
/* http://www.ibm.com/developerworks/aix/library/au-endianc/ */
long keyCopy (void *key, int keySize) {
long keyCopy = 0L;
signed char *kc = (signed char*)&keyCopy;
signed char *k = (signed char*)key;
int i = 1;
int offset;
if (*((char*)&i)) {
for(i=0; i < keySize; ++i) {
kc[i] |= k[i];
}
if (k[i-1] < 0) {
for (; i < sizeof(long); ++i) {
kc[i] |= -1;
}
}
} else {
offset = sizeof(long) - keySize;
while (keySize--) {
kc[offset + keySize] = k[keySize];
}
if (*k < 0) {
while (offset--) {
kc[offset] |= -1;
}
}
}
return keyCopy;
}
|
C | #include <stdio.h>
void swap_max(int a[], int x, int y)
{
int d = a[y], e = 0;
for (int i = y; i < x; i++)
{
if (a[i] > d)
{
d = a[i];
e = i;
}
}
if (d != a[y])
{
a[e] = a[y];
a[y] = d;
}
}
void ssort(int p[], int z)
{
for (int i = 0; i < z; i++)
{
swap_max(p, z, i);
}
}
|
C | /*
深度优先遍历,dfs与bfs结合
*/
vector<int> lexicalOrder(int n) {
vector<int> res;
set<string> zdx;
while (n>0) zdx.insert(to_string(n--));
set<string>::iterator iter = zdx.begin();
while (iter!=zdx.end())
{
stringstream out(*iter++);
out >> n;
res.push_back(n);
}
return res;
} |
C |
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
int main()
{
int i, n, ch, data, pos;
do
{
printf("\n\n\n-----------Stack using Linked List------------:\n");
printf("\n\n1. Push the element.\n");
printf("\n2. Pop the element.\n");
printf("\n3. Display\n");
printf("\n0. Exit\n");
printf("\nEnter the choice :");
scanf("%d", &ch);
switch(ch)
{
case 1:printf("\nEnter the number n : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("\nEnter the value to be insert: ");
scanf(" %d", &data);
push(data);
}
display();
break;
case 2:pop();
display();
break;
case 3:display();
break;
case 0:exit(1);
default :printf("\nInvalid Input\n");
}
}while(ch > 0);
printf("\n");
return 0;
}
|
C | #include "stdlib.h"
#include <string.h>
#include "stdio.h"
void yap(int *argc, char *argv[])
{
FILE *dosya;
char *satir = NULL;
char mod[2];
int satir_sayac = 1;
char c;
mod[0] = argv[1][0];
mod[1] = argv[1][1];
char *dosyaAdi = malloc(sizeof(char) * 100);
dosyaAdi = argv[2];
size_t buff = 0;
size_t nread = 0;
if ((dosya = fopen(dosyaAdi, "r")) != NULL)
{
while ((nread = getline(&satir, &buff, dosya)) != -1)
{
if (strstr(satir, "strcpy"))
{
if (strcmp(mod,"-s")==0)
{
printf("Satır %d: strcpy() kullanılmış.\n", satir_sayac);
}
else if (strcmp(mod,"-r")==0)
{
printf("Satır %d: strcpy() kullanılmış. Yerine strncpy() kullanmalısınız.\n", satir_sayac);
}
}
satir_sayac++;
}
}
else
printf("Dosya Bulunamadı...");
fclose(dosya);
satir_sayac = 1;
if ((dosya = fopen(dosyaAdi, "r")) != NULL)
{
while ((nread = getline(&satir, &buff, dosya)) != -1)
{
if (strstr(satir, "strcat"))
{
if (strcmp(mod,"-s")==0)
{
printf("Satır %d: strcat() kullanılmış.\n", satir_sayac);
}
else if (strcmp(mod,"-r")==0)
{
printf("Satır %d: strcat() kullanılmış. Yerine strlcat() kullanmalısınız.\n", satir_sayac);
}
}
satir_sayac++;
}
}
else
printf("Dosya Bulunamadı...");
fclose(dosya);
satir_sayac = 1;
if ((dosya = fopen(dosyaAdi, "r")) != NULL)
{
while ((nread = getline(&satir, &buff, dosya)) != -1)
{
if (strstr(satir, "gets"))
{
if (strcmp(mod,"-s")==0)
{
printf("Satır %d: gets() kullanılmış.\n", satir_sayac);
}
else if (strcmp(mod,"-r")==0)
{
printf("Satır %d: gets() kullanılmış. Yerine fgets() kullanmalısınız.\n", satir_sayac);
}
}
satir_sayac++;
}
}
else
printf("Dosya Bulunamadı...");
fclose(dosya);
satir_sayac = 1;
if ((dosya = fopen(dosyaAdi, "r")) != NULL)
{
while ((nread = getline(&satir, &buff, dosya)) != -1)
{
if (strstr(satir, "getpw"))
{
if (strcmp(mod,"-s")==0)
{
printf("Satır %d: getpw() kullanılmış.\n", satir_sayac);
}
else if (strcmp(mod,"-r")==0)
{
printf("Satır %d: getpw() kullanılmış. Yerine getpwuid() kullanmalısınız.\n", satir_sayac);
}
}
satir_sayac++;
}
}
else
printf("Dosya Bulunamadı...");
fclose(dosya);
satir_sayac = 1;
if ((dosya = fopen(dosyaAdi, "r")) != NULL)
{
while ((nread = getline(&satir, &buff, dosya)) != -1)
{
if (strstr(satir, "sprintf"))
{
if (strcmp(mod,"-s")==0)
{
printf("Satır %d: sprintf() kullanılmış.\n", satir_sayac);
}
else if (strcmp(mod,"-r")==0)
{
printf("Satır %d: sprintf() kullanılmış. Yerine snprintf() kullanmalısınız.\n", satir_sayac);
}
}
satir_sayac++;
}
}
else
printf("Dosya Bulunamadı...");
free(satir);
fclose(dosya);
}
int main(int *argc, char *argv[])
{
yap(argc, argv);
return 0;
}
|
C | #include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <assert.h>
void test_symlink(char *salt) {
char filename[100];
char linkpath[100];
pid_t pid = getpid();
sprintf(filename, "./%sfile_%d", salt, pid);
printf("creating file: %s\n", filename);
int fd = open(filename, O_RDWR | O_CREAT, 0644);
if (fd == -1) {
perror("open");
exit(1);
}
sprintf(linkpath, "./file_%d_link_path", pid);
int ret = symlink(filename, linkpath);
if (ret == -1) {
perror("symlink");
exit(1);
}
struct stat buf;
ret = lstat(linkpath, &buf);
if (ret == -1) {
perror("lstat");
exit(1);
}
assert(S_ISLNK(buf.st_mode));
char bufname[100];
ssize_t size = readlink(linkpath, bufname, 100);
if (size == -1) {
perror("readlink");
}
printf("'%s', '%s'", bufname, filename);
assert(strcmp(bufname, filename) == 0);
assert(stat(linkpath, &buf) == 0);
assert(!S_ISLNK(buf.st_mode));
assert(unlink(filename) == 0);
assert(unlink(linkpath) == 0);
}
int main() {
test_symlink("little_target");
test_symlink("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbig_target");
}
|
C | /*
** client.c -- a stream socket client demo
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include "commons/config.h"
#include "commons/string.h"
#include "commons/temporal.h"
#include "commons/process.h"
#include "commons/collections/list.h"
#include "commons/log.h"
#include <semaphore.h>
#include <pthread.h>
#include "../../Nuestras/src/laGranBiblioteca/sockets.c"
#include "../../Nuestras/src/laGranBiblioteca/config.c"
#include "../../Nuestras/src/laGranBiblioteca/funcionesParaTodosYTodas.c"
#include <arpa/inet.h>
#include "../../Nuestras/src/laGranBiblioteca/datosGobalesGenerales.h"
void* rutinaPrograma(void*);
char* diferencia(char*,char*);
void transformarFechaAInts(char*, int[4]);
void* rutinaEscucharKernel();
void switchManejoError(int exitCode);
typedef struct {
int pid;
bool estaTerminado;
bool hayParaImprimir;
char * mensajeAImprimir;
}t_Estado;
struct{
int pid;
char* mensaje;
} mensajeDeProceso;
int socketKernel;
char* mensajeActual;
t_list* listaEstadoPrograma;
bool error;
bool signal_terminar;
t_log* logConsola;
pthread_mutex_t mutex_lista;
pthread_mutex_t mutex_ordenDeEscritura;
pthread_mutex_t mutex_mensajeActual;
pthread_mutex_t mutex_espera;
pthread_mutex_t hayQueEscribir;
pthread_mutex_t yaSeEscribio;
size_t tamanoArchivo(FILE * archivo){
size_t tamano;
fseek(archivo,0,SEEK_END);//ACA FALTA HANDELEAR ERROR
tamano = ftell(archivo);
fseek(archivo,0,SEEK_SET);
return tamano;
}
void string_iterate(char* strings, void (*closure)(char)) {
int i = 0;
while (strings[i] != '\0') {
closure(strings[i]);
i++;
}
}
char* procesarArchivo(char* archivo, int tamano){
//char ** lineas = string_split(archivo, "\n");
char* archivoProcesado = string_new();
bool laAnteriorFueUnEnter = false;
void agregar(char caracter){
if(caracter != '\t'){
char* aux = malloc(sizeof(char)*5);
aux[0] = caracter;
aux[1] = '\0';
string_append(&archivoProcesado, aux);
free(aux);
}
}
void dejarSoloUnEnter(char caracter){
if(caracter == '\n'){
if(!laAnteriorFueUnEnter){
agregar(caracter);
}
laAnteriorFueUnEnter = true;
}
else{
agregar(caracter);
if(caracter != '\t')
laAnteriorFueUnEnter = false;
}
}
string_iterate(archivo, dejarSoloUnEnter);
return archivoProcesado;
}
char * generarScript(char * nombreDeArchivo){
FILE* archivo;
if ( !(archivo = fopen(nombreDeArchivo, "r")) )
{
perror("Error: el archivo no esta en el directorio o no existe \n");
log_error(logConsola,"Error: el archivo %s no esta en el directorio o no existe ",nombreDeArchivo);
return NULL;// Va si o si , en caso de que exista el error sino tira segmentation fault
}
size_t tamano = tamanoArchivo(archivo);
char* script = malloc(tamano+1);//lee el archivo y lo guarda en el script AnsiSOP
fread(script,tamano,1,archivo);
script[tamano] = '\0';
char* scriptProcesado = procesarArchivo(script, tamano);
free(script);
fclose(archivo);
log_info(logConsola,"Se creo el script correctamente este dice: %s",scriptProcesado);
return scriptProcesado;
}
void transformarFechaAInts(char * fecha, int arrayFecha[4]){
char** arrayCalendario = string_split(fecha,":");
int i;
for (i=0;i<4;i++){
arrayFecha[i] = atoi(arrayCalendario[i]);
}
liberarArray(arrayCalendario);
}
char* transformarArrayAFecha(int arrayInt[4]){
int i;
char* fecha[4];
char * aux;
aux = string_itoa(arrayInt[0]);
for(i=1;i<4;i++){
fecha[i] = string_itoa(arrayInt[i]);
string_append_with_format(&aux,":%s",fecha[i]);
free(fecha[i]);
}
//string_append_with_format(&aux,":%s",fecha[1]);
//string_append_with_format(&aux,":%s",fecha[2]);
//string_append_with_format(&aux,":%s",fecha[3]);
//aux = strcat(strcat(strcat(fecha[0], fecha[1]),fecha[2]), fecha[3]);
return aux;
}
char* diferencia(char* fechaInicio,char* fechaFin){
int resultadoInt[4];
int arrayInicio[4];
transformarFechaAInts(fechaInicio, arrayInicio);
int arrayFin[4];
transformarFechaAInts(fechaFin,arrayFin);
int i;
for(i=0;i<4;i++){
resultadoInt[i] = arrayFin[i]-arrayInicio[i];
if(resultadoInt[i] < 0){
resultadoInt[i-1]--;
if(i != 3) {
resultadoInt[i] = 60 + resultadoInt[i];
}else {
resultadoInt[i] = 1000 + resultadoInt[i];
};
}
}
char* diferencia = transformarArrayAFecha(resultadoInt);
return diferencia;
}
void conectarConKernel(){
int rta_conexion;
socketKernel = conexionConServidor(getConfigString("PUERTO_KERNEL"),getConfigString("IP_KERNEL"));
// validacion de un correcto hadnshake
if (socketKernel== 1){
log_error(logConsola,"Falla en el protocolo de comunicación,en conectarConKernel");
perror("Falla en el protocolo de comunicación");
exit(1);
}
if (socketKernel == 2){
log_error(logConsola,"No se ha conecto con Kernel , en conectarConKernel");
perror("No se conecto con Kernel");
exit(1);
}
if ( (rta_conexion = handshakeCliente(socketKernel, Consola)) == -1) {
log_error(logConsola,"Error en el handshake con el Servidor, en conectarConKernel");
perror("Error en el handshake con el Servidor");
close(socketKernel);
}
log_info(logConsola,"Se conecto la Consola y el Kernel");
printf("Conexión exitosa con el Servidor(%i)!!\n",rta_conexion);
}
void agregarAListaEstadoPrograma(int pid, bool estado){
t_Estado* aux = malloc(sizeof(t_Estado));
aux->pid = pid;
aux->estaTerminado = estado;
aux->hayParaImprimir = false;
aux->mensajeAImprimir = NULL;
sem_wait(&mutex_lista);
list_add(listaEstadoPrograma, aux);
sem_post(&mutex_lista);
}
t_Estado* encontrarElDeIgualPid(int pid){
t_Estado * programaEstado;
bool sonIguales(t_Estado * elementos){
return elementos->pid == pid;
}
sem_wait(&mutex_lista);
programaEstado = list_find(listaEstadoPrograma, (void*) sonIguales);
sem_post(&mutex_lista);
return programaEstado;
}
void matarHiloPrograma(int pid){
bool sonIguales(t_Estado * elementos){
return elementos->pid == pid;
}
t_Estado * ret;
ret = encontrarElDeIgualPid(pid);
if(ret == NULL){
perror("Error: el pid no existe o ya ha finalizado el programa");
log_error(logConsola,"Error: el pid no existe o ya ha finalizado el programa");
}
else{
sem_wait(&mutex_lista);
ret->estaTerminado=true;
sem_post(&mutex_lista);
sem_post(&hayQueEscribir);
sem_wait(&yaSeEscribio);
log_info(logConsola,"Se cambio el estado del pid %d a terminado",pid);
}
}
void crearHiloDetachPrograma(int* pid){
pthread_attr_t attr;
pthread_t hilo ;
//Hilos detachables cpn manejo de errores tienen que ser logs
int res;
res = pthread_attr_init(&attr);
if (res != 0) {
log_error(logConsola,"Error en los atributos del hilo, en crearHiloDetachable");
perror("Error en los atributos del hilo");
}
res = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (res != 0) {
log_error(logConsola,"Error en el seteado del estado de detached, en crearHiloDetachable");
perror("Error en el seteado del estado de detached");
}
res = pthread_create (&hilo ,&attr,rutinaPrograma, (void *) pid);
if (res != 0) {
log_error(logConsola,"Error en la creacion del hilo, en crearHiloDetachable");
perror("Error en la creacion del hilo");
}
log_info(logConsola,"Se creo un hilo Detachable para el proceso %d",*pid);
pthread_attr_destroy(&attr);
}
void inicializarSemaforos(){
log_info(logConsola,"Se inicializan los semaforos");
sem_init(&mutex_lista,0,1);
sem_init(&mutex_ordenDeEscritura,0,0);
sem_init(&mutex_mensajeActual,0,1);
sem_init(&mutex_espera,0,0);
sem_init(&hayQueEscribir,0,0);
sem_init(&yaSeEscribio,0,0);
}
void liberarNodoListaEstado(t_Estado* nodo){
free(nodo->mensajeAImprimir);
free(nodo);
}
void sigint_handler(int signal) {
printf("Se recibio una SIGINT, se finalizará el proceso\n" );
log_warning(logConsola,"Se recibio una SIGINT, se finalizará el proceso");
enviarMensaje(socketKernel,desconectarConsola, &socketKernel, 4);
list_destroy_and_destroy_elements(listaEstadoPrograma,liberarNodoListaEstado);
close(socketKernel);
exit(-1);
return;
}
int main(void)
{
logConsola = log_create("Consola.log","Consola",0,0);
printf("Inicializando Consola.....\n\n");
//char* gensc = generarScript("for");
//puts(gensc);
size_t len = 0;
char* mensaje = NULL;
listaEstadoPrograma = list_create();
error = false;
signal_terminar = false;
inicializarSemaforos();
signal(SIGINT, sigint_handler);
// ******* Configuración inicial Consola
printf("Configuracion Inicial:\n");
configuracionInicial("/home/utnso/workspace/tp-2017-1c-While-1-recursar-grupo-/Consola/consola.config");
imprimirConfiguracion();
conectarConKernel();
pthread_t hiloMaster ;
pthread_create(hiloMaster, NULL,rutinaEscucharKernel, NULL);
while(!error && !signal_terminar){//Ciclo donde se ejecutan los comandos principales.
printf("\nIngrese Comando: \n");
getline(&mensaje,&len,stdin);
log_info(logConsola,"Se escribió un comando en la consola");
char** comandoConsola = NULL;//Esta variable es para cortar el mensaje en 2.
comandoConsola = string_split(mensaje, " "); // separa la entrada en un char**
if(strcmp(comandoConsola[0],"desconectarConsola\n") == 0){
liberarArray(comandoConsola);
enviarMensaje(socketKernel,desconectarConsola, &socketKernel, 4);
log_info(logConsola,"Se desconecto a Consola. Se le envio un mensaje al Kernel");
break;
}
if(strcmp(comandoConsola[0],"limpiarMensajes\n") == 0){
system("clear");
log_info(logConsola,"Se limpiaron los mensajes de la consola");
liberarArray(comandoConsola);
continue;
}
if(strcmp(comandoConsola[0],"iniciarPrograma") == 0){//Primer Comando iniciarPrograma
char** nombreDeArchivo= string_split(comandoConsola[1], "\n");//Toma el parametro que contiene el archivo y le quita el \n
char* script = generarScript(nombreDeArchivo[0]);
if (script==NULL){
continue;}
enviarMensaje(socketKernel,envioScriptAnsisop, script,strlen(script)+1);
log_info(logConsola,"Se le envio el script al Kernel que dice : %s", script);
liberarArray(nombreDeArchivo);
liberarArray(comandoConsola);
free(script);
sem_wait(&mutex_ordenDeEscritura);
continue;
}
if(strcmp(comandoConsola[0],"finalizarPrograma") == 0){
char** stream= string_split(comandoConsola[1],"\n");
int *pid = malloc(sizeof(int));
*pid = atoi(*stream);
if(encontrarElDeIgualPid(*pid)==NULL){
printf(" el pid es incorrecto \n");
}
else{
enviarMensaje(socketKernel,finalizarCiertoScript ,pid, sizeof(int));
log_info(logConsola,"Se le envia el pid %d para que Kernel lo finalice",pid);
}
liberarArray(comandoConsola);
liberarArray(stream);
continue;
}
if (error){
liberarArray(comandoConsola);
break;
}
puts("Comando Inválido!\n");
}
sem_wait(&mutex_lista);
list_destroy_and_destroy_elements(listaEstadoPrograma,liberarNodoListaEstado);
sem_post(&mutex_lista);
close(socketKernel);
free(mensaje);
liberarConfiguracion();
log_info(logConsola,"Se liberan los recursos");
log_destroy(logConsola);
return 0;
}
void* rutinaPrograma(void* parametro){
int pid ;
char* tiempoInicio = temporal_get_string_time();
int cantImpresiones = 0;
pid = *((int*)parametro);
t_Estado * programaEstado ;
agregarAListaEstadoPrograma(pid,false);
programaEstado = encontrarElDeIgualPid(pid);
printf("Numero de pid del proces: %d \n",pid);
log_info(logConsola,"Se inicializo rutinaPrograma %d en el tiempo %s",pid,tiempoInicio);
sem_post(&mutex_ordenDeEscritura);
sem_post(&mutex_espera);
while(1){
sem_wait(&hayQueEscribir);
sem_wait(&mutex_lista);
if(programaEstado->hayParaImprimir){
cantImpresiones++;
printf("Mensaje del pid %d: %s\n", pid, programaEstado->mensajeAImprimir);
log_info(logConsola,"Se imprimio el mensaje del pid %d: %s\n", pid, programaEstado->mensajeAImprimir);
programaEstado->hayParaImprimir = false;
sem_post(&yaSeEscribio);
}else if(programaEstado->estaTerminado){
sem_post(&yaSeEscribio);
sem_post(&mutex_lista);
break;
}else{
sem_post(&hayQueEscribir);
}
sem_post(&mutex_lista);
}
char* tiempoFin = temporal_get_string_time();
char* diferencia1 = diferencia(tiempoInicio,tiempoFin);
log_info(logConsola,"Finalizo el pid: %d", pid);
printf("\nAcaba de finalizar el pid: %d\n", pid);
log_info(logConsola,"Tiempo de inicio: %s\n",tiempoInicio);
printf("Tiempo de inicio: %s\n",tiempoInicio);
log_info(logConsola,"Tiempo de Finalización: %s\n",tiempoFin);
printf("Tiempo de Finalización: %s\n",tiempoFin);
log_info(logConsola,"Tiempo de Ejecución: %s\n",diferencia1);
printf("Tiempo de Ejecución: %s\n",diferencia1);
log_info(logConsola,"Cantidad de impresiones del programa ansisop: %d\n",cantImpresiones);
printf("Cantidad de impresiones del programa ansisop: %d\n",cantImpresiones);
free(diferencia1);
free(tiempoFin);
free(tiempoInicio);
log_info(logConsola,"Se liberaron los recursos del hilo detachable asociado al pid %d",pid);
bool sonIguales(t_Estado * elementos){
return elementos->pid == pid;
}
sem_wait(&mutex_lista);
list_remove_and_destroy_by_condition(listaEstadoPrograma,sonIguales,liberarNodoListaEstado);
sem_post(&mutex_lista);
}
void* rutinaEscucharKernel() {
while (!error) {
int operacion;
void * stream;
operacion = recibirMensaje(socketKernel, &stream);
switch (operacion) {
case (envioDelPidEnSeco): {
int pid;
pid = *((int*) stream);
/*pid = *((int*) stream);
crearHiloDetachPrograma(&pid);
sem_wait(&mutex_espera);
break;
*/
if(pid == -1){
printf("La planificacion fue detenida, no se aceptan nuevos scripts.\n");
sem_post(&mutex_ordenDeEscritura);
}
else{
crearHiloDetachPrograma(&pid);
sem_wait(&mutex_espera);
}
break;
}
case (imprimirPorPantalla): {
t_mensajeDeProceso aux = deserializarMensajeAEscribir(stream);
t_Estado* programaEstado;
programaEstado = encontrarElDeIgualPid(aux.pid);
sem_wait(&mutex_lista);
programaEstado->mensajeAImprimir = string_duplicate(aux.mensaje);
programaEstado->hayParaImprimir = true;
sem_post(&mutex_lista);
sem_post(&hayQueEscribir);
sem_wait(&yaSeEscribio);
free(aux.mensaje);
break;
}
case (pidFinalizado): {
int pid;
pid = (*(int*) stream);
matarHiloPrograma(pid);
log_info(logConsola,"Se finalizo el pid %d correctamente",pid);
printf("Se ha finalizado correctamente el pid: %d \n", pid);
break;
}
case (errorFinalizacionPid): {
int pid;
int exitCode;
pid = (*(int*) stream);
exitCode = (*(int*) (stream+4));
matarHiloPrograma(pid);
log_warning(logConsola,"No se ha finalizado correctamente el pid: %d \n", pid,exitCode);
printf("No se ha finalizado correctamente el pid: %d \n", pid);
switchManejoError(exitCode);
break;
}
case (0):{
log_error(logConsola,"Se desconecto el kernel");
printf("Se desconecto el kernel\n");
sem_wait(&mutex_lista);
list_destroy_and_destroy_elements(listaEstadoPrograma,liberarNodoListaEstado);
sem_post(&mutex_lista);
error = true;
exit(-1);
break;
}
case (pidFinalizadoPorFaltaDeMemoria): {
int pid;
pid = (*(int*) stream);
matarHiloPrograma(pid);
log_error(logConsola,"No se ha finalizado correctamente el pid %d por falta de memoria",pid);
printf("\nNo se ha finalizado correctamente el pid %d por falta de memoria\n",pid);
break;
}
default: {
perror("Error: no se pudo obtener mensaje \n");
}
}
if (operacion != 0)
free(stream);
}
}
void switchManejoError(int exitCode){
switch(exitCode){
case noSePudoReservarRecursos :{
printf("Se finalizó porque no se pudo reservar recursos.\n");
}break;
case archivoInexistente :{
printf("Se finalizó porque el archivo es inexistente.\n");
}break;
case lecturaDenegadaPorFaltaDePermisos :{
printf("Se finalizó porque no se tienen permisos de lectura para el archivo.\n");
}break;
case escrituraDenegadaPorFaltaDePermisos :{
printf("Se finalizó porque no se tienen permisos de escritura para el archivo.\n");
}break;
case excepcionMemoria :{
printf("Se finalizó porque se lanzo una excepción de memoria.\n");
}break;
case finalizacionDesdeConsola :{
printf("Se finalizó porque se utilizo el comando de finalizacion por consola.\n");
}break;
case reservarMasMemoriaQueTamanoPagina:{
printf("Se finalizó porque se reservó más memoria que tamanio de pagina.\n");
}break;
case noSePuedenAsignarMasPaginas :{
printf("Se finalizó porque no se pueden asignar mas páginas.\n");
}break;
case finalizacionDesdeKenel :{
printf("Se finalizó porque se utilizo el comando de finalizacion por consola del Kernel.\n");
}break;
case intentoAccederAUnSemaforoInexistente:{
printf("Se finalizó porque se intento acceder a un semaforo inexistente.\n");
}break;
case intentoAccederAUnaVariableCompartidaInexistente:{
printf("Se finalizó porque se intento acceder a una variable compartida inexistente.\n");
}break;
case lecturaDenegadaPorFileSystem:{
printf("Se finalizó porque se denego la lectura por el FileSystem.\n");
}break;
case escrituraDenegadaPorFileSystem:{
printf("Se finalizó porque se denego el escritura por el FileSystem.\n");
}break;
case noSeCreoElArchivoPorFileSystem:{
printf("Se finalizó porque se denego la creacion por el FileSystem.\n");
}break;
case falloEnElFileDescriptor:{
printf("Se finalizó porque ocurrio un fallo en el File Descriptor.\n");
}break;
case borradoFallidoOtroProcesoLoEstaUtilizando:{
printf("Se finalizó porque no se pudo borrar el archivo debido a que otro proceso lo esta utilizando.\n");
}break;
case borradoFallidoPorFileSystem:{
printf("Se finalizó porque se denego el borrado por FileSystem.\n");
}break;
case seQuiereUtilizarUnaVariableNoDeclarada:{
printf("Se finalizó porque se quiso utilizar una variable no declarado.\n");
}break;
default:{
}
}
}
|
C | #include <stdio.h>
int main()
{
int ar1[4]={0},ar2[4]={0},ar3[4]={0};
float ar4[4],apodotikotita,temp;
int i=0,n,k=-1,j;
FILE *fp;
if(fp=fopen("in.txt", "r")){
fscanf(fp, "%d",&n);
printf("Reading file for %d lines of data...\n",n);
while(i<n){
fscanf(fp, "%d",&ar1[i]);
fscanf(fp, "%d",&ar2[i]);
fscanf(fp, "%d",&ar3[i]);
//Ypologismos
apodotikotita=ar1[i]-ar1[i]*(ar2[i]/3000.0)-ar3[i]*ar1[i]/40.0;
if (apodotikotita>0){
k++;
ar4[k]=apodotikotita;
}
i++;
}
printf("Printing Array with results...\n");
for(i=0;i<n;i++){
printf("i=%d=%d=%d=%d\n",i,ar1[i],ar2[i],ar3[i]);
}
for(i=0;i<=k;i++){
printf("k=%d-apodotikotita=%f\n",i,ar4[i]);
}
//bubble sort
for(i=1;i<=k;i++){
for(j=k;j>=i;j--){
if(ar4[j]>ar4[j-1]){
temp=ar4[j];
ar4[j]=ar4[j-1];
ar4[j-1]=temp;
}
}
}
printf("Meta to bubble sort\n");
for(i=0;i<=k;i++){
printf("k=%d-apodotikotita=%f\n",i,ar4[i]);
}
fp=fopen("out.txt", "w");//write to file
}
else{
printf("...error while opening file...");
}
return 0;
}
|
C |
#include "Pali.h"
int IsPalindrome (const char *str)
{
int flag = 0; /* check equal */
int counter = 0 ;
int len = strlen(str);
/* eaual the first char + counter in the string to the last char - counter in the string*/
for (; counter < (len/2) ; counter++)
if (*(str+counter) == *(str +len-counter -1)) /* if equal change flag to 1*/
{
flag=1;
}
else
{
flag=0;
}
return flag;
}
|
C | #ifndef _HEXADECIMAL_H_
#define _HEXADECIMAL_H_
#include <stdlib.h>
/**
* @file Hexadecimal Representation
*/
/**
* @brief Print the hexadecimal representation of a variable.
*
* @param address the address of the variable in memory
* @param size the size, in bytes, of the variable
*/
void PrintHex(void *address, size_t size);
#endif
|
C | //name-naveen roll-1601CS28
// Date-31/07/2017
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//stucture define
struct node
{
char serialno[10];
char title[10];
char author[10];
int boolnumber;
struct node* next;
};
//print linked list and book details
void print(struct node *head)
{
struct node *newnode=NULL;
newnode=head;
while(newnode!=NULL)
{
printf("%s %s %s",newnode->serialno,newnode->title,newnode->author);
if(newnode->next)
printf(", ");
newnode=newnode->next;
}
}
struct node *head=NULL;// globle define head of linked list
int main()
{
char enter;
char a,b,c,d,e,f;
do{
printf("--------------------------------------------------------------------------------------\n");
printf("a.Make a new entry of book\nb.View Details of a book\nc.how list of available books\nd.Issue a book\ne.Return a book\nf.Exit\n");
printf("Enter any options::");
scanf(" %c",&enter);
if(enter=='a')//enter details of book name of serial number ,title , and author names
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
printf("Please enter serial number ,title and author:");
scanf("%s %s %[^\t\n]s",newnode->serialno,newnode->title,newnode->author);
newnode->boolnumber=1;
if(head==NULL)
head=newnode;
else
newnode->next=head;
head=newnode;
printf("New Enter Successful\n");
}
else if(enter=='b')// view details of books
{
struct node* newcheck=head;
printf("\n");
struct node *newprint=(struct node*)malloc(sizeof(struct node));
newprint->next=NULL;
printf("Choose any option:\n");
printf("1.By Serial No\n2.By Title\n3.By Author\n");
int number2;
scanf("%d",&number2 );
if(number2==3){
printf("Enter Author name::\n");
scanf(" %[^\n]s",newprint->author);
int number=0;
while(newcheck!=NULL)
{
if(strcmp(newcheck->author,newprint->author)==0)
{
printf("%s %s %s",newcheck->serialno,newcheck->title,newcheck->author);
if(newcheck->boolnumber==0)
printf(" Issued\n");
else
printf("Not Issued\n");
number++;
}
newcheck=newcheck->next;
}
if(number==0)
printf("Author Book Not exit\n");
}
else if(number2==1){
printf("Enter the serial no::\n");
scanf(" %[^\n]s",newprint->serialno);
int number=0;
while(newcheck!=NULL)
{
if(strcmp(newcheck->serialno,newprint->serialno)==0)
{
printf("%s %s %s",newcheck->serialno,newcheck->title,newcheck->author);
if(newcheck->boolnumber==0)
printf(" Issued\n");
else
printf(" Not Issued\n");
number++;
}
newcheck=newcheck->next;
}
if(number==0)
printf("Serial Book Not exit\n");
}
else if(number2==2){
printf("Enter Title name::\n");
scanf(" %[^\n]s",newprint->title);
int number=0;
while(newcheck!=NULL)
{
if(strcmp(newcheck->title,newprint->title)==0)
{
printf("%s %s %s",newcheck->serialno,newcheck->title,newcheck->author);
if(newcheck->boolnumber==0)
printf(" Issued\n");
else
printf(" Not Issued\n");
number++;
}
newcheck=newcheck->next;
}
if(number==0)
printf("Title Book Not exit\n");
}
}
else if(enter=='c')//show the details of available books
{
printf("List of available books\n");
struct node* newavail=(struct node*)malloc(sizeof(struct node));
newavail=head;
while(newavail!=NULL)
{
if(newavail->boolnumber)
{
printf("%s %s %s ",newavail->serialno,newavail->title,newavail->author);
printf(" Available\n");
}
newavail=newavail->next;
}
}
else if(enter=='d')
{
int count1=0,count4=0;
printf("Issue a book\n");
struct node* newissuse=(struct node*)malloc(sizeof(struct node));
newissuse->next=NULL;
struct node *newcheck1=head;
scanf(" %s",newissuse->serialno );
while(newcheck1!=NULL)
{
if(strcmp(newcheck1->serialno,newissuse->serialno)==0)
{
if(newcheck1->boolnumber==0)
count4++;
newcheck1->boolnumber=0;
count1++;
}
newcheck1=newcheck1->next;
}
if(count1==0||count4==1)
printf("Its a Issued book (not available in libary)\n");
}
else if(enter=='e')//return a books
{
printf("Return a book\n");
int count2=0,count3=0;
struct node* newissuse1=(struct node*)malloc(sizeof(struct node));
newissuse1->next=NULL;
struct node *newcheck11=head;
scanf(" %s",newissuse1->serialno );
while(newcheck11!=NULL)
{
if(strcmp(newcheck11->serialno,newissuse1->serialno)==0)
{
if(newcheck11->boolnumber==1)
{
count3++;
}
newcheck11->boolnumber=1;
count2++;
}
newcheck11=newcheck11->next;
}
if(count2==0||count3==1)
printf("Wrong book(again return)\n");
}
else if(enter=='f')
{
printf("exit\n");
}
else if(enter!='a'&&enter!='b'&&enter!='c'&&enter!='d'&&enter!='e'&&enter!='f')
printf("Wrong enter please choose in a,b,c,d,e,f\n");
}while(enter!='f');
return 0;
} |
C | #include <stdio.h>
#include "ft_str_is_alpha.c"
int main()
{
char chaine_alpha[] = "aaaabbbsbdfjkkkcjdhejeejhfnfjQQQQDHKSJhhhkdjAASJJFK";
char chaine_non_alpha[] = "aaagggfffsdsddsQQQ[]_avdbn";
char chaine_vide[] = "";
printf("La premiere chaine est alphabetique : %s\n", chaine_alpha);
printf("La deuxieme chaine n'est pas alphabetique : %s\n", chaine_non_alpha);
printf("Ma troisieme chaine est vide \n");
printf("Est-ce que ma premier chaine est alpha ? %d\n", ft_str_is_alpha(chaine_alpha));
printf("Est-ce que ma deuxieme chaine est alpha ? %d\n", ft_str_is_alpha(chaine_non_alpha));
printf("Que renvoie ma troisieme chaine qui est vide ? %d\n", ft_str_is_alpha(chaine_vide));
return 0;
}
|
C | #include<stdio.h>
void table(int n);
int main(void)
{
int no;
printf("\n Enter No :: ");
scanf("%d", &no);
table(no); // function call
return 0;
}
void table(int n)
{
int counter;
printf("\n print table of %d in function :: \n", n);
for(counter=1; counter<=10; counter++)
{
printf("\n %d * %d = %d ", n, counter, n*counter);
}
return ;
}
// if u dont have return any value return type should be void
// void nothing
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <err.h>
#include <dynamic.h>
#include <ts.h>
void usage()
{
extern char *__progname;
(void) fprintf(stderr, "Usage: %s [INPUT FILE] [OUTPUT FILE]\n", __progname);
exit(1);
}
int main(int argc, char **argv)
{
ts_stream stream;
ssize_t n;
if (argc != 3)
usage();
ts_stream_construct(&stream);
n = ts_stream_load(&stream, argv[1]);
if (n == -1)
err(1, "ts_stream_load");
n = ts_stream_save(&stream, argv[2]);
if (n == -1)
err(1, "ts_stream_save");
ts_stream_destruct(&stream);
}
|
C | /*
** EPITECH PROJECT, 2018
** PSU
** File description:
** Created by MP,
*/
#include <common.h>
int nbr_str (char *line, char c)
{
int nbr = 0;
int len = strlen(line);
for (int i = 0; line[i] != '\0' && i != len; i++) {
if (line[i] == c || line[i] == ' ' || line[i] == '\t') {
while (i < len && (line[i] == c ||
line[i] == ' ' || line[i] == '\t'))
i++;
}
else {
nbr++;
while (i < len && (line[i] != c &&
line[i] != ' ' && line[i] != '\t'))
i++;
}
if (i == len)
break;
}
return (nbr);
}
char *catch_str (char *line, char c, int *i)
{
char *str;
int x = *i;
int l = *i;
int p = 0;
while (line[l] && (line[l] != c && line[l] != ' ' && line[l] != '\t'))
l++;
if (l == 0)
return (NULL);
str = malloc(sizeof(char) * (l + 1));
while (line[x] && (line[x] != c && line[x] != ' ' && line[x] != '\t')) {
str[p] = line[x];
p++;
x++;
}
str[p] = '\0';
*i = x;
return (str);
}
char *check_line (char *line, char c, int *i)
{
int len = strlen(line);
for (; line[*i] != '\0' && *i < len; (*i)++) {
if (line[*i] == c || line[*i] == ' ' || line[*i] == '\t') {
while (*i < len && (line[*i] == c || line[*i] == ' ' ||
line[*i] == '\t'))
(*i)++;
(*i)--;
}
else
return (catch_str(line, c, i));
}
return (NULL);
}
char **the_strtowordtab (char *line, char c)
{
static int i = 0;
char **tab = NULL;
int r = 0;
int limit = 0;
if (line == NULL)
return (NULL);
limit = nbr_str(line, c);
tab = malloc(sizeof(char *) * (limit + 1));
while (r != limit) {
tab[r] = check_line(line, c, &i);
r++;
}
tab[r] = NULL;
i = 0;
return (tab);
}
|
C | #include<stdio.h>
int main()
{
int num;
scanf("%d",&num);
int no_of_bits=sizeof(int)*8;
for(int k=0;k<no_of_bits;k++)
{
if(num<<k|num>>(no_of_bits-k))
printf("%d",num);
}
}
|
C | /**
* alilib-ali2.c
* Converts an arbitrarily large integer to something else
* (double, int, string, long) for alilib.
*
* <insert appropriate open source license>
*/
// +---------+-------------------------------------------------------
// | Headers |
// +---------+
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "alilib.h"
// +------------+----------------------------------------------------
// | Procedures |
// +------------+
/**
* Find the long that corresponds to a. If a > LONG_MAX,
* returns LONG_MAX. If a < LONG_MIN, returns LONG_MIN.
*/
long
ali2long (ALInt *a)
{
long l = atol (ali2str (a));
if (l > LONG_MAX)
{
return LONG_MAX;
}
else if (l < LONG_MIN)
{
return LONG_MIN;
}
else
{
return l;
}
} // ali2long
/**
* Find the double that corresponds to a. If a > DOUBLE_MAX,
* returns DOUBLE_MAX. If a < DOUBLE_MIN, returns DOUBLE_MIN.
*/
double
ali2double (ALInt *a)
{
double d = atof (ali2str (a));
if (d > DOUBLE_MAX)
{
return DOUBLE_MAX;
}
else if (d < DOUBLE_MIN)
{
return DOUBLE_MIN;
}
else
{
return d;
}
} // ali2double
/**
* Find the int that corresponds to a. If a > INT_MAX,
* returns INT_MAX. If a < INT_MIN, returns INT_MIN.
*/
int
ali2int (ALInt *a)
{
int i = atoi (ali2str (a));
if (i > INT_MAX)
{
return INT_MAX;
}
else if (i < INT_MIN)
{
return INT_MIN;
}
else
{
return i;
}
} // ali2int
/**
* Convert a to string representation. Returns a newly-allocated
* string.
*/
char *
ali2str (ALInt *a)
{
// Malloc a new string
char * ret = malloc (sizeof (char) * a->ndigits + 1);
if (a->sign == -1)
{
ret[0] = '-';
}
else
{
ret[0] = ' ';
}
for (int i = 1; i < 5; i++) {
ret[i] = a->digits[i];
}
ret += '\0';
// Return the new string
return ret;
} // ali2str |
C | #include <stdio.h>
int main () {
char a[256];
printf("Enter a message: ");
scanf("%[^\n]s", a);
printf("%s\n", a);
return 0;
} |
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include"second.h"
int check (int argc, char** argv){
int fin=1;
if(argc-1!=8){ //checking that 5 inputs have been fed
return 0;
}
int cachesize=atoi(argv[1]);
int cache2size=atoi(argv[5]);
if(floor(log2(cachesize))!=log2(cachesize)){ //checking that 1st input (cache size) is pow of 2
return 0;
}
int blocksize=atoi(argv[4]);
if(floor(log2(blocksize))!=log2(blocksize)){ //checking that 4th input (block size) is pow of 2
return 0;
}
if(floor(log2(cache2size))!=log2(cache2size)){ //checking that 1st input (cache size) is pow of 2
return 0;
}
FILE *curr=fopen(argv[8],"r");
if(curr==0){
return 0;
}
fclose(curr);
return fin;
}
int cachehit(unsigned long long address,struct set *cache,int pol,int A,int s,int b,int L2){
unsigned long long one=1;
unsigned long long set = ((((one<<s)-1)<<b)&address)>>b;
//unsigned long block= ((1<<b)-1)&address;
unsigned long long tag= ((((one<<(48-(s+b)))-1)<<(s+b))&address)>>(s+b);
//if(L2==0){
// printf("L1 %llx\n",tag);
//}
//else{
// printf("L2 %llx\n",tag);
//}
// printf("tag %llu\n",tag);
//printf("b %d\n",b);
for (int i=0;i<A;i++){
if(cache[set].lines[i].valid==1){
if(cache[set].lines[i].tag==tag){
if((pol==1 && A!=1)&&L2==0){//moving most recently used to the end of list, note: looks like LRU does not apply to L2
struct LLNode* temp=cache[set].lines[i].ptr;
//printf("%p\n",temp->next);
if(temp->next!=0){
if(temp->prev!=0){
temp->prev->next=temp->next;
temp->next->prev=temp->prev;
}
else if(temp->prev==0){
cache[set].front=temp->next;
cache[set].front->prev=0;
}
cache[set].back->next=temp;
temp->prev=cache[set].back;
cache[set].back=cache[set].back->next;
cache[set].back->next=0;
}
}
if(L2==1){
cache[set].lines[i].valid=0;
struct LLNode* temp=cache[set].lines[i].ptr;
if(temp->prev!=0){
//printf("%d\n",cache[set].back->val);
if(temp->next!=0){
temp->prev->next=temp->next;
temp->next->prev=temp->prev;
}
else{
temp->prev->next=0;
cache[set].back=temp->prev;
}
temp->next=cache[set].front;
temp->prev=0;
cache[set].front=temp;
//temp->prev=0;
}
}
return 1;
}
}
}
//printf("%ld %llx",set,address);
return 0;
}
void replace(unsigned long long address, struct set* cache,int s, int b, int index){
unsigned long long one=1;
unsigned long long set = ((((one<<s)-1)<<b)&address)>>b;
unsigned long block= ((one<<b)-1)&address;
unsigned long long tag= ((((one<<(48-(s+b)))-1)<<(s+b))&address)>>(s+b);
cache[set].lines[index].valid=1;
cache[set].lines[index].tag=tag;
cache[set].lines[index].blocks=block;
}
void replace2layer(unsigned long long address, struct set* cacheL1,struct set* cacheL2,int sizevar[2][7]){
unsigned long long one=1;
int s1 = sizevar[0][4];
int b1 = sizevar[0][5];
int s2 = sizevar[1][4];
int b2 = sizevar[1][5];
unsigned long long setL1 = ((((one<<s1)-1)<<b1)&address)>>b1;
//unsigned long block= ((1<<b)-1)&address;
int ind1 = update(address,cacheL1,s1,b1);
unsigned long long tag= cacheL1[setL1].lines[ind1].tag<<(s1+b1);//((((one<<(48-(s1+b1)))-1)<<(s1+b1))&address);
unsigned long long addressorig=(setL1<<b1)+tag+cacheL1[setL1].lines[ind1].blocks;
//printf("%llx\n",tag);
//printf("orig: %llx\n",addressorig);
if(cacheL1[setL1].lines[ind1].valid==1){
int ind2= update(addressorig,cacheL2,s2,b2);
replace(addressorig,cacheL2,s2,b2,ind2);
//printf("%llx\n",addressorig);
}
replace(address,cacheL1,s1,b1,ind1);
}
void freecache(struct set* cache, int S, int A){
for (int i=0;i<S;i++){
//for(int j=0;j<A;j++){
// free(cache[i].lines[j].blocks);
//}
struct LLNode *temp=cache[i].front;
while(temp!=0){
cache[i].front=temp->next;
free(temp);
temp=cache[i].front;
}
free(cache[i].lines);
}
free(cache);
}
struct LLNode *enqueue(int val, struct LLNode *back){
/*
* in java everything is passed as references
* in C things will be passed by memory so important to manually
* pass as references
*/
struct LLNode *temp= malloc(sizeof(struct LLNode));
temp -> val = val; //since temp is a struct pointer have to use
//-> to refer to its field
temp -> next = 0; //0 is null pointer in C for now
temp->prev=back;
if(back==0){
return temp;
}
back->next=temp;
return back;
}
struct LLNode *pop(struct LLNode *front){
if(front == 0){
return front;
}
struct LLNode *next = front->next;
free(front);
return next;
}
int update(unsigned long long address, struct set *cache, int s, int b){//ret index of line to replace, updates the queue to
unsigned long long one=1;
unsigned long long set = ((((one<<s)-1)<<b)&address)>>b;
//unsigned long block= ((1<<b)-1)&address;
//unsigned long tag= ((1<<(48-(s+b)))-1)<<(s+b);
struct LLNode* temp =cache[set].front;
if(temp->next!=0){
//printf("%d\n",cache[set].back->val);
cache[set].back->next=temp;
cache[set].front=temp->next;
temp->next=0;
temp->prev=cache[set].back;
cache[set].back=temp;
cache[set].front->prev=0;
}
return temp->val;
}
void printLL(struct set* cache, int S, int A){
for (int i=0;i<S;i++){
struct LLNode* temp=cache[i].front;
while(temp!=0){
printf("%lld, ",cache[i].lines[temp->val].tag);
temp=temp->next;
}
printf("\n");
}
printf("end\n");
}
struct set* populate(char** argv,struct set* cache, int sizevar[2][7],int capindex, int associndex, int bckindex, int polindex, int bcksize){
int C,S,A,B; //C -cache capacity, S-# of sets, A-Assoc. of Cache, B-blocks in Assoc
int s,b; //bits for Set and Block in address
char replacepol=0; //0 is FIFO, 1 is Least Recently Used
if(strcmp(argv[polindex],"fifo")==0){
replacepol=0;
}
else if(strcmp(argv[polindex],"lru")==0){
replacepol=1;
}
else{
// printf("error");
return 0;
}
A=0;
if(capindex!=-1){
C=atoi(argv[capindex]);
}
if(bckindex!=-1){
B=atoi(argv[bckindex]);
}
else{
B=bcksize;
}
S=0;
s=0;
b=0;
char command[6];
// char* colon;
for (int i=0;i<5;i++){
command[i]=argv[associndex][i];
}
command[5]='\0';
//printf("%s",command);
if(strcmp(argv[associndex],"direct")==0){
A=1;
}
else if(strcmp(command,"assoc")==0){
if(strlen(argv[associndex])==5){
A=C/B;
}
else{
//printf("%s",argv[2]);
sscanf(argv[associndex],"%5s:%d",command,&A);
}
}
else{
//printf("error");
return 0;
}
S=C/(A*B);
s=log2(S);
b=log2(B);
//printf("%d %d\n",s,b);
//Creating cache according to specifications
cache=malloc(S*sizeof(struct set));
for(int i=0;i<S;i++){
cache[i].lines=malloc(A*sizeof(struct assoc));
cache[i].front=0;
cache[i].back=0;
for(int j=0;j<A;j++){
cache[i].lines[j].valid=0;
cache[i].lines[j].tag=0;
cache[i].lines[j].blocks=0;//malloc(B*sizeof(int));
cache[i].back=enqueue(j,cache[i].back);
if(cache[i].front==0){
cache[i].front=cache[i].back;
}
else{
cache[i].back=cache[i].back->next;
}
//printf("%d %p\n",j, cache[i].front->next);
cache[i].lines[j].ptr=cache[i].back;
}
}
int i=0;
if(bckindex==-1){
i=1;
}
sizevar[i][0]=C;
sizevar[i][1]=S;
sizevar[i][2]=A;
sizevar[i][3]=B;
sizevar[i][4]=s;
sizevar[i][5]=b;
sizevar[i][6]=replacepol;
//for(int j=0;j<7;j++){
// printf("Cache Facts: %d, %d\n",j,sizevar[i][j]);
//}
return cache;
}
int main(int argc, char* argv[1+argc]){
int ch=check(argc,argv);
if(ch==0){
printf("error");
return EXIT_SUCCESS;
}
FILE* file=fopen(argv[8],"r");
int sizevar[2][7];
struct set* cacheL1 = 0;
cacheL1=populate(argv,cacheL1,sizevar,1,2,4,3,-1);
if(cacheL1==0){
printf("error");
return EXIT_SUCCESS;
}
struct set* cacheL2 =0;
cacheL2=populate(argv,cacheL2,sizevar,5,6,-1,7,sizevar[0][3]);
if(cacheL2==0){
printf("error");
return EXIT_SUCCESS;
}
//printf("prepared cold cache");
//printf("Starting with a Cold Cache");
//printf("
//printLL(cache,S,A);
//Reading trace files
int ans[2][4];
for(int i=0;i<2;i++){
for(int j=0;j<4;j++){
ans[i][j]=0; //0-# memread, 1-# memwrite, 2-# cachehit, 3-# cachemiss
}
}
char action[5];
unsigned long long address=0;
int hit=0;
while(fscanf(file,"%s 0x%llx\n",action,&address)!=EOF){
hit=cachehit(address,cacheL1,sizevar[0][6],sizevar[0][2],sizevar[0][4],sizevar[0][5],0);//policy,Assoc,s,b, L2 or not
//printf("%llx L1 %d\n",address,hit);
if(hit==1){
ans[0][2]+=1;
}
else if(hit==0){
hit=cachehit(address,cacheL2,sizevar[1][6],sizevar[1][2],sizevar[1][4],sizevar[1][5],1);//handles the L2 delete
//printf("%llx L2 %d\n",address,hit);
ans[0][3]+=1;
if(hit==1){
ans[1][2]+=1;
}
else{
ans[0][0]+=1;
ans[1][3]+=1;
}
//int index=update(address,cacheL1,sizevar[0][4],sizevar[0][5]);
replace2layer(address,cacheL1,cacheL2,sizevar);
}
if(strcmp(action,"R")==0){
/* if(hit==0){
ans[0]+=1;
ans[3]+=1;
int index=update(address,cache,s,b);
replace(address,cache,s,b,index);
}*/
}
else if(strcmp(action,"W")==0){
ans[0][1]+=1;
/*if(hit==0){
ans[0]+=1;
ans[3]+=1;
int index=update(address,cache,s,b);
replace(address,cache,s,b,index);
}*/
}
//printLL(cacheL1,sizevar[0][1],sizevar[0][2]);
//printLL(cacheL2,sizevar[1][1],sizevar[1][2]);
//printf("%s %llx\n",action,address);
}
//printLL(cache,S,A);
freecache(cacheL1,sizevar[0][1],sizevar[0][2]);
freecache(cacheL2,sizevar[1][1],sizevar[1][2]);
printf("memread:%d\nmemwrite:%d\nl1cachehit:%d\nl1cachemiss:%d\n",ans[0][0],ans[0][1],ans[0][2],ans[0][3]);
printf("l2cachehit:%d\nl2cachemiss:%d\n",ans[1][2],ans[1][3]);
//printf("C %d, A %d, B %d\n",C,A,B);
return 0;
}
|
C | /*
C The Hard Way
more function pointers
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
// just some error checking
void die(const char *message)
{
if(errno) perror(message);
else printf("Error: %s\n", message);
exit(1);
}
// typedef for function pointer
typedef int (*compare_cb)(int a, int b);
// classic bubble sort that returns a pointer to an int
int *bubble_sort(int *numbers, int count, compare_cb cmp)
{
int *target = malloc(count * sizeof(int));
if (!target) die("Memory error.\n");
memcpy(target, numbers, count * sizeof(int));
for(int i = 0; i < count; i++)
for(int j = 0; j < count - 1; j++)
if(cmp(target[j], target[j+1]) > 0)
{
int temp = target[j+1];
target[j+1] = target[j];
target[j] = temp;
}
return target;
}
// order of sorting
int sorted_order(int a, int b)
{
return a - b;
}
int reverse_order(int a, int b)
{
return b - a;
}
int strange_order(int a, int b)
{
if(a == 0 || b == 0) return 0;
else return a%b;
}
// Actual sorting and testing if sorting executes correctly
void test_sorting(int *numbers, int count, compare_cb cmp)
{
int *sorted = bubble_sort(numbers, count, cmp);
if(!sorted) die("Failed to sort as requested.\n");
for(int i = 0; i < count; i++) printf("%d ", sorted[i]);
printf("\n");
free(sorted);
// breaking.... === optional ===
unsigned char *data = (unsigned char*)cmp;
for (int i = 0; i < 25; i++)
printf("%02x:", data[i]);
printf("\n");
}
// MAIN
int main(int argc, char *argv[])
{
if(argc < 2) die("USAGE: <program> <array elem> <array elem> ...\n");
int count = argc -1;
char **inputs = argv + 1;
int *numbers = malloc(count * sizeof(int));
if(!numbers) die("Memory error\n");
for(int i = 0; i < count; i++)
numbers[i] = atoi(inputs[i]);
test_sorting(numbers, count, sorted_order);
test_sorting(numbers, count, reverse_order);
test_sorting(numbers, count, strange_order);
free(numbers);
return 0;
}
|
C | // NEVER ACTUALLY USED IN KERNEL CODE
// THIS FILE HASN'T BEEN REVIEWED AND IS DIRTY
#include "../common/stdlib.h"
#include "mem.h"
#include "uart.h"
#include "mailbox.h"
int mailbox_send(mailbox_message_t msg){
uart_puts(" Sending a message\n"); // Debugging
mailbox_status_t stat;
// Make sure we can send mail
do {
stat = *MAIL0_STATUS;
} while (stat.full);
*MAIL0_WRITE = msg; // Send the message
uart_puts(" A message is sent\n"); // Debugging
return 0;
}
mailbox_message_t mailbox_receive(){
uart_puts(" Receiving a message\n"); // Debugging
mailbox_status_t stat;
mailbox_message_t res;
// Make sure that the message is from the right channel
do {
// Make sure there is mail to recieve
uart_puts(" waiting for the right channel\n"); // Debugging
do {
stat = *MAIL0_STATUS;
} while (stat.empty);
res = *MAIL0_READ; // Get the message
} while (res.channel != 1); // We're using channel 1 for RaspPi B+ (model 1)
uart_puts(" A message is received\n"); // Debugging
return res;
}
|
C | #include <stdio.h>
main()
{
char sel;
do
{
scanf("\n%c",&sel);
if (sel >= 'a' && sel <= 'z')
printf("Minuscula\n");
else if (sel >= 'A' && sel <= 'Z')
printf("Maiuscula\n");
else if (sel >= '0' && sel <= '9')
printf("Digito\n");
else
printf("Sem classificacao\n");
}
while (sel != 'f');
}
|
C | #include<stdio.h>
int main()
{
int lr,ur;
int lc,uc;
int i,j,n,arr[20][20];
printf("\nEnter a number:");
scanf("%d",&n);
lr=lc=0;
ur=uc=n-1;
int count=1;
while(lr<=ur&&lc<=uc)
{
for(i=lc;i<=uc;i++)
arr[lr][i]=count++;
lr++;
for(i=lr;i<=ur;i++)
arr[i][uc]=count++;
uc--;
for(i=uc;i>=lc;i--)
arr[ur][i]=count++;
ur--;
for(i=ur;i>=lr;i--)
arr[i][lc]=count++;
lc++;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%-3d",arr[i][j]);
printf("\n");
}
return 0;
}
|
C | #include<stdio.h>
#include<string.h>
#define MAX 1000000
int factorCount[MAX]={};
void distinct_factor_count()
{
int i, j;
for(i=2;i<=MAX;i++)
if(!factorCount[i])
for(j=i;j<=MAX;j+=i)
factorCount[j]++;
}
int main()
{
distinct_factor_count();
int n;
while(scanf("%d",&n) &&n)
printf("%d : %d\n",n,factorCount[n]);
return 0;
}
|
C | /*
* 线程池的实现
*/
#include "threadPoll.h"
extern void threadCall(struct TaskNote *arg);
char initThreadPoll(int threadNum, struct ThPoll **thPoll)
{
pthread_t tid; //线程号
pthread_attr_t tattr;//线程属性
int i = 0;//循环变量
//初始化线程池结构体
*thPoll = (struct ThPoll *)malloc(sizeof(struct ThPoll));
(*thPoll)->head = (struct TaskNote *)malloc(sizeof(struct TaskNote));//*的优先级低于->和.
(*thPoll)->head->fd = -1;
(*thPoll)->head->next = NULL;
(*thPoll)->isEnd = '1';
pthread_mutex_init(&(*thPoll)->thmutext, NULL);//初始化锁和条件变量
pthread_cond_init(&(*thPoll)->thcond, NULL);
//设置线程为detach
pthread_attr_init(&tattr);
pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
//创建threadNum个线程
for(i = 0;i < threadNum; ++i) {
pthread_create(&tid, &tattr, threadFun, *thPoll);
}
//销毁不用的资源
pthread_attr_destroy(&tattr);
}
char addTaskToList(int fd, int epollfd, struct ThPoll *thPoll)
{
//线程池被销毁了,就不允许添加任务
if(thPoll->isEnd == '0') {
set_log("thread poll addTaskToList 线程池已被销毁");
return '1';
}
//创建一个任务节点加入链表
struct TaskNote *newTask = (struct TaskNote *)malloc(sizeof(struct TaskNote));
newTask->fd = fd;
newTask->epollfd = epollfd;
//需要加锁访问防止造成冲突,TODO:是否会出现死锁,或者饿死
pthread_mutex_lock(&thPoll->thmutext);
newTask->next = thPoll->head->next; //头插法
thPoll->head->next = newTask;
pthread_mutex_unlock(&thPoll->thmutext);
//唤醒一个线程
// printf("加入任务链表,唤醒一个线程:addTaskToList\n");
pthread_cond_signal(&thPoll->thcond);
return '0';
}
void *threadFun(void *arg)
{
struct ThPoll *thpoll = (struct ThPoll *)arg;
//当线程池存在就一直等待任务链表,然后执行任务
while(thpoll->isEnd == '1') {
struct TaskNote *task = NULL, *current = thpoll->head;
//等待条件变量,和任务链表
pthread_mutex_lock(&thpoll->thmutext);
while(thpoll->head->next == NULL) {
pthread_cond_wait(&thpoll->thcond, &thpoll->thmutext);
}
pthread_mutex_unlock(&thpoll->thmutext);
//判断线程池是否销毁
if(thpoll->isEnd == '0')
break;
//取出一个任务,取出尾节点
pthread_mutex_lock(&thpoll->thmutext);
while(current->next != NULL) {
task = current; //记录的是尾节点的前一个
current = current->next;
}
current = task->next; //删除尾节点
task->next = NULL;
pthread_mutex_unlock(&thpoll->thmutext);
//执行任务
// printf("开始执行任务thread id:%u \n", (unsigned int)pthread_self());
if(current != NULL)
/*运行任务处理函数*/
threadCall(current);
free(current); //执行完任务就释放任务节点
}
//退出线程
// printf("线程退出\n");
pthread_exit(NULL);
}
void destroyThreadPoll(struct ThPoll *thPoll)
{
//先将标志设定,这样就避免添加任务,而且一部分线程就会退出
pthread_mutex_lock(&thPoll->thmutext);
thPoll->isEnd = '0';
pthread_mutex_unlock(&thPoll->thmutext);
//释放任务链表
struct TaskNote *current = thPoll->head;
pthread_mutex_lock(&thPoll->thmutext);
while(current->next != NULL) {
thPoll->head->next = current->next->next; //记录下下一个
free(current->next); //删除下一个
current = thPoll->head; //重新使current等于头结点
}
thPoll->head = NULL;
pthread_mutex_unlock(&thPoll->thmutext);
//发送广播直到所有线程都退出,因为已经将任务链表清空,所以线程收到信号后都会退出
pthread_cond_broadcast(&thPoll->thcond);
//释放线程池结构
sleep(1);//确保线程在这时已经全部退出,或者添加线程号到结构体中,检测还有几个号,不过这个也行
free(thPoll->head);
pthread_mutex_destroy(&thPoll->thmutext);
pthread_cond_destroy(&thPoll->thcond);
free(thPoll);
}
|
C |
/*
*
* dig
*
* created with FontCreator
* written by F. Maximilian Thiele
*
* http://www.apetech.de/fontCreator
* [email protected]
*
* File Name : dig
* Date : 06.03.2016
* Font size in bytes : 892
* Font width : 7
* Font height : 11
* Font first char : 42
* Font last char : 59
* Font used chars : 17
*
* The font data are defined as
*
* struct _FONT_ {
* uint16_t font_Size_in_Bytes_over_all_included_Size_it_self;
* uint8_t font_Width_in_Pixel_for_fixed_drawing;
* uint8_t font_Height_in_Pixel_for_all_characters;
* unit8_t font_First_Char;
* uint8_t font_Char_Count;
*
* uint8_t font_Char_Widths[font_Last_Char - font_First_Char +1];
* // for each character the separate width in pixels,
* // characters < 128 have an implicit virtual right empty row
*
* uint8_t font_data[];
* // bit field of all characters
*/
#include <inttypes.h>
#include <avr/pgmspace.h>
#ifndef DIG_H
#define DIG_H
#define DIG_WIDTH 7
#define DIG_HEIGHT 11
static const uint8_t dig[] PROGMEM = {
0x03, 0x7C, // size
0x07, // width
0x0B, // height
0x2A, // first char
0x11, // char count
// char widths
0x03, 0x06, 0x02, 0x03, 0x02, 0x03, 0x06, 0x04, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x02,
// font data
0x02, 0x05, 0x02, 0x00, 0x00, 0x00, // 42
0x10, 0x10, 0x7C, 0x7C, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 43
0x80, 0x80, 0xA0, 0x60, // 44
0x40, 0x40, 0x40, 0x00, 0x00, 0x00, // 45
0x00, 0x00, 0x00, 0x00, // 46
0x80, 0x7C, 0x03, 0x20, 0x00, 0x00, // 47
0xFE, 0xFF, 0x01, 0x01, 0xFF, 0xFE, 0x00, 0x20, 0x20, 0x20, 0x20, 0x00, // 48
0x0C, 0x06, 0xFF, 0xFF, 0x00, 0x00, 0x20, 0x20, // 49
0x82, 0xC3, 0x61, 0x31, 0x1F, 0x0E, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // 50
0x82, 0x83, 0x09, 0x09, 0xFF, 0xF6, 0x00, 0x20, 0x20, 0x20, 0x20, 0x00, // 51
0x60, 0x58, 0x46, 0xFF, 0xFF, 0x40, 0x00, 0x00, 0x00, 0x20, 0x20, 0x00, // 52
0x9C, 0x9F, 0x0B, 0x09, 0xF9, 0xF1, 0x00, 0x20, 0x20, 0x20, 0x20, 0x00, // 53
0xFC, 0xFE, 0x09, 0x09, 0xFB, 0xF2, 0x00, 0x20, 0x20, 0x20, 0x20, 0x00, // 54
0x01, 0xC1, 0xF1, 0x3D, 0x0F, 0x03, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, // 55
0xEE, 0xFF, 0x11, 0x11, 0xFF, 0xEE, 0x00, 0x20, 0x20, 0x20, 0x20, 0x00, // 56
0x9E, 0xBF, 0x21, 0x21, 0xFF, 0x7E, 0x00, 0x20, 0x20, 0x20, 0x00, 0x00, // 57
0x8C, 0x8C, 0x20, 0x20 // 58
};
#endif
|
C | #include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<arpa/inet.h>
#include <string.h>
#include "log.h"
#include "Locker.h"
#include "locker_pthread.h"
#define MAXBUF 1024
//whole system log
Logger* log = NULL;
int main(int argc ,char** argv) {
Locker* locker = locker_pthread_create();
log = create_log("client9.log", locker, 6);
int i =3;
int ssock;
int clen;
int writelen;
struct sockaddr_in server_addr;
char buf[MAXBUF];
char end[2]={0x10,0x13};
if(argc<3)
return 1;
if ((ssock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))<0) {
perror("create simple sockstream error.");
log->debug(log,__FILE__ ,__LINE__,__FUNCTION__,"create simple sockstream error.");
exit(1);
}
clen = sizeof(server_addr);
memset(&server_addr,0,sizeof(server_addr));
server_addr.sin_family =AF_INET;
server_addr.sin_addr.s_addr=inet_addr(argv[1]);
server_addr.sin_port =htons(atoi(argv[2]));
if(connect(ssock,(struct sockaddr *)&server_addr,clen)<0) {
perror("connect to server error.");
log->debug(log,__FILE__ ,__LINE__,__FUNCTION__,"connect to server error.");
exit(1);
}
char* serverip = inet_ntoa(server_addr.sin_addr);
memset(buf,0,MAXBUF);
writelen=write(ssock,argv[3],strlen(argv[3]));
log->debug(log,__FILE__ ,__LINE__,__FUNCTION__,"write data:\%s",argv[3]);
if(writelen != strlen(argv[3])) {
perror("write to socket error.");
log->debug(log,__FILE__ ,__LINE__,__FUNCTION__,"write to socket error.");
exit(1);
}
writelen=write(ssock,end,2);
log->debug(log,__FILE__ ,__LINE__,__FUNCTION__,"write data:\%s",end);
if(writelen != 2) {
perror("write end to socket error.");
log->debug(log,__FILE__ ,__LINE__,__FUNCTION__,"write end to socket error.");
exit(1);
}
if(read(ssock,buf,MAXBUF)<=0)
{
perror("read from socket error.");
log->debug(log,__FILE__ ,__LINE__,__FUNCTION__,"read from socket error.");
exit(1);
}
log->debug(log,__FILE__ ,__LINE__,__FUNCTION__,"read from socket data:%s.",buf);
close(ssock);
} |
C | #include<stdio.h>
int main()
{
int array[10], sum = 0,i;
for (i = 0; i < 10; ++i) {
scanf("%d", &array[i]);
sum += array[i];
if (sum >= 100) {
if (sum - 100 <= 100 - (sum-array[i]))
printf("%d\n", sum);
else
printf("%d\n", sum-array[i]);
return 0;
}
}
printf("%d\n", sum);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.