一?點睛
在Linux下對文件進行輸入輸出操作(I/O操作)有3中編程方式。
1?調(diào)用C庫中文件的I/O函數(shù),比如fopen、fread、fwrite、fclose等。
2?使用Linux的系統(tǒng)調(diào)用
3 C 文件流的操作
二?I/O介紹
I/O就是輸入/輸出,它是主存和外部設(shè)備(比如硬盤和U盤)之間復(fù)制數(shù)據(jù)的過程,其中數(shù)據(jù)從設(shè)備到內(nèi)存的過程稱為輸入,數(shù)據(jù)從內(nèi)存到設(shè)備的過程叫輸出。I/O可以分為高級I/O和低級I/O。
高級I/O:也稱帶緩沖的I/O,比方ANSI?C提供的標準I/O庫。帶緩沖的I/O在系統(tǒng)調(diào)用前采用一定的策略,速度慢,但比不帶緩沖的I/O安全,如fopen、fread、fwrite等。
低級I/O:也稱為不帶緩沖的I/O,它是Linux提供的系統(tǒng)調(diào)用,速度快,如函數(shù)open、read、write等。
?三?實戰(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?運行
[root@localhost test]# g test.cpp -o test
[root@localhost test]# ./test
fileno(stdin) = 0
fileno(stdout) = 1
fileno(stderr) = 2
2?創(chuàng)建一個只讀文件
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?運行
[root@localhost test]# g test.cpp -o test
[root@localhost test]# ./test
create 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啊。
因為這里涉及到一個umask函數(shù)。當(dāng)新文件被創(chuàng)建時,其最初的權(quán)限由文件創(chuàng)建掩碼決定。
用戶每次注冊進入系統(tǒng)時,umask命令都被執(zhí)行,并自動設(shè)置掩碼改變默認值,新的權(quán)限將會把舊的覆蓋。
就像這樣:
0666 & ~022 = 0644
3?打開并關(guān)閉一個文件
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?運行
[root@localhost test]# g test.cpp -o test
[root@localhost test]# ./test
Open file test.txt successfully,fd:3
當(dāng)前目錄下沒有test.txt,就新建一個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?運行
......
fd:1018
fd:1019
fd:1020
fd:1021
fd:1022
fd:1023
error,can't openf file
?
來源:http://www./content-3-147251.html
|