linux的fwrite()使用方法,目前時間寫入文本的程式

來源:互聯網
上載者:User

標籤:style   ar   color   os   使用   sp   檔案   資料   on   

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‘),否則會因為字元個數多了而造成亂碼

    看完的朋友,覺得對你們有協助就頂一個,如果覺得哪裡不好,可以發表下看法,共同學習。

linux的fwrite()使用方法,目前時間寫入文本的程式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.