linux printf往文件里面写入内容

printf用于向控制台打印字符串,而这里面的控制台其实是标准输出,fd值为1,故可以用下面代码写文件:

int main()
{
	close(1);
	int i = 1;

	int fd1 = open("/chkpnt/log.txt",O_WRONLY | O_CREAT, 0666);
	printf("i = %d\n",i);


	return 0;
}

代码里面,先将fd=1关闭掉,然后open一个文件,出来的文件描述符fd1的值就是1,然后printf向fd为1的文件里面写入东西,执行时,最终可以看到log.txt里面的字符串。

现在将程序做修改如下:

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>



int main()
{
	close(1);
	int i = 1;

	int fd1 = open("/chkpnt/log.txt",O_WRONLY | O_CREAT, 0666);
	
	while(1)
	{
		printf("i = %d\n",i);
		i++;
		sleep(1);
	}
	


	return 0;
}

此种请看下,程序一直在运行,每隔1秒写入一行内容,但是可以发现log.txt中看不到任何内容。

将此程序进行修改,去掉sleep(1)。此时相当于疯狂往log.txt里面写入,很快发现log.txt文件很大。

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>



int main()
{
	close(1);
	int i = 1;

	int fd1 = open("/chkpnt/log.txt",O_WRONLY | O_CREAT, 0666);
	
	while(1)
	{
		printf("i = %d\n",i);
		i++;
	}
	


	return 0;
}

此时再将sleep(1)加上,同时加上文件刷新fsync(fd1),代码如下所示:

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>



int main()
{
	close(1);
	int i = 1;

	int fd1 = open("/chkpnt/log.txt",O_WRONLY | O_CREAT, 0666);
	
	while(1)
	{
		printf("i = %d\n",i);
		fsync(fd1);
		i++;
	}
	


	return 0;
}

此时发现,log.txt里面依然没有内容。

最后将fsync(fd1);换成fflush(stdout);,然后发现log.txt里面有内容了,代码如下:

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>



int main()
{
	close(1);
	int i = 1;

	int fd1 = open("/chkpnt/log.txt",O_WRONLY | O_CREAT, 0666);

	while(1)
	{
		sleep(1);
		printf("i = %d\n",i);

		i = i + 1;
		fflush(stdout);
	}


	return 0;
}

为何fsync不行,fflush可以,难道是因为printf和fflush都是stdio.h里面的吗,有大神知道原因的,请不吝赐教。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值