标准C库对文件操作的引入
生活随笔
收集整理的這篇文章主要介紹了
标准C库对文件操作的引入
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
modeopen和fopen的區(qū)別
fopen、fread、fwrite的使用
(1)fopen
(2)fwrite
size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream); ptr: 表示緩沖區(qū) size: 代表一條記錄的長(zhǎng)度 nmemb: 代表寫(xiě)入長(zhǎng)度的個(gè)數(shù) stream: 表示要寫(xiě)入哪個(gè)文件(已打開(kāi)文件的指針,一般就是fopen的返回值) 返回值:讀或?qū)懙挠涗洈?shù),成功時(shí)返回的記錄數(shù)等于 nmemb,出錯(cuò)或讀到文件末尾時(shí)返回的記錄數(shù)小于 nmemb,也可能返回 0。(3)fread
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);ptr: 表示緩沖區(qū) size: 代表一條記錄的長(zhǎng)度 nmemb: 代表寫(xiě)入長(zhǎng)度的個(gè)數(shù) stream: 表示要寫(xiě)入哪個(gè)文件(已打開(kāi)文件的指針,一般就是fopen的返回值) 返回值:Fread()會(huì)返回實(shí)際讀取到的nmemb數(shù)目, 也可能返回0,如果此值比參數(shù)nmemb 來(lái)得小,則代表可能讀到了文件尾或有錯(cuò)誤發(fā)生, 這時(shí)必須用feof()或ferror()來(lái)決定發(fā)生什么情況。(4)fseek
int fseek(FILE *stream, long offset, int whence); //用法和lseek類(lèi)似,作用定位光標(biāo)代碼示例
#include <stdio.h> #include<string.h> int main() {FILE*fp;char*str="I am handsome";char readbuf[128]={0};fp=fopen("./feng.txt","w+");fwrite(str,sizeof(char),strlen(str),fp);fwrite(str,sizeof(char)*strlen(str),1,fp);fseek(fp,0,SEEK_SET);fread(readbuf,sizeof(char),strlen(str),fp);printf("read sata:%s\n",readbuf);return 0; }標(biāo)準(zhǔn)c庫(kù)寫(xiě)結(jié)構(gòu)體到文件
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> struct text {int a;char c; }; int main() {FILE*fp;struct text data={100,'a'};struct text data2;fp=fopen("./file1","w+");//"./file1" is wenjianlujingint n_write=fwrite(&data,sizeof(struct text),1,fp);//write return zijie de changdufseek(fp,0,SEEK_SET);int n_read=fread(&data2,sizeof(struct text),1,fp);printf("read %d,context %c\n",data2.a,data2.c);fclose(fp);return 0; }文件其他函數(shù)講解
(1)fputc
(2)feof
int feof(FILE *stream); 作用:測(cè)試是否到達(dá)文件的尾巴,若沒(méi)有則返回0,若到達(dá)則返回非0。(3)fgetc
int fgetc(FILE *stream); 作用:將文件中的字符一個(gè)個(gè)讀到返回的c中,然后再printf輸出代碼演示
#include<stdio.h> #include<string.h> int main() {FILE*fp;int i;char*str="I am handsome";int len=strlen(str);fp=fopen("./file1","w+");fputc('a',fp);for(i=0;i<len;i++){fputc(*str,fp);str++;}fclose(fp);return 0; } include<stdio.h> #include<string.h> int main() {FILE*fp;char i;fp=fopen("./file1","r");while(!feof(fp)){i=fgetc(fp);printf("%c\n",i);}fclose(fp);return 0;}總結(jié)
以上是生活随笔為你收集整理的标准C库对文件操作的引入的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 玩转oracle 11g(35):rma
- 下一篇: java学习(32):巩固练习