Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I Want to convert the output of this code to string type , but i cant make it.

C++
#pragma warning(disable : 4996)
#include <iostream>
int main()
{
    char cmd[10];
    strcpy(cmd, "dir");
    system(cmd);
}




What I have tried:

I tried to convert that using stringstream and other methods , none of them worked.
Posted
Updated 19-Oct-22 2:35am

Are you possibly searching for popen?
See, for instance: The Marvelous popen() Function | C For Dummies Blog[^]
 
Share this answer
 
Comments
merano99 20-Oct-22 17:34pm    
+5
CPallini 21-Oct-22 6:02am    
Thank you.
C
#include <iostream>
#include <stdio.h>
int main()
{
	system("dir");
	puts((char*)stdin);
}


C++
#include <iostream>
#include <stdio.h>
#include <string.h>
int main()
{
	char cmd[10];
	strcpy_s(cmd, 10, "dir");
	system(cmd);
	puts((char*)stdin);
}
 
Share this answer
 
Comments
merano99 20-Oct-22 17:33pm    
+5; iostream not needet, stdlib missing
Death Smoke 20-Oct-22 18:50pm    
I Didnt understand your solution can you explain for me more how i can use that output as string ?
Alexandrnn 21-Oct-22 4:32am    
char strs[1024];

while(fgets(strs,1024, stdin)) puts(strs);
The command system() creates a new process to handle the specified command.
C
char cmd[10];
strcpy(cmd, "dir");
system(cmd);

In most cases, this is neither performant nor useful. But of course you can start a process with C this way. You could also redirect the output to a file and then read this file again. More performant and without needing a file you can realize this by using system calls. The effort is not insignificant, since you have to redirect inputs and outputs to a pipe before starting the process instead of simply system(). While on Unix you would use a combination on fork(), pipe() and exec() this could be solved as follows on Windows:
Creating a Child Process with Redirected Input and Output
https://learn.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output

If you only want to get the contents of a directory, you can use the combination of FindFirstFile() and FindNextFile().

Listing the Files in a Directory
https://learn.microsoft.com/en-us/windows/win32/fileio/listing-the-files-in-a-directory
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900