Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define NULL_CHECK(p) if (p == NULL) return NULL;
- #define CHUNK_CHARS 32
- #define CHUNK_POINTERS 8
- char *readLine(FILE *file) {
- char *line = NULL, ch;
- int index = 0, currSize = 0;
- while ((ch = fgetc(file)) != EOF) {
- if (index == currSize) {
- currSize += CHUNK_CHARS;
- line = realloc(line, sizeof(char) * currSize);
- NULL_CHECK(line);
- }
- if (ch != '\n') {
- line[index++] = ch;
- } else {
- break;
- }
- }
- NULL_CHECK(line);
- if (index == currSize) {
- currSize++;
- line = realloc(line, sizeof(char) * currSize);
- } else {
- currSize = index + 1;
- line = realloc(line, sizeof(char) * currSize);
- }
- NULL_CHECK(line);
- line[index] = 0;
- return line;
- }
- char **readLines(FILE *file) {
- char **lines = NULL, *line = NULL;
- int index = 0, currSize = 0;
- while ((line = readLine(file)) != NULL) {
- if (index == currSize) {
- currSize += CHUNK_POINTERS;
- lines = realloc(lines, sizeof(char*) * currSize);
- NULL_CHECK(lines);
- }
- lines[index++] = line;
- }
- NULL_CHECK(lines);
- if (index == currSize) {
- currSize++;
- lines = realloc(lines, sizeof(char*) * currSize);
- } else {
- currSize = index + 1;
- lines = realloc(lines, sizeof(char*) * currSize);
- }
- NULL_CHECK(lines);
- lines[index] = NULL;
- return lines;
- }
- void free2d(char **p2p) {
- for (int i = 0; p2p[i] != NULL; i++) {
- free(p2p[i]);
- }
- free(p2p);
- }
- void writeLines(char **lines) {
- for (int i = 0; lines[i] != NULL; i++) {
- puts(lines[i]);
- }
- }
- int main(void) {
- char **lines = NULL;
- lines = readLines(stdin);
- writeLines(lines);
- free2d(lines);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement