一、同一个进程,多次打开同一个文件,然后读出内容的结果是: 分别读【我们使用open两次打开同一个文件时,fd1和fd2所对应的文件指针是不同的2个独立的指针】
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char const *argv[]) {
int fd1 = -1;
int fd2 = -1;
char buf1[20] = {0};
char buf2[20] = {0};
int count1 = 0;
int count2 = 0;
fd1 = open( "ghostwu.txt", O_RDWR );
if ( -1 == fd1 ) {
printf("文件打开失败\n");
perror( "open" );
return -1;
}else {
printf("文件打开成功,fd1=%d\n", fd1);
}
count1 = read( fd1, buf1, 5 );
if ( -1 == count1 ) {
printf( "文件读取失败\n" );
perror( "read" );
}else {
printf( "文件读取成功,读取的内容是%s\n", buf1 );
}
fd2 = open( "ghostwu.txt", O_RDWR );
if ( -1 == fd1 ) {
printf("文件打开失败\n");
perror( "open" );
return -1;
}else {
printf("文件打开成功,fd2=%d\n", fd1);
}
count2 = read( fd2, buf2, 10 );
if ( -1 == count2 ) {
printf( "文件读取失败\n" );
perror( "read" );
}else {
printf( "文件读取成功,读取的内容是%s\n", buf2 );
}
close( fd1 );
close( fd2 );
return 0;
}
二、同一个进程,多次打开同一个文件,然后写入内容的结果是: 分别写,当使用O_APPEND,就是接着写
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char const *argv[]) {
int fd1 = -1;
int fd2 = -1;
char buf1[] = "ghost";
char buf2[] = "wu";
int count1 = 0;
int count2 = 0;
fd1 = open( "ghostwu.txt", O_RDWR );
if ( -1 == fd1 ) {
printf("文件打开失败\n");
perror( "open" );
return -1;
}else {
printf("文件打开成功,fd1=%d\n", fd1);
}
count1 = write( fd1, buf1, strlen( buf1 ) );
if ( -1 == count1 ) {
printf( "文件写入失败\n" );
perror( "write" );
}else {
printf( "文件写入成功,写入的内容是%s\n", buf1 );
}
fd2 = open( "ghostwu.txt", O_RDWR );
if ( -1 == fd1 ) {
printf("文件打开失败\n");
perror( "open" );
return -1;
}else {
printf("文件打开成功,fd2=%d\n", fd1);
}
count2 = write( fd2, buf2, strlen( buf2 ) );
if ( -1 == count2 ) {
printf( "文件写入失败\n" );
perror( "write" );
}else {
printf( "文件写入成功,写入的内容是%s\n", buf2 );
}
close( fd1 );
close( fd2 );
return 0;
}
上面代码保持不变,再写入的时候加入flag标志:
fd1 = open( "ghostwu.txt", O_RDWR | O_APPEND );
fd2 = open( "ghostwu.txt", O_RDWR | O_APPEND );
三、 dup后的fd和原来打开文件的fd指向的是同一个文件,同时对这个文件写入时,是接着写
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char const *argv[]) {
int fd1 = -1;
int fd2 = -1;
fd1 = open( "ghostwu.txt", O_RDWR );