open用於打開一個文件,通過設置不同的flag,可以讓進程只讀,只寫,可讀/可寫等操作 一、對一個不存在或者存在的文件(test.txt),進行寫入操作 1 /* 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名稱:cp.c 5 * ...
open用於打開一個文件,通過設置不同的flag,可以讓進程只讀,只寫,可讀/可寫等操作
一、對一個不存在或者存在的文件(test.txt),進行寫入操作

1 /*================================================================ 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名稱:cp.c 5 * 創 建 者:ghostwu(吳華) 6 * 創建日期:2018年01月10日 7 * 描 述:用open和write實現cp命令 8 * 9 ================================================================*/ 10 11 #include <stdio.h> 12 #include <sys/types.h> 13 #include <sys/stat.h> 14 #include <fcntl.h> 15 #include <errno.h> 16 17 int main(int argc, char *argv[]) 18 { 19 int fd, openflags; 20 21 //openflags = O_WRONLY | O_CREAT; 22 23 openflags = O_WRONLY; 24 25 fd = open( "test.txt" , openflags ); 26 if( fd < 0 ) { 27 printf( "%d\n", errno ); 28 perror( "write to file" ); 29 } 30 return 0; 31 }View Code
1)當test.txt不存在時, 文件打開失敗,會把操作系統的全局變數errno設置一個錯誤號, 這裡設置的是2,對於一個2,我們完全不知道是什麼錯誤,所以調用perror函數,他會把編號2解釋成可讀性的錯誤信息,
那麼這裡被解讀成"No such file or directory",可以通過"grep "No such file or directory" /usr/include/*/*.h" 找到errno為2對應的頭文件
2)如果test.txt文件存在,不會報錯,打開一個正常的文件描述符,文件原來的內容不會受影響
二、加入O_CREAT標誌

1 /*================================================================ 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名稱:cp.c 5 * 創 建 者:ghostwu(吳華) 6 * 創建日期:2018年01月10日 7 * 描 述:用open和write實現cp命令 8 * 9 ================================================================*/ 10 11 #include <stdio.h> 12 #include <sys/types.h> 13 #include <sys/stat.h> 14 #include <fcntl.h> 15 #include <errno.h> 16 17 int main(int argc, char *argv[]) 18 { 19 int fd, openflags; 20 21 //openflags = O_WRONLY | O_CREAT; 22 23 openflags = O_WRONLY | O_CREAT; 24 25 fd = open( "test.txt" , openflags ); 26 printf( "fd = %d\n", fd ); 27 if( fd < 0 ) { 28 printf( "%d\n", errno ); 29 perror( "write to file" ); 30 } 31 return 0; 32 }View Code
1)如果test.txt不存在,那就創建test.txt,不會報錯
2)如果test.txt存在,test.txt原內容不會受到影響
三、加入O_TRUNC標誌
openflags = O_WRONLY | O_CREAT | O_TRUNC;
1)如果test.txt不存在,那就創建test.txt,不會報錯
2)如果test.txt存在,test.txt原內容會被清空
四、許可權位

1 /*================================================================ 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名稱:cp.c 5 * 創 建 者:ghostwu(吳華) 6 * 創建日期:2018年01月10日 7 * 描 述:用open和write實現cp命令 8 * 9 ================================================================*/ 10 11 #include <stdio.h> 12 #include <sys/types.h> 13 #include <sys/stat.h> 14 #include <fcntl.h> 15 #include <errno.h> 16 17 int main(int argc, char *argv[]) 18 { 19 int fd, openflags; 20 mode_t fileperms; 21 22 openflags = O_WRONLY | O_CREAT | O_TRUNC; 23 24 //rwxrw-r-x 25 fileperms = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IXOTH; 26 27 fd = open( "test.txt" , openflags, fileperms ); 28 printf( "fd = %d\n", fd ); 29 if( fd < 0 ) { 30 printf( "%d\n", errno ); 31 perror( "write to file" ); 32 } 33 return 0; 34 }View Code