📜  c 代码库 - C 编程语言(1)

📅  最后修改于: 2023-12-03 14:39:41.433000             🧑  作者: Mango

C 代码库 - C 编程语言

C 语言是一种高效、可靠且灵活的编程语言,被广泛应用于系统编程、网络编程、开发操作系统和嵌入式系统等等。在 C 语言中,程序员能够高度自定义和控制计算机的硬件资源,并且以 C 语言为基础开发的工具和库也很多。

本代码库致力于收录 C 编程语言相关的知识和代码片段,包括但不限于以下方面:

  • C 语言基础知识
  • 常见算法和数据结构
  • 实用工具和库
  • 操作系统编程
C 语言基础知识
Hello World
#include <stdio.h>

int main() {
    printf("Hello World!\n");
    return 0;
}
变量和数据类型
#include <stdio.h>

int main() {
    int age = 20;
    float score = 87.5;
    char name[] = "John";

    printf("My name is %s, I am %d years old and my score is %.1f.\n", name, age, score);

    return 0;
}
控制流程
#include <stdio.h>

int main() {
    int x = 10;
    int y = 5;

    if(x > y) {
        printf("%d is greater than %d.\n", x, y);
    } else if(x < y) {
        printf("%d is less than %d.\n", x, y);
    } else {
        printf("%d is equal to %d.\n", x, y);
    }

    int i;
    for(i = 0; i < 5; i++) {
        printf("The value of i is %d.\n", i);
    }

    int j = 0;
    while(j < 5) {
        printf("The value of j is %d.\n", j);
        j++;
    }

    return 0;
}
函数和指针
#include <stdio.h>

int add(int x, int y) {
    return x + y;
}

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main() {
    int a = 10;
    int b = 5;
    int sum = add(a, b);
    printf("The sum of %d and %d is %d.\n", a, b, sum);

    printf("Before swapping, a = %d, b = %d.\n", a, b);
    swap(&a, &b);
    printf("After swapping, a = %d, b = %d.\n", a, b);

    return 0;
}
常见算法和数据结构
数组
#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int i;
    for(i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}
链表
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

void printList(struct Node *head) {
    struct Node *ptr = head;
    while(ptr != NULL) {
        printf("%d ", ptr->data);
        ptr = ptr->next;
    }
    printf("\n");
}

int main() {
    struct Node *head = NULL;
    struct Node *second = NULL;
    struct Node *third = NULL;

    head = (struct Node*) malloc(sizeof(struct Node));
    second = (struct Node*) malloc(sizeof(struct Node));
    third = (struct Node*) malloc(sizeof(struct Node));

    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    printList(head);

    return 0;
}
#include <stdio.h>

#define SIZE 5

int stack[SIZE];
int top = -1;

void push(int value) {
    if(top == SIZE - 1) {
        printf("Stack overflow!\n");
        return;
    }

    top++;
    stack[top] = value;
}

int pop() {
    if(top == -1) {
        printf("Stack underflow!\n");
        return -1;
    }

    int value = stack[top];
    top--;
    return value;
}

int main() {
    push(1);
    push(2);
    push(3);
    push(4);
    push(5);

    printf("%d\n", pop());
    printf("%d\n", pop());
    printf("%d\n", pop());
    printf("%d\n", pop());
    printf("%d\n", pop());
    printf("%d\n", pop());

    return 0;
}
队列
#include <stdio.h>

#define SIZE 5

int queue[SIZE];
int front = -1;
int rear = -1;

void enqueue(int value) {
    if(rear == SIZE - 1) {
        printf("Queue overflow!\n");
        return;
    }

    if(front == -1) {
        front = 0;
    }

    rear++;
    queue[rear] = value;
}

int dequeue() {
    if(front == -1) {
        printf("Queue underflow!\n");
        return -1;
    }

    int value = queue[front];
    front++;

    if(front > rear) {
        front = -1;
        rear = -1;
    }

    return value;
}

int main() {
    enqueue(1);
    enqueue(2);
    enqueue(3);
    enqueue(4);
    enqueue(5);

    printf("%d\n", dequeue());
    printf("%d\n", dequeue());
    printf("%d\n", dequeue());
    printf("%d\n", dequeue());
    printf("%d\n", dequeue());
    printf("%d\n", dequeue());

    return 0;
}
#include <stdio.h>
#include <stdlib.h>

struct TreeNode {
    int data;
    struct TreeNode *left;
    struct TreeNode *right;
};

struct TreeNode* createNode(int data) {
    struct TreeNode *newNode = (struct TreeNode*) malloc(sizeof(struct TreeNode));
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

void inorderTraversal(struct TreeNode *root) {
    if(root != NULL) {
        inorderTraversal(root->left);
        printf("%d ", root->data);
        inorderTraversal(root->right);
    }
}

int main() {
    struct TreeNode *root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);

    printf("Inorder traversal of the tree is: ");
    inorderTraversal(root);
    printf("\n");

    return 0;
}
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

struct Graph {
    int numVertices;
    struct Node **adjLists;
    int *visited;
};

struct Node* createNode(int data) {
    struct Node *newNode = (struct Node*) malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

struct Graph* createGraph(int numVertices) {
    struct Graph *graph = (struct Graph*) malloc(sizeof(struct Graph));
    graph->numVertices = numVertices;

    graph->adjLists = (struct Node**) malloc(numVertices * sizeof(struct Node*));
    int i;
    for(i = 0; i < numVertices; i++) {
        graph->adjLists[i] = NULL;
    }

    graph->visited = (int*) malloc(numVertices * sizeof(int));
    for(i = 0; i < numVertices; i++) {
        graph->visited[i] = 0;
    }

    return graph;
}

void addEdge(struct Graph *graph, int src, int dest) {
    struct Node *newNode = createNode(dest);
    newNode->next = graph->adjLists[src];
    graph->adjLists[src] = newNode;

    newNode = createNode(src);
    newNode->next = graph->adjLists[dest];
    graph->adjLists[dest] = newNode;
}

void printGraph(struct Graph *graph) {
    int i;
    for(i = 0; i < graph->numVertices; i++) {
        struct Node *ptr = graph->adjLists[i];
        printf("Adjacency list of vertex %d: ", i);
        while(ptr != NULL) {
            printf("%d -> ", ptr->data);
            ptr = ptr->next;
        }
        printf("NULL\n");
    }
}

void DFS(struct Graph *graph, int vertex) {
    struct Node *adjList = graph->adjLists[vertex];
    struct Node *temp = adjList;

    graph->visited[vertex] = 1;
    printf("%d ", vertex);

    while(temp != NULL) {
        int connectedVertex = temp->data;

        if(graph->visited[connectedVertex] == 0) {
            DFS(graph, connectedVertex);
        }

        temp = temp->next;
    }
}

int main() {
    struct Graph *graph = createGraph(5);
    addEdge(graph, 0, 1);
    addEdge(graph, 0, 2);
    addEdge(graph, 1, 3);
    addEdge(graph, 2, 3);
    addEdge(graph, 3, 4);

    printGraph(graph);

    printf("Depth First Traversal: ");
    DFS(graph, 0);
    printf("\n");

    return 0;
}
实用工具和库
字符串处理
#include <stdio.h>
#include <string.h>

int main() {
    char str1[10] = "Hello";
    char str2[10] = "World";

    printf("Length of str1: %d\n", strlen(str1));
    printf("Length of str2: %d\n", strlen(str2));

    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);

    strcpy(str1, "Hi");
    printf("Copied string: %s\n", str1);

    printf("Comparison result: %d\n", strcmp(str1, str2));

    return 0;
}
文件操作
#include <stdio.h>

int main() {
    FILE *fp;
    char ch;

    fp = fopen("example.txt", "r");

    if(fp == NULL) {
        printf("Failed to open file.\n");
        return 0;
    }

    while((ch = fgetc(fp)) != EOF) {
        printf("%c", ch);
    }

    fclose(fp);

    return 0;
}
网络编程
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

#define PORT 8080

int main() {
    int server_fd, new_socket, valread;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char *hello = "Hello from server";

    char buffer[1024] = {0};
    if((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    if(bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    if(listen(server_fd, 3) < 0) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }

    if((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
        perror("accept failed");
        exit(EXIT_FAILURE);
    }

    valread = read(new_socket, buffer, 1024);
    printf("%s\n", buffer);
    send(new_socket, hello, strlen(hello), 0);
    printf("Hello message sent\n");
    return 0;
}
操作系统编程
进程创建与同步
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main() {
    int pid = fork();

    if(pid < 0) {
        printf("Fork failed.\n");
    } else if(pid == 0) {
        printf("Child process.\n");
    } else {
        printf("Parent process.\n");
        wait(NULL);
        printf("Child process finished.\n");
    }

    return 0;
}
线程创建与同步
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define THREADS 5

void *printMessage(void *threadId) {
    printf("Thread ID: %ld\n", (long) threadId);
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[THREADS];
    int i;

    for(i = 0; i < THREADS; i++) {
        int rc = pthread_create(&threads[i], NULL, printMessage, (void *) i);

        if(rc) {
            printf("Error creating thread %d.\n", i);
        }
    }

    pthread_exit(NULL);
}
锁和信号量
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

#define THREADS 2
#define ITERATIONS 100

int sum = 0;
sem_t mutex;

void *addNumbers(void *threadId) {
    int i;
    for(i = 0; i < ITERATIONS; i++) {
        sem_wait(&mutex);
        sum++;
        sem_post(&mutex);
    }
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[THREADS];
    sem_init(&mutex, 0, 1);
    int i;

    for(i = 0; i < THREADS; i++) {
        int rc = pthread_create(&threads[i], NULL, addNumbers, (void *) i);

        if(rc) {
            printf("Error creating thread %d.\n", i);
        }
    }

    for(i = 0; i < THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    printf("The sum is: %d\n", sum);

    pthread_exit(NULL);
}
总结

该代码库介绍了 C 编程语言的基础知识、常见算法和数据结构、实用工具和库、操作系统编程相关的知识和代码片段。通过学习和研究该代码库中的代码,程序员能够更深入地理解 C 语言及其应用领域,提升编程技能和水平。