i am currently rewriting a log parsing script from bash into C, and i was just wondering if i could get some advice regarding how i can set the array called buffer to expand dynamically instead of being limited to 1024, I think i would use malloc, but im not too sure how to properly implement it for this specific application, any help is greatly appreciated, thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _GNU_SOURCE
void main(int argc, char *argv[], char *envp[])
{
FILE *fd;
char *name;
name = getenv("MCEXEC_PLAYERNAME");
char *filename;
filename = malloc(sizeof "/home/minecraft/freedonia/playerdata/deathlog-.txt" - 1 + strlen(name) + 1);
if (!filename) exit(EXIT_FAILURE);
sprintf(filename,"/home/minecraft/freedonia/playerdata/deathlog-%s.txt",name);
char buff[1024];
if ((fd = fopen(filename, "r")) != NULL)
{
fseek(fd, 0, SEEK_SET);
while(!feof(fd))
{
memset(buff, 0x00, 1024);
fscanf(fd, "%[^\n]\n", buff);
}
printf("%s\n", buff);
}
else
printf( "fail" );
}
Use malloc to allocate the array dynamically.
If needed, realloc it to alter its size.
EDIT:
Instead of:
char buff[1024];use:
You can use another variable like:
char tmp[256];to read from file and store it intobuff. As you puttmpintobuff, keep note of the size of chars inbuff. If necessary, make a call to realloc: