C經典 檔案的操作

2021-07-11 17:11:07 字數 3731 閱讀 6692

一、常用函式

二、檔案指標,指向檔案的指標

file *fp;

三、檔案的開啟與關閉

file *fp = fopen(檔名,使用檔案方式)

如:file *fp = null;

fp = fopen(」 file.txt」,」r」);//r 表示讀檔案

int result = fclose(fp) ;// =0,如果不等於0,表示發生錯誤

四、讀寫方式

五、補充:

\0 :表示字串結束

\n :表示回車換行

eof :表示檔案的末尾

六、關於中文讀取

因為乙個漢字佔三個位元組,乙個位元組等於8位

在c語言裡每個字串結束時都以\0

所以在讀取的時候不能唯讀三個,會亂碼

file *fp = fopen(「a.txt」,」r」);

裡存放的是中文

錯誤**如:

char ch[3] ;

fgets(ch,3, fp);

printf("%s\n",ch);

正確**如:

char ch[4] ;

fgets(ch,4, fp);

printf("%s\n",ch);

七、示例**1

#include 

#include

int main(int argc, const

char * argv)

}else

printf("\n");

file *fr = null;

fr = fopen("a.txt", "r");

if(fr != null)

}else

//fclose(fw);

//fclose(fr);

printf("\n");

return

0;}

七、示例**2

#include 

#include

int main(int argc, const

char * argv)

fclose(fp);

printf("\n");

//把指標移到開始位置

rewind(fp);

//讀取資料

ch = fgets(fp);

while(ch != eof)

}else

printf("\n");

return

0;}

八、fread與fwrite函式1)fread(buffer,size,count,fp);

示例**:

fwrite寫入資料

file *fp =fopen("a.txt","wb");

if(fp !=null)else

fclose(fp);

fread讀取資料

file *fp =fopen("a.txt","rb");

if(fp !=null)else

fclose(fp);

九、結構體的讀寫

#include 

struct student;

int main(int argc, const

char * argv)

,,};

file *fp = fopen("stu.data", "wb+");

if(fp !=null)

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

rewind(fp);

struct student s[3];

for(int i = 0; i < 3; i++)

}fclose(fp);

printf("\n\n");

return

0;}

十、fscanf和fprintf的用法

示例1

#include 

int main(int argc, const char * argv)

printf("\n");

return

0;}

示例2

#include /** 

讀寫如下檔案

1,2#

3,4#

5,6#

*/int main(int argc, const

char * argv)

; //定義指標

file *fp = fopen("a.txt", "w+");

//if (fp!=null)

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

rewind(fp);

//讀取

int arr[3][2];

for (int i = 0; i <3; i ++)

}fclose(fp);

return

0;}

一、檔案隨機讀取,定位fseek

fseek(fp,curposition,headposition);

如:fseek(fp,100l,0);

檔案首:seek_set 0

當前位置:seek_cur 1

檔案尾部:seek_end 2

示例:讀取第二個學生的成績

#include 

struct student;

int main(int argc, const

char * argv)

,,};

file *fp = fopen("stu.data", "wb+");

if(fp !=null)

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

//定位到第二個學生

fseek(fp,sizeof(struct student),seek_set);

fread(&stu,sizeof(struct student),1,fp);

printf("%s\t",stu.name);}}

fclose(fp);

printf("\n\n");

return

0;}

C 中常用的經典檔案操作方

c 追加檔案 sw.writeline 追逐理想 sw.writeline kzlll sw.writeline net筆記 sw.flush sw.close c 拷貝檔案 c 刪除檔案 file.delete delfile c 移動檔案 c 建立目錄 遞迴刪除資料夾及檔案 實現乙個靜態方法將指...

C 中常用的經典檔案操作方法

c 追加檔案 在指定目錄下新建乙個檔案,並寫入內容。sw.writeline 追逐理想 writeline寫入內容到mytext.txt。sw.flush sw.close c 拷貝檔案 string orignfile,newfile file.copy orignfile,newfile,tru...

PHP檔案操作的經典案例

遍歷目錄函式,只讀取目錄的最外層的內容 function readdirectory path if is dir path.item closedir handle return arr 獲取資料夾大小 function dirsize path if is dir path.item close...