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

void main(){
printf("你好");
system("ping 127.0.0.1");
printf("再见");
}
如何将“你好”和“再见”打到屏幕上,将ping的信息打到"ping.result"文件里?

富国沪深
浏览 54回答 2
2回答

慕容森

可以利用重定向实现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 blocke.printStackTrace();}}printStream = new PrintStream(new FileOutputStream(new File("c:\\systemout.log"),true));// set output to file instead of consoleSystem.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 blocke.printStackTrace();} finally {if (printStream !=null) {printStream.close();}// Reset the output to consoleSystem.setOut(sysout);System.setErr(syserr);System.out.println("After Redirect:System.out.println");System.err.println("After Redirect:System.err.println");}}} 

不负相思意

最简单的方法就是利用重定向实现system("ping 127.0.0.1 >xxxx");//xxxx为要写入的文件名,包括路径
打开App,查看更多内容
随时随地看视频慕课网APP