DISCLAIMER: I'm new to C.
What is the best way to convert every line in a .txt file (can be other file types too) to a dinamic calloc() array, and the other way around?
In my file I have to following:
1 Hello
2 18
3 World
4 15
etc...
I want something like this in the array:
[0] Hello
[1] 18
[2] World
[3] 15
etc...
The code i have now:
FILE *file;
file = fopen("test.txt", "r");
int i = 0;
//make dynamic calloc array
//while line!= EOF
//put line[i] into array
//i++
//realloc array, size +1
fclose(file);
Is this way of doing this a good one or is there a better one? If someone could help me a little bit with the code I would be really thankful.
You are close to the right solution, but here you are reallocing the dynamic array every time there is a new line, what you could do, is to allocate N
byte in advance in the array and realloc each time with this size, this will avoid frequent memory movement of the array and sys call:
FILE *file;
file = fopen("test.txt", "r");
int i = 0;
int max = 256;
int resize = 512;
char **arr = malloc(max * sizeof(*arr));
//make dynamic calloc array
//while line!= EOF
//put line[i] into array
//i++
if(i == max)
realloc array, size + reisze;
fclose(file);
i would get the number of lines first and then allocate memory for an array to avoid realloc() call (possibly allocates a new memory block and copies memory area). but i'm not sure that this way is more efficient. here's my example code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static int get_nlines(FILE* fp)
{
int nlines = 0;
int ch;
while (!feof(fp)) {
ch = fgetc(fp);
if (ch == '\n') {
nlines++;
}
}
fseek(fp, 0, SEEK_SET);
return nlines;
}
static char* get_value(char* s)
{
char* pch;
pch = strtok(s, " ");
if (pch != NULL) {
pch = strtok(NULL, " ");
if (pch != NULL) {
return strdup(pch); // need to free() after use
} else {
return NULL;
}
} else {
return NULL;
}
}
int main()
{
FILE* fp = fopen("test.txt", "r");
if (fp != NULL) {
int nlines = get_nlines(fp);
printf("nlines: %d\n", nlines);
// make values..
char** values = calloc(nlines + 1, sizeof(char*)); // +1 for a sentinel
if (values != NULL) {
char line[1024];
int idx = 0;
while (fgets(line, sizeof(line), fp) != NULL) {
values[idx] = get_value(line);
idx++;
}
}
// use values..
char** p = &values[0];
while (*p != NULL) {
printf("%s\n", *p);
p++;
}
// clean values..
p = &values[0];
while (*p != NULL) {
free(*p);
p++;
}
fclose(fp);
} else {
perror("test.txt");
}
}
the result:
$ ./a.out
nlines: 4
Hello
18
World
15
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With