Linux Run Shell in C++

Linux Run Shell in C++


int cmd_line(const char *cmd, string& strRet) {
	FILE *stream;
	int readlen;
	strRet.clear();
	char s[2048];
	stream = popen(cmd, "r"); //將“ls -l”命令的輸出 通過管道讀取(“r”參數)到FILE* stream
	if (stream)
	{
		while (fgets(s, 2048, stream))
			strRet += s;
	}

	pclose(stream);
	return readlen;
}


int readAllText(const char* path, string& strRet) {
	ifstream fin(path);
	if (!fin.is_open()) {
		cout << "open failed!\n";
		return -1;
	}
	strRet.clear();
	char ch;
	while (fin.get(ch)) {
		strRet += ch;
	}
	fin.close();
	return strRet.size();
}

int run_shell(const char* shell_path, string& strret)
{
	string strcmd;
	int iret = readAllText(shell_path, strcmd);
	if (iret > 0)
	{
		cmd_line(strcmd.c_str(), strret);
	}
	return iret;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章