一、二进制文件
1. 写入二进制文件
void writeBinaryContent() {
char location[] = "../file.txt";
FILE * fp = fopen(location, "w");
// CEC4 BCFE -> 文件
char buff[128] = {0xce, 0xc4, 0xbc, 0xfe};
unsigned int res = fwrite(buff, 2, 2, fp);
printf("%d\n", res);
fclose(fp);
}
2. 读取二进制文件
void readBinaryContent() {
char location[] = "../file.txt";
FILE * fp = fopen(location, "r");
char buff[128];
unsigned int res = fread(buff, 2, 2, fp);
printf("%d\n", res);
buff[4] = 0;
printf("%s", buff);
fclose(fp);
}
二、文本文件
1. 写入文本文件
void writeTextContent() {
char location[] = "../file.txt";
FILE * fp = fopen(location, "w");
// int res = fputc(97, fp); // 操作失败会返回一个负数
int res = fputs("文件io", fp); // 操作失败会返回 -1(EOF)
printf("%d\n", res);
fclose(fp);
}
2. 读取文本文件
void readTextContent() {
char location[] = "../file.txt";
FILE * fp = fopen(location, "r");
// int res = fgetc(fp); // 只适用于英文字符
char buff[128];
// char* res;
// res = fgets(buff, 5, fp);
// printf("res == buff ? %d\n", buff == res);
// printf("%#x\n", res);
// fscanf(fp, "%s", buff); // fscanf 首先读取一串字符串,当它读取到 \n 或者是空格就会直接读到的内容
fclose(fp);
}
三、标准输入输出流
- -输入 到 屏幕显示 过程
- scanf 和 printf 的实现
void myPrintf(char * str) {
fprintf(stdout, "%s", str);
}
void myScanf(char * buff) {
fscanf(stdin, "%s", buff);
}
三、递归
自己调用自己
斐波那契数列:
- 1 1 2 3 5 8 …
- 第 20 项 等于 什么呢?
#include <stdio.h>
// 计算斐波那契数列的第 n 项
int fib(int n, int mem[]) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 1;
}
if (mem[n] != 0) {
return mem[n];
}
int res = fib(n - 1, mem) + fib(n - 2, mem);
mem[n-1] = res;
return res;
}
int main() {
int mem[100];
for (int i = 0; i < 101; i++) {
mem[i] = 0;
}
printf("%d\n", fib(1000, mem));
}