c89 file io

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
char buff[1000];
char chbuff;
int success;

// file_exists   true       false
// r             从头读      失败
// w             *销毁文件*  创建文件
// a             *销毁文件*  创建文件
// '+'同时赋予读/写能力
FILE* file = fopen("p/to/file.txt", "r+");
if (file == NULL) return;

// 读
success = fgets(buff, sizeof buff, file);
chbuff = fgetc(file);
fscanf(file, "%s", buff);

// 写
fputs("hello", file);
fputc('c', file);
fprintf(file, "hello world!\n");

// 定位
fpos_t* pos = NULL;
// 读
int posn = ftell(file); // 获取当前位置
fgetpos(file, pos);
// 写
rewind(file); // 回到开头
fseek(5, SEEK_SET); // 从开头数 5
fseek(5, SEEK_CUR); // 从当前数 5
fseek(5, SEEK_END); // 从末尾数 5
fsetpos(file, pos + 114514);

fclose(file);
读写函数 file 参数の位置

  1. 有变长参数包,如 fscanf/fprintf,参数 file 在开头
  2. 无变长参数包,如 fputs / fgetc,参数 file 在结尾
最后更新于 Dec 29, 2025 20:46 +0800