《C语言从零到系统编程》
1. 环境搭建
1.1 编译器安装
- Windows: 安装 MinGW-w64 或 Visual Studio Community(含MSVC编译器)。
- Linux: 使用包管理器安装GCC:
sudo apt install gcc # Debian/Ubuntu sudo yum install gcc # CentOS
- macOS: 安装Xcode Command Line Tools:
xcode-select --install
1.2 IDE配置(以VS Code为例)
- 安装扩展:C/C++、Code Runner。
- 创建
hello.c
文件,输入以下代码:#include <stdio.h> int main() { printf("Hello, System Programming!\n"); return 0; }
- 按
Ctrl+Alt+N
运行代码,观察输出。
2. 基础语法与数据类型
2.1 变量与运算符
int age = 25;
float price = 19.99;
char grade = 'A';
// 位运算示例
int a = 5; // 0101
int b = 3; // 0011
int c = a & b; // 0001 (1)
2.2 控制结构
// if-else
if (age >= 18) {
printf("Adult\n");
} else {
printf("Minor\n");
}
// 循环
for (int i=0; i<5; i++) {
printf("%d ", i); // 0 1 2 3 4
}
3. 函数、结构体与指针
3.1 函数与指针
// 交换两个数的函数
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("x=%d, y=%d\n", x, y); // x=20, y=10
}
3.2 结构体与动态内存
typedef struct {
char name[50];
int age;
} Person;
Person *p = malloc(sizeof(Person));
strcpy(p->name, "Alice");
p->age = 30;
free(p); // 必须手动释放!
4. 文件操作与动态内存管理
4.1 文件读写
FILE *file = fopen("data.txt", "w");
if (file != NULL) {
fprintf(file, "Hello File!\n");
fclose(file);
}
// 读取文件
char buffer[100];
file = fopen("data.txt", "r");
fgets(buffer, 100, file);
printf("%s", buffer); // Hello File!
4.2 动态数组实现
int *arr = malloc(5 * sizeof(int));
arr[0] = 10;
arr = realloc(arr, 10 * sizeof(int)); // 扩容至10元素
free(arr);
5. 系统调用入门(Linux示例)
5.1 进程创建(fork)
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
printf("Child Process\n");
} else {
printf("Parent Process\n");
}
return 0;
}
5.2 执行外部命令(exec)
#include <unistd.h>
execlp("ls", "ls", "-l", NULL); // 执行 ls -l
6. 实战:实现一个简易Shell
代码框架
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_INPUT 1024
int main() {
char input[MAX_INPUT];
while (1) {
printf("mysh> ");
fgets(input, MAX_INPUT, stdin);
input[strcspn(input, "\n")] = '\0'; // 去除换行符
pid_t pid = fork();
if (pid == 0) {
// 子进程执行命令
execlp(input, input, NULL);
exit(0);
} else {
wait(NULL); // 父进程等待
}
}
return 0;
}
运行效果
mysh> ls
hello.c data.txt mysh
mysh> pwd
/home/user/code
7. 下一步学习建议
- 扩展Shell功能:添加管道(
|
)、重定向(>
)支持。 - 深入学习系统编程:阅读《UNIX环境高级编程》。
- 参与开源项目:贡献Linux工具(如coreutils)的小功能。
GitHub参考仓库:simple-shell(包含完整代码与扩展练习)
这篇文档通过从环境搭建到实战项目的完整路径,帮助读者理解C语言如何与操作系统交互。下一步可根据需求深入文件系统、信号处理等主题。