1. fopen fclose(并指针=NULL)
#include<stdio.h>
//文件路径 //打开方式
FILE *fopen(const char *path, const char *mode);
打开方式如下:
r: 只读,文件必须存在,从头读
r+: 读写,文件必须存在,从头读写
w: 只写,文件不存在就创建,存在就清空,从头写
w+:写读,文件不存在就创建,存在就清空,从头写读
a: 追加,文件不存在就创建,存在不清空,从尾写
a+: 追读,文件不存在就创建,纯在不清空,从尾写,从头读
#include <stdio.h>
int main(void){
//打开文件
FILE* fp = fopen("a.txt", "r");
if(NULL == fp){
printf("文件打开失败\n");
return -1;
}
printf("文件打开成功\n");
//对文件的操作
//..
//关闭文件,并NULL指针
fclose(fp);
fp = NULL;
return 0;
}
2. fread fwrite
#include <stdio.h>
int main(void){
FILE* fp = fopen("a.txt", "w+");
if(NULL == fp){
printf("文件打开失败\n");
return -1;
}
//对文件进行操作
//将数组a中8个数据写入到a.txt文件中
int a[8] = {1,2,3,4,5,6,7,8};
int size_w = fwrite(a, sizeof(int), 8, fp);
printf("实际写入了%d个数据\n", size_w);
rewind(fp);
//将这8个数据从a.txt文件中读取出来存储到数组b中
int b[8] = {0};
int size_r = fread(b, sizeof(int), 8, fp);
printf("实际读取了%d个数据\n", size_r);
for(int i = 0; i < size_r; i++){
printf("%d ", b[i]);
}
printf("\n");
//关闭文件
fclose(fp);
fp = NULL;
return 0;
}
3. rewind ftell
rewind函数将位置指针移动到开头
ftell函数用来返回位置指针的数值
4. fseek
fseek函数将位置指针移动到文件的任意位置
//函数原型
int fseek(FILE *stream, long offset, int whence);
FILE* fp = fopen("a.txt","w+");
fseek(fp, 2, SEEK_SET); //读写位置从文件头向后移动2字节
fseek(fp, 4, SEEK_CUR); //读写位置从当前位置向后移动4字节
fseek(fp, -6, SEEK_END); //读写位置从文件尾向前移动6字节
printf("位置在%ld\n",ftell(fp)); //显示当前文件的读写位置
//fseek.c
#include <stdio.h>
int main(void){
FILE* fp = fopen("a.txt", "w+");
if(NULL == fp){
printf("文件打开失败\n");
return -1;
}
//对文件进行操作
//将数组a中8个数据写入到a.txt文件中
int a[8] = {1,2,3,4,5,6,7,8};
int size_w = fwrite(a, sizeof(int), 8, fp);
printf("实际写入了%d个数据\n", size_w);
rewind(fp);
//将这8个数据从a.txt文件中读取出来存储到数组b中
int b[8] = {0};
int size_r = fread(b, sizeof(int), 8, fp);
printf("实际读取了%d个数据\n", size_r);
for(int i = 0; i < size_r; i++){
printf("%d ", b[i]);
}
printf("\n");
//fseek
//打开新文件后, 位置指针在文件开头
//---- ---- ---- ---- ---- ---- ---- ----
//1 2 3 4 5 6 7 8
// ^
// 读取的时候,从当前位置向后读
printf("当前文件的位置指针是:%ld\n", ftell(fp)); //32,即前有32字节
int c[2] = {0};
fseek(fp, 8, SEEK_SET);//从文件开头向后移动8个字节
//---- ---- ---- ---- ---- ---- ---- ----
//1 2 3 4 5 6 7 8
// ^
fread(c, sizeof(int), 2, fp);
printf("%d %d\n", c[0], c[1]);//3 4
//---- ---- ---- ---- ---- ---- ---- ----
//1 2 3 4 5 6 7 8
// ^
printf("当前文件的位置指针是:%ld\n", ftell(fp)); // 16,即前有16字节
//关闭文件
fclose(fp);
fp = NULL;
return 0;
}
5. fprintf fscanf
效率低于fwrite和fread,不适合处理数据多的文件
//fprintf.c
#include <stdio.h>
int main(void){
//READ
//b.txt: 1000 helo 7.9
FILE* fpr = fopen("b.txt", "r");
int a = 0;
char str[24] = {0};
double d = 0.0;
fscanf(fpr, "%d%s%lg", &a, str, &d);
fclose(fpr);
fpr = NULL;
printf("a = %d, str = %s, d = %lg\n", a, str, d);
//WRITE
//将a,str,d的数据写入到c.txt
FILE* fpw = fopen("c.txt", "w+");
fprintf(fpw, "%d,%s,%lg\n", a, str, d);
fclose(fpw);
fpw = NULL;
return 0;
}
6. stdin stdout stderr
int a = 10;
printf("%d\n", a); == fprintf(stdout, "%d\n", a);
scanf("%d", &a); == fscanf(stdin, "%d\n", a);