C\C++关于FILE结构定义说明
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
文件的打开、关闭、以及简单读写
# include <stdio.h>
# include <stdlib.h>
int main() {
FILE * open_file(char *, char *);
FILE *fp;
fp = open_file("C:/Users/kinglyjn/Desktop/test.txt", "a+");
char c = getchar();
while (c!='*') {
fputc(c, fp);
c = getchar();
}
fclose(fp);
fp = open_file("C:/Users/kinglyjn/Desktop/test.txt", "r");
c = fgetc(fp);
while (c!=EOF) {
putchar(c);
c = fgetc(fp);
}
fclose(fp);
return 0;
}
FILE * open_file(char * filename, char * mode) {
FILE *fp = fopen(filename, mode);
if (fp==NULL) {
printf("打开失败!\n");
exit(1);
} else {
printf("打开成功!\n");
}
return fp;
}
块读写函数fwrite和fread
# include <stdio.h>
# include <stdlib.h>
typedef struct Student {
char name[10];
float score;
} Stu;
int main() {
FILE * open_file(char *, char *);
FILE *fp;
Stu stus[3] = { {"张三", 22.2}, {"李四", 33.3}, {"王五", 44.4} };
Stu stus2[3];
int len = 3;
fp = open_file("/Users/zhangqingli/Desktop/test.txt", "w");
for (int i=0; i<len; i++) {
fwrite(&stus[i], sizeof(Stu), 1, fp);
}
fclose(fp);
fp = open_file("/Users/zhangqingli/Desktop/test.txt", "r");
for (int i=0; i<len; i++) {
fread(&stus2[i], sizeof(Stu), 1, fp);
}
fclose(fp);
for (int i=0; i<len; i++) {
printf("%-10s %-5.2f\n", stus2[i].name, stus2[i].score);
}
return 0;
}
FILE * open_file(char * filename, char * mode) {
FILE *fp = fopen(filename, mode);
if (fp==NULL) {
printf("打开失败!\n");
exit(1);
} else {
printf("打开成功!\n");
}
return fp;
}
格式化文件输入和输出函数fprintf和fscanf
- printf/scanf函数的读写对象是终端
- fprintf/fscanf函数的读写对象是磁盘文件
# include <stdio.h>
# include <stdlib.h>
typedef struct {
char name[10];
float score;
} St;
int main() {
FILE * fp;
FILE * open_file(char * filename, char * mode);
fp = open_file("/Users/zhangqingli/Desktop/test.txt", "w");
fprintf(fp, "%s %f", "张三", 23.2);
fprintf(fp, "%s %f", "李四", 23.3);
fprintf(fp, "%s %f", "王五", 23.4);
fclose(fp);
St *stus = (St *) malloc(sizeof(St)*3);
fp = open_file("/Users/zhangqingli/Desktop/test.txt", "r");
int i=0;
while (!feof(fp)) {
fscanf(fp, "%s %f", stus[i].name, &stus[i].score);
i++;
}
fclose(fp);
for (int i=0; i<3; i++) {
printf("姓名:%s 分数:%f\n", stus[i].name, stus[i].score);
}
return 0;
}
FILE * open_file(char * filename, char * mode) {
FILE *fp = fopen(filename, mode);
if (fp==NULL) {
printf("打开失败!\n");
exit(1);
} else {
printf("打开成功!\n");
}
return fp;
}
文件的定位
# include <stdio.h>
# include <stdlib.h>
int main() {
FILE *fp1;
FILE * open_file(const char *, const char *);
fp1 = open_file("/Users/zhangqingli/Desktop/test.txt", "rb");
fseek(fp1, 0, SEEK_END);
long len = ftell(fp1);
printf("文件的大小为:%ld 字节\b", len);
return 0;
}
FILE * open_file(const char * filename, const char * mode) {
FILE *fp = fopen(filename, mode);
if (fp==NULL) {
printf("文件打开时出错!\n");
exit(1);
}
return fp;
}