fwrite函数

1.函数功能

用来读写一个数据块。

2.一般调用形式

fwrite(buffer,size,count,fp);

3.说明

(1)buffer:是一个指针,对fread来说,它是读入数据的存放地址。对fwrite来说,是要输出数据的地址。

(2)size:要读写的字节数;

(3)count:要进行读写多少个size字节的数据项;

(4)fp:文件型指针

这是工作中用 fwrite函数写的例子,不仅记录下自己的学习情况,也分享给各位朋友这个fwrite函数实例。

这个fwrite实例是当前时间写入文本的程序,下面这个是fwrite函数的使用方法。
int markfile(void )
{
    FILE *sp ;
//    char buff[512] ;
    char count = 0;
    char *currentime = NULL;
    char *wday[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
    time_t timep;
    struct tm *p;
    time(&timep);
    p = localtime(&timep);
    currentime = ctime(&timep);
//    memset(buff,0,512);
//    sprintf(buff,"%s",currentime);
    printf("%d/%d/%d",(1900+p->tm_year),(1+p->tm_mon),p->tm_mday);
    printf(" %s %d:%d:%d\n",wday[p->tm_wday],p->tm_hour,p->tm_min,p->tm_sec);
    if((sp = fopen("/root/kay/mark.txt","a+")) == NULL)
       return 0;
    fwrite(currentime,size(currentime)-1,1,sp);
    fclose(sp);
    return 1;
}

size(currentime)( = 26 )的作用是得出指针currentime所指的字符串的个数(包括'\0'),但是会输出乱码(应该是字符串的个数太长了),因此,我把个数减掉一个,就能舒适正确结果。

用另外一种方法:
int markfile(void )
{
    FILE *sp ;
    char buff[512] ;
    char count = 0;
    char *currentime = NULL;
    char *wday[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
    time_t timep;
    struct tm *p;
    time(&timep);
    p = localtime(&timep);
    currentime = ctime(&timep);
//    memset(buff,0,512);
    sprintf(buff,"%s",currentime);
    printf("%d/%d/%d",(1900+p->tm_year),(1+p->tm_mon),p->tm_mday);
    printf(" %s %d:%d:%d\n",wday[p->tm_wday],p->tm_hour,p->tm_min,p->tm_sec);
    if((sp = fopen("/root/kay/mark.txt","a+")) == NULL)
       return 0;
    fwrite(currentime,(count = strlen(buff)),1,sp);
    printf("%d\n",count);
    fclose(sp);
    return 1;
}
count = strlen(buff) 来获得字符的个数  结果是25,

综上的对比 觉得是fwrite()输出的字符不要包括结束符('\0'),否则会因为字符个数多了而造成乱码

看完的朋友,觉得对你们有帮助就顶一个,如果觉得哪里不好,可以发表下看法,共同学习。

05-14 12:40