C中printf 和write的区别
来源:互联网 发布:linux less 编辑:程序博客网 时间:2024/05/05 14:45
调试程序过程中遇到一个问题:遇到printf的语句时有时候能马上打印出字符串,有时候要程序退出时才一次性打印出字符串,但是write每次都能直接打印出字符串。
原来是因为printf是行缓冲函数,只有满了一行才马上打印, write在用户态没有缓冲,所以直接输出。
eg:
#include <apue.h>
#include <fcntl.h>
#include <string.h>
int main(void)
{
int fd;
char str[100];
//创建文件,并输入任意内容供测试
fd = open("test3.6.file", O_WRONLY | O_CREAT, 0660);
if(fd < 0)
err_quit("open test3.6.file failed");
write(fd, "Hello world!\n", 13);
write(fd, "1234567890\n", 11);
write(fd, "abcdefg\n", 8);
close(fd);
//测试读取从 文件开头,中间,结尾
fd = open("test3.6.file", O_RDWR | O_APPEND);
if(fd < 0)
err_quit("open test3.6.file rdwr failed");
printf("read from start: ");
//fflush(stdout);
lseek(fd, 0, SEEK_SET);
if( read(fd, str, 13) > 0)
write(STDOUT_FILENO, str, strlen(str));
printf("read from MID: ");
// fflush(stdout);
lseek(fd, 14, SEEK_SET);
if( read(fd, str, 11) > 0)
write(STDOUT_FILENO, str, strlen(str));
printf("read from END: ");
// fflush(stdout);
lseek(fd, -8, SEEK_END);
if( read(fd, str, 8) > 0)
write(STDOUT_FILENO, str, strlen(str));
//测试往文件中写
lseek(fd, 0, SEEK_SET);
write(fd, "##########", 10);
lseek(fd, 20, SEEK_SET);
write(fd, "@@@@@@@@@@", 10);
lseek(fd, 0, SEEK_END);
write(fd, "**********", 10);
exit(0);
}
如果把上面代码中fflush注释掉,那每次运行的结果如下:
Hello world!
234567890
********
read from start: read from MID: read from END:
如果再printf打印的字符串后面添加‘\n’或者fflush, 则能正常输出:
read from start: Hello world!
read from MID: 234567890
read from END: ********
- C中printf 和write的区别
- c语言中sprinf和printf的区别
- JAVA 中printf与c的区别
- c语言 puts 和 printf的区别
- Vxworks中printf()和logMsg()的区别
- C语言中printf(),sprintf(),scanf(),sscanf()的用法和区别
- C语言中printf(),sprintf(),scanf(),sscanf()的用法和区别
- 浅析C语言中printf(),sprintf(),scanf(),sscanf()的用法和区别
- C语言中printf(),sprintf(),scanf(),sscanf(),fscanf()的用法和区别
- c#write和 writeline read和 readline 的区别
- C51与标准C在printf中标识符的区别
- Write-Through和Write-Back的区别
- Channel.write() 和 ChannelHandlerContext.write() 的区别
- jsp中out的print和write的区别
- ABAP 中 MOVE ... TO 和 WRITE ... TO 的区别
- JSP中out.write()和out.print()的区别
- 【问答】JSP中out.print 和 out.write 的区别
- hadoop 中context.collect 和 context.write的区别
- C++中双冒号(::)和冒号(:)的用法
- 个人学习笔记---linux系统调用怎么陷入内核空间
- [Tools]eclipse build path介绍与配置
- android常用工具类
- linux基于信号量同步的共享内存IPC实现
- C中printf 和write的区别
- Win7下Eclipse中文字体太小
- javascript事件
- 圆形圆角imagView
- Ubuntu51.04如何安装搜狗输入法
- Hadoop之Hbase数据库的应用
- wget命令详解
- boost 1.47.0 linux/windows 编译库:regex与iostreams
- Python的二进制位运算