为了账号安全,请及时绑定邮箱和手机立即绑定

例如,我在代码中写了如下内容

例如,我在代码中写了如下内容

C++
富国沪深 2023-01-12 19:15:30
void main(){printf("你好");system("ping 127.0.0.1");printf("再见");}如何将“你好”和“再见”打到屏幕上,将ping的信息打到"ping.result"文件里?
查看完整描述

2 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

可以利用重定向实现system函数输出到文件。
例如:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class Test {
publicstaticvoid main(String[] args) {

PrintStream printStream = null;
PrintStream sysout = System.out;
PrintStream syserr = System.err;
try {
File file = new File("c:\\systemout.log");

if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
printStream = new PrintStream(new FileOutputStream(new File(
"c:\\systemout.log"),true));

// set output to file instead of console
System.setOut(printStream);
System.setErr(printStream);
System.out.println("Before Redirect:System.out.println");
System.err.println("Before Redirect:System.err.println");
} catch (FileNotFoundException e) {
//TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (printStream !=null) {
printStream.close();
}
// Reset the output to console
System.setOut(sysout);
System.setErr(syserr);

System.out.println("After Redirect:System.out.println");
System.err.println("After Redirect:System.err.println");
}

}


查看完整回答
反对 回复 2023-01-15
?
不负相思意

TA贡献1777条经验 获得超10个赞

最简单的方法就是利用重定向实现


system("ping 127.0.0.1 >xxxx");//xxxx为要写入的文件名,包括路径


查看完整回答
反对 回复 2023-01-15
  • 2 回答
  • 0 关注
  • 53 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信