Linux下的popen函数是一个用来执行shell命令的函数,它可以执行shell命令,并将shell命令的标准输出保存到文件中,也可以从文件中读取shell命令的标准输出。popen函数的使用方法如下:
1. 使用popen函数执行shell命令
#includeint main(void) { FILE* fp; char buf[1024]; // 使用popen函数执行shell命令 fp = popen("ls -l", "r"); if (fp == NULL) { printf("popen error\n"); return -1; } // 读取shell命令的标准输出 while (fgets(buf, 1024, fp) != NULL) { printf("%s", buf); } // 关闭文件 pclose(fp); return 0; }
上面的代码使用popen函数执行了“ls -l”这个shell命令,并将shell命令的标准输出保存到文件中,使用fgets函数从文件中读取shell命令的标准输出,使用pclose函数关闭文件。
2. 使用popen函数从文件中读取shell命令的标准输出
#includeint main(void) { FILE* fp; char buf[1024]; // 打开文件 fp = fopen("/tmp/output.txt", "r"); if (fp == NULL) { printf("fopen error\n"); return -1; } // 从文件中读取shell命令的标准输出 while (fgets(buf, 1024, fp) != NULL) { printf("%s", buf); } // 关闭文件 fclose(fp); return 0; }
上面的代码使用fopen函数打开了文件“/tmp/output.txt”,使用fgets函数从文件中读取shell命令的标准输出,使用fclose函数关闭文件。
3. 使用popen函数写入文件
#includeint main(void) { FILE* fp; char buf[1024]; // 使用popen函数打开文件 fp = popen("/tmp/output.txt", "w"); if (fp == NULL) { printf("popen error\n"); return -1; } // 写入文件 fputs("Hello world!\n", fp); // 关闭文件 pclose(fp); return 0; }
上面的代码使用popen函数打开了文件“/tmp/output.txt”,使用fputs函数将“Hello world!”这句字符串写入文件,使用pclose函数关闭文件。
4. 使用popen函数读取文件
#includeint main(void) { FILE* fp; char buf[1024]; // 使用popen函数打开文件 fp = popen("/tmp/output.txt", "r"); if (fp == NULL) { printf("popen error\n"); return -1; } // 读取文件 while (fgets(buf, 1024, fp) != NULL) { printf("%s", buf); } // 关闭文件 pclose(fp); return 0; }
上面的代码使用popen函数打开了文件“/tmp/output.txt”,使用fgets函数从文件中读取内容,使用pclose函数关闭文件。
以上就是Linux下使用popen函数的使用方法,通过popen函数可以很方便的执行shell命令,从而实现对文件的读写操作。