-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 );
if ( -1 == fd1 ) {
perror( "open" );
return -1;
}else {
printf("文件打开成功:fd=%d\n", fd1);
}
//dup后的文件,同时write 是接着写入
fd2 = dup( fd1 );
printf("文件dup成功:fd=%d\n", fd2);
//分别向fd1和fd2指向的文件写入
char buf1[] = "ghost";
char buf2[] = "wu";
int count1 = -1, count2 = -1;
while ( 1 ) {
count1 = write( fd1, buf1, strlen( buf1 ) );
if ( -1 == count1 ) {
perror( "buf1->write" );
return -1;
}else {
printf("buf1->文件写入成功\n");
}
sleep( 1 );
count2 = write( fd2, buf2, strlen( buf2 ) );
if ( -1 == count2 ) {
perror( "buf2->write" );
return -1;
}else {
printf("buf2->文件写入成功\n");
}
}
close( fd1 );
close( fd2 );
return 0;
}
在linux系统中,内核占用了0、1、2这三个fd,当我们运行一个程序得到一个进程时,内部就默认已经打开了3个文件,
对应的fd就是0、1、2。分别叫stdin、stdout、stderr。也就是标准输入、标准输出、标准错误