Skip to content

Instantly share code, notes, and snippets.

@surinoel
Created November 1, 2019 02:51
Show Gist options
  • Save surinoel/8a757693387f31ac356bb2a50817f37c to your computer and use it in GitHub Desktop.
Save surinoel/8a757693387f31ac356bb2a50817f37c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
struct person {
char name[20];
int age;
};
static int write_info(struct person *p) {
int fd;
ssize_t ret;
fd = open("list.txt", O_CREAT | O_WRONLY | O_APPEND, 0744);
if(fd == -1) {
printf("open() fail\n");
return -1;
}
ret = write(fd, (struct person *)p, sizeof(struct person));
if(ret < sizeof(struct person)) {
printf("write fail\n");
return -1;
}
close(fd);
return 0;
}
static int mmap_read(void) {
int i;
int fd;
int ret;
struct stat sb;
struct person *p;
fd = open("list.txt", O_RDONLY);
if(fd == -1) {
printf("open() fail\n");
return -1;
}
/*
void *mmap(void *addr, size_t length, int prot, int flags,
int fd, off_t offset);
int fstat(int fd, struct stat *buf);
*/
ret = fstat(fd, &sb);
if(ret == -1) {
printf("fstat() error\n");
close(fd);
return -1;
}
p = mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
if(p == MAP_FAILED) {
printf("mmap() fail\n");
close(fd);
return -1;
}
for(i=0; i<sb.st_size/sizeof(struct person); i++) {
printf("name : %s, age = %d\n",
p[i].name, p[i].age);
}
close(fd);
return 0;
}
int main(int argc, char **argv) {
struct person p[2] = { { "유영재", 20}, {"손님", 30} };
write_info(&p[0]);
write_info(&p[1]);
mmap_read();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment