这里注意一下,结构以结构的格式写入文件,获取的时候可以直接赋值给结构,不需要中间获取再拆解
NAME
pread, pwrite - read from or write to a file descriptor at a given offset
SYNOPSIS
#include <unistd.h>
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
DESCRIPTION
pread() reads up to count bytes from file descriptor fd at offset offset (from the start of the file) into the buffer starting at buf. The file offset is not changed.
pwrite() writes up to count bytes from the buffer starting at buf to the file descriptor fd at offset offset. The file offset is not changed.
The file referenced by fd must be capable of seeking.
RETURN VALUE
On success, the number of bytes read or written is returned (zero indicates that nothing was written, in the case of pwrite(), or end of file, in the case of pread()), or -1
on error, in which case errno is set to indicate the error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define test_file "/root/practice/check"
typedef struct storage_cs_file_s
{
int api_enable;
char api_interface[64];
char api_command[64];
char api_action[4];
} cs_file_t;
int main()
{
int fd = -1;
cs_file_t *p_cs_file = NULL;
int file_seek = 0;
p_cs_file = malloc(sizeof(cs_file_t));
sprintf(p_cs_file->api_interface,"wangdan");
sprintf(p_cs_file->api_command,"hello");
sprintf(p_cs_file->api_action,"pro");
fd = open(test_file, O_CREAT|O_WRONLY, 0777);
if (-1 == fd)
{
printf("error!!\n");
}
flock(fd, LOCK_EX);
pwrite(fd, p_cs_file, sizeof(cs_file_t), file_seek);
file_seek += sizeof(cs_file_t);
ftruncate(fd, file_seek);
flock(fd, LOCK_UN);
return 1;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define test_file "/root/practice/check"
typedef struct storage_cs_file_s
{
int api_enable;
char api_interface[64];
char api_command[64];
char api_action[4];
} cs_file_t;
int main()
{
int fd = -1;
int file_seek = 0;
cs_file_t *p_cs_file = NULL;
p_cs_file = malloc(sizeof(cs_file_t));
memset(p_cs_file, 0, sizeof(cs_file_t));
fd = open(test_file, O_RDONLY);
flock(fd, LOCK_EX);
pread(fd, p_cs_file, sizeof(cs_file_t), file_seek);
printf("%s\n%s\n%s\n",p_cs_file->api_interface,p_cs_file->api_command,p_cs_file->api_action);
memset(p_cs_file, 0, sizeof(cs_file_t));
file_seek += sizeof(cs_file_t);
pread(fd, p_cs_file, sizeof(cs_file_t), file_seek);
printf("%s\n%s\n%s\n",p_cs_file->api_interface,p_cs_file->api_command,p_cs_file->api_action);
memset(p_cs_file, 0, sizeof(cs_file_t));
flock(fd, LOCK_UN);
return 0;
}