日常学习
2023/4/19
POPEN & PCLOSE
- 函数原型
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
- 函数行为
popen函数(常用)建立管道,fork子进程,调用sehll执行命令。
pclose函数关闭由popen函数返回的I/O文件流。 - 参数解释
type:r表示command的标准输出是管道,父进程利用文件指针从管道中读取数据。w表示command的标准输入是管道,父进程利用文件指针向管道中写入数据。
command: I/O文件指针。 - 应用示例
#include <stdio.h>
int main( int argc, char **argv ) {
FILE *r_fp = popen( "ls", "r" );
FILE *w_fp = popen( "wc -l", "w" );
char buf[ 65536 ] = { 0 };
while ( ( fgets( buf, sizeof( buf ), r_fp ) ) != NULL ) {
fputs( buf, w_fp );
}
pclose( r_fp );
pclose( w_fp );
return 0;
}
SYSTEM
- 函数原型
#include <stdlib.h>
int system(const char *command);
- 函数行为
system函数fork一个子进程,并在该子进程中执行command。 - 参数解释
no more to say - 返回值
如果命令成功执行,返回值是用来执行command的子shell的终止状态。 - 应用示例
#include <stdio.h>
int main( int argc, char **argv ) {
int ret = system("ls");
if (ret != 0) {
printf("Wrong");
}
return 0;
}
sprintf & sscanf
``

浙公网安备 33010602011771号