Example #1
0
int parser_EmployeeSavetoText(FILE* pFile, LinkedList* pArrayListEmployee)
{
    Employee* pEmployee = NULL;
    int retorno = -1;
    int i;
    int bufferId;
    int bufferSueldo;
    int bufferHorasTrabajadas;
    char bufferNombre[1024];


    if(pFile != NULL && pArrayListEmployee != NULL)
    {
        for(i = 0; i < ll_len(pArrayListEmployee); i++)
        {
            if(i == 0)
            {
                fprintf(pFile, "id,nombre,horas,sueldo\n");
            }

            pEmployee = ll_get(pArrayListEmployee, i);
            Employee_getNombre(pEmployee, bufferNombre);
            Employee_getId(pEmployee, &bufferId);
            Employee_getSueldo(pEmployee, &bufferSueldo);
            Employee_getHorasTrabajadas(pEmployee, &bufferHorasTrabajadas);

            fprintf(pFile, "%d, %s, %d, %d\n", bufferId, bufferNombre, bufferSueldo, bufferHorasTrabajadas);

            retorno = 0;
        }
    }

    return retorno;
}
 // may fail
 static bool get(char & ch)
 {
    if (ll_rx_reg_full()){
       ch = ll_get();
       return true;
    }else{
       return false;
    }
 }
Example #3
0
int main() {
  log_info("Creating a linked list.");
  LinkedList* list = ll_new();
  check(list->first == NULL, "List was not correctly initialised.");
  check(list->length == 0, "List should not have any elements.");

  log_info("Adding an element to the list.");
  int v = 1337;
  int* vpointer = malloc(sizeof(int));
  *vpointer = v;
  ll_prepend(list, vpointer);
  check(list->length == 1, "Length increment failed");
  check(list->first != NULL, "Append failed");
  check(list->first->data == vpointer, "Bad address");
  log_info("The address of list->first->data %p",
      list->first->data);
  check(*((int*) list->first->data) == v, "Bad value");
  log_info("The value is %d as expected",
      *((int*) list->first->data));

  log_info("Adding another element.");
  v = 1338;
  int* another = malloc(sizeof(int));
  *another = v;
  ll_prepend(list, another);
  check(list->length == 2, "Length increment failed");
  check(*((int*) list->first->data) == v, "List increment screwed up");

  log_info("Checking list[0].");
  check(*((int*) ll_get(list, 0)) == v, "First element does not match what was last prepended.");
  log_info("Checking list[1].");
  check(*((int*) ll_get(list, 1)) == 1337, "First element does not match what was first prepended.");

  log_info("Freeing the linked list.");
  ll_free(list);
  return 0;
error:
  return 1;
}
Example #4
0
// private
void ll_push(LList* list, LNode* node) {
  assert(node != NULL);

  assert(node->next == NULL); //assert node is atomic

  if (list->length == 0) {
    list->head = node;
    list->length = 1;
  }else {
    LNode* tail = ll_get(list, list->length - 1);

    tail->next = node;
    list->length += 1;
  }
}
Example #5
0
void top_unsubscribe(char *name, unsigned long id) {
    Topic *st;

    if (tshm_get(topicTable, name, (void **)&st)) {
        long n;
        unsigned long entId;

        /* remove entry that matches au->id */
        pthread_mutex_lock(&(st->lock));
        for(n = 0; n < ll_size(st->regAUs); n++) {
            (void)ll_get(st->regAUs, n, (void **)&entId);
            if (entId == id) {
                (void)ll_remove(st->regAUs, n, (void **)&entId);
                break;
            }
        }
        pthread_mutex_unlock(&(st->lock));
    }
}
Example #6
0
int parser_EmployeeSavetoBinary(FILE* pFile, LinkedList* pArrayListEmployee)
{
    Employee* pEmpleado = NULL;
    int retorno = -1;
    int i;

    if(pFile != NULL)
    {
        for(i=0; i< ll_len(pArrayListEmployee); i++)
        {
            pEmpleado = ll_get(pArrayListEmployee,i);
            fwrite(pEmpleado,sizeof(Employee), 1, pFile);
            retorno = 0;
        }

        retorno = 0;
    }

    return retorno;
}
Example #7
0
// remove from end, returning pointer to element
LNode* ll_pop(LList* list) {
  assert(list->length > 0);

  if (list->length == 1) {
    LNode* output = list->head;
    list->head = NULL;
    list->length = 0;
    return output;
  }


  //INVARIANT: list->length >= 2

  LNode* parent = ll_get(list, list->length - 2);
  LNode* output = parent->next;

  parent->next = NULL;
  list->length -= 1;

  return output;
}
Example #8
0
/**
 * \brief Toma el indice de un empleado por el Id recorriendo todo el LinkedList
 *
 * \param pArrayListEmployee LinkedList* Es la LinkedList donde se buscan los empleados.
 * \param index int* Se retorna por parametros el index donde se encuentra el empleado.
 * \return En caso de exito retorna 1, si no 0
 *
 */
int employee_getIndexById(LinkedList* pArrayListEmployee,int id, int* index)
{
    int retorno = -1;
    Employee* pEmpleado;
    int bufferId;
    int i;
    if(pArrayListEmployee != NULL)
    {
        for(i=0;i < ll_len(pArrayListEmployee);i++)
        {
            pEmpleado = ll_get(pArrayListEmployee,i);
            employee_getId(pEmpleado,&bufferId);
            if(bufferId == id)
            {
                *index = ll_indexOf(pArrayListEmployee, pEmpleado);
                retorno = 0;
                break;
            }
        }
    }
    return retorno;
}
Example #9
0
/**
 * Run every test as set up in the PROBLEM linked list
 *
 * @param argc the size of argv
 * @param argv the collection of arguments to the program
 */
void run_all_tests(int argc, char* argv[])
{
	char* student="";
	char* latefile=NULL;
	long late_ts;
	int i;
	
	if(argc > 3){
		printUsage(argv[0]);
		exit(0);
	}
	else if(argc >= 2){
		student = argv[1];
		if(argc == 3 && strncmp(argv[2], "*latefile=", 10) == 0)
		{
			latefile = argv[2] + 10;
		}
	}

	if(problems->size == 0){
		printf("No tests to run...\n");
		exit(1);
	}

	//TODO: when it's time to add multiple late deadlines, open the LATE_SUBMISSION file

  late_ts = (latefile==NULL ? 0 : 1);

	_STRBUF* xml_buffer = _strbuf_init(MIN_XMLBUF_LEN);

	_strbuf_append(xml_buffer, "<?xml version=\"1.0\"?>\n");
	_strbuf_append(xml_buffer, "<!DOCTYPE tester SYSTEM \"/home2/c/cse1xx/misc/tester.dtd\">\n");

	char* suffix = ct_get_file_suffix();

	char testlist_tag[MAX_TAG_LEN*2];
	
	sprintf(testlist_tag, "<testlist problem_set_type=\"%s\" problem_set_number=\"%d\"",
			_pstype_to_str(ct_get_problem_set_type()), ct_get_problem_set_num());
	
	if(suffix==NULL || strcmp(suffix, "")==0){
		strcat(testlist_tag, " file_suffix=\"");
		strcat(testlist_tag, suffix);
		strcat(testlist_tag, "\"");
	}
	strcat(testlist_tag, ">\n");

	_strbuf_append(xml_buffer, testlist_tag);

	char student_tag[MAX_TAG_LEN];
	sprintf(student_tag, "<student username=\"%s\">\n", student);
	_strbuf_append(xml_buffer, student_tag);

	PROBLEM* temp_prob;
	for(i = 0; i < problems->size; i++){
		ll_get(problems, i, (void**)&temp_prob);
		run_problem_tests(temp_prob, late_ts, xml_buffer);
	}

	// Finish off the XML grading file
	_strbuf_append(xml_buffer, "</student></testlist>\n");

	if(strcmp(student, "") != 0)
	{
		char* filename = _calloc_or_die(strlen(student)+strlen(suffix)+10, sizeof(char),
				"Couldn't calloc name of XML file");
		strcat(filename, student);
		strcat(filename, suffix);
		strcat(filename, ".tester");
		
		FILE* file = fopen((const char*)filename, "w");
		fwrite(xml_buffer->buffer, sizeof(char), strlen(xml_buffer->buffer), file);
		
		fclose(file);
		free(filename);
	}

	_strbuf_free(xml_buffer);
}
Example #10
0
int main(int argc, char** argv) {
    llist *l = malloc(sizeof(llist));
    
    const int reference[11] = {20, 19, 18, 14, 12, 10, 8, 6, 4, 2, -1};
    const int size = sizeof(reference) / sizeof(int);
    
    int error = 1;
    
    // Add numbers 20, 18, 16, 14, ... 2, 0 to the list.
    {
        int i;
        for (i = 20; i >= 0; i -= 2) {
            ll_push(l, i);
        }
    }
    if (ll_size(l) != 11) {
        return error;
    }
    ll_print(l);
    error++;
    
    ll_pop(l);
    ll_push(l, -1);
    ll_insert(l, 1, 19);
    ll_remove(l, 3);
    printf("Phase 2 complete (pop, push, insert, remove).\n");
    
    // Check first and last index.
    if (l -> first -> value != reference[0]) {
        return error;
    }
    printf("Phase 3A complete (check first value).\n");
    error++;
    
    if (l -> last -> value != reference[size - 1]) {
        return error;
    }
    printf("Phase 3B complete (check last value).\n");
    error++;
    
    // Check by traversing.
    {
        node *n = l -> first;
        int index = 0;
        while (n != NULL) {
            if (n -> value == reference[index++]) {
                n = n -> next;
            } else {
                return error;
            }
        }
    }
    printf("Phase 4A complete (traverse forward).\n");
    error++;
    
    // Check by backward traversing.
    {
        node *n = l -> last;
        int index = size - 1;
        while (n != NULL) {
            if (n -> value == reference[index--]) {
                n = n -> prev;
            } else {
                return error;
            }
        }
    }
    printf("Phase 4B complete (traverse backward).\n");
    error++;
    
    // Check by indexing.
    {
        int i;
        for (i = 0; i < ll_size(l); i++) {
            if (reference[i] != ll_get(l, i)) {
                return error;
            }
        }
    }
    printf("Phase 5 complete (iterate).\n");
    error++;
    
    printf("Completed without error.\n");
    return 0;
}
Example #11
0
struct s_node* ll_get_tail(struct s_list *list)
{
	return ll_get(list, list->size-1);
}
Example #12
0
struct s_node* ll_get_head(struct s_list *list)
{
	return ll_get(list, 0);
}
Example #13
0
int main(int argc, char *argv[]) {
    char buf[1024];
    char *p;
    LinkedList *ll;
    long i, n;
    FILE *fd;
    char **array;
    Iterator *it;

    if (argc != 2) {
        fprintf(stderr, "usage: ./lltest file\n");
        return -1;
    }
    if ((ll = ll_create()) == NULL) {
        fprintf(stderr, "Error creating linked list of strings\n");
        return -1;
    }
    if ((fd = fopen(argv[1], "r")) == NULL) {
        fprintf(stderr, "Unable to open %s to read\n", argv[1]);
        return -1;
    }
    /*
     * test of add()
     */
    printf("===== test of add\n");
    while (fgets(buf, 1024, fd) != NULL) {
        if ((p = strdup(buf)) == NULL) {
            fprintf(stderr, "Error duplicating string\n");
            return -1;
        }
        if (!ll_add(ll, p)) {
            fprintf(stderr, "Error adding string to linked list\n");
            return -1;
        }
    }
    fclose(fd);
    n = ll_size(ll);
    /*
     * test of get()
     */
    printf("===== test of get\n");
    for (i = 0; i < n; i++) {
        if (!ll_get(ll, i, (void **)&p)) {
            fprintf(stderr, "Error retrieving %ld'th element\n", i);
            return -1;
        }
        printf("%s", p);
    }
    /*
     * test of remove
     */
    printf("===== test of remove\n");
    for (i = n - 1; i >= 0; i--) {
        if (!ll_remove(ll, i, (void **)&p)) {
            fprintf(stderr, "Error removing string from linked list\n");
            return -1;
        }
        free(p);
    }
    /*
     * test of destroy with NULL userFunction
     */
    printf("===== test of destroy(NULL)\n");
    ll_destroy(ll, NULL);
    /*
     * test of insert
     */
    if ((ll = ll_create()) == NULL) {
        fprintf(stderr, "Error creating linked list of strings\n");
        return -1;
    }
    fd = fopen(argv[1], "r");		/* we know we can open it */
    printf("===== test of insert\n");
    while (fgets(buf, 1024, fd) != NULL) {
        if ((p = strdup(buf)) == NULL) {
            fprintf(stderr, "Error duplicating string\n");
            return -1;
        }
        if (!ll_insert(ll, 0, p)) {
            fprintf(stderr, "Error adding string to linked list\n");
            return -1;
        }
    }
    fclose(fd);
    for (i = 0; i < n; i++) {
        if (!ll_get(ll, i, (void **)&p)) {
            fprintf(stderr, "Error retrieving %ld'th element\n", i);
            return -1;
        }
        printf("%s", p);
    }
    /*
     * test of set
     */
    printf("===== test of set\n");
    for (i = 0; i < n; i++) {
        char bf[1024], *q;
        sprintf(bf, "line %ld\n", i);
        if ((p = strdup(bf)) == NULL) {
            fprintf(stderr, "Error duplicating string\n");
            return -1;
        }
        if (!ll_set(ll, i, p, (void **)&q)) {
            fprintf(stderr, "Error replacing %ld'th element\n", i);
            return -1;
        }
        free(q);
    }
    /*
     * test of toArray
     */
    printf("===== test of toArray\n");
    if ((array = (char **)ll_toArray(ll, &n)) == NULL) {
        fprintf(stderr, "Error in invoking ll_toArray()\n");
        return -1;
    }
    for (i = 0; i < n; i++) {
        printf("%s", array[i]);
    }
    free(array);
    /*
     * test of iterator
     */
    printf("===== test of iterator\n");
    if ((it = ll_it_create(ll)) == NULL) {
        fprintf(stderr, "Error in creating iterator\n");
        return -1;
    }
    while (it_hasNext(it)) {
        char *p;
        (void) it_next(it, (void **)&p);
        printf("%s", p);
    }
    it_destroy(it);
    /*
     * test of destroy with free() as userFunction
     */
    printf("===== test of destroy(free)\n");
    ll_destroy(ll, free);

    return 0;
}
Example #14
0
static void write_cf(void)
{
	char tmp[0x100], rv[0x40];
	struct conf_item *ci = NULL;
	char *lp, *cp;
	int add, i;
	char *cfname = get_confname();
	int cfld = ll_create();
	FILE *fd = fopen(cfname, "w");

	if (fd == NULL)
		err_sys("failed to open configuration file '%s'", cfname);

	for (ll_reset(conf_items); (ci = ll_getall(conf_items)); ) {
		if (ci->type != t_sep && ci->type != t_func &&
		    (!ci->dep || (ci->dep && *ci->dep))) {
			switch (ci->type) {
			case t_int:
				sprintf(rv, "%d", *ci->v.i);
				break;
			case t_list:
				if (!argv_count(ci->list))
					continue;
				sprintf(rv, "%s", ci->list[*ci->v.i]);
				str_tolower(rv);
				break;
			case t_sep:
			case t_func:
				break;
			}

			add = 1;

			for (i = 0; i < ll_size(cfld); i++) {
				lp = ll_get(cfld, i);
				cp = lp += strspn(lp, " ");
				if (!strncasecmp(cp, ci->cfname, strcspn(cp, " ="))
				    && strlen(ci->cfname) == strcspn(cp, " =")) {
					add = 0;
					cp += strcspn(cp, "=") + 1;
					cp += strspn(cp, " ");
					strncpy(tmp, cp, strcspn(cp, " #\n"));
					if (strcasecmp(tmp, rv)) {
						strncpy(tmp, lp, strcspn(lp, " ="));
						tmp[strcspn(lp, " =")] = '\0';
						strcat(tmp, " = ");
						strcat(tmp, rv);
						strcat(tmp, "\n");
						ll_replace(cfld, i, "s", tmp);
					}
				}
			}

			if (add) {
				strcpy(tmp, ci->cfname);
				strcat(tmp, " = ");
				strcat(tmp, rv);
				strcat(tmp, "\n");
				ll_push(cfld, "s", tmp);
			}
		}
	}

	for (ll_reset(cfld); (lp = ll_getall(cfld)); )
		fputs(lp, fd);
	fclose(fd);

	ll_destroy(cfld);
	free(cfname);
}
Example #15
0
void *socket_thread(void *thread) {
    int server_fd = ((thread_data *) thread)->socket;
    struct sockaddr_storage client_addr;
    int client_addr_size;
    int client_fd;
    thread_id send_thread_id, receive_thread_id;
    int bytes_handled;
    char buffer[BUFFER_SIZE];
    time_t current_time;
    size_t time_buffer_bytes;
    struct tm *local_time;

    while(true) {
        client_addr_size = sizeof(client_addr);
        lock(&accept_lock);
        client_fd = accept(server_fd, (struct sockaddr *) &client_addr,
                           &client_addr_size);
        if(client_fd == -1) {
            close(client_fd);
            continue;
        }
        unlock(&accept_lock);

        ((thread_data *) thread)->socket = client_fd;

        start_joinable_thread(&receive_thread_id, receive_thread, thread);

        ll_clear(((thread_data *) thread)->message_queue);

        for(;;) {
            sleep(1);
            if(ll_size(((thread_data *) thread)->message_queue)) {
                message *sending_message = ll_get(((thread_data *) thread)->message_queue, 0);

                current_time = time(NULL);
                local_time = localtime(&current_time);
                if(local_time != NULL) {
                    time_buffer_bytes = strftime(buffer, BUFFER_SIZE,
                                                 "%a, %d %b %Y %T %Z", local_time);
                    if(time_buffer_bytes != 0) {
                        sending_message->headers[sending_message->header_size] =
                            (char *) malloc(strlen("Echoed-at: ") +
                                            strlen(buffer) + strlen("\r\r"));
                        strcpy(sending_message->headers[sending_message->header_size],
                               "Echoed-at: ");
                        strcat(sending_message->headers[sending_message->header_size],
                               buffer);
                        strcat(sending_message->headers[sending_message->header_size],
                               "\r\n");
                        sending_message->header_size++;
                    }
                }

                int line_index;
                for(line_index = 0; line_index < sending_message->header_size; line_index++) {
                    if(write(client_fd, sending_message->headers[line_index], strlen(sending_message->headers[line_index])) != strlen(sending_message->headers[line_index])) {
                        syslog(LOG_INFO, "Error writing");
                    }
                    free(sending_message->headers[line_index]);
                }
                write(client_fd, "\r\n", strlen("\r\n"));
                syslog(LOG_INFO, "Message");
                for(line_index = 0; line_index < sending_message->message_size; line_index++) {
                    if(write(client_fd, sending_message->message[line_index], strlen(sending_message->message[line_index])) != strlen(sending_message->message[line_index])) {
                        syslog(LOG_INFO, "Error writing");
                    }
                    free(sending_message->message[line_index]);
                }
                write(client_fd, "\r\n", strlen("\r\n"));
                free(sending_message->headers);
                free(sending_message->message);
                free(sending_message);
                ll_remove(((thread_data *) thread)->message_queue, 0);
            }

            if(((thread_data *) thread)->should_shutdown == 1) {
                break;
            }
        }

        ll_clear(((thread_data *) thread)->message_queue);

        join_thread(&receive_thread_id);

        close(client_fd);

    }

    return NULL;
}