小甲魚 P58 讀寫檔案2

2021-08-28 20:47:25 字數 1900 閱讀 3093

小甲魚 p58 讀寫檔案2

格式化讀寫檔案

fscanf()函式:讀取

fprintf()函式:寫入

將當前的日期讀取之後,寫入到新建立的檔案裡面 

#include #include #include int main(void)

fprintf(fp, "%d-%d-%d", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday);

fclose(fp);//寫入完後要關閉,可以確保所有資料寫到檔案中

int year, month, day;

if ((fp = fopen("date.txt", "r")) == null)//w:不存在建立,存在開啟初始化

fscanf(fp, "%d-%d-%d", &year, &month, &day);

printf("%d-%d-%d\n", year, month, day);

fclose(fp);

return 0;

}

二進位制讀寫檔案

//二進位制讀寫檔案

//開啟的是二進位制模式,寫入文字

//將當前的日期讀取之後,寫入到新建立的檔案裡面

#include #include #include int main(void)

fputc('5', fp);

fputc('2', fp);

fputc('0', fp);

fputc('\n', fp);

fclose(fp);

return 0;

}

二進位制讀寫檔案愛你

fread()

fwrite()

//證明:開啟的形式,和具體寫入的模式,沒有影響的 

//fread和fwrite將乙個結構體寫入檔案中,然後讀取出來,列印螢幕上

#include #include #include struct date

;struct book

;int main(void)

strcmp(book_for_write->name, "《帶你學c帶你飛》");

strcmp(book_for_write->author, "小甲魚");

strcmp(book_for_write->publisher, "清華大學出版社");

book_for_write->date.year = 2017;

book_for_write->date.month = 11;

book_for_write->date.day = 11;

if ((fp = fopen("file.txt", "w")) == null)

fwrite(book_for_write, sizeof(struct book), 1, fp);

fclose(fp);

//為了驗證真的是否寫入成功,開啟,讀取,列印

if ((fp = fopen("file.txt", "r")) == null)

fread(book_for_read, sizeof(struct book), 1, fp);

printf("書名:%s\n", book_for_read->name);

printf("出版社:%s\n", book_for_read->publisher);

printf("出版日期: %d-%d-%d\n", book_for_read->date.year, book_for_read->date.month,

book_for_read->date.day);

fclose(fp);

return 0;

}

小甲魚 P56 開啟和關閉檔案

小甲魚 p56 開啟和關閉檔案 在完成對乙個檔案的讀寫操作之後,你必須將其關閉。fopen函式用於開啟乙個檔案並返回檔案指標 file fopen const char path,const char mode path 指定待開啟的檔案路徑和檔名 支援相對路徑,絕對路徑 如果只給出檔名而不包含路徑...

小甲魚 P29 引數和指標

小甲魚 p29 引數和指標 乙個函式僅實現乙個功能 型別名 函式名 引數列表 函式體形參和實參 形參 形式引數 實參 實際引數 傳值和傳址 指標 傳陣列 include void get array int a 10 void get array int a 10 int main int i ge...

小甲魚 P25 void指標和NULL指標

小甲魚 p25 void指標和null指標 void指標 通用指標。就是可以指向任意型別的資料,也就是說,任何型別的指標都可以賦值給void指標 include int main void 結果 字串指標,列印時,不用解引用!ps 字串在c語言中規定,只需要指向字串的起始位址,然後它就會乙個位元組乙...