2
The problem is this: I made a function that takes the output of a given OS command and stores it in a string. The idea now would be to declare a single char string in my main function using malloc
, call my function by passing the command I want to pick up the output and also passing the byte address that was allocated to my char. From that, I would go on expanding my string from initially 1 char using the realloc
within the other function to store the values that the fscanf
return directly to these spaces.
How could this be done?
Code example:
#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 won’t work, it’s just to get an idea of the structure.
Your reply was great. Thank you very much.
– Cooper