文件与I/O(四)
代码示例1:
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#include <unistd.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define MAJOR(a) (int)((unsigned short)a>>8)
#define MINOR(a) (int)((unsigned short)a & 0xFF)
int filetype(struct stat * buf);
int main(int argc, char* argv[])
{
int fd1;
int fd2;
fd1=open("test1.c",O_RDWR);
if(fd1==-1)
ERROR_EXIT("open error");
char buf1[1024]={0};
char buf2[1024]={0};
fd2=open("test1.c",O_RDWR);
if(fd2==-1)
ERROR_EXIT("open error");
read(fd1,buf1,5);
printf("buf1=%s fd1=%d\n",buf1,fd1);
read(fd2,buf2,5);
printf("buf2=%s fd2=%d\n",buf2,fd2);
int nread;
nread=write(fd1,"AAAAA",5);
if (nread==-1)
ERROR_EXIT("write errror");
memset(buf2,0,sizeof(buf2));
read(fd2,buf2,5);
memset(buf1,0,sizeof(buf1));
read(fd1,buf1,5);
printf("buf2=%s\n",buf2);
printf("buf1=%s\n",buf1);
close(fd1);
close(fd2);
return 0;
}
代码示例2:
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#include <unistd.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define MAJOR(a) (int)((unsigned short)a>>8)
#define MINOR(a) (int)((unsigned short)a & 0xFF)
int filetype(struct stat * buf);
int main(int argc, char* argv[])
{
int fd;
fd=open("test1.c",O_WRONLY);
if(fd==-1)
ERROR_EXIT("open error");
close(1);
dup(fd);
printf("hello\n");
return 0;
}
文件共享知识