68 lines
1.4 KiB
C
68 lines
1.4 KiB
C
|
#include "utils.h"
|
||
|
|
||
|
#include <sys/stat.h>
|
||
|
|
||
|
struct string *pad_int(int n, uint pad, uint maxsize) {
|
||
|
struct string *str = (struct string *)malloc(sizeof (struct string) + 1);
|
||
|
maxsize++;
|
||
|
|
||
|
str->s = (char *)malloc((sizeof(char) * maxsize) + 1);
|
||
|
str->length = 0;
|
||
|
|
||
|
memset(str->s, 0, maxsize);
|
||
|
|
||
|
// Figure out how many place values are in n
|
||
|
int _n = abs(n);
|
||
|
uint places = 1;
|
||
|
|
||
|
for (uint i = 0; i < pad; i++) {
|
||
|
if (_n >= 10) {
|
||
|
_n /= 10;
|
||
|
places++;
|
||
|
}
|
||
|
else break;
|
||
|
}
|
||
|
|
||
|
char *padding = (char *)malloc((sizeof(char) * pad) + 1);
|
||
|
for (uint i = 0; i < pad; i++)
|
||
|
padding[i] = '0';
|
||
|
|
||
|
uint required_padding = pad - places;
|
||
|
if (required_padding > pad) required_padding = 0;
|
||
|
|
||
|
snprintf(str->s, maxsize, "%*.*s%i%c", 0, required_padding, padding, abs(n), 0);
|
||
|
free(padding);
|
||
|
|
||
|
for (uint i = 0; i < maxsize + 1; i++) {
|
||
|
if (str->s[i] == 0) {
|
||
|
str->length = i;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return str;
|
||
|
}
|
||
|
|
||
|
// alloc_string
|
||
|
struct string *alloc_string(uint l) {
|
||
|
struct string *s = (struct string *)malloc(sizeof(struct string) + 1);
|
||
|
s->s = (char *)malloc(l + 1);
|
||
|
s->length = l;
|
||
|
|
||
|
memset(s->s, 0, l);
|
||
|
|
||
|
return s;
|
||
|
}
|
||
|
|
||
|
// free_string
|
||
|
void free_string(struct string *s) {
|
||
|
free(s->s);
|
||
|
free(s);
|
||
|
}
|
||
|
|
||
|
uint load_highscore() {
|
||
|
char *home = getenv("HOME");
|
||
|
allocm(struct stat, s);
|
||
|
stat("", s);
|
||
|
}
|