C 语言示例
C语言编程示例和系统编程基础
💻 C Hello World c
🟢 simple
⭐
C Hello World程序和基本语法示例
⏱️ 15 min
🏷️ c, programming, beginner
Prerequisites:
Basic programming concepts
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 1. Basic Hello World
int main() {
printf("Hello, World!\n");
return 0;
}
// 2. Hello World with function
void sayHello() {
printf("Hello, World!\n");
}
// 3. Hello World with function parameters
void greet(const char* name) {
printf("Hello, %s!\n", name);
}
// 4. Hello World with variables
int main_variables() {
const char* message = "Hello, World!";
printf("%s\n", message);
char name[50];
printf("Enter your name: ");
scanf("%49s", name);
printf("Hello, %s!\n", name);
return 0;
}
// 5. Hello World with command line arguments
int main_args(int argc, char* argv[]) {
if (argc > 1) {
printf("Hello, %s!\n", argv[1]);
} else {
printf("Hello, World!\n");
}
return 0;
}
// 6. Hello World multiple times
int main_multiple() {
for (int i = 0; i < 5; i++) {
printf("Hello, World! %d\n", i + 1);
}
return 0;
}
// 7. Hello World with array
int main_array() {
const char* greetings[] = {"Hello", "Bonjour", "Hola", "Ciao"};
int count = sizeof(greetings) / sizeof(greetings[0]);
for (int i = 0; i < count; i++) {
printf("%s, World!\n", greetings[i]);
}
return 0;
}
// 8. Basic data types
int main_types() {
// Integer types
int integer = 42;
short short_num = 10;
long long_num = 1000000;
unsigned int unsigned_num = 50;
// Floating point types
float float_num = 3.14f;
double double_num = 2.71828;
// Character type
char character = 'A';
// Boolean (since C99)
#include <stdbool.h>
bool flag = true;
printf("Integer: %d, size: %zu bytes\n", integer, sizeof(integer));
printf("Float: %.2f, size: %zu bytes\n", float_num, sizeof(float_num));
printf("Double: %.5f, size: %zu bytes\n", double_num, sizeof(double));
printf("Character: %c, size: %zu bytes\n", character, sizeof(character));
printf("Boolean: %d, size: %zu bytes\n", flag, sizeof(bool));
return 0;
}
// 9. Control flow examples
int main_control_flow() {
int age = 18;
// If-else statement
if (age >= 18) {
printf("You are an adult\n");
} else {
printf("You are a minor\n");
}
// Switch statement
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
default: printf("Other day\n"); break;
}
// Loop examples
for (int i = 0; i < 3; i++) {
printf("For loop iteration: %d\n", i);
}
int j = 0;
while (j < 3) {
printf("While loop iteration: %d\n", j);
j++;
}
return 0;
}
// 10. Basic arithmetic operations
int main_arithmetic() {
int a = 10, b = 3;
printf("Addition: %d + %d = %d\n", a, b, a + b);
printf("Subtraction: %d - %d = %d\n", a, b, a - b);
printf("Multiplication: %d * %d = %d\n", a, b, a * b);
printf("Division: %d / %d = %d\n", a, b, a / b);
printf("Modulus: %d %% %d = %d\n", a, b, a % b);
// Floating point division
float fa = 10.0f, fb = 3.0f;
printf("Float division: %.2f / %.2f = %.2f\n", fa, fb, fa / fb);
return 0;
}
💻 C 指针和内存管理 c
🟡 intermediate
⭐⭐⭐⭐
C指针、内存分配和管理的综合示例
⏱️ 30 min
🏷️ c, pointers, memory, systems programming
Prerequisites:
Basic C syntax, Understanding of memory concepts
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 1. Basic pointer concepts
int basic_pointers() {
int num = 42;
int* ptr = # // ptr stores the address of num
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", (void*)&num);
printf("Value stored in ptr: %p\n", (void*)ptr);
printf("Value pointed to by ptr: %d\n", *ptr);
printf("Address of ptr: %p\n", (void*)&ptr);
// Modifying value through pointer
*ptr = 100;
printf("New value of num: %d\n", num);
return 0;
}
// 2. Pointer arithmetic
int pointer_arithmetic() {
int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr; // Points to first element
printf("Array elements using pointer arithmetic:\n");
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d (address: %p)\n", i, *(ptr + i), (void*)(ptr + i));
}
// Pointer increments
printf("\nPointer increments:\n");
int* current = arr;
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *current);
current++; // Move to next element
}
return 0;
}
// 3. Dynamic memory allocation
int dynamic_memory() {
// Allocating memory for an integer
int* dynamic_int = (int*)malloc(sizeof(int));
if (dynamic_int == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
*dynamic_int = 42;
printf("Dynamically allocated integer: %d\n", *dynamic_int);
free(dynamic_int);
printf("Memory freed\n");
// Allocating memory for an array
int size = 5;
int* dynamic_array = (int*)malloc(size * sizeof(int));
if (dynamic_array == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Initialize array
for (int i = 0; i < size; i++) {
dynamic_array[i] = i * 10;
}
printf("\nDynamic array elements:\n");
for (int i = 0; i < size; i++) {
printf("dynamic_array[%d] = %d\n", i, dynamic_array[i]);
}
// Resize array
int new_size = 10;
int* resized_array = (int*)realloc(dynamic_array, new_size * sizeof(int));
if (resized_array == NULL) {
printf("Reallocation failed!\n");
free(dynamic_array);
return 1;
}
// Initialize new elements
for (int i = size; i < new_size; i++) {
resized_array[i] = i * 10;
}
printf("\nResized array elements:\n");
for (int i = 0; i < new_size; i++) {
printf("resized_array[%d] = %d\n", i, resized_array[i]);
}
free(resized_array);
return 0;
}
// 4. Pointers and strings
int pointer_strings() {
// String literal (read-only)
const char* str_literal = "Hello, World!";
printf("String literal: %s\n", str_literal);
// Dynamic string allocation
char* dynamic_str = (char*)malloc(50 * sizeof(char));
if (dynamic_str == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
strcpy(dynamic_str, "Dynamic string");
printf("Dynamic string: %s\n", dynamic_str);
// Modifying dynamic string
strcat(dynamic_str, " with more text");
printf("Modified string: %s\n", dynamic_str);
// String operations with pointers
printf("\nString character by character:\n");
for (char* p = dynamic_str; *p != '\0'; p++) {
printf("'%c' (%d) ", *p, (int)*p);
}
printf("\n");
free(dynamic_str);
return 0;
}
// 5. Function pointers
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
int subtract(int a, int b) { return a - b; }
int function_pointers() {
// Array of function pointers
int (*operations[])(int, int) = {add, multiply, subtract};
const char* operation_names[] = {"Addition", "Multiplication", "Subtraction"};
int a = 10, b = 5;
for (int i = 0; i < 3; i++) {
int result = operations[i](a, b);
printf("%s: %d %s %d = %d\n", operation_names[i], a,
i == 0 ? "+" : i == 1 ? "*" : "-", b, result);
}
// Using function pointer as parameter
typedef int (*BinaryOperation)(int, int);
int compute(int x, int y, BinaryOperation op) {
return op(x, y);
}
int result = compute(20, 4, divide);
printf("Division result: %d\n", result);
return 0;
}
// Helper function for function pointers example
int divide(int a, int b) { return b != 0 ? a / b : 0; }
// 6. Double pointers
int double_pointers() {
int num = 42;
int* ptr = #
int** double_ptr = &ptr;
printf("Value: %d\n", num);
printf("Via pointer: %d\n", *ptr);
printf("Via double pointer: %d\n", **double_ptr);
// Modifying via double pointer
**double_ptr = 100;
printf("New value: %d\n", num);
return 0;
}
// 7. Memory leak simulation (don't do this in production!)
int memory_leak_example() {
printf("Memory allocation examples:\n");
// Correct allocation and deallocation
int* good_ptr = (int*)malloc(sizeof(int));
if (good_ptr != NULL) {
*good_ptr = 42;
printf("Good pointer value: %d\n", *good_ptr);
free(good_ptr);
printf("Good pointer freed correctly\n");
}
// Memory leak (intentionally not freeing for demonstration)
int* leak_ptr = (int*)malloc(sizeof(int));
if (leak_ptr != NULL) {
*leak_ptr = 100;
printf("Leak pointer value: %d\n", *leak_ptr);
// NOT freeing leak_ptr - this creates a memory leak
printf("Warning: leak_ptr not freed (memory leak)\n");
}
// Double free (demonstrates what NOT to do)
int* double_free_ptr = (int*)malloc(sizeof(int));
if (double_free_ptr != NULL) {
*double_free_ptr = 200;
free(double_free_ptr);
printf("Double free pointer freed once\n");
// free(double_free_ptr); // This would cause undefined behavior
printf("Second free avoided (would cause crash)\n");
}
return 0;
}
// 8. Structures with pointers
typedef struct Student {
char* name;
int age;
float* grades;
int num_grades;
} Student;
int structures_with_pointers() {
// Allocate student structure
Student* student = (Student*)malloc(sizeof(Student));
if (student == NULL) return 1;
// Allocate and set name
student->name = (char*)malloc(50 * sizeof(char));
if (student->name == NULL) {
free(student);
return 1;
}
strcpy(student->name, "John Doe");
student->age = 20;
student->num_grades = 3;
// Allocate grades array
student->grades = (float*)malloc(student->num_grades * sizeof(float));
if (student->grades == NULL) {
free(student->name);
free(student);
return 1;
}
student->grades[0] = 85.5f;
student->grades[1] = 92.0f;
student->grades[2] = 78.5f;
printf("Student: %s, Age: %d\n", student->name, student->age);
printf("Grades: ");
for (int i = 0; i < student->num_grades; i++) {
printf("%.1f ", student->grades[i]);
}
printf("\n");
// Free all allocated memory
free(student->grades);
free(student->name);
free(student);
return 0;
}
int main() {
printf("=== C Pointers and Memory Management Examples ===\n\n");
printf("1. Basic Pointers:\n");
basic_pointers();
printf("\n");
printf("2. Pointer Arithmetic:\n");
pointer_arithmetic();
printf("\n");
printf("3. Dynamic Memory Allocation:\n");
dynamic_memory();
printf("\n");
printf("4. Pointers and Strings:\n");
pointer_strings();
printf("\n");
printf("5. Function Pointers:\n");
function_pointers();
printf("\n");
printf("6. Double Pointers:\n");
double_pointers();
printf("\n");
printf("7. Memory Management Examples:\n");
memory_leak_example();
printf("\n");
printf("8. Structures with Pointers:\n");
structures_with_pointers();
printf("\n");
return 0;
}
💻 C 文件I/O和系统编程 c
🔴 complex
⭐⭐⭐⭐
文件操作、系统调用和底层编程
⏱️ 35 min
🏷️ c, file operations, systems programming, unix
Prerequisites:
C pointers, Memory management, Operating system concepts
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <time.h>
// 1. Basic file I/O with stdio
int basic_file_io() {
FILE* file;
const char* filename = "example.txt";
// Write to file
file = fopen(filename, "w");
if (file == NULL) {
perror("Error opening file for writing");
return 1;
}
fprintf(file, "Hello, C File I/O!\n");
fprintf(file, "This is line 2\n");
fprintf(file, "Number: %d\n", 42);
fprintf(file, "Float: %.2f\n", 3.14);
fclose(file);
printf("Data written to %s\n", filename);
// Read from file
file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file for reading");
return 1;
}
printf("\nReading file content:\n");
char line[256];
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
return 0;
}
// 2. Binary file operations
int binary_file_operations() {
const char* filename = "data.bin";
int numbers[] = {10, 20, 30, 40, 50};
int count = sizeof(numbers) / sizeof(numbers[0]);
// Write binary data
FILE* file = fopen(filename, "wb");
if (file == NULL) {
perror("Error opening binary file for writing");
return 1;
}
fwrite(numbers, sizeof(int), count, file);
fclose(file);
printf("Binary data written to %s\n", filename);
// Read binary data
int read_numbers[10];
file = fopen(filename, "rb");
if (file == NULL) {
perror("Error opening binary file for reading");
return 1;
}
size_t items_read = fread(read_numbers, sizeof(int), 10, file);
fclose(file);
printf("Read %zu items:\n", items_read);
for (size_t i = 0; i < items_read; i++) {
printf("read_numbers[%zu] = %d\n", i, read_numbers[i]);
}
return 0;
}
// 3. Low-level file operations (Unix-style)
int low_level_file_ops() {
const char* filename = "lowlevel.txt";
const char* content = "Low-level file operations in C\n";
// Write using write() system call
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("Error opening file with open()");
return 1;
}
ssize_t bytes_written = write(fd, content, strlen(content));
if (bytes_written == -1) {
perror("Error writing to file");
close(fd);
return 1;
}
close(fd);
printf("Wrote %zd bytes using low-level I/O\n", bytes_written);
// Read using read() system call
fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("Error opening file for reading");
return 1;
}
char buffer[256];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
if (bytes_read == -1) {
perror("Error reading from file");
close(fd);
return 1;
}
buffer[bytes_read] = '\0'; // Null terminate
printf("Read %zd bytes: %s\n", bytes_read, buffer);
close(fd);
return 0;
}
// 4. File information and status
int file_status_operations() {
const char* filename = "example.txt";
struct stat file_stat;
if (stat(filename, &file_stat) == -1) {
perror("Error getting file status");
return 1;
}
printf("File status for %s:\n", filename);
printf(" Size: %ld bytes\n", file_stat.st_size);
printf(" Permissions: ");
printf((file_stat.st_mode & S_IRUSR) ? "r" : "-");
printf((file_stat.st_mode & S_IWUSR) ? "w" : "-");
printf((file_stat.st_mode & S_IXUSR) ? "x" : "-");
printf((file_stat.st_mode & S_IRGRP) ? "r" : "-");
printf((file_stat.st_mode & S_IWGRP) ? "w" : "-");
printf((file_stat.st_mode & S_IXGRP) ? "x" : "-");
printf((file_stat.st_mode & S_IROTH) ? "r" : "-");
printf((file_stat.st_mode & S_IWOTH) ? "w" : "-");
printf((file_stat.st_mode & S_IXOTH) ? "x" : "-");
printf("\n");
printf(" Last modified: %s", ctime(&file_stat.st_mtime));
printf(" Is directory: %s\n", S_ISDIR(file_stat.st_mode) ? "Yes" : "No");
printf(" Is regular file: %s\n", S_ISREG(file_stat.st_mode) ? "Yes" : "No");
return 0;
}
// 5. Directory operations (Unix-style)
int directory_operations() {
const char* dirname = "test_dir";
// Create directory
if (mkdir(dirname, 0755) == -1) {
if (errno != EEXIST) {
perror("Error creating directory");
return 1;
}
printf("Directory already exists\n");
} else {
printf("Directory created successfully\n");
}
// Change directory permissions
if (chmod(dirname, 0777) == -1) {
perror("Error changing directory permissions");
return 1;
}
printf("Directory permissions changed\n");
// Note: Directory listing would require opendir/readdir which are platform-specific
printf("Directory operations completed\n");
return 0;
}
// 6. Process information
int process_info() {
printf("Process Information:\n");
printf(" Process ID: %d\n", getpid());
printf(" Parent Process ID: %d\n", getppid());
printf(" User ID: %d\n", getuid());
printf(" Group ID: %d\n", getgid());
return 0;
}
// 7. Environment variables
int environment_variables() {
printf("Environment Variables:\n");
// Get specific environment variable
char* path = getenv("PATH");
if (path != NULL) {
printf(" PATH (first 100 chars): %.100s...\n", path);
}
char* home = getenv("HOME");
if (home != NULL) {
printf(" HOME: %s\n", home);
}
// Set environment variable
if (setenv("MY_VAR", "Hello from C", 1) == 0) {
char* my_var = getenv("MY_VAR");
printf(" MY_VAR: %s\n", my_var ? my_var : "Not found");
}
return 0;
}
// 8. Error handling demonstration
int error_handling_examples() {
printf("Error Handling Examples:\n");
// Try to open non-existent file
FILE* file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
printf(" fopen error: %s (errno: %d)\n", strerror(errno), errno);
} else {
fclose(file);
}
// Try to allocate huge amount of memory
size_t huge_size = SIZE_MAX;
void* ptr = malloc(huge_size);
if (ptr == NULL) {
printf(" malloc error: %s (errno: %d)\n", strerror(errno), errno);
} else {
free(ptr);
}
return 0;
}
// 9. Time and date operations
int time_operations() {
time_t current_time;
struct tm* time_info;
char time_string[80];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info);
printf("Current time: %s\n", time_string);
printf("Year: %d\n", time_info->tm_year + 1900);
printf("Month: %d\n", time_info->tm_mon + 1);
printf("Day: %d\n", time_info->tm_mday);
printf("Hour: %d\n", time_info->tm_hour);
printf("Minute: %d\n", time_info->tm_min);
printf("Second: %d\n", time_info->tm_sec);
return 0;
}
// 10. Command execution
int command_execution() {
printf("Command Execution Examples:\n");
// Execute a simple command
int result = system("echo 'Hello from system() call'");
printf("system() call returned: %d\n", result);
// Note: For more control, you'd use fork() and exec() family
printf("Command execution completed\n");
return 0;
}
int main() {
printf("=== C File I/O and System Programming Examples ===\n\n");
printf("1. Basic File I/O:\n");
basic_file_io();
printf("\n");
printf("2. Binary File Operations:\n");
binary_file_operations();
printf("\n");
printf("3. Low-level File Operations:\n");
low_level_file_ops();
printf("\n");
printf("4. File Status Operations:\n");
file_status_operations();
printf("\n");
printf("5. Directory Operations:\n");
directory_operations();
printf("\n");
printf("6. Process Information:\n");
process_info();
printf("\n");
printf("7. Environment Variables:\n");
environment_variables();
printf("\n");
printf("8. Error Handling Examples:\n");
error_handling_examples();
printf("\n");
printf("9. Time Operations:\n");
time_operations();
printf("\n");
printf("10. Command Execution:\n");
command_execution();
printf("\n");
return 0;
}