问题描述
我的问题有点长,所以请和我裸露。
我有一个C ++应用程序,应该从用户处接收命令,在cmd.exe中执行命令,然后使用HTTP协议将结果发送到服务器。
我发现,为了从c ++程序运行命令,我需要打开一个管道,然后使用fgets()
在我的代码中读取cmd进程的输出。
这是我从管道读取的代码:
char buffer [SIZE];
//strCmd is the command to be executed in cmd
FILE* pipe = _popen(strCmd.c_str(),"r");
if (!pipe)
{
std::cerr << "cannot open pipe" << std::endl;
return NULL;
}
while (fgets(buffer,SIZE,pipe))
{
std::cout << buffer;
}
_pclose(pipe);
现在假设我将strCmd
设置为“ dir”。我从管道读取的输出是:
Volume in drive C has no label.
Volume Serial Number is 0C5C-B0D7
Directory of C:\Users\user\documents\visual studio 2017\Projects\pipe-demo-new\pipe-demo-new
10/05/2020 12:26 AM <DIR> .
10/05/2020 12:26 AM <DIR> ..
10/04/2020 05:08 PM <DIR> Debug
10/05/2020 12:26 AM 1,977 pipe-demo-new.cpp
10/04/2020 05:12 PM 8,552 pipe-demo-new.vcxproj
10/03/2020 07:43 PM 1,340 pipe-demo-new.vcxproj.filters
10/03/2020 07:43 PM 1,757 ReadMe.txt
09/06/2020 10:05 AM 1,184 selfsigned.crt
10/03/2020 07:43 PM 300 stdafx.cpp
10/03/2020 07:43 PM 320 stdafx.h
10/03/2020 07:43 PM 314 targetver.h
10/04/2020 05:12 PM <DIR> x64
8 File(s) 15,744 bytes
4 Dir(s) 13,798,125,568 bytes free
我使用这段代码将http帖子请求中的数组buffer
发送到服务器:
void SendRequest(char* buffer) {
httplib::Client cli(IP,8000);
httplib::Params params{
{ "key",buffer }
};
auto res = cli.Post("/postReq/",params);
if (res) {
cout << res->status << endl;
cout << res->get_header_value("Content-Type") << endl;
//redirect
cli.set_follow_location(true);
res = cli.Get("/postReq/");
}
}
但是我在服务器中得到的是这个(仅输出的最后一行):
4 Dir(s) 13,568 bytes free
我知道这种行为是预期的,并且正是fgets()
的工作方式。我的问题是,总有没有得到完整的输出?是否有更好的方法将输出发送到服务器?
我曾考虑过在调用fgets()
之后(在while循环内)立即发送请求,但这将以多段形式发送字符串,并且在我的情况下没有用,因为我希望字符串仅作为数据库中的一条记录。
我在Windows 10上使用Visual Studio 2017,并且服务器正在本地主机上运行。
服务器是使用django编写的。
不知道这是否重要,但我正在使用cpp-httplib发送http请求。
任何帮助表示赞赏。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)