I am beginning a personal project of converting an interpreter written in python into C. It is purely for learning purposes.
The first thing I have come across is trying to convert the following:
if __name__ == "__main__":
if not argv[-1].endswith('.py'):
...
And I have done the following conversion thus far for the endswith
method
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool endswith(char* str, char* substr)
{
// case1: one of the strings is empty
if (!str || !substr) return false;
char* start_of_substring = strstr(str, substr);
// case2: not in substring
if (!start_of_substring) return false;
size_t length_of_string = strlen(str);
size_t length_of_substring = strlen(substr);
size_t index_of_match = start_of_substring - str;
// case2: check if at end
return (length_of_string == length_of_substring + index_of_match);
}
int main(int argc, char* argv[])
{
char *last_arg = argv[argc-1];
if (endswith(last_arg, ".py")) {
// ...
}
}
Does this look like it's covering all the cases in an endswith
, or am I missing some edge cases? If so, how can this be improved and such? Finally, this isn't a criticism but more a genuine question in writing a C application: is it common that writing C will require 5-10x more code than doing the same thing in python (or is that more because I'm a beginner and don't know how to do things properly?)
And related: https://codereview.stackexchange.com/questions/54722/determine-if-one-string-occurs-at-the-end-of-another/54724