ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[toc] # 基础部分 ## 编译/执行 main.c ```c #include <stdio.h> int main() { printf("我的第一个程序,你好,%s \n", "打工人"); return 0; } ``` 编译并运行 `gcc main.c && ./a.out` gcc main.c 编译 ./a.out 运行编译结果 ## 文件操作 ```c char fname[] = "./lzsb.txt"; ``` ### 写入文件 ```c char str[] = "你好,打工人"; // 欲写入内容 FILE* f = fopen(fname, "w"); // 打开文件 fwrite(str, sizeof(str), 1, f); // 写入 fclose(f); // 关闭文件占用 ``` ### 读取文件 ``` FILE *f = fopen(fname, "r"); /* 取文件长度 START (适用2GB内文件) */ fseek(f, 0, SEEK_END); int size = ftell(f); fseek(f, 0, SEEK_SET); /* 取文件长度 END */ char buffer[size]; // 设置缓存区 fseek(f, 0, SEEK_SET); fread(buffer, size, 1, f); // 缓存变量, 读取长度, 元素个数, 文件流 fclose(f); printf("%s", buffer); ``` ## bit和byte > bit 比特位, 8bit = 1byte 计算机只能认识二进制,每个bit只能存放0或1, 所以`bit`是计算机能读懂的最小单位 ``` 11111111 一个字节,同时是8个bit(比特位) 01011011 ``` ``` 比特位,bit, b 字节,Byte, B ``` ![](https://img.kancloud.cn/c7/58/c758e0893f9fa056510b310dd8063fcb_942x648.png) ## 取值范围 ![](https://img.kancloud.cn/a1/57/a157a11274bb45e41c1bed2c93e26314_933x646.png) 参考:[【C语言】《带你学C带你飞》\_哔哩哔哩\_bilibili](https://www.bilibili.com/video/BV17s411N78s?p=7) ## 基本数据类型 ![](https://img.kancloud.cn/d7/7d/d77dd7fab53cef7fd38a445c546842f9_696x493.png) **数值类/字符数据类型长度** |类型 | 长度 | | ---|---| |int |4| |short int |2| |long long int |8| |char |1| |_Bool |1| |float |4| |double |8| |long double |16| **signed 和 unsigned(无符号)** - `signed` 带符号数字,可以存负数 - `unsigned` 不带符号数字,不允许负数;只能存在`0`和非负数,多出来的空间可以存更大的数, 比`signed`翻一倍(似乎?) > 最佳实践:默认情况所有整形都是`signed`,另外`printf`时无符号数字需要选对格式字符 ``` [signed] int age = -100; // 可以是负数 unsigned int age = 100; // 不带符号, 不能是负数,最小为0 ``` ### 数据类型强制转换 与php一样 ``` int i = 1 + (int)1.8; // 强制把1.8转换整数,舍弃小数点 ``` ## 常用函数 ### printf 格式化文本输出,全称`print format` ``` printf("%s出生于%d年%d三月", "余小波", 1997, 3); > 余小波出生于1997年3月 ``` **格式字符** - `%s` 用于替代字符串 - `%c` 用于替代一个字符 - `%d` 用于替代整数 - `%f` 用于替代小数 [更多参考](https://www.runoob.com/cprogramming/c-function-printf.html) ### sizeof 用于计算一个变量/常量/数据类型的占用长度 ```shell int age = 24; sizeof(age) > 4 ```