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;
fd = open("xi.bmp", O_RDWR);
if (fd == -1) {
perror("Error opening file");
return 1;
}
unsigned char color[3] = {255, 255, 255};
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;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/0e208f91425643b18d4a0db03ca4633c.png#pic_center)