#include <stdio.h>
#include <stdlib.h>
size_t dynamic_reader(FILE *file, char ***strings);
int main(void)
{
char **strings;
size_t lines = dynamic_reader(stdin, &strings);
for (size_t i = 0; i < lines; ++i)
{
printf("Read input: \"%s\"\n", strings
[i
]); }
// Free all the dynamically allocated memory
for (size_t i = 0; i < lines; ++i)
{
// Free a string
}
// Free the array
}
// Function:
// read_line - Reads a single line from a file
// Argument:
// file - the file to read the input from
// Returns:
// The line read
char *read_line(FILE *file)
{
int ch;
char *s = NULL;
size_t current_length = 0; // Current length of string
// Loop to read a single line
while ((ch
= fgetc(file
)) != EOF
) {
if (ch == '\n')
break; // Newline, done with the current string
if (s == NULL)
{
s
= malloc(2); // Allocate two character: One for c and one for the terminator }
else
{
// The current length is not including the terminator
// that's why we add two characters
char *temp_s
= realloc(s
, current_length
+ 2); if (temp_s == NULL)
{
// Handle error
}
s = temp_s;
}
s[current_length++] = ch;
s[current_length] = '\0'; // Terminate as a string
}
return s;
}
// Function:
// dynamic_reader - Reads multiple lines from a file
// Argument:
// file - the file to read the input from
// strings - a pointer to the array of strings where the lines would be put
// Returns:
// The number of strings in the array
size_t dynamic_reader(FILE *file, char ***strings)
{
size_t current_line = 0;
*strings = NULL;
// Loop until we hit the end of the file, or an error
do
{
char *s = read_line(file);
if (s != NULL)
{
// "Add" the string to the array of strings
if (*strings == NULL)
{
// Initial allocation
*strings
= malloc(1 * sizeof(**strings
)); }
else
{
// Reallocate array to increase size by one
char **temp_strings
= realloc(*strings
, (current_line
+ 1) * sizeof(**strings
)); if (temp_strings == NULL)
{
// Handle error
}
*strings = temp_strings;
}
(*strings)[current_line++] = s;
}
return current_line;
}