O_APPEND解决文件共享操作数据覆盖问题
多次open同一文件,实现共享操作时,指定O_APPEND可以防止数据相互覆盖的发生
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
int fd;
if((fd = open(argv[1],O_WRONLY | O_CREAT ,0655))<0)
{
perror("open file error!");
exit(1);
}
while(1)
{
write(fd,"hello",5);
write(fd,"world",5);
write(fd,"\n",1);
}
close(fd);
return 0;
}
file1
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
int fd;
if((fd = open(argv[1],O_WRONLY | O_CREAT ,0655))<0)
{
perror("open file error!");
exit(1);
}
while(1)
{
write(fd,"hhhhh",5);
write(fd,"wwwww",5);
write(fd,"\n",1);
}
close(fd);
return 0;
}
file2
int main(int argc, char *argv[])
argc是外部输入的参数个数,argv[ ]是参数的字符串数组。
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
if(argc != 3)
{
printf("please input two filename!\n");
exit(1);
}
int to_fd;
int from_fd;
int nr;
int nw;
struct stat file;
fstat(from_fd,&file);
int file_size= file.st_size;
char buffer[1024]={0};
if((from_fd = open(argv[1], O_RDONLY | O_CREAT,0655))<0)
{
perror("open from file error!");
//printf("error");
exit(1);
}
if((to_fd = open(argv[2], O_WRONLY | O_CREAT,0655))<0)
{
perror("open to file error!");
//printf("error");
exit(1);
}
while((nr=read(from_fd,buffer,sizeof(buffer)))!= 0)
{
//printf("%s",buffer);
if((nw = write(to_fd,buffer,strlen(buffer)))<0)
{
perror("write data error");
exit(1);
}
//memset(buffer,0,sizeof(buffer));
file_size=file_size -nw;
if(file_size<=0)
{
break;
}
memset(buffer,0,sizeof(buffer));
}
printf("file cp successful\n");
close(from_fd);
close(to_fd);
return 0;
}
#include
#include
#include
#include
#include
#include
#include
#include
int read_line(int fd,void * ptr,int max_len)
{
int nr;
int i=0;
char *buffer = (char *)ptr;
char temp;
while(nr=(read(fd,&temp,1))>=0)
{
if(nr == 0)
{
return 0;
}
if(temp == '\n')
{
buffer[i]='\0';
return i;
}
else
{
buffer[i]=temp;
}
i++;
}
if(nr<0)
{
perror("read error!");
exit(1);
}
return i;
}
read_line.c
#include
#include
#include
#include
#include
#include
#include
#include
extern int read_line(int,void *,int);
int main(int argc , char **argv)
{
if(argc!=2)
{
printf("please input file name!\n");
exit(1);
}
int fd;
char buffer[1024];
if((fd= open(argv[1],O_RDWR | O_CREAT,0655))<0)
{
perror("open file error!");
exit(1);
}
for(int i=0;i<3;i++)
{
memset(buffer,0,sizeof(buffer));
printf("please input data:\n");
scanf("%s",buffer);
if(write(fd,buffer,strlen(buffer))<0)
{
perror("write data error!");
exit(1);
}
write(fd,"\n",1);
}
lseek(fd,0,SEEK_SET);
memset(buffer,0,sizeof(buffer));
/*if((read(fd,buffer,sizeof(buffer)))<0)
{
perror("read data error!");
exit(1);
}
printf("buffer = %s\n",buffer);*/
while(read_line(fd,buffer,sizeof(buffer)-1) !=0)
{
printf("%s\n",buffer);
memset(buffer,0,sizeof(buffer));
}
close(fd);
return 0;
}
filedemo.c
统计一个文件中单词的个数
[https://blog.csdn.net/u010166404/article/details/46353263]