一、打开和关闭文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int open(const char* pathname,int flags)
int open(const char * pathname,int flags,mode_t mode)
int close(int fd)
功能说明:打开pathname,flags指定了打开的方式,mode指定了打开文件的权限
参数说明:pathname为需要打开的文件名,flags为打开文件的方式,mode为打开文件的权限
返回值:open成功返回文件描述符,否则,返回-1,并设置errno;close成功返回0,否则返回-1
其中,flags可为:
O_RDONLY:只读;O_WRONLY:只写;O_RDWR:读写;O_CREAT:创建;
O_APPEND:追加
实例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void){
int fd1;
if((fd1=open("test1",O_CREAT | O_RDWR,0777))==-1){
perror("Cannot create the test2 file");
return 1;
}
close(fd1);
return 0;
}
二、创建文件函数
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
int creat(const char *pathname,mode_t mode)
功能说明:按mode权限创建pathname
参数说明:pathname为创建文件名,mode为文件创建后的权限
返回值:成功返回文件描述符,否则,返回-1,并设置errno
creat函数等同于
int open(const char* pathname,O_CREAT|O_WRONLY|O_TRUNC,mode_t mode)
三、读写函数
#include <unistd.h>
ssize_t read(int fd,void* buf,size_t count)
ssize_t write(int fd,const void *buf,size_t count)
功能说明:read 函数将buf中的内容的count字节写入文件描述符为fd的文件中,
write 函数将描述符为fd的文件中的当前位置后的count个字节的内容写入buf中
参数说明:fd为文件描述符,buf为存放待写入或是待写出的内容的地址,count为写入或是写出的字节数
返回值:read返回读取的字符数;write返回写入的字符数;否则,返回-1,并设置errno
四、寻址函数
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd,off_t offset,int whence)
功能说明:在描述符为fd的文件的whence处开始偏移offset个字节
参数说明:fd为文件描述符;offset为偏移字节数,whence开始处
返回值:成功返回从文件开始到最后偏移量
五、dup和dup2函数
#include <unist.h>
int dup(int oldfd);
int dup2(int oldfd,newfd)
功能说明:dup函数复制指定的文件描述符;dup2函数也用于复制文件描述符,只是如果新的文件描述符打开时,函数现关闭新的文件描述符
参数说明:oldfd,newfd都为文件描述符
返回值:返回新的文件描述符
说明:dup将文件系统中最小的文件描述符取出返回给fd,也就是说,fd指向的是最小描述符的文件。在dup2中,如果,newfd为已经打开的文件的话,就将它关闭,并将它的文件描述符的信息给oldfd
实例:
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,char* argv[]){
int fd1;
if(argc!=2){
printf("Usage: %s filename/n",argv[0]);
return 1;
}
if((fd1=open(argv[1],O_CREAT | O_RDWR,0777))==-1){
perror("Cannot create the file");
return 1;
}
close(STDOUT_FILENO);
if(dup(fd1)==-1){
perror("Cannot reserved the std out fd");
return 1;
}
printf("Write the the file/n");
close(fd1);
return 0;
}
这个例子将输出重定向为指定的文件。并将"Write the the file"写入这个文件中。
也可以使用dup2(fd,STDOUT_FILENO) 取代dup以达到同样的效果。