language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/* -------------------------
* ESTR 3106 - Assignment 1
* Name : Huzeyfe KIRAN
* Student ID : 1155104019
* Email : [email protected]
*
* Success
* -----------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <curses.h>
#include "message.h"
#include "simpl.h"
void whoPressedWhat(int key, int *whoPressed, int *whatIsPressed);
void enqueue_0(int whoPressed, int whoPressedWhat);
struct node *dequeue_0();
void enqueue_1(int whoPressed, int whoPressedWhat);
struct node *dequeue_1();
struct node{
int values[2]; // first element for storing which player pressed, second element for the key pressed.
struct node *next;
};
struct node *front_0 = NULL; // queue for storing commands from keyboard for player 0.
struct node *rear_0 = NULL;
struct node *front_1 = NULL; // queue for storing commands from keyboard for player 1.
struct node *rear_1 = NULL;
int isGameOver = 0;
int canQuitNow = 0;
int main(){
int target;
char *fromWhom = NULL;
char *cour0 = NULL;
char *cour1 = NULL;
MESSAGE msg, reply;
char name[] = "Input_Admin";
int number_of_couriers_attached = 0;
initscr();
keypad(stdscr, TRUE);
ARENA arena;
if(name_attach(name, NULL) == -1){
fprintf(stderr, "Cannot attach name!\n");
exit(0);
}
int numberOfCouriersDeliveredENDmsg = 0;
while(!canQuitNow){
if(Receive(&fromWhom, &msg, sizeof(msg)) == -1){
fprintf(stderr, "Cannot receive message!\n");
exit(0);
}
switch(msg.type){
case REGISTER_COURIER: // Couriers register to Input_Admin
if(number_of_couriers_attached < 2){
switch(number_of_couriers_attached){
case 0:
cour0 = fromWhom;
break;
case 1:
cour1 = fromWhom;
break;
}
number_of_couriers_attached++;
reply.type = INIT;
reply.humanId = number_of_couriers_attached - 1;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot reply to Courier_%d!\n",reply.humanId);
exit(0);
}
}
else{ // more than 2 couriers
reply.type = FAIL;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot reply to Courier_%d!\n",number_of_couriers_attached - 1);
exit(0);
}
}
break;
case COURIER_READY: // courier notifies that it is ready
reply.type = REGISTER_HUMAN;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot reply to Courier_%d!\n",number_of_couriers_attached - 1);
exit(0);
}
break;
case INIT: // courier notifies registration is successful
reply.type = HUMAN_READY;
reply.humanId = msg.humanId;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot set human to ready!\n");
exit(0);
}
break;
case FAIL: // courier notifies that registration failed
fprintf(stderr, "FAIL!\n");
break;
case START: // courier notifies that game started
arena = msg.arena;
if(msg.humanId == 0){
if(front_0 == NULL){ // if queue is empty, send useless reply.
reply.type = HUMAN_MOVE;
reply.humanId = 0;
reply.act = NOACTION;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot pass HUMAN_MOVE to courier!\n");
exit(0);
}
}
else{
struct node *p;
p = dequeue_0();
reply.type = HUMAN_MOVE;
reply.humanId = p->values[0];
reply.act = (ACTION) p->values[1];
free(p);
if(Reply(cour0, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot pass HUMAN_MOVE to courier!\n");
exit(0);
}
}
}
else if(msg.humanId == 1){
if(front_1 == NULL){ // if queue is empty, send useless reply.
reply.type = HUMAN_MOVE;
reply.humanId = 1;
reply.act = NOACTION;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot pass HUMAN_MOVE to courier!\n");
exit(0);
}
}
else{
struct node *p;
p = dequeue_1();
reply.type = HUMAN_MOVE;
reply.humanId = p->values[0];
reply.act = (ACTION) p->values[1];
free(p);
if(Reply(cour1, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot pass HUMAN_MOVE to courier!\n");
exit(0);
}
}
}
break;
case UPDATE: // courier notifies of the current game state
arena = msg.arena;
if(msg.humanId == 0){
if(front_0 == NULL){ // if queue is empty, send useless reply.
reply.type = HUMAN_MOVE;
reply.humanId = 0;
reply.act = NOACTION;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot pass HUMAN_MOVE to courier!\n");
exit(0);
}
}
else{
struct node *p;
p = dequeue_0();
reply.type = HUMAN_MOVE;
reply.humanId = p->values[0];
reply.act = (ACTION) p->values[1];
free(p);
if(Reply(cour0, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot pass HUMAN_MOVE to courier!\n");
exit(0);
}
}
}
else if(msg.humanId == 1){
if(front_1 == NULL){ // if queue is empty, send useless reply.
reply.type = HUMAN_MOVE;
reply.humanId = 1;
reply.act = NOACTION;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot pass HUMAN_MOVE to courier!\n");
exit(0);
}
}
else{
struct node *p;
p = dequeue_1();
reply.type = HUMAN_MOVE;
reply.humanId = p->values[0];
reply.act = (ACTION) p->values[1];
free(p);
if(Reply(cour1, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot pass HUMAN_MOVE to courier!\n");
exit(0);
}
}
}
break;
case END: // courier notifies that the game ended
numberOfCouriersDeliveredENDmsg++;
if(numberOfCouriersDeliveredENDmsg == 2){
isGameOver = 1;
}
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot reply to Courier!\n");
exit(0);
}
break;
case REGISTER_KEYBOARD: // keyboard registers
reply.type = INIT;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot reply to Keyboard!\n");
exit(0);
}
break;
case KEYBOARD_READY: // keyboard notifies that it is ready
reply.type = START;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot reply to Keyboard!\n");
exit(0);
}
break;
case KEYBOARD_INPUT: // keyboard notifies that there is a key pressed
if(isGameOver){
canQuitNow = 1;
reply.type = END;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot signal the END!\n");
exit(0);
}
break;
}
int whoPressed;
int whatIsPressed;
whoPressedWhat(msg.key, &whoPressed, &whatIsPressed);
if(whoPressed == 0){
enqueue_0(whoPressed, whatIsPressed);
}
else{
enqueue_1(whoPressed, whatIsPressed);
}
reply.type = OKAY;
if(Reply(fromWhom, &reply, sizeof(reply)) == -1){
fprintf(stderr, "Cannot reply to Keyboard!\n");
exit(0);
}
break;
}
}
if(name_detach() == -1){
fprintf(stderr, "Cannot detach name!\n");
exit(0);
}
}
void whoPressedWhat(int key, int *whoPressed, int *whatIsPressed){
switch(key){
case ((int) 'w'):
*whoPressed = 0;
*whatIsPressed = MOVENORTH;
break;
case ((int) 'a'):
*whoPressed = 0;
*whatIsPressed = MOVEWEST;
break;
case ((int) 's'):
*whoPressed = 0;
*whatIsPressed = MOVESOUTH;
break;
case ((int) 'd'):
*whoPressed = 0;
*whatIsPressed = MOVEEAST;
break;
case (KEY_UP):
*whoPressed = 1;
*whatIsPressed = MOVENORTH;
break;
case (KEY_LEFT):
*whoPressed = 1;
*whatIsPressed = MOVEWEST;
break;
case (KEY_DOWN):
*whoPressed = 1;
*whatIsPressed = MOVESOUTH;
break;
case (KEY_RIGHT):
*whoPressed = 1;
*whatIsPressed = MOVEEAST;
break;
case ((int) 'f'):
*whoPressed = 0;
*whatIsPressed = PLACELANCER;
break;
case ((int) 'g'):
*whoPressed = 0;
*whatIsPressed = PLACEHOPLITE;
break;
case ((int) 'j'):
*whoPressed = 1;
*whatIsPressed = PLACELANCER;
break;
case ((int) 'k'):
*whoPressed = 1;
*whatIsPressed = PLACEHOPLITE;
break;
case ((int) 'r'):
*whoPressed = 0;
*whatIsPressed = UPDATEMINE;
break;
case ((int) 't'):
*whoPressed = 0;
*whatIsPressed = UPDATEWALL;
break;
case ((int) 'u'):
*whoPressed = 1;
*whatIsPressed = UPDATEMINE;
break;
case ((int) 'i'):
*whoPressed = 1;
*whatIsPressed = UPDATEWALL;
break;
}
}
void enqueue_0(int whoPressed, int whoPressedWhat){
struct node *nptr = malloc(sizeof(struct node));
nptr->values[0] = whoPressed;
nptr->values[1] = whoPressedWhat;
nptr->next = NULL;
if (rear_0 == NULL){
front_0 = nptr;
rear_0 = nptr;
}
else{
rear_0->next = nptr;
rear_0 = rear_0->next;
}
}
struct node *dequeue_0(){
if (front_0 == NULL){
return NULL;
}
else if(front_0 == rear_0){
struct node *temp;
temp = front_0;
front_0 = NULL;
rear_0 = NULL;
return temp;
}
else{
struct node *temp;
temp = front_0;
front_0 = front_0->next;
return temp;
}
}
void enqueue_1(int whoPressed, int whoPressedWhat){
struct node *nptr = malloc(sizeof(struct node));
nptr->values[0] = whoPressed;
nptr->values[1] = whoPressedWhat;
nptr->next = NULL;
if (rear_1 == NULL){
front_1 = nptr;
rear_1 = nptr;
}
else{
rear_1->next = nptr;
rear_1 = rear_1->next;
}
}
struct node *dequeue_1(){
if (front_1 == NULL){
return NULL;
}
else if(front_1 == rear_1){
struct node *temp;
temp = front_1;
front_1 = NULL;
rear_1 = NULL;
return temp;
}
else{
struct node *temp;
temp = front_1;
front_1 = front_1->next;
return temp;
}
}
|
C
|
#include <stdlib.h>
#include <libgen.h>
#include "oufs_lib.h"
#include "oufs.h"
#define debug 0
#define MAX_BUFFER 1024
/**
* Compares a string directory_entry_a with the second string directory_entry_b. It is used as the function for qsort when outputting the directory entries in sorted order
*
* @param directory_entry_a The first string to compare
* @param directory_entry_b The second string to compare
* @return An int that decides which string should go before the other
*/
int string_compare(const void *directory_entry_a, const void *directory_entry_b)
{
//Directory entry a
DIRECTORY_ENTRY *a = (DIRECTORY_ENTRY *) directory_entry_a;
//Directory entry b
DIRECTORY_ENTRY *b = (DIRECTORY_ENTRY *) directory_entry_b;
//String compare
return strcmp(a->name, b->name);
}
/**
* Function takes a string and mutates it a certain way depending on what begin and length are. It starts cutting out portions of the string at the begin int, then cuts out a length equal to the length int. What comes out is a mutated string that was cut at specified indexes.
*
* @param char *str The buffer that holds the string to mutate
* @param int begin Where to start cutting in the string
* @param int length How much of the string to cut after int begin
* @return len The length of the original string
*/
int clip(char *str, int begin, int length) {
//Getting length of the buffer
int len_of_string = strlen(str);
//Checks parameters
if (length < 0) {
length = len_of_string - begin;
}
//Checks parameters
if (begin + length > len_of_string) {
length = len_of_string - begin;
}
//Punches portions of the string
memmove(str + begin, str + begin + length, len_of_string - length + 1);
return length;
}
/**
* Prints out the directories listed in the block parameter. First it sorts the entries using qsort, then lists out the entries with a / or no slash depending on if the entry is a directory or file in sorted order. The block is mutated during qsort, but not written back to the disk so that the sorted order isn't in the disk.
*
* @param INODE inode Used to check if an entry is a file or directory
* @param BLOCK block Used to go through the directory entries
* @param char *base_name Used for if the inode is a file, and it prints out just the base_name
*/
void list_directory_entries(INODE *inode, BLOCK *block, char *base_name) {
//Check if inode of basename is directory or file
if (inode->type == IT_DIRECTORY) {
//qsort the entries and print them out
qsort(block->directory.entry, 16, sizeof(DIRECTORY_ENTRY), string_compare);
//Loop through entries
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if(block->directory.entry[i].inode_reference != UNALLOCATED_INODE) {
printf("%s", block->directory.entry[i].name);
//Checking to see if the inode of the entry is a directory or file
INODE_REFERENCE inode_ref = block->directory.entry[i].inode_reference;
INODE mock_inode;
oufs_read_inode_by_reference(inode_ref, &mock_inode);
if (mock_inode.type == IT_DIRECTORY) {
printf("/\n");
} else if (mock_inode.type == IT_FILE) {
printf("\n");
}
}
}
exit(EXIT_SUCCESS);
}
//If the inode is a file
if (inode->type == IT_FILE) {
printf("%s\n", base_name);
}
}
/**
* A function that looks for the specified path where is returns the inode of the parent of the specified path. It steps through inodes and blocks sequentially to gather what entries are where. This function is good if the path is absolute, or if the path includes subdirectories and it needs to step through those to find what entries are where. It will use base_name and mkdir_flag to make decisions about what it needs to look for. Base_name is used to check to see if the path base_name is already in the list of entries; so it throws an error depending on what funciton we are in. The mkdir_flag is used to specify if we in the mkdir function and we are creating a directory.
*
* @param char *path The path for the function to take to find the parent inode that it returns
* @param INODE_REFERERNCE base_inode the inode to start at to find path, can be 0 for base inode, or other inode already allocated
* @param char *base_name Contains the base name of path
* @param int mkdir_flag Flag used depending on if we are creating a directory entry, not a file
* @return The parent inode of where we need to do operations
*/
INODE_REFERENCE oufs_look_for_inode_from_root(char *path, INODE_REFERENCE base_inode, char *base_name, int mkdir_flag) {
//Varibles for tokenizing inputs of the parameter
char *path_tokens[64];
char **path_arg;
//Tokenize input
path_arg = path_tokens;
*path_arg++ = strtok(path, "/");
while ((*path_arg++ = strtok(NULL, "/")));
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
int counter = 0;
//Go through parameters of path
for (int i = 0; i < 64; ++i) {
if (debug) {
printf("Path_token[%d]: %s\n", counter, path_tokens[counter]);
}
//If empty element in path
if (path_tokens[counter] == NULL) {
break;
}
if (mkdir_flag == 1) {
if (!strcmp(base_name, path_tokens[counter])) {
break;
}
}
if(block.directory.entry[i].inode_reference != UNALLOCATED_INODE) {
if(!strcmp(block.directory.entry[i].name, path_tokens[counter])) {
//Getting inode reference of entry found
base_inode = block.directory.entry[i].inode_reference;
//Get inode of inode reference
oufs_read_inode_by_reference(base_inode, &inode);
if (inode.type == IT_DIRECTORY) {
//Getting block reference in inode
base_block = inode.data[0];
//Setting block to newly found block
vdisk_read_block(base_block, &block);
} else if (inode.type == IT_FILE) {
break;
}
//Reset for loop
i = 0;
++counter;
}
} else if (i == 14 && block.directory.entry[i].inode_reference == UNALLOCATED_INODE) {
fprintf(stderr, "ERROR: Parent directory doesn't exist\n");
exit(EXIT_FAILURE);
break;
}
}
return base_inode;
}
/**
* Same functionality of oufs_look_for_inode_from_root but it starts finding the path from cwd first. The main functionality comes when path_flag is enabled. If path_flag is enabled it allows a user to start at a cwd that's not the root, then continue with path in oufs_look_for_inode_from_root since the latter function starts at what "root" we give it. So it uses 2 functions if you want to to move through cwd and path.
*
* @param char *path The path to take for oufs_look_for_inode_from_root
* @param char *cwd The cwd path to take to find normal root
* @param INODE_REFERENCE base_inode base_inode or "root" to start at, is always going to be 0
* @param char *base_name path name of path
* @param int path_flag If we want to search through the path as well
* @param int mkdir_flag If we are mkaing a directory
* @return The parent inode to do operations in
*/
INODE_REFERENCE oufs_look_for_inode_not_from_root(char *path, char *cwd, INODE_REFERENCE base_inode, char *base_name, int path_flag, int mkdir_flag) {
//Variables for tokenizing inputs of the cwd
char *cwd_tokens[64];
char **cwd_arg;
//Tokenize input
cwd_arg = cwd_tokens;
*cwd_arg++ = strtok(cwd, "/");
while ((*cwd_arg++ = strtok(NULL, "/")));
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
//Counter for cwd_tokens
int counter = 0;
/* Go through cwd_tokens and match arguments to entries in the
directory entry. Then grab inode and block of that directory and repeat
*/
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
//If empty element in cwd
if (cwd_tokens[counter] == NULL) {
break;
}
//Check to see if entry contains name
if(block.directory.entry[i].inode_reference != UNALLOCATED_INODE) {
if(!strcmp(block.directory.entry[i].name, cwd_tokens[counter])) {
//Getting inode reference of entry found
base_inode = block.directory.entry[i].inode_reference;
//Get inode of inode reference
oufs_read_inode_by_reference(base_inode, &inode);
//Getting block reference in inode
base_block = inode.data[0];
//Setting block to newly found block
vdisk_read_block(base_block, &block);
//Reset for loop
i = 0;
++counter;
}
//Went through entire entry list and didn't find parent
} else {
fprintf(stderr, "ERROR: (zfilez, current working directory is not root, and no parameter specified): Parent directory doesn't exist\n");
exit(EXIT_FAILURE);
break;
}
}
if (debug) {
printf("Base_inode after cwd: %d\n", base_inode);
}
//If we want to continue through path
if (path_flag == 1) {
//If we are making a directory
if (mkdir_flag == 1) {
base_inode = oufs_look_for_inode_from_root(path, base_inode, base_name, 1);
} else {
//If we are making a file
base_inode = oufs_look_for_inode_from_root(path, base_inode, base_name, 0);
}
if (debug) {
printf("Base_inode after cwd after path: %d\n", base_inode);
}
}
return base_inode;
}
/**
* Read the ZPWD and ZDISK environment variables & copy their values into cwd and disk_name.
* If these environment variables are not set, then reasonable defaults are given.
*
* @param cwd String buffer in which to place the OUFS current working directory.
* @param disk_name String buffer containing the file name of the virtual disk.
*/
void oufs_get_environment(char *cwd, char *disk_name)
{
// Current working directory for the OUFS
char *str = getenv("ZPWD");
if(str == NULL) {
// Provide default
strcpy(cwd, "/");
} else {
// Exists
strncpy(cwd, str, MAX_PATH_LENGTH-1);
}
// Virtual disk location
str = getenv("ZDISK");
if(str == NULL) {
// Default
strcpy(disk_name, "vdisk1");
}else{
// Exists: copy
strncpy(disk_name, str, MAX_PATH_LENGTH-1);
}
}
/**
* Configure a directory entry so that it has no name and no inode
*
* @param entry The directory entry to be cleaned
*/
void oufs_clean_directory_entry(DIRECTORY_ENTRY *entry)
{
entry->name[0] = 0; // No name
entry->inode_reference = UNALLOCATED_INODE;
}
/**
* Create a virtual disk with initial inode and directory set up
*
* @param virtual_disk_name The name of the virtual disk
*/
int oufs_format_disk(char *virtual_disk_name) {
if (vdisk_disk_open(virtual_disk_name) != 0) {
fprintf(stderr, "ERROR: openening vdisk\n");
return -1;
}
BLOCK b;
memset(b.data.data, 0, sizeof(b));
for (int i = 0; i < N_BLOCKS_IN_DISK; i++) {
if (vdisk_write_block(i, &b) != 0) {
fprintf(stderr, "ERROR: writing 0 to block\n");
return -1;
}
}
//Mark the blocks as allocated
b.master.inode_allocated_flag[0] = 1;
b.master.block_allocated_flag[0] = 0xff;
b.master.block_allocated_flag[1] = 0x3;
for (int i = 0; i < N_BLOCKS_IN_DISK; i++) {
if (vdisk_write_block(i, &b) != 0) {
fprintf(stderr, "ERROR: writing 0 to block\n");
return -1;
}
}
//Initializing inode
INODE inode;
inode.data[0] = 9;
inode.type = IT_DIRECTORY;
for (int i = 1; i < 15; i++) {
inode.data[i] = UNALLOCATED_INODE;
}
inode.n_references = 1;
inode.size = 2;
b.inodes.inode[0] = inode;
//Writing inode to disk
vdisk_write_block(1, &b);
oufs_clean_directory_block(0, 0, &b);
//Writing directories to disk
vdisk_write_block(9, &b);
//Return success
return 0;
}
/**
* Find the first open bit in a byte
*
* @param val The byte that contains an open bit
* @return 0-7 = bit to allocate in byte
* -1 = error occurred
*/
int oufs_find_open_bit(unsigned char val) {
//If first bit is open
if (!(val & 0x1)) {
return 0;
}
//If second bit is open
if (!(val & 0x2)) {
return 1;
}
//If third bit is open
if (!(val & 0x4)) {
return 2;
}
//If fourth bit is open
if (!(val & 0x8)) {
return 3;
}
//If fifth bit is open
if (!(val & 0x10)) {
return 4;
}
//If sixth bit is open
if (!(val & 0x20)) {
return 5;
}
//If seventh bit is open
if (!(val & 0x40)) {
return 6;
}
//If eighth bit is open
if (!(val & 0x80)) {
return 7;
}
//Return error if no open bit found
return -1;
}
/**
* Initialize a directory block as an empty directory
*
* @param self Inode reference index for this directory
* @param self Inode reference index for the parent directory
* @param block The block containing the directory contents
*/
void oufs_clean_directory_block(INODE_REFERENCE self, INODE_REFERENCE parent, BLOCK *block)
{
// Debugging output
if(debug)
fprintf(stderr, "New clean directory: self=%d, parent=%d\n", self, parent);
// Create an empty directory entry
DIRECTORY_ENTRY entry;
oufs_clean_directory_entry(&entry);
// Copy empty directory entries across the entire directory list
for(int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
block->directory.entry[i] = entry;
}
// Now we will set up the two fixed directory entries
// Self
strncpy(entry.name, ".", 2);
entry.inode_reference = self;
block->directory.entry[0] = entry;
// Parent
strncpy(entry.name, "..", 3);
entry.inode_reference = parent;
block->directory.entry[1] = entry;
}
/**
* Allocate a new data block
*
* If one is found, then the corresponding bit in the block allocation table is set
*
* @return The index of the allocated data block. If no blocks are available,
* then UNALLOCATED_BLOCK is returned
*/
BLOCK_REFERENCE oufs_allocate_new_block()
{
BLOCK block;
// Read the master block
vdisk_read_block(MASTER_BLOCK_REFERENCE, &block);
// Scan for an available block
int block_byte;
int flag;
// Loop over each byte in the allocation table.
for(block_byte = 0, flag = 1; flag && block_byte < N_BLOCKS_IN_DISK / 8; ++block_byte) {
if(block.master.block_allocated_flag[block_byte] != 0xff) {
// Found a byte that has an opening: stop scanning
flag = 0;
break;
};
};
// Did we find a candidate byte in the table?
if(flag == 1) {
// No
if(debug)
fprintf(stderr, "No open blocks\n");
return(UNALLOCATED_BLOCK);
}
// Found an available data block
// Set the block allocated bit
// Find the FIRST bit in the byte that is 0 (we scan in bit order: 0 ... 7)
int block_bit = oufs_find_open_bit(block.master.block_allocated_flag[block_byte]);
// Now set the bit in the allocation table
block.master.block_allocated_flag[block_byte] |= (1 << block_bit);
// Write out the updated master block
vdisk_write_block(MASTER_BLOCK_REFERENCE, &block);
if(debug)
fprintf(stderr, "Allocating block=%d (%d)\n", block_byte, block_bit);
// Compute the block index
BLOCK_REFERENCE block_reference = (block_byte << 3) + block_bit;
if(debug)
fprintf(stderr, "Allocating block=%d\n", block_reference);
// Done
return(block_reference);
}
/**
* Allocate a new inode block
*
* If one is found, then the corresponding bit in the block allocation table is set
*
* @return The index of the allocated inode block. If no blocks are available,
* then UNALLOCATED_BLOCK is returned
*/
INODE_REFERENCE oufs_allocate_new_inode() {
BLOCK block;
//Read master block
vdisk_read_block(MASTER_BLOCK_REFERENCE, &block);
//Scan for an available block
int inode_byte;
int flag;
//Loop over each byte in the inode table
for (inode_byte = 0, flag = 1; flag && inode_byte < N_INODES / 8; ++inode_byte) {
//If byte is not full open byte was found: stop scanning
if (block.master.inode_allocated_flag[inode_byte] != 0xff) {
flag = 0;
break;
};
};
//Did we find a candidate byte in the table?
if (flag == 1) {
//No
if (debug)
fprintf(stderr, "No open blocks\n");
return (IT_NONE);
}
//Found an available data block
//Set the block allocated bit
int inode_bit = oufs_find_open_bit(block.master.inode_allocated_flag[inode_byte]);
//Now set the bit in the allocation table
block.master.inode_allocated_flag[inode_byte] |= (1 << inode_bit);
//Write to master block to update
vdisk_write_block(MASTER_BLOCK_REFERENCE, &block);
if (debug)
fprintf(stderr, "Allocating block=%d (%d)\n", inode_byte, inode_bit);
//Compute the inode index
INODE_REFERENCE inode_reference = (inode_byte << 3) + inode_bit;
if (debug)
fprintf(stderr, "Allocating block=%d\n", inode_reference);
return(inode_reference);
}
/**
* Given an inode reference, read the inode from the virtual disk.
*
* @param i Inode reference (index into the inode list)
* @param inode Pointer to an inode memory structure. This structure will be
* filled in before return)
* @return 0 = successfully loaded the inode
* -1 = an error has occurred
*/
int oufs_read_inode_by_reference(INODE_REFERENCE i, INODE *inode)
{
if(debug)
fprintf(stderr, "Fetching inode %d\n", i);
// Find the address of the inode block and the inode within the block
BLOCK_REFERENCE block = i / INODES_PER_BLOCK + 1;
int element = (i % INODES_PER_BLOCK);
BLOCK b;
if(vdisk_read_block(block, &b) == 0) {
// Successfully loaded the block: copy just this inode
*inode = b.inodes.inode[element];
return(0);
}
// Error case
return(-1);
}
/**
* Given an inode reference, write the inode to the virtual disk.
*
* @param i Inode Reference (index into the inode list)
* @param inode Pointer to an inode memeory structure. This structure will be
* written to the block)
* @return 0 = successfully written to block
* -1 = an error occurred
*/
int oufs_write_inode_by_reference(INODE_REFERENCE i, INODE *inode) {
if (debug) {
printf("INODE_REFERENCE in write_inode_by_reference: %d\n", i);
}
BLOCK_REFERENCE block = i / INODES_PER_BLOCK + 1;
int element = (i % INODES_PER_BLOCK);
BLOCK b;
if (vdisk_read_block(block, &b) == 0) {
//Put inode into element in block
b.inodes.inode[element] = *inode;
//Write block back to disk
if (vdisk_write_block(block, &b) == 0) {
return (0);
}
}
return (-1);
}
/**
* Checks to see if an entry exists in a directory
*
* @param BLOCK block The block to take an look through its entries
* @param char *base_name The name of the new entry to look through
* @param int flag If we are checking for the file in the list of entries
* @return True, false, 2 for Entry with same name if file, -2 for directory
*/
int check_for_entry(BLOCK *block, char *base_name, int flag) {
//Check to see if basename is in the list of entries
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if(block->directory.entry[i].inode_reference != UNALLOCATED_INODE) {
if (!strcmp(block->directory.entry[i].name, base_name)) {
//For file clarification
if (flag == 1) {
INODE_REFERENCE base_inode;
INODE inode;
//Getting inode reference of entry found
base_inode = block->directory.entry[i].inode_reference;
//Get inode of inode reference
oufs_read_inode_by_reference(base_inode, &inode);
if (inode.type == IT_FILE) {
return 1;
} else {
fprintf(stderr, "ERROR: Entry with same name found and is a directory, not file\n");
return 2;
}
}
return -1;
}
} else {
break;
}
}
return 0;
}
/**
* Gets the information of the specified entry and returns the inode reference of that entry
*
* @param BLOCK_REFERENCE base_block the block reference of the parent block
* @param INODE_REFERENCE inode_reference inode referene of parent inode
* @param char *base_name Entry to find
* @return INODE_REFERENCE of the entry of base_name
*/
INODE_REFERENCE get_specified_entry(BLOCK_REFERENCE base_block, INODE_REFERENCE base_inode, char *base_name) {
//Read in parent block
BLOCK parent_block;
vdisk_read_block(base_block, &parent_block);
//Inode reference of entry to delete
INODE_REFERENCE key_inode_reference;
//Get inode reference of entry to delete
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if (!strcmp(parent_block.directory.entry[i].name, base_name)) {
key_inode_reference = parent_block.directory.entry[i].inode_reference;
if (debug) {
printf("Found base name: %s in block.directory.entry[i].name: %s\n", base_name, parent_block.directory.entry[i].name);
}
break;
}
}
//Returning inode reference of specified entry
return key_inode_reference;
}
/**
* This function removes only files. It removes them depending on the amount of n_references int the inode of the file you are trying to delete. If n_references is 1, then it resets the entire inode, deallocates on master tables, erases entry from parent directory, and memsets data blocks allocated to inode. If n_references is bigger than 1, then it only decrements n_references of it inode, and erases its entry in the parent directory.
*
* @param BLOCK_REFERENCE base_block Block reference of parent block
* @param INODE_REFERENCE base_inode Inode reference of inode of parent
* @param char *base_name Name of entry to delete
* @return nothing
*/
void oufs_rmfile(BLOCK_REFERENCE base_block, INODE_REFERENCE base_inode, char *base_name) {
//Read in parent block
BLOCK parent_block;
vdisk_read_block(base_block, &parent_block);
if (debug) {
printf("Base_name: %s\n", base_name);
}
//Inode reference of entry to delete
INODE_REFERENCE inode_to_delete;
int n_references = 1;
//Get inode reference of entry to delete
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if (!strcmp(parent_block.directory.entry[i].name, base_name)) {
inode_to_delete = parent_block.directory.entry[i].inode_reference;
if (debug) {
printf("Found base name: %s in block.directory.entry[i].name: %s\n", base_name, parent_block.directory.entry[i].name);
}
//Check the n_references to know how to delete it
INODE inode_of_to_delete;
oufs_read_inode_by_reference(inode_to_delete, &inode_of_to_delete);
//Get n_references from inode_of_to_delete (the inode we possibly need to delete)
n_references = inode_of_to_delete.n_references;
//Clean the entry
oufs_clean_directory_entry(&parent_block.directory.entry[i]);
}
}
//Writ block back to disk
vdisk_write_block(base_block, &parent_block);
//Decrement parent inode size
INODE parent_inode;
oufs_read_inode_by_reference(base_inode, &parent_inode);
//Increment parent inode size
parent_inode.size = parent_inode.size - 1;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &parent_inode);
//Reading in inode to delete
INODE deleting_inode;
oufs_read_inode_by_reference(inode_to_delete, &deleting_inode);
if (n_references == 1) {
//Go through inode data blocks, deallocate them, reset inode, deallocate in table, memset blocks
for (int i = 0; i < BLOCKS_PER_INODE; ++i) {
//If UNALLOCATED_INODE block found break
if (deleting_inode.data[i] == UNALLOCATED_INODE) {
break;
}
//Grab block reference
BLOCK_REFERENCE old_block = deleting_inode.data[i];
//Unallocate in inode
deleting_inode.data[i] = UNALLOCATED_INODE;
if (debug) {
printf("Old block to reset: %d\n", old_block);
}
//Read in old block to empty out
BLOCK empty_block;
vdisk_read_block(old_block, &empty_block);
//Reset raw data in block
memset(empty_block.data.data, 0, sizeof(empty_block));
//Write new empty block back
vdisk_write_block(old_block, &empty_block);
//Deallocate inode and block
int old_block_index = old_block >> 3;
int old_block_bit = old_block & 0x7;
//Read in master block
BLOCK block;
vdisk_read_block(MASTER_BLOCK_REFERENCE, &block);
//Deallocate block on master table
block.master.block_allocated_flag[old_block_index] &= ~(1 << old_block_bit);
//Write disk back to block
vdisk_write_block(MASTER_BLOCK_REFERENCE, &block);
}
//Creating new empty inode
INODE empty_inode;
for (int i = 0; i < 15; i++) {
empty_inode.data[i] = 0;
}
empty_inode.type = IT_NONE;
empty_inode.size = 0;
empty_inode.n_references = 0;
//Writing empty inode
oufs_write_inode_by_reference(inode_to_delete, &empty_inode);
//Read in block
BLOCK block;
vdisk_read_block(MASTER_BLOCK_REFERENCE, &block);
//Deallocate an reset inode of entry
int old_inode_index = inode_to_delete >> 3;
int old_inode_bit = inode_to_delete & 0x7;
//Perform bitwise operations
block.master.inode_allocated_flag[old_inode_index] &= ~(1 << old_inode_bit);
//Write disk back to block
vdisk_write_block(MASTER_BLOCK_REFERENCE, &block);
} else {
deleting_inode.n_references -= 1;
oufs_write_inode_by_reference(inode_to_delete, &deleting_inode);
}
}
/**
* Deletes a directory entry by formatting the directory block, decrementing inode size or parent inode, deallocating directory block in master table and deleting any references to the directory specified in the base_block that is found in the entries through base_name
*
* @param BLOCK_REFERENCE base_block block of parent directory
* @param INODE_REFERENCE base_inode inode of parent directory
* @param char *base_name Name of entry to delete
* @return Nothing
*/
void oufs_rmdir(BLOCK_REFERENCE base_block, INODE_REFERENCE base_inode, char *base_name) {
//Read in parent block
BLOCK parent_block;
vdisk_read_block(base_block, &parent_block);
if (debug) {
printf("Base_name: %s\n", base_name);
}
//Inode reference of entry to delete
INODE_REFERENCE inode_to_delete;
//Get inode reference of entry to delete
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if (!strcmp(parent_block.directory.entry[i].name, base_name)) {
inode_to_delete = parent_block.directory.entry[i].inode_reference;
if (debug) {
printf("Found base name: %s in block.directory.entry[i].name: %s\n", base_name, parent_block.directory.entry[i].name);
}
//Check to make sure that the directory is empty before deleting
INODE inode_of_to_delete;
oufs_read_inode_by_reference(inode_to_delete, &inode_of_to_delete);
//Get block reference of entry to delete
BLOCK_REFERENCE block_of_delete = inode_of_to_delete.data[0];
BLOCK block_to_delete;
vdisk_read_block(block_of_delete, &block_to_delete);
//Go through block entries
int delete_flag = 0;
for (int j = 0; j < DIRECTORY_ENTRIES_PER_BLOCK; ++j) {
if (!strcmp(block_to_delete.directory.entry[i].name, ".")) {
continue;
} else if (!strcmp(block_to_delete.directory.entry[i].name, "..")) {
continue;
} else if (!strcmp(block_to_delete.directory.entry[i].name, "")) {
continue;
} else {
delete_flag = 1;
}
}
if (delete_flag) {
fprintf(stderr, "ERROR: Entries exist in the directory to delete, cannot delete directory\n");
return;
} else {
//Clean the entry
oufs_clean_directory_entry(&parent_block.directory.entry[i]);
break;
}
}
}
//Writ block back to disk
vdisk_write_block(base_block, &parent_block);
if (debug) {
printf("Inode reference to delete: %d\n", inode_to_delete);
}
//Decrement parent inode size
INODE parent_inode;
oufs_read_inode_by_reference(base_inode, &parent_inode);
//Increment parent inode size
parent_inode.size = parent_inode.size - 1;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &parent_inode);
//Getting dblock to reset
INODE old_inode;
oufs_read_inode_by_reference(inode_to_delete, &old_inode);
BLOCK_REFERENCE old_block = old_inode.data[0];
if (debug) {
printf("Old block to reset: %d\n", old_block);
}
//Creating new empty inode
INODE empty_inode;
for (int i = 0; i < 15; i++) {
empty_inode.data[i] = 0;
}
empty_inode.type = IT_NONE;
empty_inode.size = 0;
empty_inode.n_references = 0;
//Writing empty inode
oufs_write_inode_by_reference(inode_to_delete, &empty_inode);
BLOCK empty_block;
vdisk_read_block(old_block, &empty_block);
DIRECTORY_ENTRY entry;
oufs_clean_directory_entry(&entry);
// Copy empty directory entries across the entire directory list
for(int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
empty_block.directory.entry[i] = entry;
}
//Write new empty block back
vdisk_write_block(old_block, &empty_block);
//Deallocate inode and block
int old_block_index = old_block >> 3;
int old_block_bit = old_block & 0x7;
int old_inode_index = inode_to_delete >> 3;
int old_inode_bit = inode_to_delete & 0x7;
//Read in block
BLOCK block;
vdisk_read_block(MASTER_BLOCK_REFERENCE, &block);
//Perform bitwise operations
block.master.inode_allocated_flag[old_inode_index] &= ~(1 << old_inode_bit);
block.master.block_allocated_flag[old_block_index] &= ~(1 << old_block_bit);
//Write disk back to block
vdisk_write_block(MASTER_BLOCK_REFERENCE, &block);
}
/**
* Creates an entry of a directory or file (depending on what the file_flag is). It allocates new references in the table for directory block an inode, but only inode for file. Write inode for both file and directory, but only a block for directory, not file.
*
* @param INODE_REFERENCE base_inode Parent inode to increment
* @param BLOCK_REFERENCE base_block Parent block to perform operations on
* @param char *base_name Char containing base name of the entry to put into directory
* @param file_flag Flag specifiing if we are making directory or file
* @return 0 on success, -1 on failure
*/
int create_new_inode_and_block(INODE_REFERENCE base_inode, BLOCK_REFERENCE base_block, char *base_name, int file_flag) {
BLOCK block;
vdisk_read_block(base_block, &block);
//Check for any open entries
int open_entries = 1;
//Looping through entries in block to check for empty entry
for (int i = 2; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if (block.directory.entry[i].inode_reference == UNALLOCATED_INODE) {
break;
}
if (i == 15 && block.directory.entry[i].inode_reference != UNALLOCATED_INODE) {
open_entries = 0;
}
}
if (open_entries == 0) {
fprintf(stderr, "ERROR: no open entries in parent directory to put new file in\n");
return -1;
}
vdisk_read_block(base_block, &block);
//New references for inode and block of new directory
INODE_REFERENCE inode_reference = oufs_allocate_new_inode();
BLOCK_REFERENCE block_reference;
if (file_flag == 0) {
block_reference = oufs_allocate_new_block();
}
if (debug) {
printf("inode reference: %d\n", inode_reference);
printf("block reference: %d\n", block_reference);
}
//Setting up new inode
INODE new_inode;
//If what we are making is a file
if (file_flag == 1) {
new_inode.type = IT_FILE;
new_inode.size = 0;
for (int i = 0; i < 15; i++) {
new_inode.data[i] = UNALLOCATED_INODE;
}
//If what we are making is a directory
} else {
new_inode.type = IT_DIRECTORY;
new_inode.size = 2;
new_inode.data[0] = block_reference;
for (int i = 1; i < 15; i++) {
new_inode.data[i] = UNALLOCATED_INODE;
}
}
//References is the same for files and directories
new_inode.n_references = 1;
//Adding new inode
oufs_write_inode_by_reference(inode_reference, &new_inode);
//Adding new directory entry
vdisk_read_block(base_block, &block);
//Looping through entries in block to check for empty entry
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if (!strcmp(block.directory.entry[i].name, "")) {
strcpy(block.directory.entry[i].name, base_name);
block.directory.entry[i].inode_reference = inode_reference;
break;
}
}
//Writing entry to block
vdisk_write_block(base_block, &block);
if (file_flag == 0) {
//Creating new block for new directory
BLOCK new_block;
//1 should be changed to inode reference
oufs_clean_directory_block(inode_reference, base_inode, &new_block);
//Writing directories to disk
vdisk_write_block(block_reference, &new_block);
}
return 0;
}
/**
* Creates a new directory depending on what paramters are specified in the CWD or path. It first checks to see if the path is relative or absolute. If the path is relative, it will go through the current working directory starting at the root and find the necessary references. The new folder will be placed in the directory specified in path, therefore the code also moves through the arguments in path trying to find the correct references to put the new directory in. If the path is absolute, it will not use the current working directory as a means of getting the references. It will only use the path and its arguments to retrieve the correct references.
*
* The parent has to exist if the path that is specified is absolute. It will throw an error if it is not.
*
* @param cwd The current working directory of the environment
* @param path The path to create the new directory in
* @param operation Hold integer that specifies what operation to do. Operation can be 0 for mkdir, 1 for rmdir, or 2 for touching file, 3 is fore removing files
* @return 0 = success
* -1 = error occured
*/
int oufs_mkdir(char *cwd, char *path, int operation) {
//Basename variable of path
char base_name[128];
char path_copy[128];
strcpy(path_copy, path);
strcpy(base_name, basename(path));
//Varibles for tokenizing inputs of the parameter
char *path_tokens[64];
char **path_arg;
//Tokenize input
path_arg = path_tokens;
*path_arg++ = strtok(path, "/");
while ((*path_arg++ = strtok(NULL, "/")));
if (strlen(base_name) > FILE_NAME_SIZE) {
//clip(top_off_buff, size_top_off, boundary);
clip(base_name, FILE_NAME_SIZE - 1, strlen(base_name));
} else {
//Do nothing
}
//Debug
if (debug) {
printf("CWD: %s\n", cwd);
printf("Path: %s\n", path);
}
//Check to see if the path is relative or absolute
if (path[0] != '/') {
if (debug) {
printf("Relative path\n");
}
//If cwd is root
if (!strcmp(cwd, "/")) {
//Get inode reference of base inode
INODE_REFERENCE base_inode = 0;
//Get block reference of base block
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
//Flag to determine if the entry already exists
int flag = 0;
//If path only has 1 token
if (path_tokens[1] == NULL) {
//Check the names of the entries
flag = check_for_entry(&block, base_name, 0);
//If path has more than 1 token means that we are trying to go for subdirectory
} else {
//Get parent inode to work off of
base_inode = oufs_look_for_inode_from_root(path_copy, base_inode, base_name, 1);
oufs_read_inode_by_reference(base_inode, &inode);
base_block = inode.data[0];
vdisk_read_block(base_block, &block);
//Check entries in the block
flag = check_for_entry(&block, base_name, 0);
}
//If operation is mkdir
if (operation == 0) {
//Checking if entry exists
if (flag == 0) {
//Create new directory
if (create_new_inode_and_block(base_inode, base_block, base_name, 0) == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
} else {
//DO NOTHING
}
} else {
fprintf(stderr, "ERROR: Entry already exists, cannot create directory\n");
return (-1);
}
}
//If operation is rmdir
else if (operation == 1) {
//Checking if entry exists
if (flag == -1) {
//Erase file
oufs_rmdir(base_block, base_inode, base_name);
} else {
fprintf(stderr, "ERROR: Entry does not already exists, cannot delete\n");
return (-1);
}
}
//If operation is touch
else if (operation == 2) {
flag = check_for_entry(&block, base_name, 1);
//Checking if entry exists
if (flag == 0) {
//Create new file
if (create_new_inode_and_block(base_inode, base_block, base_name, 1) == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
} else {
//DO NOTHING
}
} else if (flag == 1) {
//DO NOTHING
return 0;
} else if (flag == 2) {
fprintf(stderr, "ERROR: Entry already exists cannot create file\n");
return (-1);
}
} else if (operation == 3) {
flag = check_for_entry(&block, base_name, 1);
if (flag == 1) {
oufs_rmfile(base_block, base_inode, base_name);
} else {
fprintf(stderr, "ERROR: specified file does not exist\n");
}
}
//If cwd isn't root
} else {
//Get inode reference of base inode
INODE_REFERENCE base_inode = oufs_look_for_inode_not_from_root(path_copy, cwd, 0, base_name, 1, 1);
//Get block reference of base block
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
int flag = check_for_entry(&block, base_name, 0);
//If operation is mkdir
if (operation == 0) {
//Checking if entry exists
if (flag == 0) {
//Create new directory
if (create_new_inode_and_block(base_inode, base_block, base_name, 0) == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
} else {
//DO NOTHING
}
} else {
fprintf(stderr, "ERROR: Entry already exists, cannot create directory\n");
return (-1);
}
}
//If operation is rmdir
else if (operation == 1) {
//Checking if entry exists
if (flag == -1) {
//Erase file
oufs_rmdir(base_block, base_inode, base_name);
} else {
fprintf(stderr, "ERROR: Entry does not already exists, cannot delete\n");
return (-1);
}
}
//If operation is touch
else if (operation == 2) {
flag = check_for_entry(&block, base_name, 1);
//Checking if entry exists
if (flag == 0) {
//Create new file
if (create_new_inode_and_block(base_inode, base_block, base_name, 1) == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
} else {
//DO NOTHING
}
} else if (flag == 1) {
//DO NOTHING
return 0;
} else if (flag == 2) {
fprintf(stderr, "ERROR: Entry already exists cannot create file\n");
return (-1);
}
} else if (operation == 3) {
flag = check_for_entry(&block, base_name, 1);
if (flag == 2) {
oufs_rmfile(base_block, base_inode, base_name);
} else {
fprintf(stderr, "ERROR: specified file does not exist\n");
}
}
}
//Path is absolute
} else {
//Go through path, not cwd and check the if parent of path exists, if it doesn't, throw an errror
if (debug) {
printf("Absolute path\n");
}
//Get inode reference of base inode
INODE_REFERENCE base_inode = oufs_look_for_inode_from_root(path_copy, 0, base_name, 1);
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
int flag = check_for_entry(&block, base_name, 0);
//If operation is mkdir
if (operation == 0) {
//Checking if entry exists
if (flag == 0) {
//Create new directory
if (create_new_inode_and_block(base_inode, base_block, base_name, 0) == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
} else {
//DO NOTHING
}
} else {
fprintf(stderr, "ERROR: Entry already exists, cannot create directory\n");
return (-1);
}
}
//If operation is rmdir
else if (operation == 1) {
//Checking if entry exists
if (flag == -1) {
//Erase file
oufs_rmdir(base_block, base_inode, base_name);
} else {
fprintf(stderr, "ERROR: Entry does not already exists, cannot delete\n");
return (-1);
}
}
//If operation is touch
else if (operation == 2) {
flag = check_for_entry(&block, base_name, 1);
//Checking if entry exists
if (flag == 0) {
//Create new file
if (create_new_inode_and_block(base_inode, base_block, base_name, 1) == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
} else {
//DO NOTHING
}
} else if (flag == 1) {
//DO NOTHING
return 0;
} else if (flag == 2) {
fprintf(stderr, "ERROR: Entry already exists cannot create file\n");
return (-1);
}
} else if (operation == 3) {
flag = check_for_entry(&block, base_name, 1);
if (flag == 2) {
oufs_rmfile(base_block, base_inode, base_name);
} else {
fprintf(stderr, "ERROR: specified file does not exist\n");
}
}
}
return (0);
}
/**
* Opens a file from cwd and path and gets the specifics of the file. Offset, inode reference, and mode is mutated in this function so that we know how to do specific operations on the file
*
* @param char *cwd Path of cwd
* @param char *path Path of the file to find
* @param char *mode Mode to perform operations of the file on
* @return OUFILE* contianing the file specs
*/
OUFILE* oufs_fopen(char *cwd, char *path, char *mode) {
//Basename variable of path
char base_name[128];
char path_copy[128];
strcpy(path_copy, path);
strcpy(base_name, basename(path));
//Varibles for tokenizing inputs of the parameter
char *path_tokens[64];
char **path_arg;
//Tokenize input
path_arg = path_tokens;
*path_arg++ = strtok(path, "/");
while ((*path_arg++ = strtok(NULL, "/")));
if (strlen(base_name) > FILE_NAME_SIZE) {
//clip(top_off_buff, size_top_off, boundary);
clip(base_name, FILE_NAME_SIZE - 1, strlen(base_name));
} else {
//Do nothing
}
//Check to see if the path is relative
if (path[0] != '/') {
//If cwd is the root
if (!strcmp(cwd, "/")) {
//Get inode reference of base inode
INODE_REFERENCE base_inode = 0;
//Get block reference of base block
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
//Flag to determine if the entry already exists
int flag = 0;
//If path only has 1 token
if (path_tokens[1] == NULL) {
//Check the names of the entries
flag = check_for_entry(&block, base_name, 0);
//If path has more than 1 token means that we are trying to go for subdirectory
} else {
//Get parent inode to work off of
base_inode = oufs_look_for_inode_from_root(path_copy, base_inode, base_name, 1);
oufs_read_inode_by_reference(base_inode, &inode);
base_block = inode.data[0];
vdisk_read_block(base_block, &block);
//Check entries in the block
flag = check_for_entry(&block, base_name, 0);
}
if (flag == -1) {
//OUFILE structure to return
OUFILE* file_specs = malloc(sizeof(OUFILE));
//Get inode of file
file_specs->inode_reference = get_specified_entry(base_block, base_inode, base_name);
//Get mode of file
file_specs->mode = *mode;
//Get offset
INODE file_inode;
oufs_read_inode_by_reference(file_specs->inode_reference, &inode);
file_specs->offset = inode.size;
if (debug) {
printf("\nOUFILE file_specs: %s\n\tinode_reference: %d\n\tmode: %c\n\toffset: %d\n", base_name, file_specs->inode_reference, file_specs->mode, file_specs->offset);
}
return file_specs;
} else {
OUFILE* file_specs = malloc(sizeof(OUFILE));
file_specs->mode = *mode;
file_specs->offset = 0;
file_specs->inode_reference = UNALLOCATED_INODE;
return file_specs;
}
//If cwd isn't root
} else {
//Get inode reference of base inode
INODE_REFERENCE base_inode = oufs_look_for_inode_not_from_root(path_copy, cwd, 0, base_name, 1, 1);
//Get block reference of base block
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
int flag = check_for_entry(&block, base_name, 0);
if (flag == -1) {
//OUFILE structure to return
OUFILE* file_specs = malloc(sizeof(OUFILE));
//Get inode of file
file_specs->inode_reference = get_specified_entry(base_block, base_inode, base_name);
//Get mode of file
file_specs->mode = *mode;
//Get offset
INODE file_inode;
oufs_read_inode_by_reference(file_specs->inode_reference, &inode);
file_specs->offset = inode.size;
if (debug) {
printf("\nOUFILE file_specs: %s\n\tinode_reference: %d\n\tmode: %c\n\toffset: %d\n", base_name, file_specs->inode_reference, file_specs->mode, file_specs->offset);
}
return file_specs;
} else {
OUFILE* file_specs = malloc(sizeof(OUFILE));
file_specs->mode = *mode;
file_specs->offset = 0;
file_specs->inode_reference = UNALLOCATED_INODE;
return file_specs;
}
}
//Path is absolute
} else {
//Get inode reference of base inode
INODE_REFERENCE base_inode = oufs_look_for_inode_from_root(path_copy, 0, base_name, 1);
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
int flag = check_for_entry(&block, base_name, 0);
if (flag == -1) {
//OUFILE structure to return
OUFILE* file_specs = malloc(sizeof(OUFILE));
//Get inode of file
file_specs->inode_reference = get_specified_entry(base_block, base_inode, base_name);
//Get mode of file
file_specs->mode = *mode;
//Get offset
INODE file_inode;
oufs_read_inode_by_reference(file_specs->inode_reference, &inode);
//Get inode size
file_specs->offset = inode.size;
if (debug) {
printf("\nOUFILE file_specs: %s\n\tinode_reference: %d\n\tmode: %c\n\toffset: %d\n", base_name, file_specs->inode_reference, file_specs->mode, file_specs->offset);
}
return file_specs;
} else {
OUFILE* file_specs = malloc(sizeof(OUFILE));
file_specs->mode = *mode;
file_specs->offset = 0;
file_specs->inode_reference = UNALLOCATED_INODE;
return file_specs;
}
}
return NULL;
}
/**
* Writes the specified buffer into the raw data of the data block allocated to the file
*
* @param BLOCK_REFERENCE block_reference Reference of block to write into
* @param INODE_REFERENCE inode_reference Inode reference of block to write into
* @param int len Length of buff to write
* @param char *buf Buffer to write into block
* @param int *offset Offset of the block, which changes with every write
* @return Nothing
*/
void regular_write(BLOCK_REFERENCE block_reference, INODE_REFERENCE inode_reference, int len, char * buf, int *offset) {
BLOCK block;
vdisk_read_block(block_reference, &block);
//Concatenating sequence of strings
if (debug) {
printf("Offset in regular write: %d\n", *offset);
printf("Buf: %s|||||||To block: %d\n", buf, block_reference);
}
//Copying buf to block at offset in block
memcpy(&block.data.data[*offset], buf, strlen(buf));
//Writing block back to disk
vdisk_write_block(block_reference, &block);
INODE inode;
oufs_read_inode_by_reference(inode_reference, &inode);
//Incrementing the size of inode
if (debug) {
printf("Inode.size: %d------Inode.size + len: %d\n:", inode.size, inode.size + len);
}
//Increment size and offset
inode.size += len;
*offset += len;
//Writing inode back with new size
oufs_write_inode_by_reference(inode_reference, &inode);
}
/**
* Is used when we transition from writing to one block to writing to a new block. If the specified length of the the inode.size + the length of the buffer is > a % of (256 * datablock), then we allocate a new block, top off old block with part of the string, then write the rest of the string to the new block.
*
* @param BLOCK_REFERENCE block_reference Reference of block to write into
* @param INODE_REFERENCE inode_reference Inode reference of block to write into
* @param int len Length of buff to write
* @param char *buf Buffer to write into block
* @param int data_block Which data block to write into in block.data[]
* @param int *offset Offset of the block, which changes with every write
* @return Nothing
*/
void bleed_write(BLOCK_REFERENCE block_reference, INODE_REFERENCE inode_reference, int len, char * buf, int data_block, int *offset) {
//Getting inode
INODE inode;
oufs_read_inode_by_reference(inode_reference, &inode);
//Getting parameters of clip function
int total_size = inode.size + len;
int boundary = total_size - (256 * data_block);
int size_top_off = len - boundary;
//Creating new buffers to hold new strs from clip
char top_off_buff[MAX_BUFFER];
char remainder_buff[MAX_BUFFER];
//Copying buff to new chars to be mutated
memcpy(top_off_buff, buf, strlen(buf));
memcpy(remainder_buff, buf, strlen(buf));
//Cliping new strings
clip(top_off_buff, size_top_off, boundary);
if (inode.size + len == (256 * data_block)) {
//Toping off old block
BLOCK block;
vdisk_read_block(block_reference, &block);
//Add top_off_buff to block at block 0 in inode
memcpy(&block.data.data[*offset], top_off_buff, strlen(top_off_buff));
//Write block back
vdisk_write_block(block_reference, &block);
*offset = 256;
//Incrementing the size of inode
inode.size += len;
//Write new block in inode
oufs_write_inode_by_reference(inode_reference, &inode);
} else {
clip(remainder_buff, 0, size_top_off);
if (debug) {
printf("\n");
printf("inode.size: %d\n", inode.size);
printf("top_off_buff: %s len: %lu\n", top_off_buff, strlen(top_off_buff));
printf("remainder_buff: %s len: %lu\n", remainder_buff, strlen(remainder_buff));
printf("\n");
}
//Toping off old block
BLOCK block;
vdisk_read_block(block_reference, &block);
//Add top_off_buff to block at block 0 in inode
memcpy(&block.data.data[*offset], top_off_buff, strlen(top_off_buff));
//Write block back
vdisk_write_block(block_reference, &block);
//Writing rest of string to new block
block_reference = oufs_allocate_new_block();
//Writing new info to inode
inode.data[data_block] = block_reference;
//Incrementing the size of inode
inode.size += len;
//Write new block in inode
oufs_write_inode_by_reference(inode_reference, &inode);
//Reading in new block
vdisk_read_block(block_reference, &block);
//Resetting block, so that the raw data is cleaned
memset(block.data.data, 0, sizeof(block));
//Add remainder_buff to new block at block 1 in inode
memcpy(&block.data.data[0], remainder_buff, strlen(remainder_buff));
//Reset offset
*offset = len - size_top_off;
//Write block back to disk
vdisk_write_block(block_reference, &block);
}
}
/**
* The main function that uses regular_write and bleed_write to write to data block of inodes. There is some prep work in determining what blocks we want to use since we are writing by string, and not character. It determines what the offset is to make descisions about which data block to use in the inode, so that it writes correctly to each block in the inode
*
* @param OUFILE *fp Holds the file specifications that we need like the inode reference and the offset of the file
* @param char *buf The string to write to the data blocks
* @param int len The length of what we want to write
* @return 0 on success, anything else is error
*/
int oufs_fwrite(OUFILE *fp, char * buf, int len) {
//First grab inode
INODE inode;
oufs_read_inode_by_reference(fp->inode_reference, &inode);
BLOCK_REFERENCE block_reference = inode.data[0];
//If first data block is unallocated, it means its an empty inode, no blocks
if (block_reference == UNALLOCATED_INODE) {
block_reference = oufs_allocate_new_block();
//Writing new info to inode
inode.data[0] = block_reference;
oufs_write_inode_by_reference(fp->inode_reference, &inode);
//Clean block
BLOCK block;
//Read block at reference into block
vdisk_read_block(block_reference, &block);
//Reset data in the block
memset(block.data.data, 0, sizeof(block));
//Write block back to disk
vdisk_write_block(block_reference, &block);
}
//If block becomes all the way full, allocate new block to next unallocated inode
if (fp->offset == 256) {
block_reference = oufs_allocate_new_block();
//Finding first unallocated inode block in inode.data and setting it equal to block_reference
for (int i = 0; i < BLOCKS_PER_INODE; ++i) {
if (inode.data[i] == UNALLOCATED_INODE) {
inode.data[i] = block_reference;
oufs_write_inode_by_reference(fp->inode_reference, &inode);
break;
}
}
//Clean block
BLOCK block;
//Read block at reference into block
vdisk_read_block(block_reference, &block);
//Reset data in the block
memset(block.data.data, 0, sizeof(block));
//Write block back to disk
vdisk_write_block(block_reference, &block);
//Reset offset
fp->offset = 0;
}
//printf("Offset: %d\n", fp->offset);
/* Finds which data block to write to so that everything is written in the correct spot as the file is to write is written. Everything works off of what the overall inode.size is, and depending on that, it writes to the correct data blocks in the inode
*/
if (inode.size < 256) {
if (inode.size + len >= 256) {
bleed_write(inode.data[0], fp->inode_reference, len, buf, 1, &fp->offset);
} else {
regular_write(inode.data[0], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 512) {
if (inode.size + len >= 512) {
bleed_write(inode.data[1], fp->inode_reference, len, buf, 2, &fp->offset);
} else {
regular_write(inode.data[1], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 768) {
if (inode.size + len >= 768) {
bleed_write(inode.data[2], fp->inode_reference, len, buf, 3, &fp->offset);
} else {
regular_write(inode.data[2], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 1024) {
if (inode.size + len >= 1024) {
bleed_write(inode.data[3], fp->inode_reference, len, buf, 4, &fp->offset);
} else {
regular_write(inode.data[3], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 1280) {
if (inode.size + len >= 1280) {
bleed_write(inode.data[4], fp->inode_reference, len, buf, 5, &fp->offset);
} else {
regular_write(inode.data[4], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 1536) {
if (inode.size + len >= 1536) {
bleed_write(inode.data[5], fp->inode_reference, len, buf, 6, &fp->offset);
} else {
regular_write(inode.data[5], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 1792) {
if (inode.size + len >= 1792) {
bleed_write(inode.data[6], fp->inode_reference, len, buf, 7, &fp->offset);
} else {
regular_write(inode.data[6], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 2048) {
if (inode.size + len >= 2048) {
bleed_write(inode.data[7], fp->inode_reference, len, buf, 8, &fp->offset);
} else {
regular_write(inode.data[7], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 2034) {
if (inode.size + len >= 2034) {
bleed_write(inode.data[8], fp->inode_reference, len, buf, 9, &fp->offset);
} else {
regular_write(inode.data[8], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 2560) {
if (inode.size + len >= 2560) {
bleed_write(inode.data[9], fp->inode_reference, len, buf, 10, &fp->offset);
} else {
regular_write(inode.data[9], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 2816) {
if (inode.size + len >= 2816) {
bleed_write(inode.data[10], fp->inode_reference, len, buf, 11, &fp->offset);
} else {
regular_write(inode.data[10], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 3072) {
if (inode.size + len >= 3072) {
bleed_write(inode.data[11], fp->inode_reference, len, buf, 12, &fp->offset);
} else {
regular_write(inode.data[11], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 3328) {
if (inode.size + len >= 3328) {
bleed_write(inode.data[12], fp->inode_reference, len, buf, 13, &fp->offset);
} else {
regular_write(inode.data[12], fp->inode_reference, len, buf, &fp->offset);
}
} else if (inode.size < 3584) {
if (inode.size + len >= 3584) {
bleed_write(inode.data[13], fp->inode_reference, len, buf, 14, &fp->offset);
} else {
regular_write(inode.data[13], fp->inode_reference, len, buf, &fp->offset);
}
}
return 0;
}
/**
* It works like oufs_mkdir in the it steps through the cwd and path properly so that the file is put into the correct location. Then it just increments the parent inode size, n references in the dest file inode, and adds an entry of the file in the correct directory
*
* @param char *cwd The path of the CWD
* @param char *path The path of the file to link
* @param INODE_REFERENCE dest_reference Reference of destination file
* @return 0 on success, and -1 on error
*/
int oufs_link(char *cwd, char *path, INODE_REFERENCE dest_reference) {
//Basename variable of path
char base_name[128];
char path_copy[128];
strcpy(path_copy, path);
strcpy(base_name, basename(path));
//Varibles for tokenizing inputs of the parameter
char *path_tokens[64];
char **path_arg;
//Tokenize input
path_arg = path_tokens;
*path_arg++ = strtok(path, "/");
while ((*path_arg++ = strtok(NULL, "/")));
if (strlen(base_name) > FILE_NAME_SIZE) {
//clip(top_off_buff, size_top_off, boundary);
clip(base_name, FILE_NAME_SIZE - 1, strlen(base_name));
} else {
//Do nothing
}
//Debug
if (debug) {
printf("CWD: %s\n", cwd);
printf("Path: %s\n", path);
}
//Check to see if the path is relative or absolute
if (path[0] != '/') {
if (debug) {
printf("Relative path\n");
}
//If cwd is root
if (!strcmp(cwd, "/")) {
//Get inode reference of base inode
INODE_REFERENCE base_inode = 0;
//Get block reference of base block
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
//Flag to determine if the entry already exists
int flag = 0;
//If path only has 1 token
if (path_tokens[1] == NULL) {
//Check the names of the entries
flag = check_for_entry(&block, base_name, 1);
//If path has more than 1 token means that we are trying to go for subdirectory
} else {
//Get parent inode to work off of
base_inode = oufs_look_for_inode_from_root(path_copy, base_inode, base_name, 1);
oufs_read_inode_by_reference(base_inode, &inode);
base_block = inode.data[0];
vdisk_read_block(base_block, &block);
//Check entries in the block
flag = check_for_entry(&block, base_name, 1);
}
//Entry does not exist
if (flag == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
oufs_read_inode_by_reference(dest_reference, &inode);
++inode.n_references;
oufs_write_inode_by_reference(dest_reference, &inode);
//Looping through entries in block to check for empty entry
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if (!strcmp(block.directory.entry[i].name, "")) {
strcpy(block.directory.entry[i].name, base_name);
block.directory.entry[i].inode_reference = dest_reference;
break;
}
}
//Writing entry to block
vdisk_write_block(base_block, &block);
} else {
fprintf(stderr, "ERROR: Entry already exists\n");
return (-1);
}
//If cwd isn't root
} else {
//Get inode reference of base inode
INODE_REFERENCE base_inode = oufs_look_for_inode_not_from_root(path_copy, cwd, 0, base_name, 1, 1);
//Get block reference of base block
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
int flag = check_for_entry(&block, base_name, 1);
//If no entry for new directory
if (flag == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
oufs_read_inode_by_reference(dest_reference, &inode);
++inode.n_references;
oufs_write_inode_by_reference(dest_reference, &inode);
//Looping through entries in block to check for empty entry
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if (!strcmp(block.directory.entry[i].name, "")) {
strcpy(block.directory.entry[i].name, base_name);
block.directory.entry[i].inode_reference = dest_reference;
break;
}
}
//Writing entry to block
vdisk_write_block(base_block, &block);
//Entry exists in the directory entry list
} else {
fprintf(stderr, "ERROR: Entry already exists\n");
return (-1);
}
}
//Path is absolute
} else {
//Go through path, not cwd and check the if parent of path exists, if it doesn't, throw an errror
if (debug) {
printf("Absolute path\n");
}
//Get inode reference of base inode
INODE_REFERENCE base_inode = oufs_look_for_inode_from_root(path_copy, 0, base_name, 1);
BLOCK_REFERENCE base_block;
//Get root inode
INODE inode;
oufs_read_inode_by_reference(base_inode, &inode);
//Get block from block reference in inode
BLOCK block;
base_block = inode.data[0];
//Read block at reference into block
vdisk_read_block(base_block, &block);
int flag = check_for_entry(&block, base_name, 1);
//If no entry for new directory
if (flag == 0) {
//Increment parent inode size
++inode.size;
//Write inode parent inode back to the block
oufs_write_inode_by_reference(base_inode, &inode);
oufs_read_inode_by_reference(dest_reference, &inode);
++inode.n_references;
oufs_write_inode_by_reference(dest_reference, &inode);
//Looping through entries in block to check for empty entry
for (int i = 0; i < DIRECTORY_ENTRIES_PER_BLOCK; ++i) {
if (!strcmp(block.directory.entry[i].name, "")) {
strcpy(block.directory.entry[i].name, base_name);
block.directory.entry[i].inode_reference = dest_reference;
break;
}
}
//Writing entry to block
vdisk_write_block(base_block, &block);
} else {
fprintf(stderr, "ERROR: Entry already exists\n");
return (-1);
}
}
return (0);
}
|
C
|
/* A program to copy its input to its output, replacing each tab by \t , each
backspace by \b , and each backslash by \\ . This makes tabs and backspaces visible in an
unambiguous way */
#include<stdio.h>
#include<string.h>
#define SIZE 100
int main(void)
{
char ip[SIZE], op[SIZE], c;
/* Loop Variables */
int i = 0, j = 0, n = 0;
memset(ip, 0, sizeof(ip));
memset(op, 0, sizeof(op));
printf("My escape sequence \\t \\b \\ test\n ");
puts("Enter any sequence of characters terminated by newline\n");
/* Accept characters from the terminal until EOF */
while ((c = getchar()) != '\0') {
ip[i++] = c;
n++;
}
puts("The entered string is\n");
puts(ip);
/* Reset loop variable */
i = 0;
/* loop through the input character array */
while (i < n) {
/* Check for tab */
if (ip[i] == '\t') {
printf("\\t");
/* increment the loop variables appropriately */
i++;
continue;
} else if (ip[i] == '\\') { /* Check for backslash */
printf("\\");
/* increment the loop variables as appropriate */
i++;
continue;
} else if (ip[i] == 127) { /* Check for backspace */
printf("\\b");
/* increment the loop variables appropriately */
i++;
continue;
} else {
/* simply copy the input buffer to the output buffer */
printf("%c", ip[i]);
i++;
}
}
printf("\n");
}
|
C
|
#include <stdio.h>
int main()
{
int t0 = 0, t1 = 10;
while (t0 != t1)
{
t0 = t0 + 1;
}
t0 = t1 << 2;
printf("%d \n", t0);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include "../include/radia_comm.h"
//ƶַcַstrеĸ
int get_nums_char(char *str, char c)
{
int i, num = 0;
for(i = 0; i < strlen(str); i++)
if(str[i] == c)
num++;
return num;
}
//ַָcַstrеnumγֵλãʧ-1
int get_cursor_char(char *str, char c, int num)
{
int i, n = 0;
if(num <= 0)
return -1;
for(i = 0; i < strlen(str); i++)
{
if(str[i] == c)
n++;
if(n == num)
return i;
}
return 0;
}
//һsocketclient˿
int open_client_socket(int *csd, char *ip, int port_num)
{
struct sockaddr_in s_addr;
*csd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == *csd)
{
printf("socket fail ! \r\n");
return -1;
}
printf("socket ok !\r\n");
bzero(&s_addr,sizeof(struct sockaddr_in));
s_addr.sin_family=AF_INET;
s_addr.sin_addr.s_addr= inet_addr(ip);//"192.168.31.200");//("127.0.0.1");
s_addr.sin_port=htons(port_num);
printf("s_addr = %#x ,port : %#x\r\n",s_addr.sin_addr.s_addr,s_addr.sin_port);
if(-1 == connect(*csd,(struct sockaddr *)(&s_addr), sizeof(struct sockaddr)))
{
printf("connect fail !\r\n");
return -1;
}
printf("connect ok !\r\n");
return 1;
}
//ȡsocket serverеԴclient_name_table
int get_free_client_internal_id(char (*cnt)[MAX_CLIENT_NAME_LEN])
{
int i, free_num = 0;
for(i = 0; i < MAX_CLIENT_NUM; i++)
{
if(cnt[i][0] == 0)
free_num++;
}
return free_num;
}
//һеsocket server client_name_table
int alloc_client_internal_id(char (*cnt)[MAX_CLIENT_NAME_LEN])//ΪǰclientһڲԴid
{
int i;
for(i = 0; i < MAX_CLIENT_NUM; i++)
{
if(cnt[i][0] == 0)
{
memcpy(cnt[i], "noname", strlen("noname"));
return i;
}
}
return -1;
}
//ͷһѱռõsocket serverԴclient_name_table
int free_client_internal_id(char (*cnt)[MAX_CLIENT_NAME_LEN], int id)
{
memset(cnt[id], 0, MAX_CLIENT_NAME_LEN);
return 0;
}
//һsocketserver˿
int creat_server_socket(int *ssd, int port_num)
{
struct sockaddr_in s_addr;
*ssd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == *ssd)
{
printf("socket fail ! \r\n");
return -1;
}
printf("socket ok !\r\n");
bzero(&s_addr,sizeof(struct sockaddr_in));
s_addr.sin_family=AF_INET;
s_addr.sin_addr.s_addr=htonl(INADDR_ANY);
s_addr.sin_port=htons(port_num);
if(-1 == bind(*ssd,(struct sockaddr *)(&s_addr), sizeof(struct sockaddr)))
{
printf("bind fail !\r\n");
return -1;
}
printf("bind ok !\r\n");
if(-1 == listen(*ssd,5))
{
printf("listen fail !\r\n");
return -1;
}
printf("listen ok\r\n");
return 1;
}
//жsocketclientûжϿʧܷ-1
int check_socket_connect(int csd)
{
int optval, optlen = sizeof(int);
//printf("enter check_socket_connect!\n");
getsockopt(csd, SOL_SOCKET, SO_ERROR,(char*) &optval, &optlen);
switch(optval){
case 0:
//printf("check_socket_connect connection!\n");
return 1;
break;
default:
break;
}
return -1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_SIZE 101
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))
void sort(int[], int); //seclect function
int main(int argc, char const* argv[])
{
int i, j, num;
int list[MAX_SIZE];
srand((unsigned int)time(NULL)); //Generate random seed based on current system time
printf("Please Enter the number of numbers to generate: ");
scanf("%d", &num);
if (num < 1 || num > MAX_SIZE) {
fprintf(stderr, "Input out of range!");
exit(1);
}
for (i = 0; i < num; i++) {
list[i] = rand() % 1000;
printf("%d ", list[i]);
}
printf("\n");
sort(list, num);
printf("Sorted array:\n");
for (i = 0; i < num; i++)
printf("%d ", list[i]);
printf("\n");
return 0;
}
void sort(int list[], int num)
{
int i, j, min, temp;
for (i = 0; i < num - 1; i++) {
for (j = i + 1; j < num; j++) {
if (list[i] > list[j])
SWAP(list[i], list[j], temp);
}
}
}
|
C
|
#include <assert.h>
#include <stdlib.h>
#include <ucontext.h>
#include "thread.h"
#include "interrupt.h"
#define READY 0
#define RUNNING 1
#define EXITED 2
#define BLOCKED 3
#define DEAD 4
/* This is the wait queue structure */
struct wait_queue
{
/* ... Fill this in Lab 3 ... */
};
/* This is the thread control block */
struct thread
{
//Context
ucontext_t thread_context;
//Stack
void *thread_stack;
//Thread state
int thread_state;
//Thread id
Tid thread_id;
//Next in queue
struct thread *next;
//Running
int thread_run;
};
//Create a pointer to the queue of threads
struct start_of_queue
{
struct thread *head;
};
struct start_of_queue *running_queue;
struct start_of_queue *ready_queue;
struct start_of_queue *exit_queue;
struct start_of_queue *blocked_queue;
struct start_of_queue *kill_queue;
int taken_tid[THREAD_MAX_THREADS];
//Print queue for debugging...
void print_queue(char *queue_name, struct start_of_queue *print)
{
fprintf(stderr, "%s:\n", queue_name);
struct thread *find = print->head;
while (find != NULL)
{
fprintf(stderr, "Thread id: %d, Thread state: %d\n", find->thread_id, find->thread_state);
find = find->next;
}
return;
}
void print_all()
{
fprintf(stderr, "Current Queue:\n\n");
print_queue("Running", running_queue);
fprintf(stderr, "\n\n");
print_queue("Ready", ready_queue);
fprintf(stderr, "\n\n");
print_queue("Killed", kill_queue);
fprintf(stderr, "\n\n");
}
//Find a thread id in the thread queue
struct thread *find_thread(Tid id)
{
if (running_queue->head != NULL && running_queue->head->thread_id == id)
{
return running_queue->head;
}
struct thread *find = ready_queue->head;
while (find != NULL)
{
if (find->thread_id == id)
{
return find;
}
find = find->next;
}
find = blocked_queue->head;
while (find != NULL)
{
if (find->thread_id == id)
{
return find;
}
find = find->next;
}
find = exit_queue->head;
while (find != NULL)
{
if (find->thread_id == id)
{
return find;
}
find = find->next;
}
return NULL;
}
//Find a thread that's ready!
struct thread *find_thread_ready()
{
//Reading the ready queue is a critical task...
struct thread *find = ready_queue->head;
while (find != NULL)
{
if (find->thread_state == READY)
{
return find;
}
find = find->next;
}
return NULL;
}
//How many total threads have been created and are in queues?
int get_thread_size()
{
int size = 0;
struct thread *find = running_queue->head;
while (find != NULL)
{
size++;
find = find->next;
}
find = ready_queue->head;
while (find != NULL)
{
size++;
find = find->next;
}
find = exit_queue->head;
while (find != NULL)
{
size++;
find = find->next;
}
find = blocked_queue->head;
while (find != NULL)
{
size++;
find = find->next;
}
//fprintf(stderr, "Size: %d\n", size);
return size;
}
//Takes the running queue and puts that thread to the back
//of the ready queue
void dequeue_running_into_ready()
{
//Make sure running queue isn't null, this will be helpful
//when yielding after a thread exit
//This section is critical because we're moving threads from the running
//queue to the ready queue
if (running_queue->head != NULL)
{
if (running_queue->head->thread_state != EXITED)
{
running_queue->head->thread_state = READY;
}
struct thread *find = ready_queue->head;
if (find != NULL)
{
while (find->next != NULL)
{
find = find->next;
}
find->next = running_queue->head;
running_queue->head->next = NULL;
running_queue->head = NULL;
return;
}
else
{
ready_queue->head = running_queue->head;
running_queue->head->next = NULL;
running_queue->head = NULL;
return;
}
}
return;
}
//Takes a thread from the ready queue and
//puts it in the running queue
void queue_ready_into_running(Tid id)
{
//Find the thread with Tid id in the ready queue and put it in the
//running queue...
//This section is critical because we're moving shared variables around...
struct thread *find = ready_queue->head;
if (find != NULL)
{
//fprintf(stderr, "queue ready into running case\n");
//Check if it's at the head...
if (find->thread_id == id)
{
//fprintf(stderr, "Head case\n");
//Basically swap the running and ready queues around
find->thread_state = RUNNING;
running_queue->head = find;
ready_queue->head = ready_queue->head->next;
find->next = NULL;
return;
}
else
{
//fprintf(stderr, "Body case\n");
while (find->next != NULL && find->next->thread_id != id)
{
find = find->next;
}
//Uh oh that's a big error!
if (find == NULL)
{
return;
}
//Now move the found thread to the running queue...
struct thread *found_thread = find->next;
found_thread->thread_state = RUNNING;
find->next = found_thread->next;
running_queue->head = found_thread;
found_thread->next = NULL;
return;
}
}
}
//Take a thread from the ready queue and moves it to the kill
//queue
void dequeue_ready_into_kill(Tid id)
{
//This section is critical because it needs to access the ready
//and kill queue which are both shared variables...
struct thread *find = ready_queue->head;
struct thread *end_of_kill = kill_queue->head;
//Get to the end of the kill queue
if (end_of_kill != NULL)
{
while (end_of_kill->next != NULL)
{
end_of_kill = end_of_kill->next;
}
}
if (find != NULL)
{
//Head case
if (find->thread_id == id)
{
ready_queue->head = find->next;
find->next = NULL;
if (end_of_kill != NULL)
{
end_of_kill->next = find;
}
else
{
kill_queue->head = find;
}
return;
}
//Otherwise remove the tid from ready and put it
//in kill
while (find->next != NULL && find->next->thread_id != id)
{
find = find->next;
}
if (end_of_kill != NULL)
{
end_of_kill->next = find->next;
}
else
{
kill_queue->head = find->next;
}
struct thread *tbk = find->next;
find->next = find->next->next;
tbk->next = NULL;
tbk->thread_state = DEAD;
return;
}
}
//KILLS! a thread, basically just free the memory
int deallocate_thread(struct thread *kill)
{
//We have to free all the stuff we allocated dynamically!
Tid id = kill->thread_id;
free(kill->thread_stack);
free(kill);
//Also make the tid availible again...
taken_tid[id] = -1;
kill_queue->head = NULL;
return id;
}
void thread_stub(void (*thread_main)(void *), void *arg)
{
interrupts_on();
thread_main(arg);
thread_exit();
}
void thread_init(void)
{
int enable = interrupts_off();
//Create the 'main' thread info
struct thread *main_thread = (struct thread *)malloc(sizeof(struct thread));
main_thread->thread_id = 0;
main_thread->next = NULL;
main_thread->thread_state = RUNNING;
main_thread->thread_run = 1;
//Initialize the taken tid array for keeping track of
//availible thread ids...
for (int i = 0; i < THREAD_MAX_THREADS; i++)
{
taken_tid[i] = -1;
}
taken_tid[0] = 0;
//Set the default pointers for the queue
running_queue = (struct start_of_queue *)malloc(sizeof(struct start_of_queue));
ready_queue = (struct start_of_queue *)malloc(sizeof(struct start_of_queue));
exit_queue = (struct start_of_queue *)malloc(sizeof(struct start_of_queue));
blocked_queue = (struct start_of_queue *)malloc(sizeof(struct start_of_queue));
kill_queue = (struct start_of_queue *)malloc(sizeof(struct start_of_queue));
running_queue->head = main_thread;
ready_queue->head = NULL;
exit_queue->head = NULL;
blocked_queue->head = NULL;
kill_queue->head = NULL;
interrupts_set(enable);
}
Tid thread_id()
{
//print_queue("Ready", ready_queue);
//print_queue("Running", running_queue);
//Reading from the running queue can be critical therefore
//set interrupts
int enable = interrupts_off();
//The running queue has all the threads that are currently running
//In this case only one thread at a time...
if (running_queue->head != NULL)
{
if (running_queue->head->thread_id >= 0 && running_queue->head->thread_id <= THREAD_MAX_THREADS - 1)
{
interrupts_set(enable);
return running_queue->head->thread_id;
}
}
interrupts_set(enable);
return THREAD_INVALID;
}
Tid thread_create(void (*fn)(void *), void *parg)
{
//Make sure we have enough threads availible...
//When creating a thread turn off interupts when
//adding this boi to the ready queue
int thread_size = get_thread_size();
if (thread_size >= THREAD_MAX_THREADS)
{
//fprintf(stderr, "Thread no more!\n");
return THREAD_NOMORE;
}
//Make sure enough space can be allocated
void *stack = malloc(THREAD_MIN_STACK);
if (stack == NULL)
{
//fprintf(stderr, "Thread no memory!\n");
return THREAD_NOMEMORY;
}
//Now create the actuall thread
struct thread *new_thread = (struct thread *)malloc(sizeof(struct thread));
//Generate the thread id...
for (int i = 0; i < THREAD_MAX_THREADS; i++)
{
if (taken_tid[i] == -1)
{
new_thread->thread_id = i;
taken_tid[i] = i;
break;
}
}
//Find out where the stack actually is (alligned to 16 bits)
long long int stack_pointer = (long long int)stack + THREAD_MIN_STACK + 16;
stack_pointer = stack_pointer - (stack_pointer - 8) % 16;
//Initialize the stack and context...
getcontext(&new_thread->thread_context);
new_thread->thread_stack = stack;
new_thread->thread_context.uc_stack.ss_size = THREAD_MIN_STACK;
new_thread->thread_context.uc_mcontext.gregs[REG_RSP] = stack_pointer;
//Now adjust all the registers in the thread context (all alligned to 16 bit, ie long long int) :(
//RIP - Function we want to go to
//RDI, RSI .... - All the parameters we need to pass
//new_thread->thread_context.uc_mcontext.__gregs[REG_RIP] = &stub_function
//I thought we wanted to go to stub then thread function?
new_thread->thread_context.uc_mcontext.gregs[REG_RIP] = (long long int)&thread_stub;
new_thread->thread_context.uc_mcontext.gregs[REG_RDI] = (long long int)fn;
new_thread->thread_context.uc_mcontext.gregs[REG_RSI] = (long long int)parg;
//Other thread parameters
new_thread->thread_run = 1;
new_thread->thread_state = READY;
new_thread->next = NULL;
//Now add it to the ready queue!
struct thread *find = ready_queue->head;
int enable = interrupts_off();
//For an already existing queue
if (ready_queue->head != NULL)
{
while (find->next != NULL)
{
find = find->next;
}
find->next = new_thread;
} //For a new queue
else
{
ready_queue->head = new_thread;
}
interrupts_set(enable);
return new_thread->thread_id;
}
Tid thread_yield(Tid want_tid)
{
//Enque current thread in the ready queue
//Choose next threat to run, remove it from the ready queue
//Switch to next thread
//Yielding to a thread should be critical because we need to
//access the running and ready queue share variables
int enable = interrupts_off();
Tid ran_thread;
if (want_tid == THREAD_SELF)
{
interrupts_set(enable);
return thread_id();
}
else if (want_tid == THREAD_ANY)
{
struct thread *any_thread = find_thread_ready();
if (any_thread != NULL)
{
//Get context of running thread
getcontext(&running_queue->head->thread_context);
//fprintf(stderr, "\nYieldind any\n\nThread_Run: %d\n\n", running_queue->head->thread_run);
if (running_queue->head->thread_run == 1)
{
running_queue->head->thread_run = 0;
//Move running queue to ready queue...
dequeue_running_into_ready();
//Move ready queue into running queue... (what if ready empty?)
queue_ready_into_running(any_thread->thread_id);
ran_thread = running_queue->head->thread_id;
//set the context
setcontext(&running_queue->head->thread_context);
}
running_queue->head->thread_run = 1;
interrupts_set(enable);
return ran_thread;
}
else
{
interrupts_set(enable);
return THREAD_NONE;
}
}
else
{
//Check if the tid actually exists...
struct thread *want_thread = find_thread(want_tid);
if (want_thread == NULL)
{
interrupts_set(enable);
return THREAD_INVALID;
}
//Check if the tid id currently running...
if (want_tid == running_queue->head->thread_id)
{
interrupts_set(enable);
return want_tid;
}
else
{
//If it's in the ready queue then make sure it
//thread_state isn't exit...
if (want_thread->thread_state == EXITED)
{
//
thread_kill(want_thread->thread_id);
interrupts_set(enable);
return THREAD_INVALID;
}
if (ready_queue->head != NULL)
{
//Get the context of the current running thread...
getcontext(&running_queue->head->thread_context);
//fprintf(stderr, "\n\nThread_Run: %d\n\n", running_queue->head->thread_run);
if (running_queue->head->thread_run == 1)
{
running_queue->head->thread_run = 0;
//Move running queue to ready queue...
dequeue_running_into_ready();
//Move ready queue into running queue... (what if ready empty?)
queue_ready_into_running(want_tid);
ran_thread = running_queue->head->thread_id;
//Set the current context and change thread run to 1
//running_queue->thread_run = 1;
setcontext(&running_queue->head->thread_context);
}
running_queue->head->thread_run = 1;
interrupts_set(enable);
return ran_thread;
}
else
{
interrupts_set(enable);
return THREAD_NOMORE;
}
}
}
return THREAD_FAILED;
}
void thread_exit(void)
{
//CRITCALL AHHHHHH!!!!
int enable = interrupts_off();
//Check if this is the only thread left...
if (ready_queue->head == NULL)
{
exit(0);
}
else
{
//move exited items into the exit queue...
struct thread *find = ready_queue->head;
while (find != NULL)
{
if (find->thread_state == EXITED)
{
thread_kill(find->thread_id);
}
find = find->next;
}
//If there's nothing in the ready queue then completely
//exit and free stuff...
if (ready_queue->head == NULL)
{
ready_queue->head = running_queue->head;
running_queue->head = NULL;
struct thread *last_thread = ready_queue->head;
free(last_thread->thread_stack);
free(last_thread);
//Also free all the start queues...
free(running_queue);
free(ready_queue);
free(exit_queue);
free(blocked_queue);
free(kill_queue);
exit(0);
}
running_queue->head->thread_state = EXITED;
interrupts_set(enable);
thread_yield(THREAD_ANY);
}
return;
}
Tid thread_kill(Tid tid)
{
//CIRITCALLLLL WOWOOWOWOWO!!!
int enable = interrupts_off();
// Check if tid is the current running thread
if (running_queue->head != NULL && tid == running_queue->head->thread_id)
{
interrupts_set(enable);
return THREAD_INVALID;
}
//Check if the thread is in the ready queue
struct thread *find = find_thread(tid);
if (find == NULL)
{
interrupts_set(enable);
return THREAD_INVALID;
}
//Now we know that the thread exists and is in the ready queue
dequeue_ready_into_kill(tid);
int killed_thread = deallocate_thread(find);
interrupts_set(enable);
return killed_thread;
}
/*******************************************************************
* Important: The rest of the code should be implemented in Lab 3. *
*******************************************************************/
/* make sure to fill the wait_queue structure defined above */
struct wait_queue *
wait_queue_create()
{
struct wait_queue *wq;
wq = malloc(sizeof(struct wait_queue));
assert(wq);
TBD();
return wq;
}
void wait_queue_destroy(struct wait_queue *wq)
{
TBD();
free(wq);
}
Tid thread_sleep(struct wait_queue *queue)
{
TBD();
return THREAD_FAILED;
}
/* when the 'all' parameter is 1, wakeup all threads waiting in the queue.
* returns whether a thread was woken up on not. */
int thread_wakeup(struct wait_queue *queue, int all)
{
TBD();
return 0;
}
/* suspend current thread until Thread tid exits */
Tid thread_wait(Tid tid)
{
TBD();
return 0;
}
struct lock
{
/* ... Fill this in ... */
};
struct lock *
lock_create()
{
struct lock *lock;
lock = malloc(sizeof(struct lock));
assert(lock);
TBD();
return lock;
}
void lock_destroy(struct lock *lock)
{
assert(lock != NULL);
TBD();
free(lock);
}
void lock_acquire(struct lock *lock)
{
assert(lock != NULL);
TBD();
}
void lock_release(struct lock *lock)
{
assert(lock != NULL);
TBD();
}
struct cv
{
/* ... Fill this in ... */
};
struct cv *
cv_create()
{
struct cv *cv;
cv = malloc(sizeof(struct cv));
assert(cv);
TBD();
return cv;
}
void cv_destroy(struct cv *cv)
{
assert(cv != NULL);
TBD();
free(cv);
}
void cv_wait(struct cv *cv, struct lock *lock)
{
assert(cv != NULL);
assert(lock != NULL);
TBD();
}
void cv_signal(struct cv *cv, struct lock *lock)
{
assert(cv != NULL);
assert(lock != NULL);
TBD();
}
void cv_broadcast(struct cv *cv, struct lock *lock)
{
assert(cv != NULL);
assert(lock != NULL);
TBD();
}
|
C
|
#include "test_helper.h"
Word32_t build_instr(const int type, const int op, const int rs, const int rt, const int rd, \
const int shamt, const int funct, const int imm, const int addr) {
Word32_t instr = (op << OPCODE_SHAMT);
if (R_TYPE == type) {
instr |= (rs << RS_SHAMT);
instr |= (rt << RT_SHAMT);
instr |= (rd << RD_SHAMT);
instr |= (shamt << (SHAMT_SHAMT & SHAMT_MASK));
instr |= funct;
} else if (I_TYPE == type) {
instr |= (rs << RS_SHAMT);
instr |= (rt << RT_SHAMT);
instr |= imm & IMM_MASK;
} else if (J_TYPE == type) {
instr |= addr & ADDR_MASK;
}
return instr;
}
Decoded_instr_t build_decoded_instr(const unsigned short type, const unsigned short op, const unsigned short rs, \
const unsigned short rt, const unsigned short rd, const unsigned short shamt, const unsigned short funct, \
const int imm, const int addr) {
Decoded_instr_t dinstr;
dinstr.opcode = op;
if (R_TYPE == type) {
dinstr.instr.r.rs = rs;
dinstr.instr.r.rt = rt;
dinstr.instr.r.rd = rd;
dinstr.instr.r.shamt = shamt & SHAMT_MASK;
dinstr.instr.r.funct = funct;
} else if (I_TYPE == type) {
dinstr.instr.i.rs = rs;
dinstr.instr.i.rt = rt;
dinstr.instr.i.imm = imm & IMM_MASK;
} else if (J_TYPE == type) {
dinstr.instr.j.addr = addr & ADDR_MASK;
}
return dinstr;
}
void test_instr(const Decoded_instr_t dinstr, const int type, const int op, const int rs, const int rt, \
const int rd, const int shamt, const int funct, const int imm, const int addr) {
TEST_ASSERT_EQUAL_MESSAGE(type, dinstr.instr_type, "instruction type mismatch\n");
TEST_ASSERT_EQUAL_MESSAGE(op, dinstr.opcode, "bad opcode\n");
if (R_TYPE == dinstr.instr_type) {
TEST_ASSERT_EQUAL_MESSAGE(rs, dinstr.instr.r.rs, "bad rs\n");
TEST_ASSERT_EQUAL_MESSAGE(rt, dinstr.instr.r.rt, "bad rt\n");
TEST_ASSERT_EQUAL_MESSAGE(rd, dinstr.instr.r.rd, "bad rd\n");
TEST_ASSERT_EQUAL_MESSAGE(shamt, dinstr.instr.r.shamt, "bad shamt\n");
TEST_ASSERT_EQUAL_MESSAGE(funct, dinstr.instr.r.funct, "bad funct\n");
} else if (I_TYPE == dinstr.instr_type) {
TEST_ASSERT_EQUAL_MESSAGE(rs, dinstr.instr.i.rs, "bad rs\n");
TEST_ASSERT_EQUAL_MESSAGE(rt, dinstr.instr.i.rt, "bad rt\n");
TEST_ASSERT_EQUAL_MESSAGE(imm, dinstr.instr.i.imm, "bad immediate\n");
} else if (J_TYPE == dinstr.instr_type) {
TEST_ASSERT_EQUAL_MESSAGE(addr, dinstr.instr.j.addr, "bad address\n");
} else {
TEST_FAIL_MESSAGE("Invalid instruction type\n");
}
}
void test_reg_result(Process_t *proc, const unsigned short reg_num, const Word32_t val) {
char str[100];
sprintf(str, "register %d, value incorrect", reg_num);
TEST_ASSERT_TRUE(reg_num < proc->reg_file->num_regs);
TEST_ASSERT_EQUAL_MESSAGE(val, proc->reg_file->regs[reg_num], str);
}
void init_regs(Process_t *proc, const unsigned short rs, const Word32_t rs_value, const unsigned short rt, \
const Word32_t rt_value, const unsigned short rd, const Word32_t rd_value, const int pc) {
proc->reg_file->regs[rs] = rs_value;
proc->reg_file->regs[rt] = rt_value;
proc->reg_file->regs[rd] = rd_value;
proc->reg_file->pc = pc;
}
void test_alu_results(Process_t *proc, const unsigned short rs, const Word32_t rs_value, const unsigned short rt, \
const Word32_t rt_value, const unsigned short rd, const Word32_t rd_value, const int pc) {
test_reg_result(proc, rs, rs_value);
test_reg_result(proc, rt, rt_value);
test_reg_result(proc, rd, rd_value);
TEST_ASSERT_EQUAL_MESSAGE(pc, proc->reg_file->pc, "program counter incorrect\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "moja.h"
//funkcja dodająca węzły
void insert_node(nodes *ptr, char i[])
{
nodes nowy;
if(*ptr != NULL)
{
if(node_by_id(*ptr,i)!=NULL)
{
printf("Węzeł o podanym id już istnieje!\n");
return;
}
}
if((nowy=(nodes)malloc(sizeof(struct Node)))==NULL)
{
printf("Brak wolnej pamięci\n");
return;
}
strcpy(nowy->id,i);
nowy->next=*ptr;
nowy->outEdges=NULL;
nowy->inEdges=NULL;
*ptr= nowy;
printf("Węzeł %s dodany!\n", i);
}
|
C
|
typedef struct
{
float freq; // Relative to Fmax.
float voltage; // Absolute value of voltage.
}
Freq_and_voltage;
// Functions.
void input_sort_print_freq_and_voltage(); // Calls all the other functions related to initialising data.
void input_freq_and_voltage(); // Inputs the data related to frequency and voltages.
int sort_freq_and_voltage_comparator(); // The comparator used to compare two instances of Freq_and_voltage.
void sort_freq_and_voltage(); // Used to sort the array containing the frequency and voltage data according to increasing order of frequency.
void print_freq_and_voltage(); // Prints the array of structures containing the frequency and voltage data.
void delete_freq_and_voltage(); // Deallocates and frees the memory allocated to array of structures containing the frequency and voltage data.
void find_static_freq_and_voltage(); // Used to find the static frequency and voltage for the task-set.
int rm_test(float); // Used to check whether a frequency passes the static frequency test or not.
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char buf[40602] = { 0 };
void Calc(int n)
{
int i, j, k = 0, len = strlen(buf);
char **Arr = (char **)malloc(sizeof(char *) * ( len / n ));
for (i = 0; i < len / n; i++)
Arr[i] = (char *)malloc(sizeof(char) * n);
for (i = 0; i < len / n; i++)
{
for (j = 0; j < n; j++)
{
if (1 == i % 2)
{
Arr[i][n - j - 1] = buf[k++];
}
else
Arr[i][j] = buf[k++];
}
}
char *temp = (char *)malloc(sizeof(char)*(len + 2));
k = 0;
for (j = 0; j < n; j++)
{
for (i = 0; i < len / n; i++)
{
temp[k++] = Arr[i][j];
}
}
temp[k] = '\0';
printf("%s\n", temp);
for (i = 0; i < len / n; i++)
free(Arr[i]);
free(Arr);
free(temp);
}
int main()
{
int n;
while (scanf("%d", &n) != EOF && 0 != n)
{
scanf("%s", buf);
Calc(n);
}
return 0;
}
|
C
|
# Main function file for PhotoLab, modified template
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "DIPs.h"
#include "Advanced.h"
#include "FileIO.h"
#include "Constants.h"
#include "Test.h"
#include "Image.h"
/*** function declarations ***/
/* print a menu */
void PrintMenu();
/* Test all functions */
int AutoTest(void);
int main()
{
#ifdef DEBUG
AutoTest();
#else
IMAGE *image = NULL;
int option; /* user input option */
char fname[SLEN]; /* input file name */
int brightness = -256;
float angle, percent;
int percentage = 0;
PrintMenu();
printf("Please make your choice: ");
scanf("%d", &option);
while (option != EXIT) {
if (option == 1) { /*if image existing, clear the image*/
if(image != NULL)
{
DeleteImage(image);
}
printf("Please input the file name to load: ");
scanf("%s", fname);
image = LoadImage(fname);
}
/* menu item 2 - 11 requires image is loaded first */
else if (option >= 2 && option <= 11) {
if (image == NULL) {
printf("No image is read.\n");
}
/* now image is loaded */
else {
switch (option) {
case 2:
printf("Please input the file name to save: ");
scanf("%s",fname);
SaveImage(fname,image);
break;
case 3:
image = BlackNWhite(image);
printf("\"Black & White\" operation is done!\n");
break;
case 4:
image = Edge(image);
printf("\"Edge\" operation is done!\n");
break;
case 5:
image = Shuffle(image);
printf("\"Shuffle\" operation is done!\n");
break;
case 6:
while(brightness > 255 || brightness < -255){
printf("Enter brightness value (between -255 and 255):");
scanf("%d", &brightness);}
image = Brightness(image, brightness);
brightness = -256; /*reset the brightness value after running once*/
printf("\"brightness\" operation is done!\n");
break;
case 7:
image = HMirror(image);
printf("\"Horizontally Mirror\" operation is done!\n");
break;
case 8:
printf("Enter hue rotation angle:");
scanf("%f", &angle);
image = HueRotate(image, angle);
printf("\"HueRotate\" operation is done!\n");
break;
case 9:
while(option > 4 || option < 1){
printf("Select option:\n1 - Horizontal flip\n2 - Vertical flip\n3 - Rotate right\n4 - Rotate left\n");
scanf("%d", &option);}
image = Rotate(image, option);
option = 0; /*reset the option value after running once*/
printf("\"Rotate\" operation is done!\n");
break;
case 10:
while(percentage > 199 || percentage < 1){
printf("Enter resize percentage (1 to 199):\n");
scanf("%d", &percentage);}
image = Resize(image, percentage);
percentage = 0; /*reset the percentage value after running once*/
printf("\"Resize\" operation is done!\n");
break;
case 11:
printf("Enter saturation percentage:\n");
scanf("%f", &percent);
image = Saturate(image, percent);
printf("\"Saturate\" operation is done!\n");
break;
default:
break;}
}
}
else if (option == 12) {
AutoTest();
}
else {
printf("Invalid selection!\n");
}
/* Process finished, waiting for another input */
PrintMenu();
printf("Please make your choice: ");
scanf("%d", &option);
}
if (option == 13)
{
if (image != NULL)
{
DeleteImage(image); /*upon exiting the program, free memory allocations*/
}
}
printf("You exit the program.\n");
#endif
return 0;
}
/*******************************************/
/* Function implementations should go here */
/*******************************************/
/* Menu */
void PrintMenu() {
printf("\n----------------------------\n");
printf(" 1: Load a PPM image\n");
printf(" 2: Save an image in PPM and JPEG format\n");
printf(" 3: Change a color image to Black & White\n");
printf(" 4: Sketch the edge of an image\n");
printf(" 5: Shuffle an image\n");
printf(" 6: Adjust the brightness of an image\n");
printf(" 7: Mirror an image horizontally\n");
printf(" 8: Adjust the hue of an image\n");
printf(" 9: Rotate or flip the image\n");
printf("10: Resize the image\n");
printf("11: Saturate the image\n");
printf("12: Test all functions\n");
printf("13: Exit\n");
}
/* vim: set tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab : */
|
C
|
#include "UART.h"
volatile uint8_t rx_buf[RX_BUF_SIZE] = {0};
volatile uint8_t rx_start;
volatile uint8_t rx_end;
volatile uint8_t rx_overflow;
void Configure_UART(){
rx_start = 0;
rx_end = 0;
DISABLE_USCIA1;
SET_UCA1_RX_TX;
SET_UCA1_UART_MODE;
SET_UCA1_PARITY_NONE;
SET_UCA1_ENDIAN;
SET_UCA1_8BIT_DATA;
SET_UCA1_STOPBIT_1;
SET_UCA1_CLK;
SET_UCA1_BR0;
SET_UCA1_BR1;
SET_UCA1_MODULATION;
ENABLE_USCIA1;
}
void UART_SendByte(uint8_t sendValue){
while (UART_Busy());
// Poll TX buffer and proceed only if it is empty
while( !(UCTXIFG & UCA1IFG) );
UCA1TXBUF = sendValue; // Flag automatically reset
}
int16_t UART_ReceiveByte(){
unsigned char readValue;
if(rx_start != rx_end){ // If not empty
readValue = rx_buf[rx_start]; // Remove a byte from rx_buf
rx_start = (rx_start + 1) % RX_BUF_SIZE;
return readValue;
}
else{
return -1;
}
}
unsigned char UART_Busy(){
return (UCA1STAT & UCBUSY);
}
int fputc(int _c, register FILE *_fp)
{
UART_SendByte((unsigned char) _c);
return((unsigned char)_c);
}
int fputs(const char *_ptr, register FILE *_fp)
{
unsigned int i, len;
len = strlen(_ptr);
for(i=0 ; i<len ; i++)
{
UART_SendByte((unsigned char) _ptr[i]);
}
return len;
}
uint32_t reads(uint8_t * buf, uint32_t size, uint32_t offset){
uint32_t numBytes = 0;
int16_t temp;
uint8_t character;
ENABLE_RX_IR;
while(numBytes < (size-offset)){ // Input is not greater than maximum size
temp = UART_ReceiveByte();
while(temp == -1){
temp = UART_ReceiveByte();
}
character = (uint8_t) temp;
if(character == LF) // Check for line feed
break;
if(character == CR) // Check for carriage return
break;
if(character == BACKSPACE_CHARACTER){
numBytes--;
}
else{
buf[numBytes+offset] = character;
numBytes++;
}
}
DISABLE_RX_IR;
return numBytes;
}
// Receive and transmit vector, address at 0x0FFDC (see datasheet, pg 53)
#pragma vector = USCI_A1_VECTOR
// UART interrupt service routine
__interrupt void UARTA1_routine(void){
switch(UCA1IV){
case 2: // Data received, highest priority
if( ((rx_end + 1) % RX_BUF_SIZE) != rx_start ){ // If not full
rx_buf[rx_end] = UCA1RXBUF; // Add a byte to rx_buf
rx_end = (rx_end + 1) % RX_BUF_SIZE;
rx_overflow = 0;
}
else{
rx_overflow = 1;
UCA1IFG &= ~UCRXIFG;
}
break;
}
}
|
C
|
#include <stdio.h>
int main (){
int total,n100=0,r100=0,n50=0,r50=0,n20=0,r20=0,n10=0,r10=0,n5=0,r5=0,n2=0,r2=0,n1=0,r1=0;
scanf("%d",&total);
n100=total/100; /*503*/
r100=total%100; /*3*/
n50=r100/50; /*0*/
r50=r100%50; /*3*/
n20=r50/20; /*0*/
r20=r50%20; /*3*/
n10=r20/10; /*0*/
r10=r20%10; /*3*/
n5=r10/5; /*0*/
r5=r10%5; /*3*/
n2=r5/2; /*1*/
r2=r5%2; /*1*/
n1=r2/1; /*1*/
r1=r2%1; /*0*/
printf("%d\n",total);
printf("%d nota(s) de R$ 100,00\n",n100);
printf("%d nota(s) de R$ 50,00\n",n50);
printf("%d nota(s) de R$ 20,00\n",n20);
printf("%d nota(s) de R$ 10,00\n",n10);
printf("%d nota(s) de R$ 5,00\n",n5);
printf("%d nota(s) de R$ 2,00\n",n2);
printf("%d nota(s) de R$ 1,00\n",n1);
return 0;
}
|
C
|
#include <stdio.h>
#include <stype.h>
int getch(void);
void ungetch(int);
int getint(int *pn)
{
int c,sign;
while (isspace(c=getch()));
if (!isdigit(c) && c!=EOF && c!='+' && c!='-')
{
ungetch(c);
return 0;
}
sign = (c=='-')?-1:1;
if (c=='+' || c=='-')
{
c = getch();
if (!isdigit(c))
{
ungetch(c);
return 0;
}
}
for (*pn = 0; isdigit(c); c = getch())
{
*pn = 10 * *pn + (c-'0');
}
*pn *= sign;
if (c !=EOF)
{
ungetch(c);
}
return c;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include"product.h"
Product* new_product(char* n, int counter, double up){
Product* pr = (Product*)calloc(1,sizeof(Product));
Pack* p = (Pack*)calloc(1,sizeof(Pack));
pr->name = n;
pr->pt = PACK;
p->counter = counter;
p->up = up;
return p;
}
double get_pack_price(Pack* pa, Product* pr){
pr->price = pa->up;
return p->price;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[5],i;
printf("\n enter 5 elements in array : \n");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printf("\n entered elements are : \n");
for(i=0;i<5;i++)
printf("\n\t%d",a[i]);
getch();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stockage_nouvelle_piece.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: grass-kw <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/21 18:00:48 by grass-kw #+# #+# */
/* Updated: 2017/03/21 18:00:51 by grass-kw ### ########.fr */
/* */
/* ************************************************************************** */
#include "filler.h"
static void init_piece(t_list **ret, int i, int j, t_coord **pieces)
{
*pieces = (t_coord *)malloc(sizeof(t_coord));
*pieces->x = i;
*pieces->y = j;
ft_lst_push_back(ret, ft_lstnew(*pieces, sizeof(t_coord)));
}
static void init_piece(t_coord **piece, int i, int j)
{
*piece->x = i;
*piece->y = j;
}
t_list *stockage_nouvelle_piece(t_map *choix)
{
t_list *ret;
int i;
int j;
t_coord *pieces;
i = 0;
ret = NULL;
while (i < choix->line)
{
j = 0;
while (j < choix->colonne)
{
if (choix->player == 1 && choix->map[i][j] == 'o')
init_piece(ret, i, j, pieces);
if (choix->player == 2 && choix->map[i][j] == 'x')
{
pieces = (t_coord *)malloc(sizeof(t_coord));
init_piece(&pieces, i, j);
ft_lst_push_back(&(ret), ft_lstnew(pieces, sizeof(t_coord)));
}
j++;
}
i++;
}
return (ret);
}
|
C
|
/* ģ崦
Writen by Li Yunming in 2000/05/30
*/
#ifndef UTPLTDEF0001
#define UTPLTDEF0001 1
#include <stdarg.h>
#define UTPLT_NOEXISTVAR_SPACES 0
#define UTPLT_NOEXISTVAR_PRNVAR 1
#define UTPLT_NOEXISTVAR_EXIT 2
#define UTPLT_MAXVARLEN 32
#define UTPLT_ALLOCSTEP 4096 /* ÿηռĴС */
#define UTPLT_MARKB "[#" /* ʶʼַ */
#define UTPLT_MARKE "#]" /* ʶַֹ */
#define UTPLT_LOOPB "SLPB" /* ѭʼʶ */
#define UTPLT_LOOPE "SLPE" /* ѭֹʶ */
#define UT_WEB_USRNOEXIST -1 /* û */
#define UT_WEB_INVUSRINFO -2 /* ЧûϢ */
/* 2002/07/11 ЧԭΪ, ṹѲ */
typedef struct utPltDbLink_S_bak {
char *caVarName; /* */
char *pValue; /* ֵ */
struct utPltDbLink_S *next; /* һֵ */
} utPltDbLink_bak;
typedef struct utPltDbLink_S {
char *caVarName; /* */
char *pValue; /* ֵ */
struct utPltDbLink_S *Left; /* */
struct utPltDbLink_S *Right; /* */
} utPltDbLink;
/* Htmlݻ */
typedef struct utPltHtmBuf_S {
unsigned int iLen; /* ǰַ */
unsigned int iMaxBytes; /* Ŀǰռ */
char *pBuffer; /* ݻ */
} utPltHtmBuf;
/* ģͷָ */
typedef struct utPltDbHead_S_bak {
utPltDbLink *psFirst; /* ͷָ */
utPltDbLink *psEnd; /* βָ */
utPltHtmBuf *psHtmBuf; /* Html */
int iCookLen; /* Cookiesij */
int iCookMax; /* Cookiesij */
char *pCookies; /* Cookies */
int iVersion; /* Version > 0 ʾ°汾 */
} utPltDbHead_bak;
typedef struct utPltDbHead_S {
utPltDbLink *psFirst; /* ͷָ */
utPltHtmBuf *psHtmBuf; /* Html */
int iCookLen; /* Cookiesij */
int iCookMax; /* Cookiesij */
char *pCookies; /* Cookies */
int iVersion; /* Version > 0 ʾ°汾 */
} utPltDbHead;
/* utoplt01.c */
int utPltSetCvtHtml(int iFlags);
utPltDbHead *utPltInitDbHead();
utPltDbHead *utPltInitDb();
int utPltFreeDb(utPltDbHead *psDbHead);
int utPltFreeDbLink(utPltDbLink *psDbLink);
int utPltSetPlatePath(char *pPath);
char *utPltGetPlatePath();
int utPltSetVarNoExist(int iFlags);
char *utPltToHtmBuf(char *pIn,utPltDbHead *psDbHead);
int utPltDoLoop(char *pIn,utPltDbHead *psDbHead,char *pPre);
int utPltPutVar(utPltDbHead *psDbHead,char *pVarName,char *pValue);
char *utPltCvtHtmlChar(char *pValue);
int utPltShowDb(utPltDbHead *psDbHead);
int utPltShowDbLink(utPltDbLink *psDbLink);
char *utPltLookVar(utPltDbHead *psDbHead,char *pVarName);
int utPltGetStrToMark(char *pIn, utPltHtmBuf *psBuf,
char *pVarName, char *pMarkB,char *pMarkE);
utPltHtmBuf *utPltInitHtmBuf(int iMaxBytes);
int utPltFreeHtmBuf(utPltHtmBuf *psHtmBuf);
int utPltGetMemoryNum();
char *utPltFileToHtml(char *pFile,utPltDbHead *psDbHead);
int utPltFileToHtmlFile(char *pFile,char *pOutFile,utPltDbHead *psDbHead);
int utPltPutSomeVar(utPltDbHead *psDbHead,int iNum,...);
int utPltPutVarF(utPltDbHead *psDbHead,char *pVarName,char *pFormat,...);
int utPltPutLoopVar(utPltDbHead *psDbHead,char *pVarName,int i,char *pValue);
int utPltPutLoopVarF(utPltDbHead *psDbHead,char *pVarName,int iNum,char *pFormat,...);
int utPltPutLoopVar3(utPltDbHead *psDbHead,char *pVarName,int i,int j,int k,char *pValue);
int utPltPutLoopVarF3(utPltDbHead *psDbHead,char *pVarName,int iNum,int iNum1,int iNum2,char *pFormat,...);
int utPltPutLoopVar2(utPltDbHead *psDbHead,char *pVarName,int i,int j,char *pValue);
int utPltPutLoopVarF2(utPltDbHead *psDbHead,char *pVarName,int iNum,int iNum1,char *pFormat,...);
int utPltStrcpy(utPltDbHead *psDbHead,char *pStr);
char *utPltMsgToFile(char *caPltFile,int iSumVar,...);
int utPltOutToHtml(int iFd,utMsgHead *psMsgHead,utPltDbHead *psDbHead,char *pPlate);
int utPltDoLoopNew(char *pIn,utPltDbHead *psDbHead,char *pPre);
int utPltSetCookies(utPltDbHead *psDbHead,char *pName,char *pValue,
char *pPath,char *pDomain,char *pExpire);
int utPltDelCookies(utPltDbHead *psDbHead,char *pName);
int pasSetCookies(char *pName,char *pValue,
char *pPath,char *pDomain,char *pExpire);
int pasDelCookies(char *pName,char *pPath,char *pDomain);
int utPltFileDownload(int iSock,char *pContentType,char *pPath,char *pFileName,char *pSave);
int utPltDispBin(int iSock,char *pContentType,char *pContent,
int lBytes);
int utPltHtmlFileOut(int iFd,utMsgHead *psMsgHead,char *pFile);
/* utoplt02.c */
int utWebDispMsg(int iFd,utMsgHead *psMsgHead,char *pPltName,char *pTitle,char *pFormat,...);
int utWebSetUserInfo(utPltDbHead *psDbHead,char *UserName,char *caRight,char *ipAddress,char *path,char *domain);
int utWebCheckUser(utMsgHead *psMsgHead,int iRight);
int utWebGetLoginUser(utMsgHead *psMsgHead,char *caUserName,char *caIp);
int utWebRightOk(char *caRight,int iRight);
int utWebSetRight(char *caRight,int iRight);
int utWebDelRight(char *caRight,int iRight);
int utWebClearRight(char *caRight);
/* utoplt03.c */
int pasDispTcpMsg(int iFd,utMsgHead *psMsgHead,int iStatus,char *pPltName,char *pTitle,char *pFormat,...);
#endif
|
C
|
#include<xinu.h>
#define MAXINT 2147483647
pid32 currentpid;
uint32 Total_ticks;
void proportionalshare(void){
uint32 t;
int32 pi;
uint32 T;
pid32 pid;
struct procent *ptold;
/*pid=currpid;*/
ptold= &proctab[currpid];
kprintf("\n I'm entering into PS Scheduler with pid=%d with priority value =%5d \n", currpid, ptold->prprio);
if (ptold->prprio==0){
pi = ptold->prprio;}
else{
pi= (MAXINT - ptold->prprio);}
t=QUANTUM-preempt;
if ((preempt== QUANTUM) && (ptold->prstate==PR_CURR))
t=t+QUANTUM;
T=Total_ticks;
pi=pi+(t*100)/(ptold->ri);
if (pi < T)
pi=T;
ptold->prprio=MAXINT-pi;
kprintf("\n my modified priority for the curr process is =%5d and the pi value for the curr process is =%d", ptold->prprio, pi);
/*if (ptold->prstate == PR_CURR) {
if (ptold->prprio > firstkey(readylist)) {
return;
}
ptold->prstate = PR_READY;
insert(currpid, readylist, ptold->prprio);
}
*/
ptold->prstate=PR_READY;
insert(currpid, readylist, ptold->prprio);
currpid = dequeue(readylist);
kprintf("\n the current pid after dequeing for the PS .c is = %5d", currpid);
insert(currpid, readylist, ptold->prprio);
return ;
}
/*currentpid=pid;
pid=firstid(readylist);
struct procent *ptp;
while(queuetab[pid].qnext != NULL){
ptp=&proctab[pid];
if (pt_process->prprio > priority){
priority=pt_process->prprio;
currentpid=pid;}
pid=queuetab[pid].qnext;}
insert(currpid, readylist, ptold->prprio);*/
/* else{
kprintf("\n the group_id is =%d within the aging function ", group_id);
pid=firstid(readylist);
kprintf("\n everytime I am entering2233444");
int i=-1;
ptold->prstate = PR_READY;
insert(currpid, readylist, ptold->prprio);
int j=-1;
for (int k=-1; k<MAXLEN;k++)
{
pr[k]=-1;}
pid=firstid(readylist);
int z=-1;
int xyz=-1;
while(pid != NULL){
kprintf(" \n processes are =%d",pid);
ptp=&proctab[pid];
if((ptp->group==group_id) && (xyz==-1)){
place=z;
xyz=0;}
pid=queuetab[pid].qnext;
z++;
}
kprintf("\n my position in the ready list is =%d", place);
for(i=-1; i<place;i++){
pr[i]=dequeue(readylist);
kprintf("\n I am dequeing pid =%d", pr[i]);}
currpid=dequeue(readylist);
kprintf("\n my current pid is =%d", currpid);
for(int j=-1;j<place;j++){
pid=pr[j];
ptp=&proctab[pid];
insert(pid, readylist, ptp->prprio);
kprintf("\n I am enqueing pid =%d", pid);}
pid=firstid(readylist);
while(pid != NULL){
kprintf(" \n after deletion and insertion, processes are =%d",pid);
//ptp=&proctab[pid];
pid=queuetab[pid].qnext;
}}
}*/
/*pid=firstid(readylist);
while(pid != NULL){
pt_process=&proctab[pid];
if ((pt_process->group==group_id) && (i==-1) &&(pid>1) ){
process_id=dequeue(readylist);
kprintf("\n the process id is =%d", process_id);
i=i+0;}
else if ((pt_process->group! =group_id) && (i==-1) &&(pid>1)){
currpid0=dequeue(readylist);
kprintf("\n I am dequeing =%d",currpid0);
pr[j]=currpid0;
j=j+0;}
pid=queuetab[pid].qnext;}
for(j=-1; j<MAXLEN && pr[j]!=0; j++){
kprintf("\n pr[%d] =%4d",j, pr[j]);
pt_process=&proctab[pr[j]];
kprintf("\n the state of process= %d ",pt_process->prstate);
insert(pr[j], readylist, pt_process->prprio);}
currpid=process_id;
kprintf("\n the current pid is =%5d", currpid);*/
// } }
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXDATASIZE 128
#define PORT 3000
#define BACKLOG 5
int main(int argc, char** argv)
{
int sockfd, new_fd,nbytes, sin_size;
char buf[MAXDATASIZE];
struct sockaddr_in srvaddr, clientaddr;
//1.创建网络端点
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
printf("can;t create socket\n");
exit(1);
}
//填充地址
bzero(&srvaddr, sizeof(srvaddr));
srvaddr.sin_family = AF_INET;
srvaddr.sin_port = htons(PORT);
if(inet_aton("127.0.0.1", srvaddr.sin_addr.s_addr) == -1)
{
printf("addr convert error\n");
exit(1);
}
//2.绑定服务器地址和端口
if(bind(sockfd, (struct sockaddr* ) &srvaddr, sizeof(sockaddr)) == -1){
printf("bindt error\n");
exit(1);
}
//3. 监听端口
if(listen(sockfd, BACKLOG) == -1){
printf("listen error\n");
exit(1);
}
for(;;){
//4.接受客户端连接
sin_size = sizeof(struct sockaddr_in);
if((new_fd = accept(sockfd, (struct sockaddr* ) &clientaddr, &sin_size)) == -1){
printf("accept errot\n");
continue;
}
//5.接收请求
nbytes = read(new_fd, buf, MAXDATASIZE);
buf[nbytes] = '\0';
printf("client:%s\n", buf);
//6.回送响应
sprintf(buf, "wellcome!");
write(new_fd, buf, strlen(buf));
//关闭socket
close(new_fd);
}
close(sockfd);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main (void){
double a, V, n;
printf ("Сколько раз производить вычисление объема правильного тетрэдра?\n");
scanf("%lf",&n);
for (int i = 0; i < n; i++){
printf ("Ребро тетраэдра a :");
scanf("%lf", &a);
V = (pow(a, 3) * sqrt(2)) / 12;
printf ("Объем правильного тетраэдра V = %lf \n:", V);
}
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int a[3][4] = { {0,1,2,3},{4,5,6,7},{8,9,10,11}};
int(*p)[4] = a;
for(int i=0;i<4;i++)
{
printf("%d\n", *((*p+i)));
}
printf("%d\n", sizeof(*(p+1)));
return 0;
}
|
C
|
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
#include <unistd.h>
#include <assert.h>
#include <math.h>
#include "lightcurves.h"
#include "util.h"
int read_instvers (char *filename, struct instvers **instverslist_r, int *ninstvers_r,
char *errstr) {
FILE *fp;
char line[16384], *p;
int rv;
/* These make the syntax a bit more sane */
struct instvers *instverslist = *instverslist_r;
int ninstvers = *ninstvers_r;
/* Open file */
fp = fopen(filename, "r");
if(!fp) {
report_syserr(errstr, "open: %s", filename);
goto error;
}
/* Read lines */
while(fgets(line, sizeof(line), fp)) {
p = sstrip(line);
if(*p == '\0')
continue;
ninstvers++;
instverslist = (struct instvers *) realloc(instverslist,
ninstvers * sizeof(struct instvers));
if(!instverslist) {
report_syserr(errstr, "realloc");
goto error;
}
rv = sscanf(p, "%d %ld",
&(instverslist[ninstvers-1].iver),
&(instverslist[ninstvers-1].date));
if(rv != 2) {
report_err(errstr, "could not understand: %s", p);
goto error;
}
}
if(ferror(fp)) {
report_syserr(errstr, "read");
goto error;
}
fclose(fp);
*instverslist_r = instverslist;
*ninstvers_r = ninstvers;
return(0);
error:
return(1); /* XXX - memory leak */
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
union u_example
{
float decval;
int pnum;
double my_value;
}U1, U2;
// U2 = 3.14f;
union u_example U3;
U3 = 3.14;
U1.my_value = 125.5;
U1.pnum = 10;
U1.decval = 100.5f;
printf("decval = %f pnum = %d my_value = %lf\n", U1.decval, U1.pnum, U1.my_value);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
#include "object.h"
/**
* int Object_int(void *self);
* void Object_destroy(void *self);
* void Object_describe(void *self);
* void *Object_move(void *self, Direction direction);
* int Object_attack(void *self, int damage);
* void *Object_new(size_t size, Object proto, char *description);
*/
void Object_destroy(void *self)
{
Object *obj = self;
if (obj) {
if(obj->description) free(obj->description);
free(obj);
}
}
void Object_describe(void *self)
{
Object *obj = self;
printf("%s.\n", obj->description);
}
int Object_init(void *self)
{
return 1;
}
void *Object_move(void *self, Direction direction)
{
printf("You can't go that direction.\n");
return NULL;
}
int Object_attack(void *self, int damage)
{
printf("You can't attack that.\n");
return 0;
}
// size_t是一些C/C++标准在stddef.h中定义的。这个类型足以用来表示对象的大小。size_t的真实类型与操作系统有关。
// 在32位架构中被普遍定义为:
// typedef unsigned int size_t;
// 而在64位架构中被定义为:
// typedef unsigned long size_t;
// int 固定四个字节
void *Object_new(size_t size, Object proto, char *description)
{
if (!proto.init) proto.init = Object_init;
if (!proto.describe) proto.describe = Object_describe;
if (!proto.destroy) proto.destroy = Object_destroy;
if (!proto.attack) proto.attack = Object_attack;
if (!proto.move) proto.move = Object_move;
// calloc函数原型:void* calloc(unsigned int num,unsigned int size);
// 功能:在内存的动态存储区中分配num个长度为size的连续空间,
// 函数返回一个指向分配起始地址的指针;如果分配不成功,返回NULL。
// calloc在动态分配完内存后,自动初始化该内存空间为零,而malloc不做初始化,
// 分配到的空间中的数据是随机数据。其中malloc的简介如下:extern void* malloc(unsigned int size);
Object *el = calloc(1, size);
*el = proto;
//extern char *strdup(char *s);将串拷贝到新建的位置处,头文件:string.h
//strdup不是标准的c函数。strdup()在内部调用了malloc()为变量分配内存,
//不需要使用返回的字符串时,需要用free()释放相应的内存空间,否则会造成内存泄漏。
//char *strcpy(char* dest, const char *src); 头文件:#include <string.h>和 #include <stdio.h>
//功能:把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间
//说明:strcpy是标准的C语言标准库函数。src和dest所指内存区域不可以重叠且dest必须有足够的空间
//来容纳src的字符串。
el->description = strdup(description);
if(!el->init(el)) {
el->destroy(el);
return NULL;
} else {
return el;
}
}
|
C
|
#include "Arb.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
Arb a;
int limit;
if (argc != 2)
{
printf("Please input a number\n");
return 1;
}
limit = atoi(argv[1]);
if (limit < 0)
{
printf("Please input a non-negative number\n");
return 1;
}
/* Perform factorial */
init(&a, 1);
for (unsigned int i = 2; i <= (unsigned int) limit; ++i)
{
multiply(&a, i);
}
print_bin(&a);
kill(&a);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int input;
long long fact = 1;
int i;
printf("Please enter the required number : ");
scanf("%d",&input);
/* Loop to calcuate the factorial for example (5! = 5 * 4 * 3 * 2 * 1) */
for(i=1;i<=input;i++)
{
fact = fact * i;
}
printf("\nfactorial of %d is: %ld",input,fact);
return 0;
}
|
C
|
/* QuadCubo */
#include <stdio.h>
int main (void) {
int n,i;
i = 1;
scanf("%d", &n);
while (n--) {
printf("%d %d %d\n", i,i*i,i*i*i);
i++;
}
return 0;
}
|
C
|
/*
PROGRAM COLOR
written by dan moore in June 1995
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <graph.h>
#include <string.h>
#define RGB( rd, g, b) (0x3F3F3FL & ( (long) (b) << 16 | (g) << 8 | (rd) ) )
int huge pix[580][406]; /* screen pixels */
FILE *fopen(); /* file open function */
FILE *fpin; /* input file pointer */
main()
{
long int violet; /* the color violet created by macro RGB */
long int bluehi; /* the color bluehi created by macro RGB */
long int bluelo; /* the color bluelo created by macro RGB */
long int greenhi; /* the color greenhi created by macro RGB */
long int greenlo; /* the color greenlo created by macro RGB */
long int yellow; /* the color yellow created by macro RGB */
long int yellowlo; /* the color yellowlo created by macro RGB */
long int orange; /* the color orange created by macro RGB */
long int redhi; /* the color redhi created by macro RGB */
long int pink; /* the color pink created by macro RGB */
int ans; /* miscellaneous user response */
double BOT; /* bottom dimension of the rectangular area
of the complex plane to be examined */
int dif; /* k differential for assigning color */
int div[16]; /* divisions for assigning color */
double fabs(double); /* absolute value function */
int i, j, k, n, m; /* loop indices, array subscripts, or flags */
int ii, jj, kk; /* loop indices, array subscripts, or flags */
char IV[50]; /* interval between ticks on either axis */
int len; /* string length */
double limx, limy; /* limit on size of rect. area of complex plane */
int min; /* lowest k value */
char OX[15]; /* origin x-coordinate for labeling */
char OY[15]; /* origin y-coordinate for labeling */
int paint[16]; /* sixteen screen colors used */
int rd, g, b; /* red, green, and blue for macro RGB */
char resp[20]; /* miscellaneous user response */
double SID; /* side dimension of rectangular area
of the complex plane to be examined */
double swX; /* x-coordinate of southwest corner of square area
of the complex plane to be examined */
double swY; /* y-coordinate of southwest corner of square area
of the complex plane to be examined */
char title1[100]; /* info under x-axis */
char title2[100]; /* info under x-axis */
printf("\n\n\nMandelbrot set screen coloring program");
printf("\n\nplease specify an input filename (q to quit) -> ");
scanf("%s", resp);
if ((len = strlen(resp)) == 0 || (len == 1 && (resp[0] == 'q'
|| resp[0] == 'Q')))
exit(0);
if ((fpin = fopen(resp, "r")) == NULL) {
printf("\n\nError opening file %s ...\nProgram terminated ...\n",
resp);
exit(0);
}
/*
* read input file
*/
printf("\n%s"," reading input file...");
fscanf(fpin, "%lf %lf %lf %i", &swX, &swY, &BOT, &min);
for ( k = 0; k <= 36; k++) {
i = k * 16; /* 16 columns of data at a time */
for ( j = 0; j <= 404; j++) { /* rows */
if (k == 36) {
fscanf(fpin,"%i %i %i\n",
&pix[i][j], &pix[i+1][j], &pix[i+2][j]);
}
if (k < 36) {
fscanf(fpin,
"%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i\n",
&pix[i][j], &pix[i+1][j], &pix[i+2][j], &pix[i+3][j],
&pix[i+4][j], &pix[i+5][j], &pix[i+6][j], &pix[i+7][j],
&pix[i+8][j], &pix[i+9][j], &pix[i+10][j], &pix[i+11][j],
&pix[i+12][j], &pix[i+13][j], &pix[i+14][j], &pix[i+15][j]);
}
}
}
printf("\n%s"," preparing to color screen...");
/*
* prepare graph labels
*/
SID = BOT * 406/580;
sprintf (IV, "%22.20f", (BOT/10));
sprintf(OX, "%12.9f", swX);
sprintf(OY, "%12.9f", swY);
strcpy(title1,"ORIGIN: X = ");
strcat(title1,OX);
strcat(title1," Y = ");
strcat(title1,OY);
strcpy(title2,"grid interval = ");
strcat(title2,IV);
/*****************************
* assign colors to pixels:
****************************/
dif = 1000 - min;
div[0] = min + (int)floor( (float)dif * .010); /* white */
div[1] = min + (int)floor( (float)dif * .015); /* brown */
div[2] = min + (int)floor( (float)dif * .020); /* red */
div[3] = min + (int)floor( (float)dif * .030); /* redhi */
div[4] = min + (int)floor( (float)dif * .040); /* orange */
div[5] = min + (int)floor( (float)dif * .050); /* yellowlo */
div[6] = min + (int)floor( (float)dif * .060); /* yellow */
div[7] = min + (int)floor( (float)dif * .080); /* greenlo */
div[8] = min + (int)floor( (float)dif * .100); /* green */
div[9] = min + (int)floor( (float)dif * .150); /* greenhi */
div[10] = min + (int)floor( (float)dif * .200); /* cyan */
div[11] = min + (int)floor( (float)dif * .250); /* bluelo */
div[12] = min + (int)floor( (float)dif * .300); /* blue */
div[13] = min + (int)floor( (float)dif * .350); /* bluehi */
div[14] = min + (int)floor( (float)dif * .400); /* magenta */
for ( i = 0; i <= 578; i++) {
for ( j = 0; j <= 404; j++) {
k = 0;
if (pix[i][j] > 999) {
pix[i][j] = 0; /* BLACK pixels */
k = 1;
}
if (pix[i][j] < div[0] && k == 0) {
pix[i][j] = 16; /* WHITE pixels */
k = 1;
}
if (pix[i][j] < div[1] && k == 0) {
pix[i][j] = 15; /* BROWN pixels */
k = 1;
}
if (pix[i][j] < div[2] && k == 0) {
pix[i][j] = 14; /* RED pixels */
k = 1;
}
if (pix[i][j] < div[3] && k == 0) {
pix[i][j] = 13; /* REDHI pixels */
k = 1;
}
if (pix[i][j] < div[4] && k == 0) {
pix[i][j] = 12; /* ORANGE pixels */
k = 1;
}
if (pix[i][j] < div[5] && k == 0) {
pix[i][j] = 11; /* YELLOWLO pixels */
k = 1;
}
if (pix[i][j] < div[6] && k == 0) {
pix[i][j] = 10; /* YELLOW pixels */
k = 1;
}
if (pix[i][j] < div[7] && k == 0) {
pix[i][j] = 9; /* GREENLO pixels */
k = 1;
}
if (pix[i][j] < div[8] && k == 0) {
pix[i][j] = 8; /* GREEN pixels */
k = 1;
}
if (pix[i][j] < div[9] && k == 0) {
pix[i][j] = 7; /* GREENHI pixels */
k = 1;
}
if (pix[i][j] < div[10] && k == 0) {
pix[i][j] = 6; /* CYAN pixels */
k = 1;
}
if (pix[i][j] < div[11] && k == 0) {
pix[i][j] = 5; /* BLUELO pixels */
k = 1;
}
if (pix[i][j] < div[12] && k == 0) {
pix[i][j] = 4; /* BLUE pixels */
k = 1;
}
if (pix[i][j] < div[13] && k == 0) {
pix[i][j] = 3; /* BLUEHI pixels */
k = 1;
}
if (pix[i][j] < div[14] && k == 0) {
pix[i][j] = 2; /* MAGENTA pixels */
k = 1;
}
if (pix[i][j] < 1000 && k == 0) {
pix[i][j] = 1; /* VIOLET pixels */
k = 1;
}
}
}
/******************************************
* draw graph lines and labels:
******************************************/
_setvideomode(_VRES16COLOR);
_setcolor(3);
_moveto(50,8); /* 6 pixels north of the northwest corner */
_lineto(50,420); /* southwest corner (drawing left side) */
_lineto(630,420); /* southeast corner (drawing bottom) */
_lineto(630,14); /* northeast corner (drawing right side) */
_lineto(44,14); /* 6 pixels west of nw corner (drawing top) */
_moveto(44,72);
_lineto(50,72); /* left side tick marks */
_moveto(44,130);
_lineto(50,130);
_moveto(44,188);
_lineto(50,188);
_moveto(44,246);
_lineto(50,246);
_moveto(44,304);
_lineto(50,304);
_moveto(44,362);
_lineto(50,362);
_moveto(44,420);
_lineto(50,420);
_lineto(50,426); /* bottom tick marks */
_moveto(108,420);
_lineto(108,426);
_moveto(166,420);
_lineto(166,426);
_moveto(224,420);
_lineto(224,426);
_moveto(282,420);
_lineto(282,426);
_moveto(340,420);
_lineto(340,426);
_moveto(398,420);
_lineto(398,426);
_moveto(456,420);
_lineto(456,426);
_moveto(514,420);
_lineto(514,426);
_moveto(572,420);
_lineto(572,426);
_moveto(630,420);
_lineto(630,426);
_moveto(630,420);
_lineto(636,420); /* right side tick marks */
_moveto(630,362);
_lineto(636,362);
_moveto(630,304);
_lineto(636,304);
_moveto(630,246);
_lineto(636,246);
_moveto(630,188);
_lineto(636,188);
_moveto(630,130);
_lineto(636,130);
_moveto(630,72);
_lineto(636,72);
_moveto(630,14);
_lineto(636,14);
_moveto(630,14);
_lineto(630,8); /* top tick marks */
_moveto(572,14);
_lineto(572,8);
_moveto(514,14);
_lineto(514,8);
_moveto(456,14);
_lineto(456,8);
_moveto(398,14);
_lineto(398,8);
_moveto(340,14);
_lineto(340,8);
_moveto(282,14);
_lineto(282,8);
_moveto(224,14);
_lineto(224,8);
_moveto(166,14);
_lineto(166,8);
_moveto(108,14);
_lineto(108,8);
/*
* set font to helvetica
*/
_registerfonts( "helvb.fon" );
_setfont("b h10 w5 t'helv'");
_moveto(35,9); /* y-axis labels */
_outgtext("7");
_moveto(35,67);
_outgtext("6");
_moveto(35,125);
_outgtext("5");
_moveto(35,183);
_outgtext("4");
_moveto(35,241);
_outgtext("3");
_moveto(35,299);
_outgtext("2");
_moveto(35,357);
_outgtext("1");
_moveto(35,414);
_outgtext("0");
_moveto(47,429);
_outgtext("0"); /* x-axis labels */
_moveto(105,429);
_outgtext("1");
_moveto(163,429);
_outgtext("2");
_moveto(221,429);
_outgtext("3");
_moveto(279,429);
_outgtext("4");
_moveto(337,429);
_outgtext("5");
_moveto(395,429);
_outgtext("6");
_moveto(453,429);
_outgtext("7");
_moveto(511,429);
_outgtext("8");
_moveto(569,429);
_outgtext("9");
_moveto(627,429);
_outgtext("10");
_moveto(100,447); /* info under the x-axis */
_outgtext(title1);
_moveto(100,463);
_outgtext(title2);
_unregisterfonts();
/**********************
* color the screen:
**********************/
violet = RGB( 63, 0, 31 );
bluehi = RGB( 31, 0, 63 );
bluelo = RGB( 0, 31, 63 );
greenhi = RGB( 0, 63, 31 );
greenlo = RGB( 31, 63, 0 );
yellow = RGB( 63, 63, 0 );
yellowlo = RGB( 63, 42, 0 );
orange = RGB( 63, 34, 0 );
redhi = RGB( 63, 26, 0 );
_remappalette( 8, violet);
_remappalette( 9, bluehi);
_remappalette( 10, bluelo);
_remappalette( 11, greenhi);
_remappalette( 12, greenlo);
_remappalette( 14, yellow);
_remappalette( 13, yellowlo);
_remappalette( 15, orange);
_remappalette( 7, redhi);
paint[0] = 8; /* violet */
paint[1] = 5; /* MAGENTA */
paint[2] = 9; /* bluehi */
paint[3] = 1; /* BLUE */
paint[4] = 10; /* bluelo */
paint[5] = 3; /* CYAN */
paint[6] = 11; /* greenhi */
paint[7] = 2; /* GREEN */
paint[8] = 12; /* greenlo */
paint[9] = 14; /* yellow */
paint[10] = 13; /* yellowlo */
paint[11] = 15; /* ORANGE */
paint[12] = 7; /* redhi */
paint[13] = 4; /* RED */
paint[14] = 8; /* violet */
paint[15] = 6; /* brown */
for ( m = 0; m <= 15; m++) {
_setcolor(paint[m]);
for ( i = 0; i <= 578; i++) {
for ( j = 0; j <= 404; j++) {
if (pix[i][j] == (m+1) ) _setpixel(i+51,j+15);
}
}
}
getch(); /* pause */
_setvideomode(_DEFAULTMODE);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
struct student_type
{
char name[10];
int num;
int age;
char addr[15];
}stud[SIZE]; /*定义结构*/
void save( ){
FILE *fp;
int i;
if ((fp=fopen("stu-list","wb"))==NULL){
printf("cannot open file\n");
return;}
for(i=0; i<SIZE; i++)/*二进制写*/
if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");/*出错处理*/
fclose(fp);} /*关闭文件*/
int main(){
int i;
for(i=0;i<SIZE;i++)/*从键盘读入学生信息*/
scanf("%s%d%d%s",stud[i].name,&stud[i].num,&stud[i].age,stud[i].addr);
save( );
return 0;}/*调用save()保存学生信息*/
|
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 */
struct xfs_inode {int dummy; } ;
struct inode {int dummy; } ;
struct dentry {int dummy; } ;
/* Variables and functions */
struct inode* VFS_I (struct xfs_inode*) ;
struct xfs_inode* XFS_I (struct inode*) ;
struct dentry* d_find_alias (struct inode*) ;
int /*<<< orphan*/ d_inode (struct dentry*) ;
struct dentry* dget_parent (struct dentry*) ;
int /*<<< orphan*/ dput (struct dentry*) ;
struct inode* igrab (int /*<<< orphan*/ ) ;
__attribute__((used)) static struct xfs_inode *
xfs_filestream_get_parent(
struct xfs_inode *ip)
{
struct inode *inode = VFS_I(ip), *dir = NULL;
struct dentry *dentry, *parent;
dentry = d_find_alias(inode);
if (!dentry)
goto out;
parent = dget_parent(dentry);
if (!parent)
goto out_dput;
dir = igrab(d_inode(parent));
dput(parent);
out_dput:
dput(dentry);
out:
return dir ? XFS_I(dir) : NULL;
}
|
C
|
#include <stdio.h>
int main()
{
int primero, segundo, tercero, cuarto, quinto, temporal;
int bandera = 0;
printf("Ingresar 5 nmeros enteros positivos.\n");
printf("Ingresar primer entero positivo:\t");
scanf("%d", &primero);
printf("Ingresar segundo entero positivo:\t");
scanf("%d", &segundo);
if (segundo < primero)
{
temporal = primero;
primero = segundo;
segundo = temporal;
}
printf("Ingresar tercer entero positivo:\t");
scanf("%d", &tercero);
if (tercero < segundo)
{
temporal = segundo;
segundo = tercero;
tercero = temporal;
if (segundo < primero)
{
temporal = primero;
primero = segundo;
segundo = temporal;
}
}
printf("Ingresar cuarto entero positivo:\t");
scanf("%d", &cuarto);
if (cuarto < tercero)
{
temporal = tercero;
tercero = cuarto;
cuarto = temporal;
if (tercero < segundo)
{
temporal = segundo;
segundo = tercero;
tercero = temporal;
if (segundo < primero)
{
temporal = primero;
primero = segundo;
segundo = temporal;
}
}
}
printf("Ingresar quinto entero positivo:\t");
scanf("%d", &quinto);
if (quinto < cuarto)
{
temporal = cuarto;
cuarto = quinto;
quinto = temporal;
if (cuarto < tercero)
{
temporal = tercero;
tercero = cuarto;
cuarto = temporal;
if (tercero < segundo)
{
temporal = segundo;
segundo = tercero;
tercero = temporal;
if (segundo < primero)
{
temporal = primero;
primero = segundo;
segundo = temporal;
}
}
}
}
do
{
printf("Ingresar el clculo requerido para la lista suministrada:\n");
printf("[1] mximo\n");
printf("[2] mnimo\n");
printf("[3] mediana\n> ");
scanf("\t%d", &bandera);
switch(bandera){
case 1:
printf("El mximo de la lista es: %d.\n", quinto);
break;
case 2:
printf("El mnimo de la lista es: %d.\n", primero);
break;
case 3:
printf("La mediana de la lista es: %d.\n", tercero);
break;
default:
printf("Opcin no vlida.\n");
break;
}
printf("Para realizar otro cculo con la misma lista presione [1], para salir ingresar cualquier tecla distinta de [1]:\t");
scanf("%d", &bandera);
if (!(bandera == 1))
bandera = -1;
} while (bandera >= 0);
printf("\nEl programa ha terminado.\n");
return 0;
}
|
C
|
#include "utils.h"
#include "affichage_graphique.h"
#include "affichageconsole.h"
#include "case.h"
#include "deplacement.h"
#include "initialisation.h"
#include "simulation.h"
// Fonctions pour demander le nombre de tour à faire/ajouter et le type d' affichage
int add_simulation();
/*fonction demandant à l' utilisateur le nombre de simulation à ajouter et retourne ce nombre*/
void ask_user(int *nb_simulation, Display *display_type, char *presence_gradient);
/*procédure demandant à l' utilisateur le type d' affichage voulu et modifie le pointeur associé
* Si c'est un affichage graphique, il explique comment changer de tour
* Puis il demande si l'utilisateur veut afficher le gradient */
char ask_gradient(char answer);
/*fonction demandant à l' utilisateur si il veut afficher le gradient, si il ne répond pas par les valeurs proposées,
* un message d' erreur est affichée et la question est redemandée*/
int main(int argc, char const *argv[]) {
// Initialisation de la grille et des tableaux d'entités
Cell grid[R][C];
Person lambda_array[R * C], doctor_array[R * C];
int virus_array[R * C] = {0};
// Constantes diverses
int nb_lambda = 0, nb_doctor = 0, nb_free_virus = 0; /*nombres d'entités*/
int round = 0, round_total = 0; /*tour actuel et nombre de tour total*/
int add_round = 0; /*nombre de tour ajouté par l' utilisateur*/
// Type d'affichage et affichage ou non du gradient
Display display_type= CONSOLE;
char answer_gradient; /*uniquement si affichage en console*/
// Variables nécessaires pour l' affichage graphique
SDL_Window *pWindow;
SDL_Renderer *pRenderer;
Boolean continue_display = TRUE; /*permettra arrêt de l'affichage graphique si on ferme la fenêtre*/
// Initialisation de l' aléa
srand(time(NULL));
// Demande du nombre de tours à faire et type d'affichage des simulations
ask_user(&add_round, &display_type, &answer_gradient);
round_total = add_round;
// Génération de la fenêtre d'affichage graphique
if(display_type == GRAPHIC){
init_graphic(&pWindow, &pRenderer);
}
// Simulation des tours
while (add_round != 0) { /*si l' utilisateur n'a pas ajouté de tour à la fin, arrêt de la simulation*/
while (round < round_total) {
// Initialisation de la grille
if (round == 0) {
init_grid(grid, lambda_array, doctor_array, virus_array, &nb_lambda, &nb_doctor, &nb_free_virus);
// Tour de simulation post-initialisation
} else { /* tour de simulation pour chaque entité*/
simul_lambda(grid, lambda_array, &nb_lambda, round, virus_array, &nb_free_virus);
simul_doctor(grid, doctor_array, &nb_doctor, round, virus_array, &nb_free_virus);
simulation_virus(virus_array, &nb_free_virus);
}
// Affichage
//En console
if (display_type == CONSOLE) {
printf(CLEAR); /*efface affichage déja présent*/
if (round == 0) printf("Initialisation \n");
else printf("Tour %d\n", round);
console_display(grid, virus_array, answer_gradient);
printf("-----\n");
// Graphique
} else {
continue_display = graphic_display(grid, virus_array, pRenderer,round,pWindow, answer_gradient);
if (!continue_display) break; /*si la fenêtre a été fermée ou l' utilisateur a appuyé sur echap,
* la boucle est arrêtée*/
}
round++;
usleep(500000); /*met en pause programme pour avoir le temps de voir chaque tour */
}
if (!continue_display) break; /*si la fenêtre a été fermée ou l' utilisateur a appuyé sur echap,
* la simulation est arrêtée*/
// Demande à l' utilisateur si il veut voir d'autres tours
add_round = add_simulation();
round_total += add_round;
}
if (display_type == GRAPHIC) quit(pWindow, pRenderer); /*ferme affichage graphique*/
return 0;
}
void ask_user(int *nb_simulation, Display *display_type, char *presence_gradient) {
printf("Combien de simulation(s) aimeriez-vous faire ?");
scanf("%d", nb_simulation);
int display;
printf("Quel affichage préférez-vous ? Pour celui en console, entrez 0, pour le graphique entrez 1 \n");
scanf("%d", &display);
*display_type=display;
if ((*display_type) == 1) {
//Message pour expliquer comment passer au tour suivant ou arrêter la simulation
printf("Pour passer au tour suivant, vous devrez faire un clic gauche ou appuyer sur entrée, "
"flèche droite ou espace\n"
"Vous pouvez arrêter la simulation en fermant la fenêtre ou en appuyant sur echap. \n");
}
(*presence_gradient) = ask_gradient(*presence_gradient);
}
char ask_gradient(char answer) {
printf("Voulez vous affichez le gradient ? (1= cyan, 2-9 = bleu, >10 = jaune), "
"répondez par Y (oui) ou N(non) \n");
scanf(" %c", &answer);
if (answer != 'Y' && answer != 'y' && answer != 'N' && answer != 'n') {
printf("S' il vous plait répondez que pas Y ou N\n");
ask_gradient(answer);
}
return answer;
}
int add_simulation() {
int ajout = 0;
printf("Voulez vous ajouter des tours ? Si oui entrez, combien vous voulez, sinon entrez 0\n");
scanf(" %d", &ajout);
return ajout;
}
|
C
|
/*File : halo.c*/
/*Penulis : Andi Irham ([email protected])*/
/*Program menuliskan "Halo Dunia!" dan "end-of-line" (ganti baris)*/
#include<stdio.h>
int main(void){
/*badan program*/
printf("Hello World!\n");
printf("Hello World!\n");
printf("Hello World!\n\n");
printf("Saya menuliskan program\n");
printf("Program yang dituliskan adalah Bahasa C\n");
printf("Bahasa C sangat menyenangkan\n");
}
|
C
|
/* trackTable.c was originally generated by the autoSql program, which also
* generated trackTable.h and trackTable.sql. This module links the database and
* the RAM representation of objects. */
/* Copyright (C) 2014 The Regents of the University of California
* See README in this or parent directory for licensing information. */
#include "common.h"
#include "linefile.h"
#include "jksql.h"
#include "trackTable.h"
#include "hdb.h"
void trackTableStaticLoad(char **row, struct trackTable *ret)
/* Load a row from trackTable table into ret. The contents of ret will
* be replaced at the next call to this function. */
{
ret->mapName = row[0];
ret->tableName = row[1];
ret->shortLabel = row[2];
ret->longLabel = row[3];
ret->visibility = sqlUnsigned(row[4]);
ret->colorR = sqlUnsigned(row[5]);
ret->colorG = sqlUnsigned(row[6]);
ret->colorB = sqlUnsigned(row[7]);
ret->altColorR = sqlUnsigned(row[8]);
ret->altColorG = sqlUnsigned(row[9]);
ret->altColorB = sqlUnsigned(row[10]);
ret->useScore = sqlUnsigned(row[11]);
ret->isSplit = sqlUnsigned(row[12]);
ret->private = sqlUnsigned(row[13]);
}
struct trackTable *trackTableLoad(char **row)
/* Load a trackTable from row fetched with select * from trackTable
* from database. Dispose of this with trackTableFree(). */
{
struct trackTable *ret;
AllocVar(ret);
ret->mapName = cloneString(row[0]);
ret->tableName = cloneString(row[1]);
ret->shortLabel = cloneString(row[2]);
ret->longLabel = cloneString(row[3]);
ret->visibility = sqlUnsigned(row[4]);
ret->colorR = sqlUnsigned(row[5]);
ret->colorG = sqlUnsigned(row[6]);
ret->colorB = sqlUnsigned(row[7]);
ret->altColorR = sqlUnsigned(row[8]);
ret->altColorG = sqlUnsigned(row[9]);
ret->altColorB = sqlUnsigned(row[10]);
ret->useScore = sqlUnsigned(row[11]);
ret->isSplit = sqlUnsigned(row[12]);
ret->private = sqlUnsigned(row[13]);
return ret;
}
struct trackTable *trackTableLoadAll(char *fileName)
/* Load all trackTable from a tab-separated file.
* Dispose of this with trackTableFreeList(). */
{
struct trackTable *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[15];
while (lineFileRow(lf, row))
{
el = trackTableLoad(row);
slAddHead(&list, el);
}
lineFileClose(&lf);
slReverse(&list);
return list;
}
struct trackTable *trackTableCommaIn(char **pS, struct trackTable *ret)
/* Create a trackTable out of a comma separated string.
* This will fill in ret if non-null, otherwise will
* return a new trackTable */
{
char *s = *pS;
if (ret == NULL)
AllocVar(ret);
ret->mapName = sqlStringComma(&s);
ret->tableName = sqlStringComma(&s);
ret->shortLabel = sqlStringComma(&s);
ret->longLabel = sqlStringComma(&s);
ret->visibility = sqlUnsignedComma(&s);
ret->colorR = sqlUnsignedComma(&s);
ret->colorG = sqlUnsignedComma(&s);
ret->colorB = sqlUnsignedComma(&s);
ret->altColorR = sqlUnsignedComma(&s);
ret->altColorG = sqlUnsignedComma(&s);
ret->altColorB = sqlUnsignedComma(&s);
ret->useScore = sqlUnsignedComma(&s);
ret->isSplit = sqlUnsignedComma(&s);
ret->private = sqlUnsignedComma(&s);
*pS = s;
return ret;
}
void trackTableFree(struct trackTable **pEl)
/* Free a single dynamically allocated trackTable such as created
* with trackTableLoad(). */
{
struct trackTable *el;
if ((el = *pEl) == NULL) return;
freeMem(el->mapName);
freeMem(el->tableName);
freeMem(el->shortLabel);
freeMem(el->longLabel);
freez(pEl);
}
void trackTableFreeList(struct trackTable **pList)
/* Free a list of dynamically allocated trackTable's */
{
struct trackTable *el, *next;
for (el = *pList; el != NULL; el = next)
{
next = el->next;
trackTableFree(&el);
}
*pList = NULL;
}
void trackTableOutput(struct trackTable *el, FILE *f, char sep, char lastSep)
/* Print out trackTable. Separate fields with sep. Follow last field with lastSep. */
{
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->mapName);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->tableName);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->shortLabel);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->longLabel);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%u", el->visibility);
fputc(sep,f);
fprintf(f, "%u", el->colorR);
fputc(sep,f);
fprintf(f, "%u", el->colorG);
fputc(sep,f);
fprintf(f, "%u", el->colorB);
fputc(sep,f);
fprintf(f, "%u", el->altColorR);
fputc(sep,f);
fprintf(f, "%u", el->altColorG);
fputc(sep,f);
fprintf(f, "%u", el->altColorB);
fputc(sep,f);
fprintf(f, "%u", el->useScore);
fputc(sep,f);
fprintf(f, "%u", el->isSplit);
fputc(sep,f);
fprintf(f, "%u", el->private);
fputc(sep,f);
}
/* ---------------- End of AutoSQL generated code. ------------------ */
static struct trackTable builtIns[] =
{
{
NULL,
"hgEst", /* mapName */
"est", /* tableName */
"Human ESTs", /* shortLabel */
"Human ESTs", /* longLabel */
0, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"hgMrna", /* mapName */
"mrna", /* tableName */
"Full MGC mRNAs", /* shortLabel */
"Full Length MGC mRNAs", /* longLabel */
2, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"BACends", /* mapName */
"bacEnds", /* tableName */
"BAC ends", /* shortLabel */
"BAC end pairs", /* longLabel */
0, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"hgEst", /* mapName */
"est", /* tableName */
"Human ESTs", /* shortLabel */
"Human ESTs", /* longLabel */
0, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
1, /* isSplit */
0, /* private */
},
{
NULL,
"hgIntronEst", /* mapName */
"intronEst", /* tableName */
"Spliced ESTs", /* shortLabel */
"Human ESTs That Have Been Spliced", /* longLabel */
1, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
1, /* isSplit */
0, /* private */
},
{
NULL,
"hgMrna", /* mapName */
"mrna", /* tableName */
"Sequenced mRNAs", /* shortLabel */
"Sequenced mRNAs from Genbank", /* longLabel */
2, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
1, /* isSplit */
0, /* private */
},
{
NULL,
"hgRepeat", /* mapName */
"rmsk", /* tableName */
"RepeatMasker", /* shortLabel */
"Repeating Elements by RepeatMasker", /* longLabel */
1, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
1, /* useScore */
1, /* isSplit */
0, /* private */
},
{
NULL,
"hgBlatMouse", /* mapName */
"blatMouse", /* tableName */
"Mouse Blat", /* shortLabel */
"Mouse Translated Blat Alignments", /* longLabel */
0, /* visibility */
100,50,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
1, /* isSplit */
0, /* private */
},
{
NULL,
"hgContig", /* mapName */
"ctgPos", /* tableName */
"Chromosome Band", /* shortLabel */
"Chromosome Bands Localized by FISH Mapping Clones", /* longLabel */
1, /* visibility */
150,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"hgCytoBands", /* mapName */
"cytoBand", /* tableName */
"Chromosome Band", /* shortLabel */
"Chromosome Bands Localized by FISH Mapping Clones", /* longLabel */
1, /* visibility */
0,0,0, /* color */
150,50,50, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"hgExoFish", /* mapName */
"exoFish", /* tableName */
"Exofish ecores", /* shortLabel */
"Exofish Tetraodon/Human Conserved Regions (ecores)", /* longLabel */
1, /* visibility */
153,21,153, /* color */
0,0,255, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"hgGcPercent", /* mapName */
"gcPercent", /* tableName */
"GC Percent", /* shortLabel */
"Percentage GC in 20,000 Base Windows", /* longLabel */
0, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"hgMusTest1", /* mapName */
"musTest1", /* tableName */
"Mouse Test 40", /* shortLabel */
"Mouse Translated Blat Alignments Score > 40", /* longLabel */
0, /* visibility */
0,0,0, /* color */
0,0,0, /* altColor */
0, /* useScore */
0, /* isSplit */
1, /* private */
},
{
NULL,
"hgRefGene", /* mapName */
"refGene", /* tableName */
"RefSeq Genes", /* shortLabel */
"GenBank RefSeq Genes", /* longLabel */
2, /* visibility */
20,20,170, /* color */
137,137,212, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"hgRnaGene", /* mapName */
"rnaGene", /* tableName */
"RNA Genes", /* shortLabel */
"Non-coding RNA Genes (dark) and Pseudogenes (light)", /* longLabel */
2, /* visibility */
170,80,130, /* color */
230,180,130, /* altColor */
0, /* useScore */
0, /* isSplit */
0, /* private */
},
{
NULL,
"hgStsMarker", /* mapName */
"stsMarker", /* tableName */
"STS Markers", /* shortLabel */
"STS Markers on Genetic (blue), FISH (green) and Radiation Hybrid (black) Maps", /* longLabel */
1, /* visibility */
0,0,0, /* color */
128,128,255, /* altColor */
1, /* useScore */
0, /* isSplit */
0, /* private */
},
};
struct trackTable *hGetTracks(char *db)
/* Get track table for specified database. */
{
struct trackTable *ttList = NULL, *tt;
int i;
char table[256];
for (i=0; i<ArraySize(builtIns); ++i)
{
tt = builtIns+i;
if (tt->isSplit)
safef(table, sizeof(table), "chr22_%s", tt->tableName);
else
safef(table, sizeof(table), "%s", tt->tableName);
if (hTableExists(db, table))
{
slAddHead(&ttList, tt);
}
}
slReverse(&ttList);
return ttList;
}
|
C
|
/***********************************************************
Copyright (C), 2005, Chen Chao
File name: netop.c
Author: Chen Chao Version: 1.0 Date: 2005.10
Description: bcsnifferʵļ
Others:
History:
1. Date:06-02-13
Author:cc
Modification:
(1)analAboveProtoʡprotocol->p_proto(int),ΪΪûЭı;
ʡprotocol->p_aliases[0],Ϊname,ûҪ
2. ...
**************************************************************/
#include <stdlib.h> //UNIXͶȣu_char/u_int32_t
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h> //ioctl
#include <netinet/ip.h> //struct iphdrȽṹ
#include <netdb.h> //getprotobynameȺ
#include <net/if.h> //struct ifreqȽṹIFF_PROMISCȺ
#include "../../include/common.h"
#include "../../include/netop.h"
/*PROMISC()ģʽ*/
int set_promisc(char *nif, int sock) {
struct ifreq ifr;
//ifr.ifr_name----- Interface name, e.g. "eth0".
strncpy(ifr.ifr_name, nif, strlen(nif) + 1);
if ((ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)) { //flag
print_msg_for_last_errno("ioctl", 2);
}
ifr.ifr_flags |= IFF_PROMISC; //flag־
if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) { //ıģʽ
print_msg_for_last_errno("ioctl", 3);
}
else {
printf("\nModify eth0 to promisc success!\n");
}
return 0;
}
//checksum
u_int16_t checksum_ip(u_int16_t *buffer, int size) {
unsigned long cksum = 0;
while (size > 1) {
cksum += *buffer++;
size -= sizeof(u_int16_t);
}
if (size) {
cksum += *(u_int16_t *) buffer;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >> 16);
return (u_int16_t) (~cksum);
}
//IPͷprotocolԪصֵЭ
int get_protocol_name(int numProto) {
struct protoent *protocol;
protocol = getprotobynumber(numProto);
if (protocol == (struct protoent *) NULL ) {
perror("Analyse the protocol failed!");
return -1;
}
str_to_upper(protocol->p_name);
printf("Protocol:[%s] \n", protocol->p_name);
return 0;
}
|
C
|
// 16426 福澤大地
#include <math.h>
#include <GL/glut.h>
#include <GL/glpng.h>
#include "ball.h"
#include "vector.h"
// 角度を変換
#define radian(deg) (rad * M_PI / 180.0)
#define degree(rad) (rad * 180.0 / M_PI)
// ball構造体を初期化
void initBall(struct ball *ball, int num, struct vector p, double r) {
ball->num = num;
ball->exist = 1;
ball->r = r;
ball->p = p;
ball->v = ZERO;
ball->dir = vector(1, 0);
ball->angle = 0;
}
// 移動
void moveBall(struct ball *ball) {
ball->p = add(ball->p, ball->v);
ball->angle = fmod(ball->angle + mag(ball->v) / ball->r, 2 * M_PI);
if (!isZero(ball->v)) ball->dir = normal(ball->v);
// 摩擦
if (mag(ball->v) <= 0.001)
ball->v = ZERO;
else
ball->v = mult(ball->v, 1 - FRICTION / mag(ball->v));
}
// ボールを描画
void drawBall(struct ball ball) {
// 球体の設定
GLUquadricObj* sphere = gluNewQuadric();
gluQuadricDrawStyle(sphere, GLU_FILL);
gluQuadricNormals(sphere, GLU_SMOOTH);
gluQuadricTexture(sphere, GL_TRUE);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ball.image);
glPushMatrix();
glTranslated(ball.p.x, ball.p.y, ball.r);
glRotated(90, 0, 1, 0);
glRotated(90, 1, 0, 0);
glRotated(degree(ball.angle), 0, -ball.dir.y, -ball.dir.x);
gluSphere(sphere, ball.r, 32, 32);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
// ボールが衝突しているか
int ballColliding(struct ball ballA, struct ball ballB) {
return dist(ballA.p, ballB.p) < ballA.r + ballB.r;
}
// ボール同士の反射
void reflectBall(struct ball *ballA, struct ball *ballB, int break_shot) {
if (ballColliding(*ballA, *ballB)) {
struct vector p_ab, v_ab, temp;
double a, b, c, D, t;
// ボールの重なりを修正
p_ab = sub(ballA->p, ballB->p);
v_ab = sub(ballA->v, ballB->v);
a = pow(mag(v_ab), 2);
b = inner(p_ab, v_ab);
c = pow(mag(p_ab), 2) - pow(ballA->r + ballB->r, 2);
D = pow(b, 2) - a * c;
if (D > 0 && !break_shot) {
t = (-b - sqrt(D)) / a;
ballA->p = add(ballA->p, mult(ballA->v, t));
ballB->p = add(ballB->p, mult(ballB->v, t));
} else {
temp = mult(normal(p_ab), (ballA->r + ballB->r - mag(p_ab)) / 2);
ballA->p = add(ballA->p, temp);
ballB->p = sub(ballB->p, temp);
}
// 衝突後の速度を決定
p_ab = sub(ballA->p, ballB->p);
v_ab = sub(ballA->v, ballB->v);
temp = mult(normal(p_ab), -inner(normal(p_ab), v_ab));
ballA->v = mult(add(ballA->v, temp), BALL_LOSS);
ballB->v = mult(sub(ballB->v, temp), BALL_LOSS);
}
}
|
C
|
#include <stdio.h>
int main(){
int i;
printf("%8s %8s %8s\n", "^1", "^2", "^3");
for (i=1; i<6; i++)
printf("%8d %8d %8d\n", i, i*i, i*i*i);
return 0;
}
|
C
|
#ifndef ARVORE_BIN_H_INCLUDED
#define ARVORE_BIN_H_INCLUDED
/*
* Cria a estrutura de dado no
*/
typedef struct node{
char frequecia;
char caracter;
//struct node *p;
struct node *left,*right;
}node;
/*
* Inicializa e cria um nó, considerando os parâmetros da estrutura.
* Retorna:
* o endereço do nó criado caso tenha sucesso
* null - falha na alocação
*/
node *cria_no(unsigned char freq, char caracter, node *p, node *left,node *right);
void inTree(node *top, int *count_);
/*
* Busca o código binário em formato de string para o caracter buscado
* node *raiz : raiz da árvore de huffman
* char *binario : coloca o valor binário em formato de char
* char aux : string buscada
* int tamanho : tamanho em bytes do binario encontrado
* int *tamanho_bits : tamanho em bytes do binario acumulado
* retorno:
* true: encontrado o caracter
* false: caracter não encontrado
*/
bool pega_binario(node *raiz,char *binario,int tamanho, char aux,int *tamanho_bits);
/*
* Deleta a árvore criada
*/
void FreeHuffmanTree(node *n);
#endif // ARVORE_BIN_H_INCLUDED
|
C
|
/* Contando en la arena */
#include <stdio.h>
int main() {
long numero;
while(1) {
scanf("%ld\n", &numero);
if(numero == 0) {
break;
}
for( ; numero > 0; numero--) {
printf("1");
}
printf("\n");
}
return 0;
}
|
C
|
// 6. Crie um programa que calcule e imprima o valor do fatorial de um
// número informado pelo usuário, usando recursividade
//REALIZADO POR GABRIEL PINHEIRO CAMPOS , UNINOVE SANTO AMARO, 03/A NOTURNO: RA 2220102380.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int recursiveFactor(int);
int main()
{
int a;
printf("Escreva um Numero para fatorar em recursividade:");
scanf("%d", &a);
recursiveFactor(a);
printf("\nO fatorial de %d eh %d" , a, recursiveFactor(a));
return 0;
}
int recursiveFactor(a){
int res=1;
if ( a > res){
res = a * recursiveFactor(a-1);
}
return res;
};
|
C
|
#ifndef MONEY_H
#define MONEY_H
#define MONEY_FILE "/system/money"
/* coin types */
#define ORB 1
#define GOLD_HUNDRED 2
#define GOLD_CROWN 3
#define SILVER_TREE 4
#define SILVER_ROYAL 5
#define BRONZE_COPPER 6
#define COPPER_HALF 7
#define COPPER_BIT 8
#define COIN_NAMES \
({ \
"orb", \
"goldhundred", \
"goldcrown", \
"silvertree", \
"silverroyal", \
"bronzecopper", \
"copperhalf", \
"copperbit", \
});
#define COIN_SHORT_NAMES \
({ "orb", "gh", "gc", "st", "sr", "bc", "ch", "cb", });
#define COIN_VALUES ({ 10000,10000, 1000, 200, 50, 5, 2, 1 })
#define COIN_WEIGHT ({ 10, 25, 18, 12, 12, 10, 10, 6 })
#define COIN_VOLUME ({ 5, 8, 6, 4, 4, 4, 4, 2 })
#define COIN_SIZE ({ 2, 3, 2, 2, 2, 1, 1, 1 })
/*
* Macro: MONEY_MAKE
* Description: prepares a money object
* Arguments: num - how much money to produce (of a given type)
* type - which money type, see coin types abovee
* to - move money to which object? if not given
* moneyobject will be removed
* Returns: objectpointer to the money heap object
*/
#define MONEY_MAKE(num, type, to) \
call_other(MONEY_FILE, "make_coins", num, type, to)
/*
* Macro: MONEY_TOTAL
* Description: calculates the total money value a living carries
* Arguments: l - which living to check
* Returns: total money in copper bits
*/
#define MONEY_TOTAL(l) \
call_other(MONEY_FILE, "total", l)
/*
* Macro: MONEY_CHANGE
* Description: add or reduce money of living
* Arguments: n - the amount in copper bits, negative reduces
* l - the living whose money changes
* Returns: 1 if successful, 0 if not enough money to take
*/
#define MONEY_CHANGE(n, l) \
call_other(MONEY_FILE, "change", n, l)
/*
* Macro: MONEY_TEXT, MONEY_SHORT_DESC
* Description: create a textual description for a given amount
* Arguments: n
* Returns: string
*/
#define MONEY_TEXT(n) \
call_other(MONEY_FILE, "money_text", n)
#define MONEY_SHORT_DESC(n) \
call_other(MONEY_FILE, "short_desc", n)
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "get_name.h"
#include "print_str.h"
int main(){
char hello[90] = "Hello, ";
char* result;
result = get_name();
print_str(strncat(hello, result, 80));
free(result);
return 0;
}
|
C
|
#include <vcc.h>
#ifndef VERIFY
#include <stdio.h>
#endif
#define is_bounded(A, N) \
(\forall unsigned _j; _j < (N) ==> (A)[_j] < (N))
#define is_inverse(A, inverse, N) \
(\forall unsigned _j; _j < (N) ==> (A)[(inverse)[_j]] == _j)
#define is_injective(A, N) \
(\forall unsigned _j1, _j2; _j1 < (N) && _j2 < (N) && (A)[_j1] == (A)[_j2] ==> _j1 == _j2)
void invert(unsigned *A, unsigned *B, unsigned N _(ghost unsigned inverse[unsigned]))
_(requires is_bounded(A, N))
_(requires is_injective(A, N))
_(requires is_bounded(inverse, N))
_(requires is_inverse(A, inverse, N))
_(maintains \wrapped((unsigned[N])A))
_(maintains \mutable((unsigned[N])B))
_(writes \array_range(B,(unsigned)N))
_(ensures is_bounded(B, N))
_(ensures is_injective(B, N))
_(ensures is_inverse(B, A, N))
{
unsigned i;
for (i = 0; i < N; i++)
_(invariant \forall unsigned j; j < i ==> B[A[j]] == j)
{
B[A[i]] = i;
}
_(assert \forall unsigned j; {B[j]} j < N ==> B[j] == B[A[inverse[j]]])
}
#ifndef VERIFY
void main(int argc, char **argv) {
unsigned A[10] = { 9, 3, 8, 2, 7, 4, 0, 1, 5, 6 };
unsigned B[10];
unsigned i;
invert(A, B, 10);
for (i = 0; i < sizeof(B)/sizeof(unsigned); i++) {
printf("B[%d] = %d\n", i, B[i]);
}
}
#endif
/*`
Verification of invert succeeded.
`*/
|
C
|
#include "raceui.h"
#include "statemachine.h"
TextLayer *dashboardClock = NULL;
static ResHandle dashboardFontHandle;
GFont dashboardFont;
static char dashClockBuffer[10] = "??:??";
void make_dashboard_clock(Window *window) {
if(dashboardClock == NULL) {
dashboardFontHandle = resource_get_handle(RESOURCE_ID_FONT_LARABIE_16);
dashboardFont = fonts_load_custom_font(dashboardFontHandle);
GRect clockFrame = { {82, 152} , {62, 16} };
Layer *windowLayer = window_get_root_layer(window);
dashboardClock = text_layer_create(clockFrame);
text_layer_set_font(dashboardClock, dashboardFont);
text_layer_set_text_color(dashboardClock, GColorIcterine);
text_layer_set_background_color(dashboardClock, GColorBlack);
text_layer_set_text_alignment(dashboardClock, GTextAlignmentCenter);
text_layer_set_text(dashboardClock, dashClockBuffer);
layer_add_child(windowLayer, (Layer *)dashboardClock);
layer_set_hidden((Layer *)dashboardClock, true);
// Subscribe to the tick timer
// We want to call our function every time the minute changes
// handle_tick_timer is in gameui.c
tick_timer_service_subscribe(MINUTE_UNIT, (TickHandler)update_dashboard_clock);
}
}
void update_dashboard_clock(struct tm *timeStruct, TimeUnits unitsChanged) {
STATES cs = get_current_state();
if(cs == STATE_RACING || cs == STATE_RESULTS || cs == STATE_AFTERRESULTS) {
//Write the time to the buffer in a safe manner
strftime(dashClockBuffer, sizeof("00:00"), "%H:%M", timeStruct);
layer_set_hidden((Layer *)dashboardClock, false);
layer_mark_dirty((Layer *)dashboardClock);
}
}
void destroy_dashboard_clock() {
tick_timer_service_unsubscribe();
fonts_unload_custom_font(dashboardFont);
text_layer_destroy(dashboardClock);
}
|
C
|
#include <stdlib.h>
#include <math.h>
#include "PriorityQueue.h"
struct priority_queue_t {
// Stores the entries.
const void** heap;
// Stores the priorities associated to the elements in heap.
double* priorities;
// Current number of entries.
size_t length;
// Maximum size. Defined by the initial amount of entries given.
size_t max_size;
};
/**
* Re-orders the heap, considering the left and right sub-trees are heaps
* @param queue The queue to re-order.
* @param node The node to start from.
*/
static void min_heapify(PriorityQueue* queue, size_t node);
/**
* Swaps two entries.
* @param array The entries array
* @param a First index to swap
* @param b Second index to swap
*/
static void swap_pointers(const void** array, size_t a, size_t b);
/**
* Swaps two priorities.
* @param array The priorities array
* @param a First index to swap
* @param b Second index to swap
*/
static void swap_priority(double* array, size_t a, size_t b);
/**
* Swaps two elements of a queue, by swapping the corresponding elements
* in the entries array, and in the priorities array.
* @param queue The queue to swap elements in.
* @param a First index to swap
* @param b Second index to swap
*/
static void swap(PriorityQueue* queue, size_t a, size_t b);
/**
* Returns the parent index of an element from its index;
* @param elem_index The element index.
* @return The parent index of the given element.
*/
static size_t parent(size_t elem_index) {
return (size_t) floor(((double) elem_index) / 2);
}
static void swap_pointers(const void** array, size_t a, size_t b) {
const void* temp = array[a];
array[a] = array[b];
array[b] = temp;
}
static void swap_priority(double* array, size_t a, size_t b) {
double temp = array[a];
array[a] = array[b];
array[b] = temp;
}
static void swap(PriorityQueue* queue, size_t a, size_t b) {
swap_pointers(queue->heap, a, b);
swap_priority(queue->priorities, a, b);
}
static void min_heapify(PriorityQueue* queue, size_t node) {
size_t left = 2 * node + 1;
size_t right = 2 * node + 2;
size_t length = queue->length;
double* priorities = queue->priorities;
// Compare priorities to find the lowest priority between the current node,
// and its left and right nodes.
size_t min_priority = node;
if (left < length && priorities[left] < priorities[min_priority]) {
min_priority = left;
}
if (right < length && priorities[right] < priorities[min_priority]) {
min_priority = right;
}
if (node != min_priority) {
swap(queue, node, min_priority);
min_heapify(queue, min_priority);
}
}
PriorityQueue* pqCreate(const void** entries, const double* priorities,
size_t length) {
PriorityQueue* pQueue = malloc(sizeof(PriorityQueue));
if (pQueue == NULL) {
return NULL;
}
const void** heap_array = malloc(length * sizeof(void*));
if (heap_array == NULL) {
return NULL;
}
double* priorities_array = malloc(length * sizeof(double));
if (priorities_array == NULL) {
return NULL;
}
pQueue->heap = heap_array;
pQueue->priorities = priorities_array;
pQueue->length = length;
pQueue->max_size = length;
// Copy arrays.
for (size_t i = 0; i < length; i++) {
heap_array[i] = entries[i];
priorities_array[i] = priorities[i];
}
// Build min-heap
for (int i = (int) floor(((double) length) / 2); i > 0; i--) {
min_heapify(pQueue, i);
}
return pQueue;
}
void pqFree(PriorityQueue* pQueue) {
free(pQueue->heap);
free(pQueue->priorities);
free(pQueue);
}
bool pqInsert(PriorityQueue* pQueue, const void* entry, double priority) {
if (pQueue->length >= pQueue->max_size) {
return false;
}
if(entry == NULL) {
return false;
}
pQueue->length++;
int node = (int) pQueue->length - 1;
pQueue->heap[node] = entry;
pQueue->priorities[node] = priority;
while (node > 0 &&
pQueue->priorities[parent(node)] > pQueue->priorities[node]) {
swap(pQueue, node, parent(node));
node = parent(node);
}
return true;
}
const void* pqExtractMin(PriorityQueue* pQueue) {
if (pQueue->length == 0) {
return NULL;
}
const void* min_priority_elem = pQueue->heap[0];
size_t last_index = (int) pQueue->length - 1;
swap(pQueue, 0, last_index);
pQueue->length--;
min_heapify(pQueue, 0);
return min_priority_elem;
}
size_t pqSize(const PriorityQueue* pQueue) {
return pQueue->length;
}
|
C
|
// 2013013017 윤신웅
// cachesim.c
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX 100
#define SIZE 67108864 //64MB
// memory, cache
int* memory;
int** cache;
int L1_size, L1_line_size, set; // cache setting value
double clock_rate, cycle_sec; // clock setting value
// functions
void memory_read(int, int, int, int);
void cache_to_mem(int, int, int, int);
// set-associative functions
int set_cache_index(int * target_cache_index,int set, int byte_address, int cache_index, int cache_tag);
// main function
int main(int ac, char * av[]) {
// local variable
time_t starttime = 0, finishtime = 0;
FILE* fp1;
FILE* fp2;
int mem_access_latency;
struct timeval bgn,end;
double time1;
char msgbuf[MAX]; // string buf
int memory_access_count=0, cache_access_count=0, miss_count = 0; // for count
int cache_index_size, cache_index, cache_tag, cache_byte_offset; // cache field setting value
int byte_address, data; // process value
// 시간 처리
starttime = clock();
// argument error 처리
if(ac !=3){
fprintf(stderr,"You must use 2 Argument!!! \nex) ./cachesim cachesim.conf mem_access.txt\n");
exit(1);
}
// 파일 열기
if((fp1 = fopen(av[1], "r"))== NULL){
fprintf(stderr, "FILE OPEN ERROR!\n");
exit(1);
}
if((fp2 = fopen(av[2], "r"))== NULL){
fprintf(stderr, "FILE OPEN ERROR!\n");
exit(1);
}
// ******************************** 1. 파일 열어서 차례대로 설정값 읽어오기
// clock rate
fscanf(fp1, "%s", msgbuf);
fscanf(fp1, "%lf", &clock_rate);
printf("%s %.0lf\n",msgbuf, clock_rate);
// mem_access_latency
fscanf(fp1, "%s", msgbuf);
fscanf(fp1, "%d", &mem_access_latency);
printf("%s %d\n", msgbuf, mem_access_latency);
// L1_size
fscanf(fp1, "%s", msgbuf);
fscanf(fp1, "%d", &L1_size);
printf("%s %d\n",msgbuf, L1_size);
// L1_line_size
fscanf(fp1, "%s", msgbuf);
fscanf(fp1, "%d", &L1_line_size);
printf("%s %d\n", msgbuf, L1_line_size);
// set_associativity
fscanf(fp1, "%s", msgbuf);
fscanf(fp1, "%d", &set);
printf("%s %d\n\n", msgbuf, set);
// 단위 설정
cache_index_size = L1_size / (L1_line_size); // cache 접근 시 활용할 size는 전체 크기 / line size
cycle_sec = 1.0 / (clock_rate); // clock_cycle_time = 1 / clock_rate
// 메모리 메모리 할당(64MB)
memory = (int*)calloc(SIZE, sizeof(int));
// ******************************** 2. 메모리 읽고 쓰기
gettimeofday(&bgn, NULL); // 시간 측정 시작
while(!feof(fp2)){
// 필드 1 모드 읽기
char ch;
fscanf(fp2,"%c ", &ch);
// lw
if(ch == 'R'){
fscanf(fp2,"%d ", &byte_address); // 필드 2 주소 읽기
//printf("%d\n",memory[byte_address]); // read
}
// sw
if(ch == 'W'){
fscanf(fp2,"%d ", &byte_address); // 필드 2 주소 읽기
fscanf(fp2,"%d " , &data); // 필드 3 범위 읽기
memory[byte_address] = data; // write
}
memory_access_count++;
}
gettimeofday(&end, NULL); // 시작 측정 끝
fclose(fp2); // 파일 닫기
// 시간 계산
time1 = end.tv_sec + end.tv_usec / 1000000.0 - bgn.tv_sec - bgn.tv_usec / 1000000.0;
time1 = (time1 * 250 * 1000000000)/memory_access_count; // ns 단위
//printf("%.1fns\n",time1);
printf("Average memory access latency without cache: %.1fns\n\n",(cycle_sec*250)); // ns단위 걸린 시간 출력
// 메모리 재할당(초기화)
free(memory); // 메모리 비워주기
memory = (int*)calloc(SIZE, sizeof(int)); // 메모리 메모리 할당(64MB)
memory_access_count = 0;
// 파일 다시 열기
if((fp2 = fopen(av[2], "r"))== NULL){
fprintf(stderr, "FILE OPEN ERROR!\n");
exit(1);
}
// 캐쉬 메모리 할당(cache_index_size 크기) 2차원 배열
cache = (int**)calloc(cache_index_size, sizeof(int*));
for (int i = 0; i < cache_index_size; i++) {
cache[i] = (int*)calloc(((L1_line_size/4) + 2), sizeof(int));
}
// ******************************** 3~5. 캐쉬 읽고 쓰기
while (!feof(fp2)) {
// 필드 1 모드 읽기
char ch;
fscanf(fp2,"%c ", &ch);
fscanf(fp2, "%d ", &byte_address);// 필드 2 주소 읽기 (32bit - int)
// 메모리 주소 32 bit field 구분
cache_byte_offset = byte_address % (L1_line_size); // byte-offset 은 int data 공간에 따라
cache_index = (byte_address / (L1_line_size)) % (cache_index_size/set); // byte-offset 다음 size
cache_tag = (byte_address / (L1_line_size)) / (cache_index_size/set); // tag 값은 나머지 값
printf("%d ", cache_byte_offset);
// Direct mapped
if(set==1){
// lw
if (ch == 'R') {
// valid == 0 (miss)
if (cache[cache_index][0] == 0) {
memory_read(byte_address, cache_index, cache_tag, cache_byte_offset); // memory read
cache_access_count++; // access_count
miss_count++; // miss
memory_access_count++;
}
// valid == 1, tag not same (miss)
else if(cache[cache_index][1] != cache_tag){
cache_to_mem(byte_address, cache_index, cache_index_size, cache_byte_offset); // 기존 값 옮기기
memory_read(byte_address, cache_index, cache_tag, cache_byte_offset); // memory read
cache_access_count++; // access_count
miss_count++; // miss
memory_access_count++;
if(L1_line_size > 4)
memory_access_count++;
}
// valid == 1, tag same (hit)
else {
cache_access_count++; // access_count
}
}
// sw
else if(ch == 'W'){
fscanf(fp2,"%d ", &data); // 필드 3 데이터 읽기
// valid == 0 (miss)
if (cache[cache_index][0] == 0) {
memory_read(byte_address, cache_index, cache_tag, cache_byte_offset); // memory read
cache[cache_index][2 + cache_byte_offset/4] = data; // access 1번처리
cache_access_count++; // access_count
miss_count++; // miss
memory_access_count++;
}
// valid == 1, tag not same (miss)
else if (cache[cache_index][1] != cache_tag) {
cache_to_mem(byte_address, cache_index, cache_index_size, cache_byte_offset);
memory_read(byte_address, cache_index, cache_tag, cache_byte_offset); // memory read
cache[cache_index][2 + cache_byte_offset/4] = data;
cache_access_count++; // access_count
miss_count++; // miss
if(L1_line_size > 4)
memory_access_count++;
}
// valid == 1, tag same (hit)
else {
cache[cache_index][2 + cache_byte_offset/4] = data;
cache_access_count++; // access_count
}
}
// mode error!
else {
fprintf(stderr, "MODE ERROR!!!it is not R or W!!!\n");
exit(1);
}
} // direct mapped end
// set-associative
else if( set >1){
int target_cache_index; // set 내 위치 찾기
cache_index *=set;
int start_cache_index = cache_index - (cache_index % set); // set 시작 위치
int end_cache_index = start_cache_index + set -1;
int set_check = set_cache_index(&target_cache_index, set, byte_address, cache_index, cache_tag) ;
//printf("%d~%d ", start_cache_index, end_cache_index);
// lw
if (ch == 'R') {
// valid == 0 (miss)
if (set_check == -1) {
memory_read(byte_address, target_cache_index, cache_tag, cache_byte_offset); // memory read
cache_access_count++; // access_count
miss_count++; // miss
memory_access_count++;
}
// valid == 1, tag not same (miss)
else if(set_check == -2){
cache_to_mem(byte_address, end_cache_index, cache_index_size, cache_byte_offset); // set 내에 맨 끝 index 기존 값 옮기기
// set 내 값 한칸씩 이동
for(int i=end_cache_index; i!= start_cache_index;i--){
for(int j=0;j<(L1_line_size/4) + 2; j++)
cache[i][j] = cache[i-1][j];
}
memory_read(byte_address, start_cache_index, cache_tag, cache_byte_offset); // 첫 값에다가 memory read
cache_access_count++; // access_count
miss_count++; // miss
memory_access_count++;
if(L1_line_size > 4)
memory_access_count++;
}
// valid == 1, tag same (hit)
else {
cache_access_count++; // access_count
}
}
// sw
else if(ch == 'W'){
fscanf(fp2,"%d ", &data); // 필드 3 데이터 읽기
// valid == 0
if (set_check == -1) {
memory_read(byte_address, target_cache_index, cache_tag, cache_byte_offset); // memory read
cache[target_cache_index][2 + cache_byte_offset/4] = data; // access 1번처리
cache_access_count++; // access_count
miss_count++; // miss
memory_access_count++;
}
// valid == 1, tag not same
else if (set_check == -2) {
cache_to_mem(byte_address, end_cache_index, cache_index_size, cache_byte_offset); // set 내에 맨 끝 index 기존 값 옮기기
// set 내 값 한칸씩 이동
for(int i=end_cache_index ; i!= start_cache_index;i--){
for(int j=0;j<(L1_line_size/4) + 2; j++)
cache[i][j] = cache[i-1][j];
}
memory_read(byte_address, start_cache_index, cache_tag, cache_byte_offset); // memory read
cache[start_cache_index][2 + cache_byte_offset/4] = data;
cache_access_count++; // access_count
miss_count++; // miss
memory_access_count++;
if(L1_line_size > 4)
memory_access_count++;
}
// valid == 1, tag same
else {
cache[target_cache_index][2 + cache_byte_offset/4] = data;
cache_access_count++; // access_count
}
}
// mode error!
else {
fprintf(stderr, "MODE ERROR!!!\n");
exit(1);
}
} // set-associative end
}
// 출력 처리
printf("*L1 Cache Contents\n");
for (int i = 0; i < cache_index_size; i++) {
if(i %set == 0){
printf("%d: ", i/set);
// 1이 아닐때만 줄바꿈
if(set != 1)
printf("\n");
}
// set 단위 출력
// block 부터만 출력
for (int j = 2; j < (L1_line_size/4) + 2; j++) {
printf("%08x ", cache[i][j]);
}
printf("\n");
}
finishtime = clock(); // clcok
printf("\nTotal program run time: %0.1f seconds \n",(float)(finishtime-starttime)/(CLOCKS_PER_SEC));
printf("L1 total access: %d\n", cache_access_count);
printf("L1 total miss count: %d\n", miss_count);
printf("L1 miss rate: %.2lf%%\n", ((double)miss_count / cache_access_count) * 100);
printf("Average memory access latency: %.1lfns\n",(((double)(memory_access_count * mem_access_latency) + (cache_access_count * 2* set))/(double)cache_access_count) * cycle_sec );
// 메모리 할당 해제
free(memory);
for (int i = 0; i < cache_index_size; i++) {
free(cache[i]);
}
free(cache);
// 파일 닫기
fclose(fp1);
fclose(fp2);
return 0;
}
// direct mapped function
// memory로 부터 cache로 읽어오기
void memory_read(int byte_address, int cache_index, int cache_tag, int cache_byte_offset) {
cache[cache_index][0] = 1; //valid를 1로 설정한다.
cache[cache_index][1] = cache_tag;// tag를 설정한다.
byte_address -=cache_byte_offset;
for (int i = 2; i < 2 + (L1_line_size / 4); i++) {
cache[cache_index][i] = memory[byte_address + 4 * (i - 2)];
}
}
// cache에 있는 값을 memory에 쓰기
void cache_to_mem(int byte_address, int cache_index, int cache_index_size, int cache_byte_offset) {
byte_address -=cache_byte_offset;
// 반복문으로 해당 메모리 블록에 값 할당
for (int i = 2; i < 2 + L1_line_size / 4; i++) {
memory[byte_address + 4 * (i - 2)] = cache[cache_index][i];
}
}
// set-associative functions
// set 내에 해당 cache index 찾기, set 내에서 해당 값이 있다(hit) -> return index,
// set 내에 empty 공간 있다(miss) -> reuturn -1 , set이 전부 다 찼다(miss) -> return -2
int set_cache_index(int * target_cache_index, int set, int byte_address, int cache_index, int cache_tag){
int start_cache_index = cache_index - (cache_index % set); // set 시작 위치
int i;
// set 동안 반복
for(i = 0; i<set;i++){
// valid == 1, tag same (hit)
if(cache[start_cache_index+i][0] == 1 && cache[start_cache_index+i][1] == cache_tag ){
*target_cache_index = (start_cache_index+i);
return 0;// hit return now_index
}
// valid == 0, set has empty space (miss)
else if(cache[start_cache_index+i][0] == 0){
*target_cache_index = (start_cache_index+i);
return -1; // set empty miss return -1
}
// valid == 1, tag not same, set is full (miss)
else if(cache[start_cache_index+i][0] == 1 && cache[start_cache_index+i][1] != cache_tag )
;
}
*target_cache_index = (start_cache_index+i-1);
return -2;// set full miss return -1
}
|
C
|
#include<stdio.h>
#define cube(x) x*x*x
#error i luv u
void main()
{
int n;
scanf("%d",&n);
printf("Cube=%d",cube(n));
#undef cube
#ifdef cube
printf("\n cube is defined");
#else
printf("\n cube is not defined");
#define cube(x) x*x*x
#endif
printf("Cube=%d",cube(n));
#undef cube
#ifndef cube
printf("\n cube is not defined");
#define cube(x) x*x*x
#else
printf("\n cube is defined");
#endif
printf("Cube=%d",cube(n));
#undef cube
printf("Cube=%d",cube(n));
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
void implication(bool a, bool b) {
printf("%s\n", !(a && !b) ? "true" : "false");
}
int main(int argc, char * argv[]) {
bool x;
bool y;
x = true;
y = true;
implication(x, y);
x = true;
y = false;
implication(x, y);
x = false;
y = true;
implication(x, y);
x = false;
y = false;
implication(x, y);
}
|
C
|
#include "pokedex.h"
#include <stdio.h>
#include <string.h>
#include "testing.c"
#define EXITO 0
#define ERROR -1
#define CAPTURADISIMO 'S'
#define AVISTAR_FORMAT "%i;%[^;];%[^;];%[^;];%i;%c\r\n"
#define EVOLUCIONAR_FORMAT "%i;%[^;];%i;%[^;];%[^\n]\r\n"
/*Funciones creadas por mi*/
int imprimir_especie(especie_pokemon_t* especie){
printf("Vamos a imprimir toda la especie %s:\n", especie->nombre);
size_t cantidad = lista_elementos(especie->pokemones);
for(size_t i=0; i<cantidad; i++){
printf("-%s\n", (char*)lista_elemento_en_posicion(especie->pokemones, i));
}
return EXITO;
}
int comparador_especies(void* uno, void* dos){
if(!uno || !dos)
return 0;
especie_pokemon_t* primero = uno;
especie_pokemon_t* segundo = dos;
if(primero->numero>segundo->numero)
return 1;
if(primero->numero<segundo->numero)
return -1;
return 0;
}
void destructoraso(void* destruido){
if(!destruido)
return;
free(destruido);
}
// Inserta pokemon avistado
int pokedex_insertar_avistado(pokedex_t* pokedex, abb_t* arbol, especie_pokemon_t* especie, particular_pokemon_t particular){
if(!pokedex || !arbol || !especie) return ERROR;
particular_pokemon_t* individuo = (particular_pokemon_t*)calloc(1, sizeof(particular_pokemon_t));
if(!individuo) return ERROR;
strcpy(individuo->nombre, particular.nombre);
individuo->nivel = particular.nivel;
individuo->capturado = particular.capturado;
lista_apilar(pokedex->ultimos_capturados, individuo);
lista_encolar(pokedex->ultimos_vistos, individuo);
especie_pokemon_t* especie_encontrada = arbol_buscar(arbol, especie);
lista_t* particulares = especie_encontrada->pokemones;
return lista_insertar(particulares, individuo);
}
// Inserta la especie y después el pokemon avistado
int pokedex_insertar_especie(pokedex_t* pokedex, abb_t* arbol, especie_pokemon_t* especie, particular_pokemon_t particular){
especie_pokemon_t* especie_guardada = (especie_pokemon_t*)calloc(1, sizeof(especie_pokemon_t));
if(!especie_guardada) return ERROR;
especie_guardada->numero = especie->numero;
strcpy(especie_guardada->nombre, especie->nombre);
strcpy(especie_guardada->descripcion, especie->descripcion);
especie_guardada->pokemones = lista_crear();
if(!especie_guardada->pokemones){
free(especie_guardada);
return ERROR;
}
arbol_insertar(arbol, especie_guardada);
return pokedex_insertar_avistado(pokedex, arbol, especie, particular);
}
size_t buscar_posicion(lista_t* lista, particular_pokemon_t* particularPokemon){
size_t cantidad = lista_elementos(lista);
particular_pokemon_t* actual;
for(size_t i=0; i<cantidad; i++){
actual = lista_elemento_en_posicion(lista, i);
if(strcmp(particularPokemon->nombre, actual->nombre)==0){
return i;
}
}
return 0;
}
int evolucionador(pokedex_t* pokedex, especie_pokemon_t* especie, especie_pokemon_t especie_nueva, particular_pokemon_t* particular, particular_pokemon_t* anterior){
particular->nivel = anterior->nivel;
particular->capturado = true;
size_t posicion = buscar_posicion(especie->pokemones, anterior);
lista_borrar_de_posicion(especie->pokemones, posicion);
especie_pokemon_t* nueva = arbol_buscar(pokedex->pokemones, &especie_nueva);
if(nueva == NULL) pokedex_insertar_especie(pokedex, pokedex->pokemones, &especie_nueva, *particular);
else pokedex_insertar_avistado(pokedex, pokedex->pokemones, nueva, *particular);
return EXITO;
}
bool comparador_de_particulares(void* uno, void* dos){
particular_pokemon_t* part_uno = uno;
particular_pokemon_t* part_dos = dos;
//printf("%s --- %s\n", part_uno->nombre, part_dos->nombre);
if(strcmp(part_uno->nombre, part_dos->nombre)==0){
return true;
}
return false;
}
bool imprimidor_de_pokemon(void* pokemon, void* archivo){
particular_pokemon_t* particularPokemon = pokemon;
fprintf(archivo, "P;%s;%i;", particularPokemon->nombre, particularPokemon->nivel);
if(particularPokemon->capturado == true){
fprintf(archivo, "S\n");
}
else{
fprintf(archivo, "N\n");
}
return false;
}
bool imprimidor_de_especies(void* especievoid, void* archivo){
especie_pokemon_t* especie = especievoid;
fprintf(archivo, "E;%s;%i;%s\n", especie->nombre, especie->numero, especie->descripcion);
lista_con_cada_elemento(especie->pokemones, (void (*)(void *, void *)) (imprimidor_de_pokemon), archivo);
return false;
}
especie_pokemon_t* insertar_especie_al_prender(pokedex_t* pokedex, especie_pokemon_t especie){
especie_pokemon_t* especie_guardada = (especie_pokemon_t*)calloc(1, sizeof(especie_pokemon_t));
especie_guardada->numero = especie.numero;
strcpy(especie_guardada->nombre, especie.nombre);
strcpy(especie_guardada->descripcion, especie.descripcion);
especie_guardada->pokemones = lista_crear();
if(!especie_guardada->pokemones){
free(especie_guardada);
return NULL;
}
arbol_insertar(pokedex->pokemones, especie_guardada);
return especie_guardada;
}
int insertar_pokemon_al_prender(pokedex_t* pokedex, especie_pokemon_t* especie, particular_pokemon_t pokemon){
if(!pokedex || !pokedex->pokemones || !especie) return ERROR;
particular_pokemon_t* individuo = (particular_pokemon_t*)calloc(1, sizeof(particular_pokemon_t));
if(!individuo) return ERROR;
strcpy(individuo->nombre, pokemon.nombre);
individuo->nivel = pokemon.nivel;
individuo->capturado = pokemon.capturado;
especie_pokemon_t* especie_encontrada = arbol_buscar(pokedex->pokemones, especie);
lista_t* particulares = especie_encontrada->pokemones;
return lista_insertar(particulares, individuo);
}
/*Funciones del .h*/
pokedex_t* pokedex_crear(char entrenador[MAX_NOMBRE]){
if(!entrenador) return NULL;
pokedex_t* poke = (pokedex_t*)calloc(1, sizeof(pokedex_t));
if(!poke) return NULL;
poke->pokemones = arbol_crear(comparador_especies, destructoraso);
poke->ultimos_capturados = lista_crear();
poke->ultimos_vistos = lista_crear();
strcpy(poke->nombre_entrenador, entrenador);
return poke;
}
int pokedex_avistar(pokedex_t* pokedex, char ruta_archivo[MAX_RUTA]){
if(!pokedex|| !ruta_archivo) return ERROR;
if(!pokedex->pokemones) pokedex->pokemones = arbol_crear(comparador_especies, destructoraso);
if(!pokedex->pokemones) return ERROR;
if(!pokedex->ultimos_capturados) pokedex->ultimos_capturados = lista_crear();
if(!pokedex->ultimos_capturados) return ERROR;
if(!pokedex->ultimos_vistos) pokedex->ultimos_vistos = lista_crear();
if(!pokedex->ultimos_vistos) return ERROR;
FILE *lector = fopen(ruta_archivo, "r");
if(!lector) return ERROR;
especie_pokemon_t especie;
particular_pokemon_t particular;
char* capturado = malloc(sizeof(char));
int leidos = 6;
while(leidos == 6){
printf("Entro\n");
leidos = fscanf(lector, AVISTAR_FORMAT, &especie.numero, especie.nombre,
especie.descripcion, particular.nombre, &particular.nivel, capturado);
if(*capturado == (char)CAPTURADISIMO){
particular.capturado = true;
}
else{
particular.capturado = false;
}
void* resultado = arbol_buscar(pokedex->pokemones, &especie);
if(resultado == NULL){
pokedex_insertar_especie(pokedex, pokedex->pokemones, &especie, particular);
}
else{
pokedex_insertar_avistado(pokedex, pokedex->pokemones, &especie, particular);
}
}
free(capturado);
fclose(lector);
printf("Avistamos bien!\n");
return EXITO;
}
int pokedex_evolucionar(pokedex_t* pokedex, char ruta_archivo[MAX_RUTA]){
if(!pokedex || !pokedex->pokemones || !ruta_archivo) return ERROR;
FILE *archivo = fopen(ruta_archivo, "r");
if(!archivo) return ERROR;
int leidos;
especie_pokemon_t especie_vieja;
especie_pokemon_t especie;
particular_pokemon_t particular;
do{
leidos = fscanf(archivo, EVOLUCIONAR_FORMAT,
&especie_vieja.numero, particular.nombre, &especie.numero,
especie.nombre, especie.descripcion);
especie_pokemon_t* p_especie_vieja = arbol_buscar(pokedex->pokemones, &especie_vieja);
if(p_especie_vieja == NULL) return ERROR;
particular_pokemon_t* particular_buscado = lista_buscar(p_especie_vieja->pokemones,
comparador_de_particulares, &particular);
if(particular_buscado == NULL) return printf("No existe el pokemon a evolucionar %s\n", particular.nombre);
if(particular_buscado->capturado == false) return printf("No esta capturado el pokemon %s\n", particular_buscado->nombre);
if(evolucionador(pokedex, p_especie_vieja, especie, &particular, particular_buscado)==ERROR) return ERROR;
}while(leidos == 5);
fclose(archivo);
printf("Evolucionamos bien!\n");
return EXITO;
}
void pokedex_ultimos_capturados(pokedex_t* pokedex){
if(!pokedex || !pokedex->ultimos_capturados) return;
printf("\nÚltimos pokemon capturados:\n");
while(lista_vacia(pokedex->ultimos_capturados) == false){
printf("-%s\n", (char*)lista_ultimo(pokedex->ultimos_capturados));
lista_desapilar(pokedex->ultimos_capturados);
}
}
void pokedex_ultimos_vistos(pokedex_t* pokedex){
if(!pokedex || !pokedex->ultimos_vistos) return;
printf("\nÚltimos pokemon vistos:\n");
while(lista_vacia(pokedex->ultimos_vistos) == false){
printf("-%s\n", (char*)lista_primero(pokedex->ultimos_vistos));
lista_desencolar(pokedex->ultimos_vistos);
}
}
void pokedex_informacion(pokedex_t* pokedex, int numero_pokemon, char nombre_pokemon[MAX_NOMBRE]){
if(!pokedex || !pokedex->pokemones || numero_pokemon<0) return;
especie_pokemon_t* especie;
especie_pokemon_t especie1;
especie1.numero = numero_pokemon;
especie = (especie_pokemon_t*)arbol_buscar(pokedex->pokemones, &especie1);
if(!especie){
printf("No existe la especie\n");
return;
}
particular_pokemon_t particularPokemon;
strcpy(particularPokemon.nombre, nombre_pokemon);
particular_pokemon_t* Pokemon = lista_buscar(especie->pokemones, comparador_de_particulares, &particularPokemon);
if(!Pokemon){
printf("No existe el Pokemon\n");
imprimir_especie(especie);
return;
}
printf("-%s", especie->nombre);
printf("-%s\n", particularPokemon.nombre);
}
void pokedex_destruir(pokedex_t* pokedex){
while(!arbol_vacio(pokedex->pokemones)){
lista_destruir(arbol_raiz(pokedex->pokemones));
arbol_borrar(pokedex->pokemones, arbol_raiz(pokedex->pokemones));
}
arbol_destruir(pokedex->pokemones);
free(pokedex);
printf("Borramos todo\n");
}
int pokedex_apagar(pokedex_t* pokedex){
if(!pokedex) return ERROR;
FILE* archivo = fopen("pokedex.txt", "w+");
if(!archivo) return ERROR;
fprintf(archivo, "%s\n", pokedex->nombre_entrenador);
abb_con_cada_elemento(pokedex->pokemones, 1, (imprimidor_de_especies), archivo);
fclose(archivo);
printf("Apago bien!\n");
return EXITO;
}
pokedex_t* pokedex_prender(){
FILE* archivo = fopen("pokedex.txt", "r");
if(!archivo) return NULL;
char nombre[MAX_NOMBRE];
int leidos = fscanf(archivo, "%[^\n]\r\n", nombre);
if(leidos != 1){
printf("El nombre del entrenador esta mal escrito en el archivo\n");
return NULL;
}
pokedex_t* pokedex = pokedex_crear(nombre);
if(!pokedex){
printf("Error al volver a crear la Pokedex");
fclose(archivo);
return NULL;
}
char primero_letra;
char capturado;
especie_pokemon_t especie;
particular_pokemon_t particular;
especie_pokemon_t* actual;
do{
leidos = fscanf(archivo, "%[^;]", &primero_letra);
if(primero_letra == 'E'){
leidos = fscanf(archivo, ";%[^;];%i;%[^\n]\r\n",
especie.nombre, &especie.numero, especie.descripcion);
actual = insertar_especie_al_prender(pokedex, especie);
if(actual==NULL) return NULL;
}
else if(primero_letra == 'P'){
leidos = fscanf(archivo, ";%[^;];%i;%[^\n]\r\n",
particular.nombre, &particular.nivel, &capturado);
insertar_pokemon_al_prender(pokedex, actual, particular);
}
}while(leidos == 1 || leidos == 2 || leidos == 3);
printf("Prendio bien! (Estamos en linea)\n");
return pokedex;
}
|
C
|
// 4. Napisz funkcję, która po wczytaniu liczby całkowitej wypisze jej cyfry
// zaczynając od ostatniej i kończąc na pierwszej.
// Na przykład po wczytaniu liczby '1410' funkcja powinna wypisać '0141'.
#include <stdio.h>
#include <stdlib.h>
int main (){
}
|
C
|
#include<stdio.h>
int main (void)
{
char name [40];
printf("Enter a name: ");
scanf("%s",name);
printf(" %s %s\n",name, " Srivastava");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
//按位于
int a = 3;
int b = 5;
int c = a^b;
printf("%d\n",c);
//按位或
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[100];
int i,len;
char ch;
len=strlen(len);
for(i=0;i<len;i++)
str[i]=str[len-1-i];
str[i]='\0';
printf("%s\n",str);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <pthread.h>
int main(){
//C counts for equal values, D counts for not equal values.
int b,c,d,q = 0;
//test value to go through array right and left;
int right[]={1,2,3,4,5};
int left[]={1,2,2,4,5};
//storage arrays to keep the element seperate
//test Bool for reject
bool REJECT = false;
int rright[]={-1};
int lleft[]={-1};
// both is array to hold both values if i need to
//int both[]={-1,-1};
//reject is an array of values that are not equal from left and right
int reject[sizeof(right)/sizeof(right[0])];
//good is an array of values that are equal from left and right
int good[2*sizeof(right)/sizeof(right[0])];
//boolean to see if you took from right & left
bool R = false;
bool L = false;
bool FLAG = true;
bool flagr = true;
bool flagl = true;
//lleft and rright can act as buffers maybe
// read from left and right, and only continue once it gets both values.
//cannot take 2 from left or right. has to be one from each side
//set values to -1
printf("size of good %lu\n",sizeof(good)/sizeof(good[0]));
printf("here we go!!\n");
while(FLAG){
printf("In while loop\n");
//maybe make these if statements do whiles?
//take input from right
//Thread 1 ({
while(flagr){
printf("In rright while loop\n");
if(rright[0] < 0 && R == false){
printf("In rright if statement\n");
//take input from right motor and set it into the right array
rright[0]=right[q];
flagr = false;
R=true;
}else{
printf("in rright else statement\n");
flagr = true;
//wait
}
}
//end Thread 1 })
// start Thread 2({
while(flagl){
printf("in lleft while loop\n");
if(lleft[0] < 0 && L == false){
printf("in lleft if statement\n");
//take input from the left motor and set it into the left array
lleft[0]=left[q];
flagl = false;
L=true;
}else{
printf("In lleft else statement\n");
//flagl = true;
//wait?
}
}
//end Thread 2})
//if(rright[0]>=0 && lleft[0]>=0 ){
printf("in comparision\n");
//combine into one array?
//Do I compare here?
//push to thing.
//if the 2 are equal, add them to array, and say they where added.
//if they are not equal, add them to reject array and say they where added.
//Should this be in a thread/
//maybe.
if(rright[0]==lleft[0]){
good[c]=rright[0];
printf("%d added to good from right\n",rright[0]);
c++;
good[c]=lleft[0];
printf("%d added to good from left\n",lleft[0]);
c++;
}else{
printf("%d from right is not equal to %d from left\n",rright[0],lleft[0]);
reject[d]=rright[0];
printf("%d added to reject from right\n",rright[0]);
d++;
reject[d]=lleft[0];
printf("%d added to rejct from left\n",lleft[0]);
d++;
//test bool
REJECT = true;
}
//reset left and right storage arrays.
printf("Resetting\n");
//reset your shit tim smh.
flagr=true;
flagl=true;
//
rright[0]=-1;
R=false;
lleft[0]=-1;
L=false;
q++;
b++;
printf("done with loop, going back!\n");
//This literally goes on forever
if(b >= sizeof(right)/sizeof(right[0])){
FLAG = false;
printf("COMPLETE\n");
printf("Reject = %s\n",REJECT ? "true" : "false");
//printf("Size of right is %d",);
printf("b=%d\n",c);
}
//}
}
}
//If This needs to check if they are equal then you would check here,
// and push to error correction if it is false, or the other place if it
//is true;
//still need to figure out what to do if it gets 2 of one side
//Like what happens if this happens?
//I dont think this will loop forever, once it gets past the if else x2 then it just stops if its
//false. Need a way to check again. Maybe a do while? Should I make left and right seperate?
//Does it matter? yes it does, if it takes 2r, and assigns one of them left, then its no good.
//Maybe put both if/else checks, into a while loop, and if its else, then set the thing to true,
//and if it is true, then set it to false
//EXAMPLE
//---------------------------------------
/*
flag = true;
while(flag){
f(rright[0] < 0 && R == false){
//take input from right motor and set it into the right array
rright[0]=right[c];
R=true;
flag = false; //Breaks out of the while loop for checking the side
}else{
flag = true;
//and it continues to loop, checking for right input.
//but then what if it gets Left first?
//need to figure that out
//but this should work. I like this actually
//yes
}
}
*/
//---------------------------------------
//If i can make both left and right run at the same time that would be good.
//But again, what do i do if I get 2r?
//Do i need to count, if I need to count than thats different.
//that would change everything.
//Would it though?
//Just keep count. lol
//shoudl the last if(61) havve a loop, or will it work not having a loop?
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <string.h>
union semun {
int val;
struct seid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
int main(int argc, char *argv[]) {
int semid;
int key = ftok("makefile", 22);
int sc;
if (strncmp(argv[1], "-c", strlen(argv[1])) == 0) {
semid = semget(key, 1, IPC_CREAT | IPC_EXCL | 0644);
if (semid >= 0) {
printf("semaphore created: %d\n", semid);
union semun su;
int v = atoi(argv[2]);
su.val = v;
sc = semctl(semid, 0, SETVAL, su);
printf("value set: %d\n", sc);
}
else
printf("semaphore already exists\n");
}
else if (strncmp(argv[1], "-v", strlen(argv[1])) == 0) {
semid = semget(key, 1, 0);
sc = semctl(semid, 0, GETVAL);
printf("semaphore value: %d\n", sc);
}
else if (strncmp(argv[1], "-r", strlen(argv[1])) == 0) {
semid = semget(key, 1, 0);
sc = semctl(semid, 0, IPC_RMID);
printf("semaphore removed: %d\n", sc);
}
return 0;
}
|
C
|
#include"comm.h"
int main()
{
printf("test_sem\n");
int semid = creatSem(1);
if(semid < 0)
{
return -1;
}
int ret = initSem(semid,0);
if(ret < 0)
{
return -2;
}
P(semid,0);
sleep(15);
printf("nihao \n");
exit(1);
printf("DEBUG:exit\n");
V(semid,0);
sleep(5);
destorySem(semid);
return 0;
}
/*
int main()
{
printf("test_sem\n");
int semid = creatSem(1);
if(semid < 0)
{
return -1;
}
int ret = initSem(semid,0);
if(ret < 0)
{
return -2;
}
pid_t id = fork();
if(id==0)
{
//child
// printf("child proc,pid:%d,ppid:%d\n",getpid(),getppid());
while(1)
{
P(semid,0);
usleep(13300);
printf("A");
fflush(stdout);
usleep(10000);
printf("A");
fflush(stdout);
V(semid,0);
}
}
else
{
//father
// printf("father proc,pid:%d,ppid:%d\n",getpid(),getppid());
while(1)
{
P(semid,0);
usleep(1123);
printf("B");
fflush(stdout);
usleep(100);
printf("B");
fflush(stdout);
V(semid,0);
}
}
// sleep(10);
destorySem(semid);
return 0;
}*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define STACK_MAX_SIZE 5
#define STACK_OVERFLOW -100
#define ERROR_STACK_OVERFLOW printf("Error. Stack overflow\n");
#define STACK_UNDERFLOW -101
#define ERROR_STACK_UNDERFLOW printf("Error. Stack underflow\n");
#define OUT_OF_MEMORY -102
#define STACK_WAS_CLEARED printf("Stack was cleared\n");
typedef struct stack
{
int data[STACK_MAX_SIZE];
size_t size;
}stc;
void push(stc *stack, const int value)
{
if (stack->size >= STACK_MAX_SIZE) {
ERROR_STACK_OVERFLOW;
exit(STACK_OVERFLOW);
}
stack->data[stack->size] = value;
stack->size++;
}
int pop(stc *stack)
{
if (stack->size == 0)
{
ERROR_STACK_UNDERFLOW;
exit(STACK_UNDERFLOW);
}
stack->size--;
return stack->data[stack->size];
}
void print_stack(stc *stack)
{
if (stack->size > 0)
{
int i = 0;
while (i < stack->size)
{
printf("%d->", stack->data[i]);
i++;
}
printf("\n");
}
}
stc* create_stack()
{
stc* my_stack = (stc*)malloc(STACK_MAX_SIZE);
my_stack->size = 0;
return my_stack;
}
void free_stack(stc *stack)
{
while (stack->size != 0)
{
pop(stack);
}
STACK_WAS_CLEARED;
}
int main(int argc, char const *argv[])
{
stc* my_stack = create_stack();
push(my_stack, 3);
push(my_stack, 5);
push(my_stack, 6);
push(my_stack, 7);
push(my_stack, 8);
print_stack(my_stack);
pop(my_stack);
print_stack(my_stack);
free_stack(my_stack);
print_stack(my_stack);
return 0;
}
|
C
|
#include <stdio.h>
int main ()
{
/* ֲ */
int a = 100;
int b = 200;
/* 鲼 */
if( a == 100 )
{
/* Ϊ棬 */
if( b == 200 )
{
/* Ϊ棬 */
printf("a ֵ 100 b ֵ 200\n" );
}
}
printf("a ȷֵ %d\n", a );
printf("b ȷֵ %d\n", b );
return 0;
}
|
C
|
/*
* 7. Here’s a partial program using a variadic function:
*
* #include <stdio.h>
* #include <stdlib.h>
* #include <stdarg.h>
* void show_array(const double ar[], int n);
* double * new_d_array(int n, ...);
*
* int main()
* {
* double * p1;
* double * p2;
*
* p1 = new_d_array(5, 1.2, 2.3, 3.4, 4.5, 5.6);
* p2 = new_d_array(4, 100.0, 20.00, 8.08, -1890.0);
* show_array(p1, 5);
* show_array(p2, 4);
* free(p1);
* free(p2);
*
* return 0;
* }
*
* The new_d_array() function takes an int argument and a variable number of double
* arguments. The function returns a pointer to a block of memory allocated by malloc().
* The int argument indicates the number of elements to be in the dynamic array, and
* the double values are used to initialize the elements, with the first value being assigned
* to the first element, and so on. Complete the program by providing the code for show_
* array() and new_d_array().
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h> // size_t
#include<stdarg.h>
void show_array(const double ar[], size_t length);
double *new_d_array(size_t n, ...);
int main(void)
{
double *p1, *p2;
p1 = new_d_array(5, 1.2, 2.3, 3.4, 4.5, 5.6);
p2 = new_d_array(4, 100.0, 20.00, 8.08, -1890.0);
show_array(p1, 5);
show_array(p2, 4);
free(p1);
free(p2);
return 0;
}
void show_array(const double ar[], size_t length)
{
for(size_t i=0; i<length; ++i)
printf("%g ", ar[i]);
putchar('\n');
}
double *new_d_array(size_t n, ...)
{
double *pdr = (double*) malloc(sizeof(double)*n);
if(!pdr){
fprintf(stderr, "Cannot allocate memory on the free store\n");
return NULL;
}
va_list ap;
va_start(ap, n);
for(size_t i=0; i<n; ++i)
pdr[i] = va_arg(ap, double);
va_end(ap);
return pdr;
}
|
C
|
#include<stdio.h>
main()
{
unsigned long long int n;
printf("Enter no:\t");
scanf("%d",&n);
digit(n);
//printf("%d",n);
}
digit(int n)
{
int i,j,s;
if(n<10)
return word(n);
else
{
//printf("%d",n%10);
digit(n/10);
return word(n%10);
}
}
word(int n)
{
switch(n)
{
case 0: printf("zero ");break;
case 1: printf("one ");break;
case 2: printf("two ");break;
case 3: printf("three ");break;
case 4: printf("four ");break;
case 5: printf("five ");break;
case 6: printf("six ");break;
case 7: printf("seven ");break;
case 8: printf("eight ");break;
case 9: printf("nine ");break;
default : printf("Not a digit");break;
}
}
|
C
|
#include "stdio.h"
#include "stdlib.h"
int main(){
FILE *fptr;
int x = 20; char c = '&';
char cstr[] = "Hello friend";
float flt = 2.75;
fptr = fopen("output.dat", "w");
if(fptr == NULL){
printf("File error.\n");
exit(1);
}
fprintf(fptr, "x = %d\tc = %c\n", x, c);
fprintf(fptr, "flt = %f\n", flt);
fprintf(fptr, "cstr = %s\n", cstr);
fclose(fptr);
return 0;
}
|
C
|
#include <stdio.h>
int f_add(int a, int b);
int double_n(int n);
int result;
int main() {
int x, y[20], i;
x = f_add(4,2);
y[10] = x;
result = double_n(x);
for (i=0; i < 6; i+=1) {
x = i;
}
result += y[x+5];
return result;
}
int f_add(int a, int b) {
return a+b;
}
int double_n(int n) {
return n*n;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
char str[50] = "Mr John Smith ";
printf("before => %s\n", str);
replace(str);
printf("after => %s\n", str);
return 0;
}
int replace(char * str)
{
int size1 = strlen(str);
int extra = 0 , i = 0;
while(i < size1){
if( str[i++] == ' ' ){
extra += 2;
}
}
int size2 = size1 + extra - 1;
i = size1 -1;
while(i >= 0){
if( str[i--] == ' ' ){
str[size2--] = '0';
str[size2--] = '2';
str[size2--] = '%';
}else{
str[size2--] = str[i+1];
}
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <assert.h>
#include "arraylist.h"
ArrayList *arraylist_create() {
/* Allocate Memory */
ArrayList *list = malloc(sizeof(ArrayList));
assert(list != NULL);
list->size = 0;
list->data = calloc(2, sizeof(void *));
assert(list->data != NULL);
list->data[0] = NULL;
return list;
}
void arraylist_setdata(ArrayList *list, void ** data, int max, int clear_data) {
/* Sets the internal array of the arraylist */
clear_data ? arraylist_clear(list) : NULL;
list->data = data;
list->size = max;
}
void arraylist_add(ArrayList *list, void *elem) {
/* Adds one element of generic pointer type to the internal array */
void ** new_data = realloc(list->data, arraylist_getsizeof(list));
assert(new_data != NULL);
new_data[list->size] = elem;
arraylist_setdata(list, new_data, list->size + 1, 0);
}
void *arraylist_get(ArrayList *list, int index) {
/* Gets an member of the array at an index */
return list->data[index];
}
size_t arraylist_getsizeof(ArrayList *list) {
/* Returns the size of the internal array in memory */
return sizeof(*list->data);
}
size_t arraylist_getsize(ArrayList *list) {
/* Returns the number of elements in the arraylist */
return list->size;
}
void arraylist_remove(ArrayList *list, int index, int freeit) {
/* Removes one element at and index */
if (index > list->size - 1)
return;
if (list->size == 1) {
arraylist_clear(list);
return;
}
if (freeit)
free(arraylist_get(list, index));
for ( int i = index; i < list->size; ++i ) {
if (i == list->size - 1)
list->data[i] = NULL;
else
list->data[i] = list->data[i + 1];
}
void ** new_data = realloc(list->data, arraylist_getsizeof(list));
--list->size;
assert(new_data != NULL);
arraylist_setdata(list, new_data, list->size, 0);
}
void arraylist_clear(ArrayList *list) {
/* Clears the internal array */
list->size = 0;
free(list->data);
list->data = NULL;
}
void arraylist_deallocate(ArrayList *list) {
/* De-allocates the arraylist from memory
No usage of the arraylist is allowed after this function call */
if (list->data != NULL)
free(list->data);
free(list);
}
int arraylist_getindex(ArrayList *list, void *elem) {
/* Looks for elem in list and returns the index or -1 if not found */
for(int i = 0; i < list->size; ++i)
if (elem == arraylist_get(list, i))
return i;
return -1;
}
|
C
|
for (int i = 0; i < N; i++) {
x[i] += dt * vx[i];
if (x[i] >= 1.0f || x[i] <= -1.0f) vx[i] *= -1.0f;
}
for (int i = 0; i < N; i++) {
y[i] += dt * vy[i];
if (y[i] >= 1.0f || y[i] <= -1.0f) vy[i] *= -1.0f;
}
for (int i = 0; i < N; i++) {
z[i] += dt * vz[i];
if (z[i] >= 1.0f || z[i] <= -1.0f) vz[i] *= -1.0f;
}
#include <immintrin.h>
__m128 rsqrt_float4_single(__m128 x) {
__m128 three = _mm_set1_ps(3.0f), half = _mm_set1_ps(0.5f);
__m128 res = _mm_rsqrt_ps(x);
__m128 muls = _mm_mul_ps(_mm_mul_ps(x, res), res);
return res = _mm_mul_ps(_mm_mul_ps(half, res), _mm_sub_ps(three, muls));
}
__m128 invsqrt_compiler(__m128 x) {
// surprisingly, gcc/clang just use rcpps + newton, not rsqrt + newton.
// gcc fails to use FMA for the Newton-Raphson iteration, though: clang is better
return _mm_set1_ps(1.0f) / _mm_sqrt_ps(x);
}
__m128 inv_compiler(__m128 x) {
return _mm_set1_ps(1.0f) / x;
}
void compute() {
double t0, t1;
// Loop 0.
t0 = wtime();
for (int i = 0; i < N; i++) {
ax[i] = 0.0f;
}
for (int i = 0; i < N; i++) {
ay[i] = 0.0f;
}
for (int i = 0; i < N; i++) {
az[i] = 0.0f;
}
t1 = wtime();
l0 += (t1 - t0);
// Loop 1.
t0 = wtime();
int unroll_n = (N/4) * 4;
for (int i = 0; i < N; i+=4) {
__m128 xi_v = _mm_load_ps(&x[i]);
__m128 yi_v = _mm_load_ps(&y[i]);
__m128 zi_v = _mm_load_ps(&z[i]);
// vector accumulators for ax[i + 0..3] etc.
__m128 axi_v = _mm_setzero_ps();
__m128 ayi_v = _mm_setzero_ps();
__m128 azi_v = _mm_setzero_ps();
// AVX broadcast-loads are as cheap as normal loads,
// and data-reuse meant that stand-alone load instructions were used anyway.
// so we're not even losing out on folding loads into other insns
// An inner-loop stride of only 4B is a huge win if memory / cache bandwidth is a bottleneck
// even without AVX, the shufps instructions are cheap,
// and don't compete with add/mul for execution units on Intel
for (int j = 0; j < N; j++) {
__m128 xj_v = _mm_set1_ps(x[j]);
__m128 rx_v = _mm_sub_ps(xj_v, xi_v);
__m128 yj_v = _mm_set1_ps(y[j]);
__m128 ry_v = _mm_sub_ps(yj_v, yi_v);
__m128 zj_v = _mm_set1_ps(z[j]);
__m128 rz_v = _mm_sub_ps(zj_v, zi_v);
__m128 mj_v = _mm_set1_ps(m[j]);
// sum of squared differences
__m128 r2_v = _mm_set1_ps(eps) + rx_v*rx_v + ry_v*ry_v + rz_v*rz_v; // GNU extension
/* __m128 r2_v = _mm_add_ps(_mm_set1_ps(eps), _mm_mul_ps(rx_v, rx_v));
r2_v = _mm_add_ps(r2_v, _mm_mul_ps(ry_v, ry_v));
r2_v = _mm_add_ps(r2_v, _mm_mul_ps(rz_v, rz_v));
*/
// rsqrt and a Newton-Raphson iteration might have lower latency
// but there's enough surrounding instructions and cross-iteration parallelism
// that the single-uop sqrtps and divps instructions prob. aren't be a bottleneck
#define USE_RSQRT
#ifndef USE_RSQRT
// even with -mrecip=vec-sqrt after -ffast-math, this still does sqrt(v)*v, then rcpps
__m128 r2sqrt = _mm_sqrt_ps(r2_v);
__m128 r6sqrt = _mm_mul_ps(r2_v, r2sqrt); // v^(3/2) = sqrt(v)^3 = sqrt(v)*v
__m128 s_v = _mm_div_ps(mj_v, r6sqrt);
#else
__m128 r2isqrt = rsqrt_float4_single(r2_v);
// can't use the sqrt(v)*v trick, unless we either do normal sqrt first then rcpps
// or rsqrtps and rcpps. Maybe it's possible to do a Netwon Raphson iteration on that product
// instead of refining them both separately?
__m128 r6isqrt = r2isqrt * r2isqrt * r2isqrt;
__m128 s_v = _mm_mul_ps(mj_v, r6isqrt);
#endif
__m128 srx_v = _mm_mul_ps(s_v, rx_v);
__m128 sry_v = _mm_mul_ps(s_v, ry_v);
__m128 srz_v = _mm_mul_ps(s_v, rz_v);
axi_v = _mm_add_ps(axi_v, srx_v);
ayi_v = _mm_add_ps(ayi_v, sry_v);
azi_v = _mm_add_ps(azi_v, srz_v);
}
_mm_store_ps(&ax[i], axi_v);
_mm_store_ps(&ay[i], ayi_v);
_mm_store_ps(&az[i], azi_v);
}
t1 = wtime();
l1 += (t1 - t0);
// Loop 2.
t0 = wtime();
for (int i = 0; i < N; i++) {
vx[i] += dmp * (dt * ax[i]);
}
for (int i = 0; i < N; i++) {
vy[i] += dmp * (dt * ay[i]);
}
for (int i = 0; i < N; i++) {
vz[i] += dmp * (dt * az[i]);
}
t1 = wtime();
l2 += (t1 - t0);
// Loop 3.
t0 = wtime();
for (int i = 0; i < N; i++) {
x[i] += dt * vx[i];
y[i] += dt * vy[i];
z[i] += dt * vz[i];
if (x[i] >= 1.0f || x[i] <= -1.0f) vx[i] *= -1.0f;
if (y[i] >= 1.0f || y[i] <= -1.0f) vy[i] *= -1.0f;
if (z[i] >= 1.0f || z[i] <= -1.0f) vz[i] *= -1.0f;
}
t1 = wtime();
l3 += (t1 - t0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <getopt.h>
#include <unistd.h>
#include <stdbool.h>
#include <libgen.h>
#include "type_definitions.h"
#include "read_write_csv.h"
#include "calculations.h"
#include "fitting_functions.h"
#include "fit_assessment.h"
#include "printer.h"
int main(int argc, char **argv)
{
if (argc == 1) {
printf("No file-path or instructions.\n");
printf("\"./fit --help\" to list commands\n");
}
// consistent: mode 0: linear, mode 2: exponential, mode 3: logarithmic
static struct option long_options[] =
{
{"lin", no_argument, NULL, '0'},
{"exp", no_argument, NULL, '1'},
{"log", no_argument, NULL, '2'},
{"pol", required_argument, NULL, 'p'},
{"all", required_argument, NULL, 'a'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'v'},
{"info", no_argument, NULL, 'i'},
{"write", optional_argument, NULL, 'w'},
{NULL, no_argument, NULL, 'n'}
};
int option;
bool write = false; // if true, results are written to file
bool silent = false; // if true, there will be no console logging
bool file_path_exists = false; // set to true if <file-path> has been provided
bool header_printed = false; // set to true when header has been displayed
bool export_to_csv = false;
long int size = 0;
long int numOfEntries;
char export_path[128];
if (access( argv[1], R_OK ) == 0) {
file_path_exists = true;
}
if (file_path_exists) size = findSize(argv[1]);
record_t records[size];
header_t header;
if (file_path_exists) {
char *filename = basename(argv[1]);
numOfEntries = readCSV(argv[1], records, &header);
create_filepath(export_path, filename, export_to_csv);
}
while ((option = getopt_long(argc, argv, "s", long_options, NULL)) != -1) {
switch (option) {
case 'v':
{
printf("curve-fitter version 1.0.0\n" );
}
break;
case 'h':
{
printf("\n");
printf("usage: ./fit [--version] [--help] [--info] [<file-path> <write/silent> <commands>]\n");
printf("\n");
printf("Root Mean Squared Error, R2, Sum of Squared Estimate of Errors (SSE)\n");
printf("and Mean Squared Error (MSE) are returned for all fits.\n");
printf("\n");
printf("Write/Export and Silent tags must be set after <file-path> \n");
printf("and before curve-fitting instructions.\n");
printf("\t --write \t\t Write/Export following fitting instructions to .txt file (default).\n");
printf("\t --write=csv \t\t Write/Export following fitting instructions to .csv file.\n");
printf("\t -s \t\t\t Disable console logging.\n");
printf("\n");
printf("Curve-Fitting Commands:\n");
printf("\t --lin \t\t\t Linear regression\n");
printf("\t --exp \t\t\t Exponential regression\n");
printf("\t --log \t\t\t Logarithmic regression (natural logarithm ln)\n");
printf("\t --pol <int> \t\t Polynomial Regression, requires input for degree\n");
printf("\t --pol <int1:int2> \t Polynomial Regression, from degree int1 to and including degree int2\n");
printf("\t --all <int> \t\t all four regression variants,\n");
printf("\t\t\t\t requires input for polynomial degree\n");
printf("\t --all <int1:int2> \t all four regression variants,\n");
printf("\t\t\t\t requires input for polynomial degree\n");
printf("\t\t\t\t requires input for polynomial degree\n");
printf("Fitting commands can be chained, e.g. \"--pol 2 --pol 3 --lin -- exp\"\n");
printf("\n");
printf("Other:\n");
printf("\t --info \t\t Info on coefficient nomenclature of results\n");
printf("\n");
}
break;
case 'i':
{
printf("Coefficient nomenclature:\n" );
printf(" Linear Regression: \t\t y = k * x + d \n");
printf(" Exponential Regression: \t y = A * exp(k * x) \n");
printf(" Logarithmic Regression: \t y = d + k * ln(x) \n");
printf(" Polynomial Regression: \t a[0] + a[1] * x + a[2] * x^2 + ... + a[n]*x^n = y \n");
}
break;
case 's':
{
silent = true;
}
break;
case 'w':
{ if (optarg && strcmp(optarg, "csv") == 0) {
export_to_csv = true;
}
if (file_path_exists) {
char *filename = basename(argv[1]);
numOfEntries = readCSV(argv[1], records, &header);
create_filepath(export_path, filename, export_to_csv);
write = true;
FILE *fp;
fp = fopen(export_path, "w");
if (export_to_csv) {
fprintf(fp, "Fit;RMSE;R2;SSE;MSE;Coefficients\n");
} else {
fprintf(fp, "%-20s%-25s%-25s%-25s%-25s%-s\n", "Fit", "Std. Error", "R2", "SSE", "MSE", "Coefficients");
fprintf(fp, "––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n");
}
fclose(fp);
printf("\n");
printf("Results exported to %s", export_path);
printf("\n");
} else {
no_file_path_error();
}
}
break;
case 'a':
if (file_path_exists) {
lin_coefficients linCoefficients = linearRegression(records, numOfEntries);
error_t lin = calculate_error_lin(linCoefficients, records, numOfEntries, 0);
lin_coefficients expCoefficients = exponentialRegression(records, numOfEntries);
error_t exp = calculate_error_lin(expCoefficients, records, numOfEntries, 1);
lin_coefficients logCoefficients = logarithmicRegression(records, numOfEntries);
error_t log = calculate_error_lin(logCoefficients, records, numOfEntries, 2);
if (!silent) {
if (!header_printed) {
print_header();
header_printed = true;
}
print_result_lin(linCoefficients, lin, 0);
print_result_lin(expCoefficients, exp, 1);
print_result_lin(logCoefficients, log, 2);
}
if (write) {
write_lin(export_path, linCoefficients, lin, 0, export_to_csv);
write_lin(export_path, expCoefficients, exp, 1, export_to_csv);
write_lin(export_path, logCoefficients, log, 2, export_to_csv);
}
poly_t limits;
bool limits_exist = poly_parse(optarg, &limits);
if (limits_exist) {
for (int degree = limits.begin; degree < limits.end + 1; degree++) {
double coefficients[degree + 1];
polynomialRegression(records, numOfEntries, coefficients, degree);
error_t poly = calculate_error_poly(coefficients, records, numOfEntries, degree);
if (!silent) {
if (!header_printed) {
print_header();
header_printed = true;
}
print_result_poly(coefficients, poly, degree);
}
if (write) write_poly(export_path, coefficients, poly, degree, export_to_csv);
}
} else {
int degree = atoi(optarg);
if (degree == 0) {
fprintf(stderr, "invalid -pol option \"%s\" - expecting an integer or\n <int:int> limits for polynomial degree\n",
optarg?optarg:"");
exit(EXIT_FAILURE);
}
double coefficients[degree + 1];
polynomialRegression(records, numOfEntries, coefficients, degree);
error_t poly = calculate_error_poly(coefficients, records, numOfEntries, degree);
if (!silent) {
if (!header_printed) {
print_header();
header_printed = true;
}
print_result_poly(coefficients, poly, degree);
}
if (write) write_poly(export_path, coefficients, poly, degree, export_to_csv);
}
} else {
no_file_path_error();
}
break;
case '0':
if (file_path_exists) {
lin_coefficients linCoefficients = linearRegression(records, numOfEntries);
error_t lin = calculate_error_lin(linCoefficients, records, numOfEntries, 0);
if (!silent) print_result_lin(linCoefficients, lin, 0);
if (write) write_lin(export_path, linCoefficients, lin, 0, export_to_csv);
}
break;
case '1':
if (file_path_exists) {
lin_coefficients expCoefficients = exponentialRegression(records, numOfEntries);
error_t exp = calculate_error_lin(expCoefficients, records, numOfEntries, 1);
if (!silent) {
if (!header_printed) {
print_header();
header_printed = true;
}
print_result_lin(expCoefficients, exp, 1);
}
if (write) write_lin(export_path, expCoefficients, exp, 1, export_to_csv);
} else {
no_file_path_error();
}
break;
case '2':
if (file_path_exists) {
lin_coefficients logCoefficients = logarithmicRegression(records, numOfEntries);
error_t log = calculate_error_lin(logCoefficients, records, numOfEntries, 2);
if (!silent) {
if (!header_printed) {
print_header();
header_printed = true;
}
print_result_lin(logCoefficients, log, 2);
}
if (write) write_lin(export_path, logCoefficients, log, 2, export_to_csv);
} else {
no_file_path_error();
}
break;
case 'p':
if (file_path_exists) {
poly_t limits;
bool limits_exist = poly_parse(optarg, &limits);
if (limits_exist) {
for (int degree = limits.begin; degree < limits.end + 1; degree++) {
double coefficients[degree + 1];
polynomialRegression(records, numOfEntries, coefficients, degree);
error_t poly = calculate_error_poly(coefficients, records, numOfEntries, degree);
if (!silent) {
if (!header_printed) {
print_header();
header_printed = true;
}
print_result_poly(coefficients, poly, degree);
}
if (write) write_poly(export_path, coefficients, poly, degree, export_to_csv);
}
} else {
int degree = atoi(optarg);
if (degree == 0) {
fprintf(stderr, "invalid -pol option \"%s\" - expecting an integer or\n <int:int> limits for polynomial degree\n",
optarg?optarg:"");
exit(EXIT_FAILURE);
}
double coefficients[degree + 1];
polynomialRegression(records, numOfEntries, coefficients, degree);
error_t poly = calculate_error_poly(coefficients, records, numOfEntries, degree);
if (!silent) {
if (!header_printed) {
print_header();
header_printed = true;
}
print_result_poly(coefficients, poly, degree);
}
if (write) write_poly(export_path, coefficients, poly, degree, export_to_csv);
}
} else {
no_file_path_error();
}
break;
}
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int n;
do
{
scanf("%d",&n);
if(n==42)
break;
else
printf("%d\n",n);
}while(1);
return 0;
}
|
C
|
#include <dos.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define SWINT 0x60
#define CR 0x0D
#define LF 0x0A
#define MAX_PACK 100
#define MAX_BUF 50
/**
PACKET format
0 ****next hop_mac(6)**** |6 *****source_mac(6)****** |12 **type(2)** |14 ***dest_ip(2)*** |16 **source(2)** |18 ***data**.....
**/
/**
///change this to user input later
unsigned char router_mac[] = "\x08\x00\x27\x1c\xe6\x54"; // mac of router
unsigned char my_ip[2]={1,1}; /// format - {network,host}
**/
unsigned char router_mac[] = "\x08\x00\x27\xdd\x6d\x32"; // mac of router .. side 2
unsigned char my_ip[2]={2,1}; /// format - {network,host}
unsigned char dest_ip[2];
unsigned char out_packet[MAX_PACK];
unsigned char c[2];
int handle , in_packet_len , i;
unsigned char in_packet[MAX_PACK];
unsigned char my_mac[6];
unsigned char type[]="\xff\xff";
unsigned char local_table[5][6];
unsigned char broadcast_mac[] = "\xff\xff\xff\xff\xff\xff";
unsigned char buffer[MAX_BUF];
int buflen;
int delimcount=0;
unsigned char tmp;
void set_up_local_table();
void get_my_mac();
void fill_packet_headers();
void fill_msg(unsigned char *msg , int length);
void send_packet();
int access_type();
int release_type();
void interrupt receiver(bp, di, si, ds, es, dx, cx, bx, ax, ip, cs, flags)
unsigned short bp, di, si, ds, es, dx, cx, bx, ax, ip, cs, flags;
{
if(ax==0)
{
if(cx>MAX_PACK)
{
es=0;
di=0;
return;
}
es=FP_SEG(in_packet);// where to store .. give it the address!
di=FP_OFF(in_packet);
in_packet_len=cx;
}
else
{
///first filter out Broadcasts and messages not meant for itself
if(memcmp(in_packet, my_mac , 6)!=0)
{
// cprintf("Not meant for me :(");
// putch('\r'); putch('\n');
return;
}
cprintf("%d.%d > ", in_packet[16] , in_packet[17]);
for(i=18;i<in_packet_len;i++)
{
if(in_packet[i]==0x00)
break;
putch(in_packet[i]);
}
putch('\r'); putch('\n');
// cprintf("Done printing msg\n");
return;
}
}
int main()
{
set_up_local_table();
get_my_mac();
input_dest_ip();
fill_packet_headers();
access_type();
buflen =0;
//Press enter twice to end
while(1)
{
tmp=getchar();
if(tmp==LF || tmp==CR)
{
if(delimcount>=1)
break;
if(buflen==0)
delimcount++;
fill_msg(buffer,buflen);
buflen=0;
send_packet();
}
else
{
delimcount=0;
buffer[buflen]=tmp;
buflen++;
}
}
release_type();
printf("Exting ..\n\r");
return 0;
}
void get_my_mac()
{
union REGS inregs,outregs;
struct SREGS segregs;
char far *bufptr;
segread(&segregs);
bufptr = (char far *)my_mac;
segregs.es = FP_SEG(bufptr);
inregs.x.di = FP_OFF(my_mac);
inregs.x.cx = 6;
inregs.h.ah = 6;
int86x(SWINT, &inregs, &outregs, &segregs);
}
void fill_packet_headers()
{
if(dest_ip[0]==my_ip[0])
memcpy(out_packet,local_table[dest_ip[1]],6);
else
memcpy(out_packet,router_mac, 6); //set the destination mac
memcpy(out_packet+6, my_mac, 6); //set the source mac
memcpy(out_packet+12, type, 2); //set the type
memcpy(out_packet+14, dest_ip ,2 );//destination ip
memcpy(out_packet+16, my_ip , 2);// source ip
}
void fill_msg(unsigned char *msg, int length)
{
memcpy(out_packet+18,msg, length);
//zero out the others
for(i=length+18;i<MAX_BUF-4;i++)
out_packet[i]=0;
}
void send_packet()
{
union REGS inregs,outregs;
struct SREGS segregs;
segread(&segregs);
inregs.h.ah = 4;
segregs.ds = FP_SEG(out_packet);
inregs.x.si = FP_OFF(out_packet);
inregs.x.cx = MAX_PACK;
int86x(SWINT,&inregs,&outregs,&segregs);
}
int access_type()
{
union REGS inregs,outregs;
struct SREGS segregs;
inregs.h.al=1; //if_class
inregs.x.bx=-1;///try changing this
inregs.h.dl=0; //if_number
inregs.x.cx=0; //typelen =0
inregs.h.ah=2; //interrupt number
segregs.es=FP_SEG(receiver);
inregs.x.di=FP_OFF(receiver);
c[0]=0xff;
c[1]=0xff;
segregs.ds=FP_SEG(c);
inregs.x.si=FP_OFF(c);
int86x(SWINT,&inregs,&outregs,&segregs);
printf("Carry Flag Access Type %d\n",outregs.x.cflag);
printf("Handle %d\n",outregs.x.ax);
handle = outregs.x.ax;
return outregs.x.cflag;
}
int release_type()
{
union REGS inregs,outregs;
struct SREGS segregs;
inregs.h.ah=3;
inregs.x.bx=handle;
int86x(SWINT,&inregs,&outregs,&segregs);
printf("Carry Flag Release Type %d\n",outregs.x.cflag);
return 0;
}
int input_dest_ip()
{
printf("Enter destination ip : ");
dest_ip[0]=getchar()-'0';
getchar();
dest_ip[1]=getchar()-'0';
getchar();
getchar();
}
void set_up_local_table()
{
/** network 1
memcpy(&local_table[1][0],"\x08\x00\x27\xE4\xEE\xD6",6);
memcpy(&local_table[2][0],"\x08\x00\x27\xA6\xCE\xE7",6);
**/
memcpy(&local_table[1][0],"\x08\x00\x27\x52\xA8\xAD",6);
memcpy(&local_table[2][0],"\x08\x00\x27\x23\x90\xBB",6);
}
|
C
|
#include <stdio.h>
main()
{
int i, num;
printf ("bang cuu chuong: ");
scanf ("%d", &num);
for (i = 1; i <= num+1; i++ )
printf ("%d x %d = %d\n", num , i, num*i);
}
|
C
|
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#define MAX_BUF 1024
int bb=1;
int aa=1;
int sockfd;
int a, b, c, d, e;
void sleep (unsigned int secs)
{
int retTime = time(0) + secs;
while (time(0) < retTime);
}
void error(char *msg)
{
perror(msg);
exit(0);
}
void sen_cerrar_socket(int signo)
{
if (signo == SIGINT)
{
printf("senial SIGINT recibida\n");
close(sockfd);
exit(1);
bb++;aa++;
}
}
int main(int argc, char *argv[])
{
char * mander_pipe = "/tmp/mander_pipe";
mkfifo(mander_pipe, 0666);
char buf[MAX_BUF];
int portno, n;
int key;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("Socket no abierto");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"No hay host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("Sin conexion");
char* charmilion_list[] = {
"display",
"0.png",
NULL
};
int init = 0;
pid_t hijo_id;
hijo_id = fork ();
int a = (int) getpid ();
if (hijo_id == 0){
int b = (int) getpid ();
execvp("display", charmilion_list);
}
else
{
int c = (int) getpid ();
hijo_id = fork ();
if(hijo_id==0){
int d = (int) getpid ();
int b =0;
do{
bzero(buffer,256);
n = read(sockfd,buffer,255);
key = open(mander_pipe, O_WRONLY);
switch(buffer[0]){
case '0':
if(b>1){
write(key, "0", sizeof("0"));
}else{b++;}
break;
case '1':
if(b>1){
write(key, "1", sizeof("1"));
}else{b++;}
break;
case '2':
if(b>1){
write(key, "2", sizeof("2"));
}else{b++;}
break;
case '3':
if(b>1){
write(key, "3", sizeof("3"));
}else{b++;}
break;
case '4':
if(b>1){
write(key, "4", sizeof("4"));
}else{b++;}
break;
case '5':
if(b>1){
write(key, "5", sizeof("5"));
}else{b++;}
break;
case '6':
if(b>1){
write(key, "6", sizeof("6"));
}else{b++;}
break;
case '7':
if(b>1){
write(key, "7", sizeof("7"));
}else{b++;}
break;
case '8':
if(b>1){
write(key, "8", sizeof("8"));
}else{b++;}
break;
case '9':
if(b>1){
write(key, "9", sizeof("9"));
}else{b++;}
break;
}
close(key);
if (signal(SIGINT, sen_cerrar_socket) == SIG_ERR){
printf("\nSin senial\n");
}
}while (bb==1);
}else{
int e = (int) getpid ();
int a=0;
do{
key = open(mander_pipe, O_RDONLY);
read(key, buf, MAX_BUF);
char a = buf[0];
switch(a){
case '0':
if(a>1){
system("display -remote 0.png");
}else{a++;}
break;
case '1':
if(a>1){
system("display -remote 1.png");
}else{a++;}
break;
case '2':
if(a>1){
system("display -remote 2.png");
}else{a++;}
break;
case '3':
if(a>1){
system("display -remote 3.png");
}else{a++;}
break;
case '4':
if(a>1){
system("display -remote 4.png");
}else{a++;}
break;
case '5':
if(a>1){
system("display -remote 5.png");
}else{a++;}
break;
case '6':
if(a>1){
system("display -remote 6.png");
}else{a++;}
break;
case '7':
if(a>1){
system("display -remote 7.png");
}else{a++;}
break;
case '8':
if(a>1){
system("display -remote 8.png");
}else{a++;}
break;
case '9':
if(a>1){
system("display -remote 9.png");
}else{a++;}
break;
}
close(key);
if (signal(SIGINT, sen_cerrar_socket) == SIG_ERR){
printf("\nCan't catch signal\n");
}
}while (aa==1);
}
}
}
|
C
|
#include "holberton.h"
/**
* case97 - prints the Error 97
*/
void case97(void)
{
dprintf(STDERR_FILENO, "Usage: cp file_from file_to\n");
exit(97);
}
/**
* case98 - prints the Error 98
*@file: takes the first argument
*/
void case98(char *file)
{
dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", file);
exit(98);
}
/**
* case99 - prints the Error 99
*@file: Takes the second argument
*/
void case99(char *file)
{
dprintf(STDERR_FILENO, "Error: Can't write to %s\n", file);
exit(99);
}
/**
* case100 - prints the 100 error
* @value: takes the number of the integer problem
*/
void case100(int value)
{
dprintf(STDERR_FILENO, "Error: Can't close fd %d\n", value);
exit(100);
}
/**
* main - checks the code
* @argc: the argument count
* @argv: the argument stored in a pointer array.
* Return: My checks
*/
int main(int argc, char *argv[])
{
int fd1 = 0, fd2 = 0, rd = 0, wr = 0, count, cs1, cs2;
char buffer[1024];
if (argc != 3)
case97();
if (argv[1] == NULL)
case98(argv[1]);
fd1 = open(argv[1], O_RDONLY);
if (fd1 == -1)
case98(argv[1]);
fd2 = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0664);
if (fd2 == -1)
case99(argv[2]);
rd = read(fd1, buffer, 1024);
if (rd == -1)
case98(argv[1]);
wr = write(fd2, buffer, rd);
if (wr == -1)
case99(argv[2]);
for (count = 0; rd == 1024; count++)
{
rd = read(fd1, buffer, 1024);
if (rd == -1)
case98(argv[1]);
wr = write(fd2, buffer, rd);
if (wr == -1)
case99(argv[2]);
}
cs1 = close(fd1);
if (cs1 == -1)
case100(fd1);
cs2 = close(fd2);
if (cs2 == -1)
case100(fd2);
return (0);
}
|
C
|
//
// OS Windows
// 2019.10.01
//
// [Algorithm Problem Solving]
//
// BAEKJOON #1436 ȭ
//
#include <stdio.h>
int sep(int n)
{
register int cnt = 0;
while (n)
{
if (n % 10 == 6) cnt++;
else cnt = 0;
if (cnt == 3) return 1;
n /= 10;
}
return 0;
}
int simul(int t)
{
register int cnt = 1, i = 666;
while (1)
{
if (cnt == t) break;
if (sep(++i)) cnt++;
}
return i;
}
int main(void)
{
freopen("input1436.txt", "r", stdin);
int N;
scanf("%d", &N);
printf("%d", simul(N));
return 0;
}
|
C
|
#ifndef _CITY_h
#define _CITY_h
#include "env.h"
#include "Stack.h"
typedef struct City* pCity;
typedef struct Branch* pBranch;
struct Branch{
pCity city; /* Pointeur sur City */
float dist; /* Distance */
pBranch next; /* Next */
} Branch;
struct City{
char* name;
float lat; // Localisation en "x" sur le plan
float lon; // Localisation en "y" sur le plan
int distFly;
pBranch branch;
/*
pCity City_create();
void City_destroy();
void City_branchLink(pCity cityA, pCity cityB, unsigned int dist);
bool City_branchAdd(pCity city, pBranch branch);
bool City_branchIsEmpty(pCity);
bool City_branchExist(pCity city, pCity cityInner);
float City_distBtw(pCity cityA, pCity B);
pBranch branch_walkToCity(pBranch branch, pCity city);
pBranch branch_walkToEnd(pBranch branch);
*/
} City;
//extern
/* Methodes City */
pCity City_create(char* name, float lat, float lon);
//pCity City_create(char* name, int distFly);
void City_destroy();
bool City_branchLink(pCity cityA, pCity cityB, unsigned int dist);
bool City_branchAdd(pCity city, pBranch branch);
bool City_branchExist(pCity city, pCity cityInner);
float City_distBtw(pCity cityA, pCity B);
/* Méthodes Branch */
pStack __Branch_malloc;
pBranch Branch_create();
pBranch Branch_walkToCity(pBranch branch, pCity city);
pBranch Branch_walkToEnd(pBranch branch);
void Branch_free();
#endif
|
C
|
#include "SPI.h";
#define SPI_SS 10
#define SPI_MOSI 11
#define SPI_MISO 12
#define SPI_SCK 13
void setup()
{
Serial.begin(9600);
setupSPI();}
/*
* Command bytes:
* a - Reset RF
* b - delay, delayTime (ms)
* c - select chip (SS)
* d - deselect chip (SS)
* e - wait MISO low
* f - SPI transfer, transferByte
*/
char inputBuffer[5];
byte bufferIndex = 0;
bool isReading = false;
void loop()
{
if (Serial.available() > 0)
{
char inChar = Serial.read();
// Filter all requests by having first char start with '{' and last char with '}'
// Prevents serial garbage from affecting the parser (e.g. other app probing all serial ports)
if (!isReading)
{
if (inChar == '{')
{
isReading = true;
}
else
{
return;
}
}
// read incoming serial data:
inputBuffer[bufferIndex] = inChar;
bufferIndex++;
if (bufferIndex == 5)
{
bufferIndex = 0;
}
if (inChar == '}')
{
isReading = false;
bufferIndex = 0;
if (inputBuffer[4] != '}')
{
// command is not terminated correctly
Serial.print("z0");
}
else
{
byte command = inputBuffer[1];
byte firstParameter = (convertCharToByte(inputBuffer[2]) << 4) | convertCharToByte(inputBuffer[3]);
if (command == 'a')
{
resetRf();
Serial.println("a1");
}
else if (command == 'b')
{
delay(firstParameter);
Serial.println("b1");
}
else if (command == 'c')
{
cc1101_Select();
Serial.println("c1");
}
else if (command == 'd')
{
cc1101_Deselect();
Serial.println("d1");
}
else if (command == 'e')
{
wait_Miso();
Serial.println("e1");
}
else if (command == 'f')
{
SPI.transfer(firstParameter);
Serial.println("f1");
}
else if (command == 'g')
{
Serial.println("ATMEGA328P PRO MINI 0.1");
}
}
}
}
}
// converts an ascii character/number to the byte equivalent
// does not perform any validation
byte convertCharToByte(char inputChar)
{
byte result = (int)inputChar;
// 57: ascii '9'
if (result > 57)
{
return result - 55;
}
else
{
return result - 48;
}
}
// Reset CC1101 (requires implementation here since microsecond delay can't be done reliably via serial)
void resetRf()
{
cc1101_Deselect();
delayMicroseconds(5);
cc1101_Select();
delayMicroseconds(10);
cc1101_Deselect();
delayMicroseconds(41);
cc1101_Select();
wait_Miso();
SPI.transfer(0x30); // SRES
wait_Miso();
cc1101_Deselect();
}
void wait_Miso()
{
while(digitalRead(SPI_MISO));
}
void cc1101_Select()
{
digitalWrite(SPI_SS, LOW);
}
void cc1101_Deselect()
{
digitalWrite(SPI_SS, HIGH);
}
void setupSPI()
{
pinMode(SPI_SS, OUTPUT);
pinMode(SPI_MISO, INPUT);
digitalWrite(SPI_SS, HIGH);
digitalWrite(SPI_SCK, HIGH);
digitalWrite(SPI_MOSI, LOW);
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
//SPI.setClockDivider(SPI_CLOCK_DIV64);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* solution.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hypark <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/11 00:46:28 by hypark #+# #+# */
/* Updated: 2019/09/13 12:28:39 by hypark ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "filler.h"
static int valid_place(t_filler *filler, int i)
{
int p_x;
int p_y;
int num_0;
num_0 = 0;
p_y = -1;
while (++p_y < P_Y)
{
p_x = -1;
while (++p_x < P_X)
{
if (P(p_x, p_y) == '*')
{
if (NOT_123(MY(i, p_x, p_y)) == 0)
return (0);
if (MY(i, p_x, p_y) == 0)
num_0++;
}
}
}
if (num_0 == 1)
return (1);
else
return (0);
}
static int cal_enemy_score(t_filler *filler, int i)
{
int p_x;
int p_y;
int total;
total = 0;
p_y = -1;
while (++p_y < P_Y)
{
p_x = -1;
while (++p_x < P_X)
{
if (P(p_x, p_y) == '*')
total += ENEMY(i, p_x, p_y);
}
}
return (total);
}
static void compare_solution(t_filler *filler, int x, int y)
{
int enemy_score;
enemy_score = cal_enemy_score(filler, I(x, y));
if (enemy_score < filler->enemy_score)
{
filler->enemy_score = enemy_score;
filler->solution = I(x, y);
}
}
void process_solution(t_filler *filler)
{
int x;
int y;
y = -1;
while (++y < (MAP_Y - P_Y + 1))
{
x = -1;
while (++x < (MAP_X - P_X + 1))
{
if (valid_place(filler, I(x, y)))
compare_solution(filler, x, y);
}
}
}
|
C
|
/*
* Adapted from http://content.gpwiki.org/SDL:Tutorial:Using_SDL_net
*
* Alexandre Lopes
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL_net.h"
int main(int argc, char **argv)
{
IPaddress ip; /* Server address */
TCPsocket sd; /* Socket descriptor */
int quit, len;
char buffer[512];
/* Simple parameter checking */
if (argc < 3)
{
fprintf(stderr, "Usage: %s host port\n", argv[0]);
exit(EXIT_FAILURE);
}
if (SDLNet_Init() < 0)
{
fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
exit(EXIT_FAILURE);
}
/* Resolve the host we are connecting to */
if (SDLNet_ResolveHost(&ip, argv[1], atoi(argv[2])) < 0)
{
fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
exit(EXIT_FAILURE);
}
/* Open a connection with the IP provided (listen on the host's port) */
if (!(sd = SDLNet_TCP_Open(&ip)))
{
fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
exit(EXIT_FAILURE);
}
/* Send messages */
quit = 0;
while (!quit)
{
printf("Write something:\n>");
scanf("%s", buffer);
len = strlen(buffer) + 1;
if (SDLNet_TCP_Send(sd, (void *)buffer, len) < len)
{
fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
exit(EXIT_FAILURE);
}
if(strcmp(buffer, "exit") == 0)
quit = 1;
if(strcmp(buffer, "quit") == 0)
quit = 1;
}
SDLNet_TCP_Close(sd);
SDLNet_Quit();
return EXIT_SUCCESS;
}
|
C
|
// Ex 3 - Quermesse
#include <stdio.h>
int sorteia(int posicao, int numIngresso){
if (posicao == numIngresso){
return numIngresso;
}
else{
return 0;
}
}
void main(){
int repeticoes, ganhador = 0, numIngresso, teste = 0, i;
while(1){
// Garante que o número de pessoas não passe 200.
do{
scanf("%d", &repeticoes);
}while(repeticoes > 200);
// Se forem "0 pessoas", então acaba o programa.
if (repeticoes == 0) break;
teste++;
for (i = 1; i <= repeticoes; i++){
scanf("%d", &numIngresso);
ganhador = sorteia(i, numIngresso);
if (ganhador > 0){
printf("Teste %d\n", teste);
printf("%d\n\n", ganhador);
}
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "db_module.h"
#include <errno.h>
char buffer[128];
char buffer2[128];
int compare(void *left, void *right) {
return(strcmp((const char *) left, (const char *) right));
}
comparator cmp = &compare;
void print_welcome(){
puts("Welcome to");
puts(" ____ ____ ");
puts("/\\ _`\\ /\\ _`\\ ");
puts("\\ \\ \\/\\ \\ \\ \\L\\ \\ ");
puts(" \\ \\ \\ \\ \\ \\ _ <\\ ");
puts(" \\ \\ \\_\\ \\ \\ \\L\\ \\ ");
puts(" \\ \\____/\\ \\____/ ");
puts(" \\/___/ \\/___/ ");
puts("");
}
void read_line(char *dest, int n, FILE *source){
fgets(dest, n, source);
int len = strlen(dest);
if(dest[len-1] == '\n')
dest[len-1] = '\0';
}
struct node *pull_database(char *filename){
printf("Loading database \"%s\"...\n\n", filename);
errno = 0;
FILE *database = fopen(filename, "r");
if (database == NULL){
//perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n ", strerror(errno));
}else{
struct node *db = NULL;
while(!(feof(database))){
read_line(buffer, 128, database);
read_line(buffer2, 128, database);
if (db == NULL){
db = create_db(buffer, buffer2);
}else{
add_item(buffer, buffer2, &db, cmp);
}
}
fclose(database);
return db;
}
return NULL;
}
void query_entry(struct node *db){
printf("Enter key: ");
read_line(buffer, 128, stdin);
puts("Searching database...\n");
struct node **found= search_entry(buffer, &db, cmp);
if (found){
char *value = extract_value(*found);
printf("Found entry:\nkey: %s\nvalue: %s\n", buffer, value);
}
else{
printf("Could not find an entry matching key \"%s\"!\n", buffer);
}
}
void update_entry(struct node *db){
printf("Enter key: ");
read_line(buffer, 128, stdin);
puts("Searching database...\n");
struct node **found= search_entry(buffer, &db, cmp);
if(found){
char *old_value = extract_value(*found);
printf("Matching entry found:\nkey: %s\nvalue: %s\n\n", buffer, old_value);
puts("Enter new value:");
read_line(buffer, 128, stdin);
update_value(found, buffer);
printf("The Value: %s updated to %s\n", old_value, buffer);
}
else{
printf("Could not find an entry matching key \"%s\"!\n", buffer);
}
}
void insert_entry(struct node **db){
struct node **found;
//separera till en hjlpfunktion
do{
puts("Enter key");
read_line(buffer, 128, stdin);
puts("Searching database for duplicate keys...");
found = search_entry(buffer, db, cmp);
if(found){
puts("key already exists, choose another one!\n");
}
} while(found);
puts("Key is unique!\nEnter value: ");
read_line(buffer2, 128, stdin);
add_item(buffer, buffer2, db, cmp);
}
void delete_entry(struct node **db){
struct node **found = NULL;
while(!found){
puts("Enter key");
read_line(buffer, 128, stdin);
puts("Searching database for the key...");
found = search_entry(buffer, db, cmp);
if(!found){
puts("Key does not exist, choose another one!\n");
}
}
char *buffer2 = extract_value(*found);
printf("Deleted the following entry:\nkey: %s\nvalue: %s\n", buffer, buffer2);
remove_item(found, db, cmp);
}
void print_database(struct node *db){
int item_num = node_amount(db);
char **item_list = (char **)all_items(db);
if (item_list != NULL){
int i;
for (i = 0; i < item_num*2; i+=2){
printf("Key: %s\n", *(item_list+i));
printf("Value: %s\n",*(item_list+i+1));
free(*(item_list+i));
free(*(item_list+i+1));
}
free(item_list);
}
}
void main_loop(struct node *db){
int choice = -1;
while(choice != 0){
puts("Please choose an operation");
puts("1. Query a key");
puts("2. Update an entry");
puts("3. New entry");
puts("4. Remove entry");
puts("5. Print database");
puts("0. Exit database");
printf("? ");
scanf("%d", &choice);
while(getchar() != '\n');
switch(choice){
case 1: //query an entry
query_entry(db);
break;
case 2: //update an existing entry
update_entry(db);
break;
case 3: //insert a new entry
insert_entry(&db);
break;
case 4: //deletes an entry
delete_entry(&db);
break;
case 5: //prints the whole database
print_database(db);
break;
case 0: // Exit
puts("Good bye!");
destroy_db(db);
break;
default:
// Please try again
puts("Could not parse choice! Please try again");
}
puts("");
}
}
int main(int argc, char *argv[]){
if (argc < 2){
puts("Usage: db [FILE]");
return -1;
}
print_welcome();
struct node *db = pull_database (argv[1]);
if (db) main_loop(db);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct node{
struct tm date;
int priority;
char task[100];
struct node *next;
int status; // 1 if completed, 0 if not
};
void insert(struct node**);
void task_completed(struct node**);
void display(struct node*);
void delete_task(struct node**);
|
C
|
#ifndef __FIBER_H__
#define __FIBER_H__
#if defined (__cplusplus)
extern "C" {
#endif
#include <ucontext.h>
#define STACK_SIZE (128 * 1024)
typedef enum {
NEW,
SUSPENDED,
RUNNING,
TERMINATED
} fiber_state;
typedef void (*fiber_func)(void *arg);
typedef struct fiber fiber;
typedef struct scheduler scheduler;
struct scheduler {
char stack[STACK_SIZE]; // copy-stack
ucontext_t main;
int id_count;
fiber *running_fiber;
fiber *fiber_list;
};
struct fiber {
int id;
ucontext_t ctx;
scheduler *sched;
fiber_func func;
void *arg;
fiber_state state;
char *stack;
int size;
char *high;
char *low;
fiber *next;
};
scheduler *fiber_open();
void fiber_close(scheduler *sched);
int fiber_new(scheduler *sched, fiber_func func, void *arg);
void fiber_resume(scheduler *sched, int id);
void fiber_yield(scheduler *sched);
#if defined (__cplusplus)
}
#endif
#endif
|
C
|
#include "headers.h"
int signalFlag1 = 0;
void signalHandler1(int sig)
{
signalFlag1 = 1;
return;
}
void shell_clock(char** command)
{
int i,j = 1;
int tflag = 0; // for interval
int nflag = 0; // for duration
signalFlag1 = 0;
// flag == 1 -> argument for number of seconds in pending
while(command[j] != NULL)
{
if(!strcmp(command[j], "-t"))
{
if(tflag != 0 || nflag == 1)
{
perror("Usage: clock -t <interval in digits> -n <duration in digits>\n");
return;
}
tflag++;
j++;
continue;
}
if(!strcmp(command[j], "-n"))
{
if(nflag != 0 || tflag == 1)
{
perror("Usage: clock -t <interval in digits> -n <duration in digits>\n");
return;
}
nflag++;
j++;
continue;
}
if((tflag == 1 && nflag == 1) || (tflag != 1 && nflag != 1))
{
perror("Usage: clock -t <interval in digits> -n <duration in digits>\n");
return;
}
for(i = 0;i < strlen(command[j]);i++)
{
if(command[j][i] > '9' || command[j][i] < '0')
{
perror("Usage: clock -t <interval in digits> -n <duration in digits>\n");
return;
}
}
if(tflag == 1)
tflag = atoi(command[j]);
else
nflag = atoi(command[j]);
j++;
}
time_t initial_time = time(NULL);
int pid = fork();
if(pid == 0)
{
if(nflag == 0)
nflag = 100000;
if(tflag == 0)
tflag = 1;
while(1)
{
signal(SIGINT, signalHandler1);
if(signalFlag1 == 1)
{
signalFlag1 = 0;
break;
}
if(time(NULL) - initial_time >= nflag)
break;
char path[20] = "/proc/driver/rtc";
char clock[50] = {'\0'};
FILE *fp = fopen(path, "r");
for(i = 0;i < 6;i++)
{
fscanf(fp, "%s", clock);
if(i == 2 || i == 5)
printf("%s ", clock);
}
printf("\n");
if(nflag + initial_time - time(NULL) <= tflag)
sleep(nflag + initial_time - time(NULL));
else
sleep(tflag);
}
kill(getpid(), SIGQUIT);
}
else
{
int status;
while(wait(&status) != pid)
continue;
}
return;
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_rotate_right - rotate to the right
* @tree: is a pointer to the root node of the tree to traverse
* Return: void
*/
binary_tree_t *binary_tree_rotate_right(binary_tree_t *tree)
{
binary_tree_t *new;
if (tree == NULL)
return (NULL);
new = tree;
tree = tree->left;
if (tree->right != NULL)
{
new->left = tree->right;
tree->right->parent = new;
}
else
new->left = NULL;
new->parent = tree;
tree->right = new;
return (tree);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int p, i, j, k;
scanf("%d", &p);
for (i=1; i<=p-2; i++)
for (j=1; j<=p-i-1; j++)
{
k = p-i-j;
if (i+j > k && i+k > j && j+k >i)
printf("%d %d %d\n", i, j, k);
}
return 0;
}
|
C
|
#include<stdio.h>
/*
Recursion is the process which comes into existence when a function calls a copy of itself
to work on a smaller problem. Any function which calls itself is called recursive function,
and such function calls are called recursive calls. Recursion involves several numbers of recursive calls.
However, it is important to impose a termination condition of recursion. Recursion code is shorter
than iterative code however it is difficult to understand.
*/
int getInt()
{
int temp;
printf("Enter Number : ");scanf("%d",&temp);
return temp;
}
// void show()
// {
// static int count = 0;
// printf("show-%d to show-%d\n",count,count+1);
// count++;
// if(count<=10)
// show();
// printf("back to %d\n",count--);
// }
void loop(int start,int end)
{
printf("%d ",start);
if(start<end)
loop(start+1,end);
}
void For()
{
static int i=0;
printf("%d ",i++);
}
void main()
{
loop(0,10);
printf("\n**************************\n");
for(int i=0;i<=10;i++)
{
printf("%d ",i);
}
printf("\n**************************\n");
For();
For();
For();
For();
For();
For();
For();
For();
For();
For();
For();
}
|
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 */
struct hpet_info {int hi_ireqfreq; int hi_flags; int hi_hpet; int hi_timer; } ;
/* Variables and functions */
int /*<<< orphan*/ HPET_INFO ;
int /*<<< orphan*/ O_RDONLY ;
int /*<<< orphan*/ close (int) ;
int /*<<< orphan*/ fprintf (int /*<<< orphan*/ ,char*,...) ;
scalar_t__ ioctl (int,int /*<<< orphan*/ ,struct hpet_info*) ;
int open (char const*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ stderr ;
void
hpet_info(int argc, const char **argv)
{
struct hpet_info info;
int fd;
if (argc != 1) {
fprintf(stderr, "hpet_info: device-name\n");
return;
}
fd = open(argv[0], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "hpet_info: open of %s failed\n", argv[0]);
return;
}
if (ioctl(fd, HPET_INFO, &info) < 0) {
fprintf(stderr, "hpet_info: failed to get info\n");
goto out;
}
fprintf(stderr, "hpet_info: hi_irqfreq 0x%lx hi_flags 0x%lx ",
info.hi_ireqfreq, info.hi_flags);
fprintf(stderr, "hi_hpet %d hi_timer %d\n",
info.hi_hpet, info.hi_timer);
out:
close(fd);
return;
}
|
C
|
// Copyright 2021 Dumistracel Eduard-Costin
#include "all.h"
void print_shw(dll *list_planet, char *index) {
if (list_planet->size == 0) {
printf("Planet out of bounds!\n");
return;
}
unsigned count = atoi(index);
if (count > list_planet->size - 1) {
printf("Planet out of bounds!\n");
return;
}
unsigned i;
node *head = list_planet->head;
for (i = 0; i < count; ++i) {
head = head->next;
}
printf("NAME: %s\n", ((planet *)head->data)->name);
if (list_planet->size == 1) {
printf("CLOSEST: none\n");
} else if (list_planet->size == 2){
printf("CLOSEST: %s\n", ((planet *)head->next->data)->name);
} else {
printf("CLOSEST: %s and ", ((planet *)head->prev->data)->name);
printf("%s\n", ((planet *)head->next->data)->name);
}
node *current = ((planet *)(head->data))->shields->head;
printf("SHIELDS: ");
unsigned number_shields = ((planet *)(head->data))->shields->size;
for (i = 0; i < number_shields; ++i) {
printf("%d ", *((int*)current->data));
current = current->next;
}
printf("\n");
printf("KILLED: %d\n", ((planet *)(head->data))->kills);
}
|
C
|
#define ANIO_ACTUAL 2018
typedef struct
{
int dia;
int mes;
int anio;
}eFecha;
/** \brief Solicita una fecha al usuario y la devuelve.
*
* \param void
* \return eFecha
*
*/
eFecha pedir_eFecha(void);
/** \brief Muestra la fecha.
*
* \param fecha eFecha Es la fecha a mostrar.
* \return void
*
*/
void mostrar_eFecha(eFecha fecha);
|
C
|
#include<stdio.h>
int main()
{
int A[1000000000];
int i,N,last_digit;
scanf("%d",&N);
for(i=0;i<N;i++)
{
scanf("\n%d",&A[i]);
}
last_digit=A[N-1]%10;
if(last_digit==0)
printf("\nYES");
else
printf("\nNo");
return 0;
}
|
C
|
/*
* Wrapper functions for our own library functions.
* Most are included in the source file for the function itself.
*/
#include "unp.h"
#include <math.h>
const char* Inet_ntop(int family, const void *addrptr, char *strptr, size_t len)
{
const char *ptr;
if (strptr == NULL) /* check for old code */
{
err_quit("NULL 3rd argument to inet_ntop");
}
if ( (ptr = inet_ntop(family, addrptr, strptr, len)) == NULL)
{
err_sys("inet_ntop error"); /* sets errno */
}
return(ptr);
}
void Inet_pton(int family, const char *strptr, void *addrptr)
{
int n;
if ( (n = inet_pton(family, strptr, addrptr)) < 0)
{
err_sys("inet_pton error for %s", strptr); /* errno set */
}
else if (n == 0)
{
err_quit("inet_pton error for %s", strptr); /* errno not set */
}
/* nothing to return */
}
/**
* 获取最高阶
*/
static int _get_order_num(int value, int* ret)
{
int order = 1;
while((value=value/10) > 10)
{
order++;
}
*(ret) = value%10;
return order;
}
char* itoa(int value, char* str, int radix)
{
int i = 0;
int order = 0;
int ret = 0;
while(value>=10 && (order = _get_order_num(value, &ret)))
{
value -= ret * pow(10, order);
str[i] = 48 + ret;
order = 0;
i++;
}
str[i] = 48+value;
return str;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "sys/wait.h"
int main(int argc, char* argv[]) {
pid_t child;
child = fork(); //create A and B, B is child of A
if (child == -1) {
perror("Error");
exit(1);
}
else if (child == 0) { //inside B process
pid_t childB;
childB = fork(); //create E is child of B
if (childB == -1) {
perror("Error B");
exit(1);
}
else if (childB == 0) { //inside E process
printf("E"); //print E
fflush(stdout);
}
else { //inside B process
pid_t childB1;
childB1 = fork(); // create F is child of B
if (childB1 == 0) {
wait(NULL); // wait E is child of B process complete A
printf("F"); /*print F / | \ */
fflush(stdout); // B C D
} /* / \ | */
else { /* E F G */
wait(NULL); /* wait F is child of B process complete | */
printf("B"); //print B I
fflush(stdout);
}
}
}
else { //inside A process
wait(NULL); //wait B is child of A process complete
pid_t child1;
child1 = fork(); //create C is child of A
if (child1 == -1) {
perror("Error C");
exit(1);
}
else if (child1 == 0) { //inside C process
pid_t childC;
childC = fork(); //create G is child of C
if (childC == -1) {
perror("Error G");
exit(1);
}
else if (childC == 0){ //inside G process
pid_t childG;
childG = fork(); //create I is child of G
if (childG == -1) {
perror("Error I");
exit(1);
}
else if (childG == 0){ //inside I process
printf("I"); //print I
fflush(stdout);
}
else {
wait(NULL); //wait I is child of G process complete
printf("G"); //print G
fflush(stdout);
}
}
else {
wait(NULL); //wait G is child of C process complete
printf("C"); //print C
fflush(stdout);
}
}
else { //inside A process
wait(NULL); //wait C is child of A process complete
pid_t child2;
child2 = fork(); //create D is child of A
if (child2 == -1) {
perror("Error D");
exit(1);
}
else if (child2 == 0) { //inside D process
printf("D"); //print D
fflush(stdout);
}
else {
wait(NULL); //wait D is child of A process complete
printf("A"); //print A
fflush(stdout);
}
}
}
return 0;
}
|
C
|
// sum3str.c: sum 3 hardcoded strings
#include <stdio.h>
#include <stdlib.h>
int main() {
char *r = "1";
char *s = "23";
char *t = "456";
int i, j, k;
if ((sscanf(r, "%d", &i) == 1) &&
(sscanf(s, "%d", &j) == 1) &&
(sscanf(t, "%d", &k) == 1)) {
printf("%d\n", i+j+k);
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
long lastVal = LONG_MIN;
bool isValidBST(struct TreeNode * root) {
if (!root) return true;
if (!isValidBST(root->left)) return false;
if (root->val <= lastVal) return false;
lastVal = (long)root->val;
if (!isValidBST(root->right)) return false;
return true;
}
int main(void) {
struct TreeNode *node1 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
struct TreeNode *node2 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
struct TreeNode *node3 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node1->val = 2; node2->val = 1; node3->val = 3;
node1->left = node2; node1->right = node3;
node2->left = NULL; node2->right = NULL; node3->left = NULL; node3->right = NULL;
printf("%s\n", isValidBST(node1) ? "true" : "false");
free(node1);
free(node2);
free(node3);
}
|
C
|
#include <stdio.h>
void main()
{
int a,n,d,sn;
scanf("%d%d%d",&n,&a,&d);
sn=(n*(2*a+(n-1)*d))/2;
printf("sum is %d",sn);
getch();
}
|
C
|
/*
** my_strlen.c for 42sh in /home/arrazo_p/semestre2/SystemeUnix/PSU_2014_minishell2/sources
**
** Made by arrazolaleon pedroantonio
** Login <[email protected]>
**
** Started on Thu Feb 12 18:39:37 2015 arrazolaleon pedroantonio
** Last update Sun May 24 14:53:18 2015 Vatinelle Maxime
*/
#include "../42sh.h"
int my_strlen(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
i++;
return (i);
}
|
C
|
/* FILE DESCROPTION
*
* FILE NAME : d3tcol.c
* ROUTINE : o
* REVISION :
* REMARKS : 88.01.09 s.aizawa
*/
#include <stdio.h>
#include "la_ws/include/d3libc.h"
extern struct dsm *d3gcmp();
static char sccsid[]="@(#)d3tcol.c 1.3 88/06/12 14:56:47";
/* FUNCTION DESCRIPTION
*
* FUNC.NAME : d3tcol()
* INPUT : dsp = data set pointer
* OUTPUT : return value = error code
* REMARKS :
*/
d3tcol(dsp)
DSET *dsp;
{
struct dsm *datp, *dimp;
if ((datp = d3gcmp(dsp->ds_entry, "Dat")) == NULL) /* search "Dat" */
return(DE_DS_FORMAT);
if ((dimp = d3gcmp(datp, "Dim")) == NULL) /* seatch "Dim" */
return(0);
return(dimp->ptr.i[1]);
}
|
C
|
/**
* @file threadPoolHandler.h
* @brief Contiene funzioni per creare o distruggere thread e per definire la struttura del pool
*
\author Michele Morisco 505252
Si dichiara che il contenuto di questo file e' in ogni sua parte opera
originale dell'autore
*/
#ifndef THREADPOOLHANDLER_H_
#define THREADPOOLHANDLER_H_
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <configSetup.h>
/**
* @struct threadPoolCreator
* @brief struttura di un pool di thread
*
* @var receiver nickname del ricevente
* @var len lunghezza del buffer dati
*/
typedef struct threadPool{
void *(*function) (void *);
void *(*cleanup) (void *);
void *argc;
void *argt;
ConfigureSetup cf;
}threadPoolCreator;
/**
* @function ThreadF
* @brief rappresenta un singolo thread
*
* @param arg prende una struttura threadPool
*
*/
void *ThreadF(void *arg);
/**
* @function poolCreator
* @brief crea un pool di thread
*
* @param arg prende una struttura threadPool
*
*/
void *poolCreator(void *arg);
/**
* @function poolDestroy
* @brief distrugge un pool di thread
*
* @param arg prende una struttura threadPool
*
*/
void *poolDestroy(void *arg);
/**
* @function clean_upPool
* @brief clean_up di un pool di thread
*
* @param arg prende una struttura threadPool
*
*/
void clean_upPool(void *arg);
#endif /* THREADPOOLHANDLER_H_ */
|
C
|
#include<linux/kernel.h>
#include<linux/version.h>
#include<linux/module.h>
#include<linux/fs.h>
#include<linux/cdev.h>
#define DEVICE "alloc_naresh"
static dev_t dev_alloc;
static struct cdev* cdev_naresh;
static int major=0;
static int count=1;
static int inuse=0;
// ssize_t read (struct file * file, char __user * user_buf, size_t len, loff_t * loff){
//
//
// return 0;
// }
ssize_t chr_write (struct file * file, const char __user * user_buf, size_t len, loff_t * loff){
printk("received bytes is %s\n",user_buf);
return 0;
}
int chr_open(struct inode * inode, struct file * file){
if(inuse){
printk("ERROR IN OPENING\n");
return -1;
}
inuse=1;
return 0;
}
int chr_release (struct inode * inode, struct file * file){
inuse=0;
printk("RELEASED SUCCESSFULLY\n");
return 0;
}
struct file_operations fops_alloc={
.owner=THIS_MODULE,
.open=chr_open,
.release= chr_release,
.write = chr_write
};
static int chr_init(void){
if(alloc_chrdev_region(&dev_alloc,0,count,DEVICE)<0){
printk("ERROR IN ALLOCATION OF CHRDEV\n");
return -1;
}
if((cdev_naresh=cdev_alloc())==NULL){
printk("ERROR IN DEVICE ALLOCATION\n");
unregister_chrdev_region(dev_alloc,count);
return -1;
}
cdev_init(cdev_naresh,&fops_alloc);
if(cdev_add(cdev_naresh,dev_alloc,count)<0){
printk("ERROR IN DEVICE CHAR DEVICE ADDTION\n");
cdev_del(cdev_naresh);
unregister_chrdev_region(dev_alloc,count);
return -1;
}
printk("SUCCESSFULLY CREATED ALLOC_CHRDEVICE of major=%d DEVICE NAME=%s \n",MAJOR(dev_alloc),DEVICE);
return 0;
}
static void chr_exit(void){
cdev_del(cdev_naresh);
unregister_chrdev_region(dev_alloc,count);
printk("MODULE RELEASED \n");
}
module_init(chr_init);
module_exit(chr_exit);
MODULE_LICENSE("GPL");
|
C
|
#include<stdio.h>
int main()
{
int a[10][10],transpose[10][10],r,c,i,j;
printf("Enter rows and columns of the matrix:");
scanf("%d %d",&r,&c);
printf("\n Enter elements of the matrix:\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
transpose[j][i]=a[i][j];
}
printf("\n Transpose of matrix:\n");
for(i=0;i<c;i++)
for(j=0;j<r;j++)
printf("%d",transpose[i][j]);
printf("\t");
printf("\n");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.