fprintf没有将内容写入文件,却可以将内容写入标准输出(stdout)问题解释。
下面详细解释一下具体原因:
首先:IO操作分为标准IO和文件IO两种。
标准IO主要函数集:
fopen、fclose、fgetc、fgets、fputc、fputs、fread、fwrite、fseek、ftell、rewind等
文件IO主要函数集:
open、close、read、write、lseek等
第二:缓冲机制问题
标准IO:有缓冲机制,并且又分为全缓冲(针对文件)和行缓冲(针对终端)以及无缓冲(标准出错)
文件IO:无缓冲机制
第三:标准IO中缓冲机制下的刷新条件
全缓冲:
1、程序正常结束
2、缓冲区满刷新
3、强制刷新:fflush()函数
行缓冲:
1、printf()函数输出\n后
2、程序正常结束
3、缓冲区满刷新
4、强制刷新:fflush
例程:用三个例程对照
1、以文件IO形式将当前时间按照给定格式写入文件a.txt中。
此时不需要刷新缓冲区,因为文件IO不存在缓冲机制,调用write会直接将数据写入到文件中
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
time_t sec;//存放1970到目前的秒数
struct tm *T;//存放转化的时间结果
char format[50]={0};//存放给定格式时间字符串
int fd = open("a.txt",O_RDWR|O_CREAT|O_APPEND,0666);
if(fd < 0)
{
perror("open err");
return -1;
}
//读取并转化时间
sec=time(NULL);
if(sec == -1)
{
perror("get time err");
return -1;
}
T=localtime(&sec);
//将时间按照给定格式输出到数组中,方便之后输出到文件中
sprintf(format,"%d-%d-%d %d:%d:%d\n",T->tm_year+1900,\
T->tm_mon+1,T->tm_mday,T->tm_hour,T->tm_min,T->tm_sec);
//文件IO写入数据
write(fd,format,strlen(format));
close(fd);
return 0;
}
2、以标准IO形式将当前时间以给定格式写入到终端上。
此时需要刷新缓冲区,因为是标准IO存在缓冲区,且是写入到终端,所以是行缓冲,当fprintf中输出时遇见格式中的'\n'后,自动刷新缓冲区,因此不需要使用fflush()函数强制刷新
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
time_t sec;//存放1970到目前的秒数
struct tm *T;//存放转化的时间结果
//读取并转化时间
sec=time(NULL);
if(sec == -1)
{
perror("get time err");
return -1;
}
T=localtime(&sec);
//将时间按照给定格式输出到数组中,方便之后输出到文件中
fprintf(stdout,"%d-%d-%d %d:%d:%d\n",T->tm_year+1900,\
T->tm_mon+1,T->tm_mday,T->tm_hour,T->tm_min,T->tm_sec);
//这里fprintf写入终端应该是行缓冲
fclose(fp);
return 0;
}
3、以标准IO形式将当前时间以给定格式写入到文件a.txt中
此时需要刷新缓冲区,因为是标准IO存在缓冲机制,且是写入文件,属于全缓冲,遇见'\n'不会刷新缓冲区,这里需要用到fflush()函数强制刷新缓冲区来将数据写入到文件
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
time_t sec;//存放1970到目前的秒数
struct tm *T;//存放转化的时间结果
FILE *fp = fopen("test.txt","a+");
if(fp == NULL)
{
perror("fopen err");
return -1;
}
//读取并转化时间
sec=time(NULL);
if(sec == -1)
{
perror("get time err");
return -1;
}
T=localtime(&sec);
//将时间按照给定格式输出到数组中,方便之后输出到文件中
fprintf(fp,"%d-%d-%d %d:%d:%d\n",T->tm_year+1900,\
T->tm_mon+1,T->tm_mday,T->tm_hour,T->tm_min,T->tm_sec);
//这里fprintf写入文件fp应该是全缓冲,需要用fflush刷新缓冲区
fflush(fp);
fclose(fp);
return 0;
}