c-preprocessor/utils.c

154 lines
2.2 KiB
C

#include "utils.h"
#include "pp_defines.h"
#include "pp_line_id.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int write_line_to_file(FILE *f, char *line)
{
int line_len;
int written;
line_len = strlen(line);
written = fprintf(f, "%s", line);
if (written < 0 || written != line_len)
return -1;
return 0;
}
char *l_strdup(char *s)
{
int size;
char *p;
if (!s)
return NULL;
size = strlen(s) + 1;
p = calloc(size, sizeof(char));
if (p)
memcpy(p, s, size);
return p;
}
void strip_spaces_in_def(char *def)
{
int i;
int x;
int in_quotes;
in_quotes = 0;
for (i = x = 0; def[i]; i++) {
if (i > 0 && def[i] == '\"' && def[i - 1] != '\\' && !in_quotes)
in_quotes = 1;
else if (i > 0 && def[i] == '\"' && def[i - 1] != '\\'
&& in_quotes)
in_quotes = 0;
if (!in_quotes && (!isspace(def[i]) || (i > 0
&& !isspace(def[i - 1]))))
def[x++] = def[i];
else if (in_quotes)
x++;
}
def[x] = 0x00;
}
int a_strcat(char **dest, char *src)
{
char *result;
char *temp;
int needed;
needed = strlen(*dest) + strlen(src) + 1;
result = calloc(needed, sizeof(char));
if (!result)
return -1;
sprintf(result, "%s%s", *dest, src);
temp = *dest;
*dest = result;
free(temp);
return 0;
}
int get_next_whitespace_idx(char *s)
{
int c;
c = 0;
while (!isspace(*s)) {
s++;
c++;
}
return c;
}
char *skip_word(char *s)
{
char *_s;
_s = s;
while (!isspace(*_s))
_s++;
_s++;
return _s;
}
int is_cond_null(char *cond_line)
{
char *cond;
cond = NULL;
if (!strncmp(cond_line, IF_LINE_START, IF_LINE_START_SZ))
cond = cond_line + IF_LINE_START_SZ;
else if (!strncmp(cond_line, ELIF_LINE_START, ELIF_LINE_START_SZ))
cond = cond_line + ELIF_LINE_START_SZ;
if (!cond)
return 0;
return cond[0] == '0';
}
int skip_until(FILE *f, int until)
{
char line[PP_LINE_LEN + 1];
int line_len;
int res;
while (fgets(line, PP_LINE_LEN, f)) {
if (until == SKIP_UNTIL_CURR_BRANCH_END
&& IS_IF_CURR_BRANCH_END(line))
break;
if (until == SKIP_UNTIL_ENDIF_LINE && IS_ENDIF_LINE(line))
break;
}
line_len = strlen(line);
res = fseek(f, -line_len, SEEK_CUR);
if (res == -1)
return -1;
return 0;
}