So, I've been searching this around StackOverflow for awhile now but none of the semi-related posts are a solution to mine, so I hope anyone can help :)
So what I wanna do is transfer a .txt file, that has the following content on it:
1 5 8
2 4 6 9
5 7
(per example)
So, what I want to know is:
How to transfer the .txt to allocated memory using malloc;
I have to read each line separately and extract the numbers, then to compare with the contents of a structure with the ID cooresponding with the numbers in the .txt file.
If I transfer the contents of the .txt to the array (using malloc), will it still have the '\n' on the array, so I can distinguish the lines?
Since the values go from 1
to 9
, you can use 0
as a sentinel for each row, that way you don't need to predict or store the number of numbers in each line, you just store all the numbers that appear, and the add a 0
at the end that will help you know where the numbers end, something identical to how c handles strings.
The following code does what I describe
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int
appendvalue(int ***values, int row, int column, int value)
{
void *pointer;
pointer = realloc(values[0][row], (1 + column) * sizeof(int));
if (pointer == NULL)
{
fprintf(stderr, "warning: allocating memory\n");
return 0;
}
values[0][row] = pointer;
values[0][row][column] = value;
return 1 + column;
}
int
main(void)
{
FILE *file;
char buffer[100];
char *line;
int **values;
int row;
file = fopen("input.txt", "r");
if (file == NULL)
{
fprintf(stderr, "error opening the file\n");
return -1;
}
values = NULL;
row = 0;
while ((line = fgets(buffer, sizeof(buffer), file)) != NULL)
{
void *pointer;
size_t column;
while (isspace(*line) != 0)
line++;
if (*line == '\0') /* empty line -- skip */
continue;
pointer = realloc(values, (row + 1) * sizeof(int *));
if (pointer == NULL)
{
fprintf(stderr, "error allocating memory\n");
return -1;
}
values = pointer;
values[row] = NULL;
column = 0;
while ((*line != '\0') && (*line != '\n'))
{
if (isspace(*line) == 0)
column = appendvalue(&values, row, column, *line - '0');
++line;
}
column = appendvalue(&values, row, column, 0);
row += 1;
}
/* let's print each row to check */
for (--row ; row >= 0 ; --row)
{
size_t index;
for (index = 0 ; values[row][index] != 0 ; ++index)
{
printf("%d, ", values[row][index]);
}
printf("\n");
free(values[row]);
}
free(values);
return 0;
}