Created
March 18, 2015 15:39
-
-
Save perillamint/a7fe1a04292b9b182ed8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#define CHUNK_SIZE 128 | |
//I will not use NULL terminated string for performance. | |
typedef struct charwithlen_struct { | |
char *data; | |
size_t len; | |
} charwithlen_t; | |
charwithlen_t nullappend = { | |
.data = "\0", | |
.len = 1 | |
}; | |
int append_data(charwithlen_t *target, charwithlen_t *appenddata) { | |
target -> data = realloc(target -> data, target -> len + appenddata -> len); | |
if (target -> data == NULL) { | |
exit(-1); | |
} | |
memcpy(target -> data + target -> len, appenddata -> data, appenddata -> len); | |
target -> len = target -> len + appenddata -> len; | |
} | |
int main(int argc, char **argv) { | |
charwithlen_t chunk; | |
chunk.data = malloc(CHUNK_SIZE); | |
chunk.len = 0; | |
charwithlen_t readdata = { | |
.data = NULL, | |
.len = 0 | |
}; | |
charwithlen_t writedata = { | |
.data = NULL, | |
.len = 0 | |
}; | |
charwithlen_t buf; | |
buf.data = malloc(1000); | |
buf.len = 0; | |
do { | |
char str[1000]; | |
int read_ret = read(STDIN_FILENO, chunk.data, 10); | |
if(read_ret < 0) { | |
break; | |
} else { | |
chunk.len = read_ret; | |
} | |
int len = sprintf(str, "%d", chunk.len); | |
if(chunk.len != 0) | |
append_data(&readdata, &chunk); | |
} while (chunk.len != 0); | |
append_data(&readdata, &nullappend); | |
int a, b; | |
sscanf(readdata.data, "%d %d", &a, &b); | |
buf.len = snprintf(buf.data, 1000, "%d", a+b); | |
append_data(&writedata, &buf); | |
write(STDOUT_FILENO, buf.data, buf.len); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment