首页 > 系统相关 >Linux系统编程

Linux系统编程

时间:2024-03-19 17:31:25浏览次数:15  
标签:return 编程 系统 statbuf char Linux path include dir

文章目录

1. 文件里面存放了5行数据,使用追加模式打开文件,打印前3行,并写入一行,期间使用ftell打印当前位置。

#include<func.h>
int main(int argc, char * argv[]){
    ARGS_CHECK(argc,2);
    FILE *fp= fopen("./file1","a+");

    fseek(fp,0,SEEK_SET);
    char line[100];

    for(int i =0 ;i<3;i++){
        if(fgets(line,sizeof(line),fp)!=NULL){
            printf("%s",line);
        }
    }

    printf("Current position :%ld\n",ftell(fp));
    fprintf(fp,"This is a new line\n");

    fclose(fp);

    return 0;
}
fprintf(fp, "This is a new line\n"); 这行代码在最后打印一句话的原因是因为你使用了追加模式打开文件。追加模式会将文件指针定位到文件末尾,所以在你使用 fseek(fp, 0, SEEK_SET); 将文件指针移动到文件开头后,接下来的写操作会将数据追加到文件末尾。因此,即使你已经将文件指针移动到了文件开头,写入的数据仍然会被追加到文件末尾,这就是为什么在结尾处打印一句话的原因。

2. 修改文件的权限,注意必须使用命令行参数。

  • #include<func.h>
    int main(int argc,char**argv){
        ARGS_CHECK(argc,3);   //chmod 有三个变量main   0777    文件
        mode_t mode;
        sscanf(argv[1],"%o",&mode);
        int ret = chmod(argv[2],mode);
        printf("mode  = %o\n",mode);
        ERROR_CHECK(ret,NULL,"chmod");
    
        return 0;
    }
    

3. 使用两种方法打印当前目录。

#include<func.h>
int main(int argc,char**argv){
    
    
    char *ret = getcwd(NULL,0);
    ERROR_CHECK(ret,NULL,"getcwd");

  
    printf("%s\n",ret);

    return 0;
}
#include<func.h>
int main(int argc,char**argv){
    
    char buf[1024]={0};
    char *ret = getcwd(0,sizeof(buf));
    ERROR_CHECK(ret,NULL,"getcwd");

    printf("%s\n",buf);
    printf("%s\n",ret);

    return 0;
}

4. 传递一个路径名,还有一个文件名,搜索对应路径下是否有该文件,有就打印显示该文件的绝对路径。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <sys/stat.h>
#include <dirent.h>

// 搜索指定路径下是否存在指定文件,并打印该文件的绝对路径
void search_file(const char *dir_path, const char *file_name) {
    DIR *dir = opendir(dir_path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    struct dirent *entry;
    struct stat statbuf;
    char full_path[PATH_MAX];

    while ((entry = readdir(dir)) != NULL) {
        snprintf(full_path, PATH_MAX, "%s/%s", dir_path, entry->d_name);

        if (stat(full_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISREG(statbuf.st_mode) && strcmp(entry->d_name, file_name) == 0) {
            char real_path[PATH_MAX];
            if (realpath(full_path, real_path) == NULL) {
                perror("realpath");
                closedir(dir);
                return;
            }

            printf("Found file %s at path: %s\n", file_name, real_path);
            closedir(dir);
            return;
        }
    }

    printf("File %s not found in directory %s\n", file_name, dir_path);
    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <directory> <file_name>\n", argv[0]);
        return 1;
    }

    search_file(argv[1], argv[2]);

    return 0;
}

5. 传递任意一个目录路径,能够显示该目录的ls -l的效果。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>

// 显示目录的 ls -l 效果
void display_ls_l(const char *dir_path) {
    DIR *dir = opendir(dir_path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    struct dirent *entry;
    struct stat statbuf;
    while ((entry = readdir(dir)) != NULL) {
        char full_path[PATH_MAX];
        snprintf(full_path, PATH_MAX, "%s/%s", dir_path, entry->d_name);

        if (stat(full_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        // 打印文件类型和权限
        printf((S_ISDIR(statbuf.st_mode)) ? "d" : "-");
        printf((statbuf.st_mode & S_IRUSR) ? "r" : "-");
        printf((statbuf.st_mode & S_IWUSR) ? "w" : "-");
        printf((statbuf.st_mode & S_IXUSR) ? "x" : "-");
        printf((statbuf.st_mode & S_IRGRP) ? "r" : "-");
        printf((statbuf.st_mode & S_IWGRP) ? "w" : "-");
        printf((statbuf.st_mode & S_IXGRP) ? "x" : "-");
        printf((statbuf.st_mode & S_IROTH) ? "r" : "-");
        printf((statbuf.st_mode & S_IWOTH) ? "w" : "-");
        printf((statbuf.st_mode & S_IXOTH) ? "x" : "-");

        // 打印硬链接数、所有者、所属组、文件大小、最后修改时间和文件名
        struct passwd *pw = getpwuid(statbuf.st_uid);
        struct group *gr = getgrgid(statbuf.st_gid);
        printf(" %2ld %s %s %8ld %s %s\n",
               (long)statbuf.st_nlink, pw->pw_name, gr->gr_name,
               (long)statbuf.st_size, ctime(&statbuf.st_mtime), entry->d_name);
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return 1;
    }

    display_ls_l(argv[1]);

    return 0;
}

6. 打印当前目录,然后改变当前目录,再打印当前目录。

#include <stdio.h>
#include <unistd.h>

int main() {
    char cwd[1024];

    // 获取当前工作目录并打印
    if (getcwd(cwd, sizeof(cwd)) != NULL) {
        printf("Current working directory: %s\n", cwd);
    } else {
        perror("getcwd");
        return 1;
    }

    // 改变当前工作目录到 /tmp
    if (chdir("/tmp") != 0) {
        perror("chdir");
        return 1;
    }

    // 获取新的当前工作目录并打印
    if (getcwd(cwd, sizeof(cwd)) != NULL) {
        printf("New working directory: %s\n", cwd);
    } else {
        perror("getcwd");
        return 1;
    }

    return 0;
}


//还是那个问题改变的不是文件的位置,而是执行程序的位置

7. 创建一个目录,然后删除掉它。

#include <stdio.h>
#include <unistd.h>

int main() {
    const char *dir_name = "test_dir";

    // 创建目录
    if (mkdir(dir_name, 0777) == -1) {
        perror("mkdir");
        return 1;
    }

    printf("Directory created: %s\n", dir_name);

    // 删除目录
    if (rmdir(dir_name) == -1) {
        perror("rmdir");
        return 1;
    }

    printf("Directory deleted: %s\n", dir_name);

    return 0;
}

8. 实现tree命令的效果。

// 这里写a的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>

void print_tree(const char *path, int level) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        struct stat statbuf;
        char full_path[PATH_MAX];
        snprintf(full_path, PATH_MAX, "%s/%s", path, entry->d_name);

        if (stat(full_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        for (int i = 0; i < level - 1; i++) {
            printf("|   ");
        }

        if (level > 0) {
            printf("|-- ");
        }

        printf("%s\n", entry->d_name);

        if (S_ISDIR(statbuf.st_mode)) {
            print_tree(full_path, level + 1);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return 1;
    }

    print_tree(argv[1], 0);

    return 0;
}

9. 实现cp -r命令的效果。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#define BUF_SIZE 1024

void copy_file(const char *src_path, const char *dst_path) {
    int src_fd = open(src_path, O_RDONLY);
    if (src_fd == -1) {
        perror("open");
        return;
    }

    int dst_fd = open(dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if (dst_fd == -1) {
        perror("open");
        close(src_fd);
        return;
    }

    char buf[BUF_SIZE];
    ssize_t bytes_read, bytes_written;

    while ((bytes_read = read(src_fd, buf, BUF_SIZE)) > 0) {
        bytes_written = write(dst_fd, buf, bytes_read);
        if (bytes_written != bytes_read) {
            perror("write");
            close(src_fd);
            close(dst_fd);
            return;
        }
    }

    if (bytes_read == -1) {
        perror("read");
    }

    close(src_fd);
    close(dst_fd);
}

void copy_dir(const char *src_path, const char *dst_path) {
    DIR *dir = opendir(src_path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    if (mkdir(dst_path, 0777) == -1) {
        perror("mkdir");
        return;
    }

    struct dirent *entry;
    struct stat statbuf;

    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        char src_child_path[PATH_MAX];
        char dst_child_path[PATH_MAX];
        snprintf(src_child_path, PATH_MAX, "%s/%s", src_path, entry->d_name);
        snprintf(dst_child_path, PATH_MAX, "%s/%s", dst_path, entry->d_name);

        if (stat(src_child_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            copy_dir(src_child_path, dst_child_path);
        } else {
            copy_file(src_child_path, dst_child_path);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <source> <destination>\n", argv[0]);
        return 1;
    }

    copy_dir(argv[1], argv[2]);

    return 0;
}

10.新建一个文件,里边内容为hello,通过mmap映射该文件后,修改hello为world,然后解除映射

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main() {
    const char *file_path = "test.txt";
    const char *data = "hello";
    const char *new_data = "world";

    // 创建并写入文件
    int fd = open(file_path, O_RDWR | O_CREAT, 0666);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    write(fd, data, strlen(data));
    close(fd);

    // 映射文件到内存
    fd = open(file_path, O_RDWR);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    struct stat sb;
    if (fstat(fd, &sb) == -1) {
        perror("fstat");
        close(fd);
        return 1;
    }
    char *addr = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (addr == MAP_FAILED) {
        perror("mmap");
        close(fd);
        return 1;
    }

    // 修改内存中的内容为 "world"
    memcpy(addr, new_data, strlen(new_data));

    // 解除映射
    if (munmap(addr, sb.st_size) == -1) {
        perror("munmap");
        close(fd);
        return 1;
    }

    close(fd);
    return 0;
}

标签:return,编程,系统,statbuf,char,Linux,path,include,dir
From: https://blog.csdn.net/weixin_45626953/article/details/136835422

相关文章

  • 操作系统内存管理笔记
    单级页表分页储存页表页表中的页表项是连续存放的,因此页号可以是隐含的,不需要占用空间页表中的块号所记录的只是内存块号,而非内存块的起始地址案例一假设某系统物理内存大小为4GB,页面大小为4KB,则每个页表项至少应该为多少字节解答:由题目可知,内存块大小=页......
  • 微博情感评论分析系统-完整代码数据 毕业设计
    ......
  • 鸿鹄电子招投标系统源码实现与立项流程:基于Spring Boot、Mybatis、Redis和Layui的企业
    随着企业的快速发展,招采管理逐渐成为企业运营中的重要环节。为了满足公司对内部招采管理提升的要求,建立一个公平、公开、公正的采购环境至关重要。在这个背景下,我们开发了一款电子招标采购软件,以最大限度地控制采购成本,提高招投标工作的公开性和透明性,并确保符合国家电子招投标......
  • 探索发布-订阅模式的深度奥秘-实现高效、解耦的系统通信
    ​......
  • 010_域名和域名系统
    目录域名解析系统DNS域名解析过程域名解析系统DNS域名解析过程......
  • 高性能、可扩展、支持二次开发的企业电子招标采购系统源码
     在数字化时代,采购管理也正经历着前所未有的变革。全过程数字化采购管理成为了企业追求高效、透明和规范的关键。该系统通过SpringCloud、SpringBoot2、Mybatis等先进技术,打造了从供应商管理到采购招投标、采购合同、采购执行的全过程数字化管理。通过待办消息、招标公告、......
  • 小白如何在服务器上配置环境(连接Linux服务器和anaconda3安装)
    由于服务器账号原因,悲惨的博主只能从头开始配置环境,但是博主脑子的缓存比较小,一周前配好的现在就忘掉了,为了防止再发生这种问题,博主从头开始记录一下。(连接Linux服务器和anaconda3安装)第一步连接到服务器1.安装插件(ReomoteSSH),安装好了之后点击左下角的><,点击“连接到主机.........
  • 电商系统源码搭建,让你轻松拥有属于自己的网店
    在开发与测试过程中,需要注意以下几个关键细节:前端页面设计与用户体验:确保前端页面符合系统架构设计中确定的功能模块,同时注重页面设计和用户体验。后端接口安全性与性能:开发后端接口时,要确保接口的安全性和性能,确保前端页面与后端数据的有效交互。数据库设计与优化:根据系统需......
  • linux 执行 PHP脚本
    phpapiroot.phpc=crontaba=indexphpD:\www\ddhd\www\apiroot.phpc=crontaba=index上面是运行脚本的命令,适合MVC框架,在入口文件处需要对控制器c和方法a进行特殊处理才能接收到参数 $c=$_GET['c']?:'index';$a=$_GET['a']?:'index';//start......
  • 中文编程入门(Lua5.4.6中文版)第九章 Lua 迭代器 参考种田游戏
    迭代器(iterator)在游戏开发中扮演着重要角色,尤其是在Lua语言中。它是一种特殊的数据结构,能够逐个访问集合中的元素,犹如一位探险家穿越种田游戏的领土,逐一揭示各个城市与资源。在Lua中,迭代器以一种强大的机制实现,它可以跟踪并遍历表或其他集合类型的每一个项目。其中,泛型for循环......