Skip to content

Commit c486628

Browse files
committed
Added some trimming
1 parent 67548ca commit c486628

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/as4.c

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,9 @@ int main(int argc, char **argv)
134134
/* Loop until we've gotten every token on this line. */
135135
while(tokens != NULL)
136136
{
137+
/* Trim the whitespace */
138+
tokens = trim(tokens);
139+
137140
/* If we get to a ; or # on the line, ignore the rest. Allows inline comments */
138141
if(tokens[0] == ';' || tokens[0] == '#')
139142
{
@@ -642,6 +645,50 @@ int main(int argc, char **argv)
642645
/* This is the end of successful program execution. */
643646
}
644647

648+
/* Whitespace trimming function. */
649+
char *trim(char *str)
650+
{
651+
unsigned int i = 0;
652+
unsigned int j = 0;
653+
char empty[1] = {'\0'};
654+
char *retstr = NULL;
655+
656+
if(str == NULL)
657+
{
658+
return NULL;
659+
}
660+
/* Trim leading whitespace */
661+
while(isspace((unsigned char)str[i]))
662+
{
663+
i++;
664+
/* If we travel past the end of the string, the string is empty. */
665+
if(i > strlen(str))
666+
{
667+
retstr = empty;
668+
return retstr;
669+
}
670+
}
671+
retstr = calloc(1, strlen(str));
672+
if(retstr == NULL)
673+
{
674+
perror("Could not allocate memory");
675+
exit(4);
676+
}
677+
/* Trim trailing whitespace. */
678+
for(i = i, j = 0; i < strlen(str) && j < strlen(str); i++, j++)
679+
{
680+
if(isspace((unsigned char)str[i]))
681+
{
682+
break;
683+
}
684+
retstr[j] = str[i];
685+
}
686+
/* Terminate the string here as it is the end, and stop some potential weirdness. */
687+
retstr[j] = '\0';
688+
689+
return retstr;
690+
}
691+
645692
/* Help() prints the help. More useful in large programs */
646693
void help(void)
647694
{

src/as4.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,7 @@ long estrtol(char *str, char **endptr, uint8_t type);
7575

7676
unsigned long estrtoul(char *str, char **endptr, uint8_t type);
7777

78+
/* Whitespace trimming function. */
79+
char *trim(char *str);
80+
7881
#endif /* _AS4_H_ */

0 commit comments

Comments
 (0)