The problem is this: I made a function that takes the output of a certain command from the OS and stores it in a string. The idea would now be to declare a string of just one char in my main function using malloc
, call my function by passing the command I want to take the output and also passing the address of the byte that was allocated to my char. From this, I would expand my string by initially 1 char using realloc
inside the other function to store the values that fscanf
returns directly in those spaces.
How could this be done?
Code sample:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <stdint.h>
int SystemGetOut_char();
int main()
{
char *teste = malloc(1);
char command[] = "ls";
SystemGetOut_char(command, &teste);
return 0;
}
int SystemGetOut_char(char *command, char *output)
{
int chunk = 1;
FILE *fp = popen(command, "r");
int charnumber = 0;
while(fscanf(fp, "%c", &output[charnumber]) != EOF)
{
chunk++;
output = realloc(output, chunk);
charnumber++;
}
pclose(fp);
return 0;
}
NOTE: I know the code will not work, just to get an idea of the structure.