/**
* @function: atomic_append.c
*
* @brief: in this function we will show how to use O_APPEND flag to guarantee atomic operation.
* first function will open filename(if necessary creat it), and use write() add a byte
* at the end of file(use O_APPEND), all is num-bytes. if have x parm, use lseek.
*
* @parm: $atomic_append filename num-bytes [x]
*
* @log: yulong -2017/08/03 first edit
**/
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
int InputFd=0;
mode_t filePerms;
int num_bytes, count, num_write;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH; /* RW-RW-RW--*/
if((argc != 3) && (argc != 4))
printf("please enter correct parm.\n");
num_bytes=atoi(argv[2]); //save num_bytes
if(argc == 3) //use append flag
{
printf("argc == 3\n");
if((InputFd=open(argv[1], O_RDWR|O_CREAT|O_APPEND, filePerms)) == -1) //double bracket!!
perror("open error.\n");
for(count=0; count<num_bytes; count++)
{
num_write = write(InputFd, "1", 1); //write one bit at a time
}
if(close(InputFd) == -1)
perror("close error.\n");
}
else if(argc == 4 && strcmp(argv[3], "x")==0) //use lseek
{
printf("argc == 4\n");
if((InputFd=open(argv[1], O_RDWR|O_CREAT, filePerms)) == -1)
perror("open error.\n");
for(count=0; count<num_bytes; count++)
{
if(lseek(InputFd, 0, SEEK_END) == -1)
perror("lseek error\n");
num_write = write(InputFd, "1", 1); //write one bit at a time
}
if(close(InputFd) == -1)
perror("close error.\n");
}
}
/*** @function: atomic_append.c ** @brief: in this function we will show how to use O_APPEND flag to guarantee atomic operation.* first function will open filename(if necessary creat it),