Skip to content

Instantly share code, notes, and snippets.

@rellfy
Created November 12, 2020 09:09
Show Gist options
  • Save rellfy/4bda29ff525ac6d97de3d0d997f23c2d to your computer and use it in GitHub Desktop.
Save rellfy/4bda29ff525ac6d97de3d0d997f23c2d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
void *getlines(char *file);
int main(int argc, char **argv) {
if (argc != 2) {
printf("usage: <file>\n");
return 1;
}
char *file = argv[1];
printf("reading file %s\n", file);
// Get lines.
void *lines = getlines(file);
int *line_count = ((int *)lines)[0];
printf("line count: %d\n", line_count);
// Print lines.
for (int i = 1; i <= line_count; i++) {
char *line = ((char **)lines)[i];
printf("line %d: %s\n", i, line);
}
return 0;
}
void *getlines(char *file) {
// Set first pointer to integer containing line count.
void *lines = malloc(sizeof(void *));
((int *)lines)[0] = malloc(sizeof(int));
// Keep a stack value for line count.
int line_count = 0;
((int *)lines)[0] = line_count;
FILE *fp = fopen(file, "r");
char *line = NULL;
size_t buffer_size = 0;
ssize_t line_length;
if (fp == NULL)
exit(1);
while (line_length = getline(&line, &buffer_size, fp) != -1) {
line_length = strlen(line);
// Increase line count value.
line_count += 1;
((int *)lines)[0] = line_count;
// Allocate memory for line.
lines = realloc(lines, sizeof(void *) * (line_count + 2));
((char **)lines)[line_count] = malloc(line_length);
// Copy current line to allocated array.
memcpy(((char **)lines)[line_count], line, line_length);
// Set last character to null.
((char **)lines)[line_count][line_length - 1] = '\0';
}
fclose(fp);
return lines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment