简体   繁体   English

使用system()函数时混淆控制台和文件输出

[英]confusing console and file output when using system() function

I have the following code, 我有以下代码,

#include<stdio.h>
#include<stdlib.h>

int main()
{
    //freopen("file1","w",stdout);
    char str[]="command line with file";
    char s[]="extra string";
    puts(str);
    puts(s);
    system("PAUSE");    
    return 0;
}

when I see the output on console it shows me, 当我在控制台上看到输出时,它显示了我,

command line with file
extra string
Press any key to continue . . . 

And I expect same output when writing output into a file by removing the commented line in code. 通过删除代码中的注释行,将输出写入文件时,我希望得到相同的输出。 But it outputs like, 但是它输出像

Press any key to continue . . . 
command line with file
extra string

why this distinction between file and console output??? 为什么文件和控制台输出之间存在这种区别??? here system("PAUSE") function is responsible for the string output Press any key to continue . . . 这里的system(“ PAUSE”)函数负责字符串输出。 Press any key to continue . . . Press any key to continue . . .

When writing to a terminal, stdout is line-buffered. 写入终端时, stdout是行缓冲的。 It writes each line immediately. 它立即写入每一行。 When writing to a file, it's block-buffered. 写入文件时,它是块缓冲的。 It stores a few kilobytes in a buffer and flushes them out when you call fflush , or when the buffer is full, or when the program ends. 它在缓冲区中存储了几千字节,并在调用fflush或缓冲区已满或程序结束时将其清除。 The pause message is being written by a separate process which exits before your original process, at which point it must flush its buffer (if it has one). 暂停消息是由一个单独的进程编写的,该进程在原始进程之前退出,此时必须刷新其缓冲区(如果有的话)。 Then your original process's system() ends and it reaches the end of main() and exits, flushing the buffer containing your two test strings. 然后,原始进程的system()结束,并到达main()的末尾并退出,刷新包含两个测试字符串的缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM