【文件io】

1.使用文件IO完成对图像的读写操作

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

int main(int argc, char const *argv[]) {
    int fd;

    // 打开 "xi.bmp" 文件以进行读写操作
    fd = open("xi.bmp", O_RDWR);
    if (fd == -1) {
        perror("Error opening file");
        return 1;
    }

    // 定义颜色信息(白色)
    unsigned char color[3] = {255, 255, 255};

    // 设置起始位置(假设从第 55 字节开始)
    off_t start_position = 54;

    // 移动文件指针到起始位置
    if (lseek(fd, start_position, SEEK_SET) == -1) {
        perror("Error seeking file");
        close(fd);
        return 1;
    }

    // 写入颜色信息
    for (int i = 0; i < 180; i++) {
        for (int j = 0; j < 56; j++) {
            if (write(fd, color, sizeof(color)) == -1) {
                perror("Error writing to file");
                close(fd);
                return 1;
            }
        }
    }

    // 关闭文件
    if (close(fd) == -1) {
        perror("Error closing file");
        return 1;
    }

    return 0;
}

2.使用stat函数实现 ls -l 指令功能

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

int main(int argc, char *argv[]) {
    DIR *dp = NULL;

    if ((dp = opendir("./")) == NULL) {
        perror("opendir error");
        return -1;
    }

    struct dirent *rp = NULL;
    struct stat st;

    while ((rp = readdir(dp)) != NULL) {
        // 构建文件路径
        char file_path[30];
        snprintf(file_path, sizeof(file_path), "./%s", rp->d_name);

        // 获取文件信息
        if (stat(file_path, &st) == -1) {
            perror("stat");
            continue;  // 继续下一个文件
        }

        // 获取所有者和组信息
        struct passwd *user_info = getpwuid(st.st_uid);
        struct group *group_info = getgrgid(st.st_gid);

        // 打印文件信息
        printf("%o %ld %s %s %lld %s %ld %s", 
               (unsigned int)st.st_mode, 
               (long)st.st_nlink,
               (user_info != NULL) ? user_info->pw_name : "Unknown",
               (group_info != NULL) ? group_info->gr_name : "Unknown",
               (long long)st.st_size,
               rp->d_name,
               (long)st.st_mtime,
               ctime(&st.st_mtime));
    }

    closedir(dp);

    return 0;
}

在这里插入图片描述

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值