以下是
- 前言
- 1、fread
- 2、fwrite
- 3、fgetpos
- 4、fseek
- 5、fsetpos
- 6、ftell
- 7、rewind
- 8、perror
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
案例
void Demo_fread(){
char buf[100] = {0};
FILE *fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
rewind(fp);
fread(buf, size, sizeof(char), fp);
printf(buf);
fclose(fp);
}
2、fwrite
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
案例
void Demo_fwrite(){
char *buf = "T like...";
FILE *fp = fopen("test.txt", "w");
fwrite(buf, strlen(buf), sizeof(char), fp);
fclose(fp);
}
3、fgetpos
int fgetpos ( FILE * stream, fpos_t * pos );
案例
void Demo_fgetpos(){
fpos_t pos; // 定义传出参数
FILE *fp = fopen("test.txt", "r");
fgetpos(fp, &pos); // 获取指针
printf("文件指针当前位置:%dn", pos);
fclose(fp);
}
4、fseek
int fseek ( FILE * stream, long int offset, int origin ); 注意:库允许实现无意义地支持SEEK_END(因此,使用它的代码没有真正的标准可移植性)
案例
void Demo_fseek(){
fpos_t pos;
FILE *fp = fopen("test.txt", "w+");
for (char ch = 'A'; ch < 'K'; ++ch){
if (ch == 'C'){
// 设置文件指针会到开头
fseek(fp, 0, SEEK_SET);
printf("文件指针回溯...n");
}
fputc(ch, fp); // 写入文件
fgetpos(fp, &pos); // 获取文件指针当前位置
printf("文件指针当前位置:%dn", pos);
}
printf("文件指针当前位置:%dn", pos);
fclose(fp);
}
5、fsetpos
int fsetpos ( FILE * stream, const fpos_t * pos );
案例
void Demo_fsetpos(){
fpos_t pos;
FILE *fp = fopen("test.txt", "w+");
for (char ch = 'A'; ch < 'K'; ++ch){
if (ch == 'C'){
fgetpos(fp, &pos); // 获取文件指针当前位置
printf("已获取文件指针%dn", pos);
}
if (ch == 'E'){ // 当字符为E时重新设置指针到C,写入,因此C到E间的字母会被覆盖
printf("重新设置文件指针...n");
fsetpos(fp, &pos);
}
fputc(ch, fp); // 写入文件
}
fclose(fp);
}
6、ftell
long int ftell ( FILE * stream );
案例
void Demo_fread(){
char buf[100] = {0};
FILE *fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END); // 将文件指针设置到文件末尾
int size = ftell(fp); // 返回位置指示器的当前值
rewind(fp); // 将文件指针设置会开头位置
fread(buf, size, sizeof(char), fp);
printf(buf);
fclose(fp);
}
7、rewind
void rewind ( FILE * stream );
案例
void Demo_fread(){
char buf[100] = {0};
FILE *fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END); // 将文件指针设置到文件末尾
int size = ftell(fp); // 返回位置指示器的当前值
rewind(fp); // 将文件指针设置会开头位置
fread(buf, size, sizeof(char), fp);
printf(buf);
fclose(fp);
}
8、perror
void perror ( const char * str );
案例
void Demo_perror(){
FILE *fp = fopen("test1.txt", "r");
if (fp == NULL){
perror("file open");
}else{
fclose(fp);
}
}



