Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Refactor of: http://codereview.stackexchange.com/questions/142101/did-you-twist-my-words
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #include <string.h>
- bool streq(char *s1, char *s2);
- bool streq_circular(char *s1, char *s1_base, char *s2);
- bool strstr_circular(char *haystack, char *needle);
- char *tokenize(char *buf, char *delim);
- char *next_token(char *buf);
- char *jump_token(char *buf, int n);
- void parse_buffer(char *buf);
- void die(char *err);
- FILE *get_file_from_args(char **args);
- size_t get_file_length(FILE *file);
- char *copy_file(FILE *file);
- bool
- streq(char *s1, char *s2)
- {
- for(; *s1 && *s2; s1++, s2++)
- if(*s1 != *s2)
- return false;
- return true;
- }
- bool
- streq_circular(char *s1, char *s1_base, char *s2)
- {
- char *s2_offset = s2 + strlen(s1);
- return streq(s1, s2) && streq(s1_base, s2_offset);
- }
- bool
- strstr_circular(char *haystack, char *needle)
- {
- if(!needle || !haystack || strlen(needle) != strlen(haystack))
- return false;
- for(char *hs_base = haystack; haystack && haystack[0]; haystack = strchr(haystack + 1, *needle))
- if(streq_circular(haystack, hs_base, needle))
- return true;
- return false;
- }
- char *
- tokenize(char *buf, char *delim)
- {
- char *base = buf;
- for(; *buf; buf++)
- if(strchr(delim, *buf))
- *buf = '\0';
- return base;
- }
- char *
- next_token(char *buf)
- {
- if(buf == NULL)
- return NULL;
- while(*(buf++));
- return *buf ? buf : NULL;
- }
- char *
- jump_token(char *buf, int n)
- {
- while(n--)
- buf = next_token(buf);
- return buf;
- }
- void
- parse_buffer(char *buf)
- {
- bool is_rotated;
- for(buf = tokenize(buf, ",\n\r"); buf != NULL; buf = jump_token(buf, 2)){
- is_rotated = strstr_circular(buf, next_token(buf));
- puts(is_rotated ? "True" : "False");
- }
- }
- void
- die(char *err)
- {
- fprintf(stderr, "Error: %s\n", err);
- exit(1);
- }
- FILE *
- get_file_from_args(char **args)
- {
- FILE *out;
- if(!args[1])
- die("No file was provided");
- out = fopen(args[1], "r");
- if(out == NULL)
- die("Could not open file");
- return out;
- }
- size_t
- get_file_length(FILE *file)
- {
- size_t length;
- fseek(file, 0, SEEK_END);
- length = ftell(file);
- fseek(file, 0, SEEK_SET);
- return length;
- }
- char *
- copy_file(FILE *file)
- {
- size_t file_length = get_file_length(file);
- char *out = calloc(1, file_length + 2);
- if(out == NULL)
- die("Could not allocate memory");
- fread(out, 1, file_length, file);
- return out;
- }
- int
- main(int argc, char **args)
- {
- FILE *file = get_file_from_args(args);
- char *fbuf = copy_file(file);
- fclose(file);
- parse_buffer(fbuf);
- free(fbuf);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement