#include
#include
#include
#include
#include
#include
#include
#if 1
#define dbprint(format,args...) printf("file: %s \nline: %d \n" format,__FILE__,__LINE__,##args)
#endif
#define Mbuflen 512
int WrRecord(char *pc_File,char* pc_content)
{
int Rcfd;
size_t datalen;
void *src;
char *buf;
struct stat filestat;
if((pc_File == NULL )||(pc_content ==NULL))
{
dbprint("? \n");
return 0;
}
datalen = strlen(pc_content);
//keep tail & \0
if(datalen >= Mbuflen)
{
pc_content = pc_content+datalen+1 - Mbuflen;
datalen = Mbuflen - 1;
}
Rcfd = open(pc_File,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
if (Rcfd <= 0 )
{
dbprint("fileno error \n");
return -1;
}
/* get file size */
if (fstat(Rcfd, &filestat) < 0)
{
dbprint("filestat error \n");
return -1;
}
if(filestat.st_size {
/* set size of output file */
if (lseek(Rcfd, Mbuflen-1, SEEK_SET) == -1)
{
dbprint("filesize error \n");
return -1;
}
if (write(Rcfd,"", 1) != 1)
{
dbprint("write error \n");
return -1;
}
}
src = mmap(NULL, Mbuflen, PROT_READ | PROT_WRITE, MAP_SHARED,Rcfd,0 );
if(src == MAP_FAILED)
{
dbprint("mmap error\n");
return -1;
}
buf = malloc(Mbuflen);
if(buf == NULL)
{
dbprint("malloc error \n");
return -1;
}
memset(buf,0,Mbuflen);
memcpy(buf,src,((filestat.st_size
memmove(buf,buf+datalen+1,Mbuflen-datalen-1);
memcpy(buf+Mbuflen-(datalen+1),pc_content,(datalen+1));
memcpy(src,buf,Mbuflen);
free(buf);
munmap(src,Mbuflen);
close(Rcfd);
return 0;
}
//测试一下
int main(int argc,char **argv)
{
if(argc!=3)
{
printf("input filename data \n");
return -1;
}
WrRecord(argv[1],argv[2]);
return 0;
}
阅读(1319) | 评论(0) | 转发(0) |