在批处理文件上进行C++fstream写入,然后结束,没有剩余的代码行



我目前正在编写这段代码,它将创建一个带有ping某个IP地址命令的批处理文件。我希望它执行批处理文件并将结果记录到一个txt文件中。然而,由于某种原因,它在ping之后停止(?)。它确实生成了txt文件,但它不显示任何关于它的信息。它还会忽略下面的代码行。

我试过把两个"bat"合并,但都是一样的。这是我的代码:

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
    string results;
    ofstream bat;
    ifstream text ("bat.txt");
    bat.open ("bat.bat");
    bat << "@echo off n ping 216.52.241.254 n ";
    bat << "bat.bat > bat.txt";
    bat.close();
    system("bat.bat");
    bat.close();
    return 0;
}

然后控制台将只显示

Pinging 216.52.241.254 with 32 bytes of data:
Reply from 216.52.241.254: bytes=32 time=63ms TTL=245
Reply from 216.52.241.254: bytes=32 time=62ms TTL=245
Reply from 216.52.241.254: bytes=32 time=62ms TTL=245 
Reply from 216.52.241.254: bytes=32 time=62ms TTL=245
Ping statistics for 216.52.241.254:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 62ms, Maximum = 63ms, Average = 62ms

然后,它在光标闪烁的情况下停止,甚至不返回0。

所以基本上我想ping这个IP,然后结果会复制到一个txt文件中,这样同一个程序就可以读取txt文件并显示平均ping时间。问题是,它在ping之后突然结束。关于如何解决这个问题有什么想法吗?真的希望得到答案。我已经为此研究了几个小时,并尝试了不同的方法,直到我别无选择,只能在这里提问。

#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main()
{
    ofstream bat;
    bat.open ("bat.bat");
    bat << "@echo off" << endl;
    bat << "ping 216.52.241.254" << endl;
    bat.close();
    system("cmd /K bat.bat > ping_output.log");
    return 0;
}

尝试使用此方法,如果它说bat.bat不存在,请尝试在当前工作目录

中打开

最新更新