- 论坛徽章:
- 0
|
这两个例子分别是(1)两次打开同一个文件(2)两次打开两个文件 的例子,我编程做过,对于结果不太肯定,我是一名教师,正好即将要讲到这个知识点,为了给学生一个明确的说法,想找高手答疑解难。
write和read都是与内核缓冲区打交道,不是直接和磁盘文件打交道。
(1)读fd2会把刚写入fd1的内容读出来,好像fd1和fd2共享一个缓冲区
(2)读fd2不能读出刚写入fd1的内容,fd1和fd2不是共享一个缓冲区
另外还有一个问题:write(1,buf4,n)中第一个参数我写成(0 1 2)都是正确显示buf4中的内容,为什么?
谢谢!
第一个例子
#include <unistd.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <stdio.h>
int main()
{
int n;
int fd1,fd2;
char buf1[10]={"1234567890"};
char buf2[10]={"abcdefghij"};
char buf4[5];
if ( ( fd1 = open( "file1.txt",O_RDWR| O_CREAT | O_TRUNC, S_IRUSR |S_IWUSR))
==-1 )
perror("file1.txt open error");
printf("the fd1 = %d \n",fd1); //
if ( ( fd2 = open( "file1.txt", O_RDWR)) == -1 )
perror("file1.txt not open again " );
printf("the fd2 = %d \n",fd2);
if (( n = write(fd1,buf1,sizeof(buf1))) == -1)
perror("write file1.txt error");
printf("write %d char into fd1 \n",n);
if ((n = read(fd2,buf4,sizeof(buf4))) == -1 )
perror("read file1.txt error! ");
printf("read %d char from fd2 \n",n);
write(1,buf4,n);
printf("\n");
close(fd1);
close(fd2);
}
第二个例子
#include <unistd.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <stdio.h>
int main()
{
int n;
int fd1,fd2;
char buf1[10]={"1234567890"};
char buf2[10]={"abcdefghij"};
char buf4[5];
if ( ( fd1 = open( "file1.txt",O_RDWR| O_CREAT | O_TRUNC, S_IRUSR |S_IWUSR))==-1 )
perror("file1.txt open error");
printf("the fd1 = %d \n",fd1); //
if ( ( fd2 = open( "file2.txt",O_RDWR| O_CREAT | O_TRUNC, S_IRUSR |S_IWUSR))==-1 )
perror("file1.txt not open again " );
printf("the fd2 = %d \n",fd2);
if (( n = write(fd1,buf1,sizeof(buf1))) == -1)
perror("write file1.txt error");
printf("write %d char into fd1 \n",n);
if ((n = read(fd2,buf4,sizeof(buf4))) == -1 )
perror("read file1.txt error! ");
printf("read %d char from fd2 \n",n);
write(1,buf4,n);
printf("\n");
close(fd1);
close(fd2);
} |
|