Reputation: 13
So, i need a code to read a TXT file with 5 contents each line, and store each line values in a variable. but the number of lines in the TXT will vary. so i thought of excecuting something like this:
int counter=0;
char nome="TXT NAME.txt";
FILE *f = fopen(NAME,"r");
do{
if(!feof(p))
counter++;
}while(!feof(f));
fclose(f)
int X[counter][5];
so when declaring like this, X will have the number of lines of the file. but the issue is that to store the values, i would need to open and read the file again. is there a way to save the values while declaring the variable so i dont need to open twice ?
Upvotes: 0
Views: 327
Reputation: 153557
How to read a file in C and at the same time create a variable with the number of lines?
is there a way to save the values while declaring the variable so i dont need to open twice ?
A nice way is to read one line at a time with fgets()
, copy the buffer with strdup()
and save in a linked list of your creation.
Some pseudo-code to get you going.
f = open file
exit if unable to open
line_count = 0;
list = LL_Create()
char buffer[100];
while (fgets(buffer, sizeof buffer, f)) {
Maybe special handling here to deal with lines longer than 100
char *s = strdup(buffer);
LL_Append(list, s);
line_count++;
}
fclose(f);
// Use the link-list of strings
// When done
while !LL_Empty(list)
s = LL_Pop(list)
free(s);
LL_Destroy(list)
Upvotes: 1
Reputation: 36082
You can use realloc to gradually expand your "array".
But a simpler approach is to use a linked list, that way the list just grows as you read the file.
typedef struct
{
char data[5];
Line* next;
} Line;
Line* first = NULL;
Line* last = NULL;
char line[128];
while (fgets(line, sizeof(line), f)
{
Line* tmp = malloc(sizeof(Line));
memcpy(tmp->data,line,5);
tmp->next = NULL;
if (first == NULL)
{
first = last = tmp;
}
else
{
last->next = tmp;
last = tmp;
}
}
Now to go through the lines
for(Line* p = first; p != NULL; p = p->next)
{
p->data ...
}
Upvotes: 0