How to save text from console to line in C (Windows platform)

I am currently creating a console application for a school project, and I really need this feature for my application.

How to save all text from the console to a line on the C platform (Windows)?

For instance:

If I used the system("dir") function, it will output to the console and list all the subdirectories and files in the directory. And I want it to be stored in a string for later use.

+1
source share
2 answers

You can 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; } 
+1
source

Using the popen () function:

http://pubs.opengroup.org/onlinepubs/009604499/functions/popen.html

The popen () function must execute the command indicated by the string command. It must create a channel between the calling program and the executed command, and must return a pointer to a stream that can be used to read or write to the channel.

#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. Therefore, I think it can also work in windows.

+1
source

Source: https://habr.com/ru/post/1411352/


All Articles