1. 程式人生 > >fwrite fread fscanf fprintf 及C語言對字串操作函式

fwrite fread fscanf fprintf 及C語言對字串操作函式

fwrite fread fscanf fprintf 都是屬於C函式用於檔案讀寫,前兩者對二進位制檔案讀寫,後兩者只要用於格式化的讀取、輸出文字,對文字檔案讀寫。

 fscanf()  格式化的讀取,從檔案中讀取

 fprintf() 格式化的寫入,寫入到檔案中

 10:9.9,xxxx,1.jpg#

 fprintf(fp,"%d:%.2f,%s,%s#",10,9.9f,"最便宜的面膜","20150301010101.jpg");

 第二個引數是"......"中的東西,%d與%.2f之間是分隔符,%.2f是輸出兩位數的float

 在格式化輸出中:%10.8f表示輸出結果一共有10位,其中小數點後佔8位

 */

注意:在使用fscanf的時候要注意引數的正確使用,例如%f與float型別變數對應,%lf與double型別的變數對應,若不對應資料將不能正確讀取,比如%f與double型別變數對應

#include <stdio.h>

//格式化的寫入

void test1(){

//定義檔案指標

    FILE *fp = fopen("fprintf.txt""w");

//判斷檔案是否成功開啟

    if(fp != NULL){

        //格式化寫入

        int productId = 10;

        float productPrice = 9.9f

;

        char *productTitle = "最便宜的面膜";

        char *productTitleImg="20150301010101.jpg";

        fprintf(fp,"%d:%.2f,%s\n%s", productId,productPrice,productTitle,productTitleImg);

        printf("寫入成功!\n");

    }

    fclose(fp);

    fp = NULL;

}

//格式化讀取

void test2(){

//定義檔案指標

    FILE *fp = fopen("fprintf.txt"

"r");

//判斷是否開啟成功

    if(fp != NULL){

        int productId = 0;

        float productPrice = 0.0f;

        char productTitle[50];

        char productTitleImg[50];

        //格式化讀取

        fscanf(fp, "%d:%f,%s\n%s",&productId,&productPrice,productTitle,productTitleImg);

        printf("產品編號:%d\n",productId);

        printf("產品價格:¥%.2f\n",productPrice);

        printf("產品名稱:%s\n",productTitle);

        printf("產品圖片:%s\n",productTitleImg);

    }

    fclose(fp);

    fp = NULL;

}

int main(int argc, const char * argv[]) {

    test1();

    test2();

    printf("Hello, World!\n");

    return 0;

}

字串操作函式:

strcpy:複製char

strcat:連線char

strlen:長度

strcmp:比較是否一樣

strstr: 查詢字元

strncpy: 複製前幾個

pow(x,y):計算x的y次方。x、y及函式值都是double型,要加入標頭檔案 math.h

memcpy: 指定字元個數從指定位置複製到指定位置

sprintf:把格式化的資料寫入某個字串緩衝區。int sprintf( char *buffer, const char *format, [ argument] … );,注意與fprintf區別,前者對緩衝區操作,後者對檔案操作。

atoi:AscII To int,同理itoa

atof:AscII To float,同理ftoa

注意atoi函式不是C標準函式,springf是標準函式,儘量使用sprintf

sprintf:格式輸出到char*,類似於CString的Format

pritnf:輸出到螢幕