9.内存/文件的映射
2020-04-12 本文已影响0人
陈忠俊
1.内存的映射
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/mman.h>
#define E_MSG(str, val) do{perror(str); return (val);}while(0)
int main(void){
int prot = PROT_READ|PROT_WRITE;
int flags = MAP_PRIVATE|MAP_ANONYMOUS;
void *p = mmap(NULL, 1024, prot, flags, -1, 0);
if(p == MAP_FAILED) E_MSG("mmap", -1);
strcpy(p, "hello sky walker"); //复制字符到内存空间
printf("%s\n", (char *)p);
munmap(p, 1024);
return 0;
}
测试:
zhongjun@eclipse:~$ gcc mmap.c -o mm
zhongjun@eclipse:~$ ./mm
hello sky walker
2.文件的映射
#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/mman.h>
#define E_MSG(str, val) do{perror(str); return (val);} while(0)
int main(int argc, char *argv[]){
int fd = open(argv[1], O_RDWR);
if(fd == -1) return -1;
int prot = PROT_WRITE|PROT_READ;
int flags = MAP_SHARED;
void *p = mmap(NULL, 6, prot, flags, fd, 0);
if(p == MAP_FAILED)E_MSG("Mmap", -1);
close(fd);
*((int *)p) = 0x30313233;
munmap(p, 6);
return 0;
}
测试:
zhongjun@eclipse:~$echo "test" > test
zhongjun@eclipse:~$ od -tx1 -tc test
0000000 74 65 73 74 0a
t e s t \n
0000005
zhongjun@eclipse:~$
zhongjun@eclipse:~$ gcc mmap_file.c -o mm_file
zhongjun@eclipse:~$ ./mm_file test
zhongjun@eclipse:~$ od -tx1 -tc test
0000000 33 32 31 30 0a
3 2 1 0 \n
0000005
3.文件的元数据
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<pwd.h>
#include<time.h>
#include<grp.h>
int main(int argc, char *argv[]){
struct stat buf;
//if you want to use *buf, you must use malloc to assign new memory for it.
int s = stat(argv[1], &buf);
struct passwd *p = getpwuid(buf.st_uid);
if(s == -1)return -1;
printf("file size: %ld\n", buf.st_size);
printf("links: %u\n", buf.st_nlink);
printf("inode: %ld\n", buf.st_ino);
printf("uid: %u\n", buf.st_uid);
printf("Username: %s\n", p->pw_name);
printf("gid: %u\n", buf.st_gid);
printf("group name: %s\n",(getgrgid(buf.st_gid))->gr_name);
printf("modified time: %ld\n", buf.st_mtim.tv_sec);
printf("modified time: %s\n", ctime(&buf.st_mtim.tv_sec));
return 0;
}
测试:
zhongjun@eclipse:~$ ./out cc
file size: 8316
links: 1
inode: 135979
uid: 1000
Username: zhongjun
gid: 1000
group name: zhongjun
modified time: 1584883964
modified time: Sun Mar 22 21:32:44 2020
可以通过gcc -E file_name -i file_name.i,查看预编译内容里需要的数据类型
4.读取文件夹
#include<stdio.h>
#include<dirent.h>
#include<sys/types.h>
int main(int argc, char *argv[]){
DIR *dir = opendir(argv[1]);
if(dir == NULL) return -1;
printf("Opened..\n");
struct dirent *dirp;
while((dirp = readdir(dir)) != NULL)
printf("file: %s\n inode:%lu \n", dirp->d_name, dirp->d_ino);
closedir(dir);
return 0;
}
测试:
zhongjun@eclipse:~$ vim readdir.c
zhongjun@eclipse:~$ gcc readdir.c -o out
zhongjun@eclipse:~$ ./out hello
Opened..
file: .
inode:358560
file: ..
inode:228560
file: aa
inode:264473
file: bb
inode:265990
zhongjun@eclipse:~$ cat readdir.c