文件位置的操作fseek
1 #include <stdio.h> 2 /*************************** 3 * 头文件:#include <stdio.h> 4 * 函数:int fseek(FILE *stream, long offset, int whence); 5 * 功能:重定向我们的文件操作位置 6 * 参数: 7 * stream 前面打开的流地址 8 * offset 向前移动填负数,向后移动填正数,0 9 * whence SEEK_SET(开始位置), SEEK_CUR(当前位置), SEEK_END(末尾位置) 10 * 返回值: 11 * 成功:返回0 12 * 失败:返回EOF(-1) 13 * *************************/ 14 int main() 15 { 16 FILE *fp = NULL; 17 fp = fopen("test.txt","w+"); 18 if(fp == NULL) 19 { 20 printf("打开文件失败:\n"); 21 return -1; 22 } 23 24 printf("打开文件成功:\n"); 25 26 fprintf(fp,"%s %s %s %d %s\n","小明","吃饭","睡觉",2021,"打豆豆"); 27 //写完后想读前面内容 28 fseek(fp,0,SEEK_SET); 29 30 char name[20] = ""; 31 int yer = 0; 32 char movement_1[20] = ""; 33 char movement_2[20] = ""; 34 char movement_3[20] = ""; 35 36 fscanf(fp,"%s %s %s %d %s\n",name,movement_1,movement_2,&yer,movement_3); 37 printf("%s %s %s %d %s\n",name,movement_1,movement_2,yer,movement_3); 38 39 40 if(fclose(fp) == EOF ) 41 { 42 printf("关闭失败\n"); 43 } 44 else 45 { 46 printf("关闭成功\n"); 47 } 48 49 return 0; 50 }