文件描述符:
0 :文件标准输入
1 :文件标准输出
2 :文件输出出错
example:file copy process
open
#include <fcntl.h>
#include <sys/stat.h>
int fd=open(char *fname,int how); //return file discribe char=>0,1,2
int fd=open(char *fname,int how,mode_t mode);
file dicribechar filename openmode filequanxian
打开模式:O_RDONLY-只读 O_WRONLY-只写 O_RDWR-读写附加标志:O_APPEND :表示将文件位置指针移动到文件末尾
O_TRUNC :将fd所指向的文件内容清空
O_CREAT :当打开的文件不存在时,自动创建该文件,此时需要mode参数指定文件的权限
O_EXCL:
O_NONBLOCK
文件的关闭
文件操作完毕后必须关闭文件:
#include <unistd.h>
int result=close(int fd);
write系统调用
为了使用write系统调用,需要头文件unistd.h,原型如下:
#include <unistd.h>
size_t result = write(int filedes , const void *buf,size_t nbytes)
返回实际写入的 Open操作返回的 将buf所指向的存
储单元中大小为
字节大小 文件描述符 Nbytes字节的数据写入
该调用可以用来在打开的文件中写入信息,若写入不成功,则result=-1
read系统调用
#include <unistd.h>
size_t numread=read(int filedes,const void
*buf,size_t nbytes);
该调用从与文件描述符filedes相关的文件里读 入nbytes个字节的数据,并放到数据区buf里。返回实际读取的字节大小。
若读取 不成功,则nread=-1
逐个字符把一个文件复制到另一个文件
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdlib.h>
int main( )
{
char c;
int in,out;
in=open("file.in",O_RDONLY);
out=open("file.out",O_WRONLY|O_CREAT,S_IWUSR|S_IWOTH);
while(read(in,&c,1)==1)
write(out,&c,1);
exit(0);
}
[student@localhost Desktop]$ cat file.in
my name is andy.
hello,welcome to c.
hello,c.
[student@localhost Desktop]$ touch file.out
[student@localhost Desktop]$ gcc gyx.c -o gyx
[student@localhost Desktop]$ ./gyx
my name is andy.
hello,welcome to c.
hello,c.