Header File
stdio.h
Category
Input/output Routines
Prototype
FILE *_popen (const char *command, const char *mode);
FILE *_wpopen (const wchar_t *command, const wchar_t *mode);
Description
Creates a command processor pipe.
The _popen function creates a pipe to the command processor. The command processor is executed asynchronously, and is passed the command line in command. The mode string specifies whether the pipe is connected to the command processor’s standard input or output, and whether the pipe is to be opened in binary or text mode.
The mode string can take one of the following values:
rt |
Read child command’s standard output (text). |
rb |
Read child command’s standard output (binary). |
wt |
Write to child command’s standard input (text). |
wb |
Write to child command’s standard input (binary). |
The terminating t or b is optional; if missing, the translation mode is determined by the external variable _fmode.
Use the _pclose function to close the pipe and obtain the return code of the command.
Return Value
On success, _popen returns a FILE pointer that can be used to read the standard output of the command, or to write to the standard input of the command, depending on the mode string.
On error, it returns NULL.
Example
/* this program initiates a child process to run the dir command and pipes the directory listing from the child to the parent. */ #include <stdio.h> // popen() pclose() feof() fgets() puts() #include <string.h> // strlen() int main( ) { FILE* handle; // handle to one end of pipe char message[256]; // buffer for text passed through pipe int status; // function return value // open a pipe to receive text from a process running "DIR" handle = _popen("dir /b", "rt"); if (handle == NULL) { perror("_popen error"); } // read and display input received from the child process while (fgets(message, sizeof(message), handle)) { fprintf(stdout, message); } // close the pipe and check the return status status = _pclose(handle); if (status == -1) { perror("_pclose error"); } return(0); }
Portability
|
POSIX |
Win32 |
ANSI C |
ANSI C++ |
_popen |
|
+ |
|
|
_wpopen |
|
NT only |
|
|
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
|
What do you think about this topic? Send feedback!
|