文件IO函数和目录相关函数
1、
#include <head.h>
int main(int argc, const char *argv[])
{
int fd=open("/home/ubuntu/IO/xiaoxin.bmp",O_RDONLY);
if(fd==-1)
PRINT_ERROR("OPEN ERROR");
//方法1
/*
int size;
size=lseek(fd,0,SEEK_END);
//printf("文件的大小为%d\n",size);
lseek(fd,0,SEEK_SET);
if(read(fd,&size,sizeof(size))<=0)
{
perror("read error");
return -1;
}
*/
//方法2
lseek(fd,2,SEEK_SET);
int size2;
read(fd,&size2,4);
printf("文件的大小为%d\n",size2);
//文件偏移量
lseek(fd,4,SEEK_CUR);
int offset;
read(fd,&offset,4);
printf("文件的偏移量为%d\n",offset);
//宽
lseek(fd,4,SEEK_CUR);
int wide;
read(fd,&wide,4);
printf("文件的宽为%d\n",wide);
//高
lseek(fd,0,SEEK_CUR);
int height;
read(fd,&height,4);
printf("文件的高为%d\n",height);
close(fd);
return 0;
}
2、
#include <head.h>
int main(int argc, const char *argv[])
{
if (argc != 3) {
fprintf(stderr, "使用方法: %s <目录名> <文件名>\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *dir_name = argv[1];
const char *file_name = argv[2];
DIR *dir = opendir(dir_name);
if (dir == NULL) {
PRINT_ERROR("无法打开目录");
}
struct dirent *entry;
struct stat file_stat;
char file_path[1024];
int found = 0;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, file_name) == 0) {
snprintf(file_path, sizeof(file_path), "%s/%s", dir_name, file_name);
if (stat(file_path, &file_stat) == -1) {
PRINT_ERROR("获取文件信息失败");
}
printf("文件存在,属性信息如下:\n");
printf("文件路径: %s\n", file_path);
printf("文件大小: %ld 字节\n", file_stat.st_size);
printf("文件权限: %o\n", file_stat.st_mode & 0777);
printf("文件硬链接数: %ld\n", file_stat.st_nlink);
struct tm *tm_info = localtime(&file_stat.st_mtime);
if (tm_info == NULL)
{
PRINT_ERROR("localtime error");
}
printf("最后修改的时间:%d-%d-%d %d:%d:%d\n",tm_info->tm_year+1900,tm_info->tm_mon+1,tm_info->tm_mday,tm_info->tm_hour,tm_info->tm_min,tm_info->tm_sec);
found = 1;
break;
}
}
closedir(dir);
if (!found) {
printf("文件不存在\n");
}
return 0;
}