Created
November 20, 2016 23:55
-
-
Save alexanderankin/4b01dd9a509972be27179cd1a7a70934 to your computer and use it in GitHub Desktop.
Iterator for C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Learning Abstraction With C | |
* | |
* make with: cc iteratordemo.c -o iteratordemo -g | |
* | |
* works as ./iteratordemo, doesnt work as: | |
* $ valgrind --leak-check=full ./iteratordemo | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
typedef char *(iterator_function)(void); | |
char *stdin_line(void); | |
char *stdin_line(void) { | |
int c, result_size = 0; | |
char *result; | |
result = malloc(1); | |
while (1) { | |
c = getchar(); | |
if (c == '\0' || c == EOF || c == '\n') break; | |
result[result_size] = c; | |
result = realloc(result, ++result_size); | |
} | |
result[result_size] = '\0'; | |
return result; | |
} | |
char *adjacent_file_line(void); | |
FILE *adjacent_file_line_file; | |
char *adjacent_file_line(void) { | |
int c, result_size = 0; | |
char *result; | |
result = malloc(1); | |
if (!adjacent_file_line_file) { result[0] = '\0'; return result; } | |
while (1) { | |
c = fgetc(adjacent_file_line_file); | |
if (c == '\0' || c == EOF || c == '\n') break; | |
result[result_size] = c; | |
result = realloc(result, ++result_size); | |
} | |
result[result_size] = '\0'; | |
return result; | |
} | |
void printNLines(iterator_function, int); | |
void printNLines(iterator_function next, int count) { | |
char *response; | |
for (int i = 0; i < count; ++i) { | |
response = next(); | |
printf("%s\n", response); | |
free(response); | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
/* in the future, could switch on argc/v */ | |
// printNLines(stdin_line, 3); | |
adjacent_file_line_file = fopen("./adjacent_file", "r"); | |
printNLines(adjacent_file_line, 3); | |
fclose(adjacent_file_line_file); | |
adjacent_file_line_file = NULL; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment