C++文件操作具體應(yīng)用函數(shù)介紹
C++編程語言應(yīng)用方式靈活,可以被看做C語言的升級版本。我們可以通過這篇文章介紹的關(guān)于C++文件操作的相關(guān)方法來對這一計(jì)算機(jī)編程語言的相關(guān)應(yīng)用技巧有一個(gè)初步的掌握,并從中加深對這一語言的認(rèn)知程度。#t#
1.C++文件操作中的函數(shù)功能
用來讀寫一個(gè)數(shù)據(jù)塊。
2.一般調(diào)用形式
fread(buffer,size,count,fp);
fwrite(buffer,size,count,fp);
3.說明
(1)buffer:是一個(gè)指針,對fread來說,它是讀入數(shù)據(jù)的存放地址。對fwrite來說,是要輸出數(shù)據(jù)的地址。
(2)size:要讀寫的字節(jié)數(shù);
(3)count:要進(jìn)行讀寫多少個(gè)size字節(jié)的數(shù)據(jù)項(xiàng);
(4)fp:文件型指針。
注意:1 完成次寫操(fwrite())作后必須關(guān)閉流(fclose());
2 完成一次C++文件操作(fread())后,如果沒有關(guān)閉流(fclose()),則指針(FILE * fp)自動(dòng)向后移動(dòng)前一次讀寫的長度,不關(guān)閉流繼續(xù)下一次讀操作則接著上次的輸出繼續(xù)輸出;
3 fprintf() : 按格式輸入到流,其原型是int fprintf(FILE *stream, const char *format[, argument, ...]);其用法和printf()相同,不過不是寫到控制臺,而是寫到流罷了。注意的是返回值為此次操作寫入到文件的字節(jié)數(shù)。如int c = fprintf(fp, "%s %s %d %f", str1,str2, a, b) ;str1:10字節(jié);str2: 10字節(jié);a:2字節(jié);b:8字節(jié),c為33,因?yàn)閷懭霑r(shí)不同的數(shù)據(jù)間自動(dòng)加入一個(gè)空格。
文件使用之后一定要關(guān)閉,否則將不能正確顯示內(nèi)容.fwrite:讀入兩個(gè)學(xué)生信息然后用fwrite存入文件
fread:用fread從文件中讀出學(xué)生信息。
- fwrite.c
- #include <stdio.h>
- #define SIZE 2
- struct student_type
- {
- char name[10];
- int num;
- int age;
- char addr[10];
- }stud[SIZE];
- void save()
- {
- FILE *fp;
- int i;
- if((fp=fopen("stu_list","wb"))==NULL)
- {
- printf("cant open the file");
- exit(0);
- }
- for(i=0;i<SIZE;i++)
- {
- if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
- printf("file write error\n");
- }
- fclose(fp);
- }
- main()
- {
- int i;
- for(i=0;i<SIZE;i++)
- {
- scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
- save();
- }
- for(i=0;i<SIZE;i++)
- {
- printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
- }
- }
- fread.c
- #include <stdio.h>
- #define SIZE 2
- struct student_type
- {
- char name[10];
- int num;
- int age;
- char addr[10];
- }stud[SIZE];
- void read()
- {
- FILE *fp;
- int i;
- if((fp=fopen("stu_list","rb"))==NULL)
- {
- printf("cant open the file");
- exit(0);
- }
- for(i=0;i<SIZE;i++)
- {
- if(fread(&stud[i],sizeof(struct student_type),1,fp)!=1)
- printf("file write error\n");
- }
- fclose(fp);
- }
- main()
- {
- int i;
- read();
- for(i=0;i<SIZE;i++)
- {
- printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
- printf("\n");
- }
- }
C++文件操作相關(guān)方法就為大家介紹到這里。