一?點(diǎn)睛
在Linux下對(duì)文件進(jìn)行輸入輸出操作(I/O操作)有3中編程方式。
1?調(diào)用C庫(kù)中文件的I/O函數(shù),比如fopen、fread、fwrite、fclose等。
2?使用Linux的系統(tǒng)調(diào)用
3 C 文件流的操作
二?I/O介紹
I/O就是輸入/輸出,它是主存和外部設(shè)備(比如硬盤和U盤)之間復(fù)制數(shù)據(jù)的過(guò)程,其中數(shù)據(jù)從設(shè)備到內(nèi)存的過(guò)程稱為輸入,數(shù)據(jù)從內(nèi)存到設(shè)備的過(guò)程叫輸出。I/O可以分為高級(jí)I/O和低級(jí)I/O。
高級(jí)I/O:也稱帶緩沖的I/O,比方ANSI?C提供的標(biāo)準(zhǔn)I/O庫(kù)。帶緩沖的I/O在系統(tǒng)調(diào)用前采用一定的策略,速度慢,但比不帶緩沖的I/O安全,如fopen、fread、fwrite等。
低級(jí)I/O:也稱為不帶緩沖的I/O,它是Linux提供的系統(tǒng)調(diào)用,速度快,如函數(shù)open、read、write等。
?三?實(shí)戰(zhàn)
1?打印stdin、stdout和stderr的文件描述符的值
1.1?代碼
[root@localhost test]# cat test.cpp#include <stdlib.h>#include <stdio.h>int main(void){ printf("fileno(stdin) = %d\n", fileno(stdin)); printf("fileno(stdout) = %d\n", fileno(stdout)); printf("fileno(stderr) = %d\n", fileno(stderr)); return 0;}
1.2?運(yùn)行
[root@localhost test]# g test.cpp -o test[root@localhost test]# ./testfileno(stdin) = 0fileno(stdout) = 1fileno(stderr) = 2
2?創(chuàng)建一個(gè)只讀文件
2.1?代碼
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdio.h>#include <unistd.h>int main(void){ int fd = -1; char filename[] = "/root/test.txt"; fd = creat(filename,0666); if (fd == -1) printf("fail to pen file %s\n", filename); else printf("create file %s successfully\n", filename); return 0;}
2.2?運(yùn)行
[root@localhost test]# g test.cpp -o test[root@localhost test]# ./testcreate file /root/test.txt successfully[root@localhost test]# ll /root/test.txt-rw-r--r--. 1 root root 0 Mar 24 13:28 /root/test.txt
為什么呢 ?我們明明設(shè)置權(quán)限是0666啊。
因?yàn)檫@里涉及到一個(gè)umask函數(shù)。當(dāng)新文件被創(chuàng)建時(shí),其最初的權(quán)限由文件創(chuàng)建掩碼決定。
用戶每次注冊(cè)進(jìn)入系統(tǒng)時(shí),umask命令都被執(zhí)行,并自動(dòng)設(shè)置掩碼改變默認(rèn)值,新的權(quán)限將會(huì)把舊的覆蓋。
就像這樣:
0666 & ~022 = 0644
3?打開并關(guān)閉一個(gè)文件
3.1?代碼
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdio.h>#include <unistd.h>int main(void){ int fd = -1; char filename[] = "test.txt"; fd = open(filename, O_CREAT | O_RDWR, S_IRWXU); if (fd == -1) printf("fail to pen file %s,fd:%d\n", filename, fd); else printf("Open file %s successfully,fd:%d\n", filename, fd); close(fd); return 0;}
3.2?運(yùn)行
[root@localhost test]# g test.cpp -o test[root@localhost test]# ./testOpen file test.txt successfully,fd:3
當(dāng)前目錄下沒(méi)有test.txt,就新建一個(gè)test.txt,如果已經(jīng)有了,就打開它。
4?循環(huán)打開文件,而不關(guān)閉
4.1?代碼
[root@localhost test]# cat test.cpp#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdio.h>#include <unistd.h>#include <stdlib.h>int main(void){ int i = 0; int fd = 0; for (i = 1; fd >= 0; i ) { fd = open("test.txt", O_RDONLY); if (fd > 0) printf("fd:%d\n", fd); else { printf("error,can't openf file \n"); exit(1); } } return 0;}
4.2?運(yùn)行
......fd:1018fd:1019fd:1020fd:1021fd:1022fd:1023error,can't openf file
?
來(lái)源:http://www.icode9.com/content-3-147251.html聯(lián)系客服