linux 运行一个编程文件,Linux系统调用下的文件I/O编程

一 点睛

在Linux下对文件进行输入输出操作(I/O操作)有3中编程方式。

1 调用C库中文件的I/O函数,比如fopen、fread、fwrite、fclose等。

2 使用Linux的系统调用

3 C 文件流的操作

二 I/O介绍

I/O就是输入/输出,它是主存和外部设备(比如硬盘和U盘)之间复制数据的过程,其中数据从设备到内存的过程称为输入,数据从内存到设备的过程叫输出。I/O可以分为高级I/O和低级I/O。

高级I/O:也称带缓冲的I/O,比方ANSI C提供的标准I/O库。带缓冲的I/O在系统调用前采用一定的策略,速度慢,但比不带缓冲的I/O安全,如fopen、fread、fwrite等。

低级I/O:也称为不带缓冲的I/O,它是Linux提供的系统调用,速度快,如函数open、read、write等。

三 实战

1 打印stdin、stdout和stderr的文件描述符的值

1.1 代码

[root@localhost test]# cat test.cpp

#include

#include

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 创建一个只读文件

2.1 代码

#include

#include

#include

#include

#include

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

为什么呢 ?我们明明设置权限是0666啊。

因为这里涉及到一个umask函数。当新文件被创建时,其最初的权限由文件创建掩码决定。

用户每次注册进入系统时,umask命令都被执行,并自动设置掩码改变默认值,新的权限将会把旧的覆盖。

就像这样:

0666 & ~022 = 0644

3 打开并关闭一个文件

3.1 代码

#include

#include

#include

#include

#include

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

当前目录下没有test.txt,就新建一个test.txt,如果已经有了,就打开它。

4 循环打开文件,而不关闭

4.1 代码

[root@localhost test]# cat test.cpp

#include

#include

#include

#include

#include

#include

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.icode9.com/content-3-147251.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值