Reputation: 2257
I'm currently building a console app for a school project and I really need this function for my app.
How do I save all the text from console to a string in C (Windows platform)?
For example:
If I used the function system("dir")
, it will output to console and list all the subdirectories and files in a directory. And I want it to be saved on a string for later use.
Upvotes: 1
Views: 246
Reputation: 27240
Use popen() function:
http://pubs.opengroup.org/onlinepubs/009604499/functions/popen.html
The popen() function shall execute the command specified by the string command. It shall create a pipe between the calling program and the executed command, and shall return a pointer to a stream that can be used to either read from or write to the pipe.
#include ...
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
while (fgets(path, PATH_MAX, fp) != NULL
printf("%s", path);
This works on Linux. So i think it might also works in windows.
Upvotes: 1
Reputation: 141948
You could use popen()
rather than system()
:
#include <stdio.h>
#include <limits.h>
int main()
{
FILE *fp;
char path[PATH_MAX];
fp = popen("DIR", "r");
if (fp == NULL)
{
/* Handle error */
}
while (fgets(path, PATH_MAX, fp) != NULL)
{
printf("%s", path);
}
pclose(fp);
return 0;
}
Upvotes: 1