linux应用程序开发一,文件编程——知识要点

来源:互联网 发布:尘埃3中文版下载mac 编辑:程序博客网 时间:2024/06/10 02:43

系统调用-创建文件

int creat(const char  *filename, mode_t mode)

filename:要创建的文件名(包含路径,缺省为当前路径)


mode:创建模式


常见的创建模式 :

宏代码                    数字代替

S_IRUSR    可读         4

S_IWUSR    可写        2

S_XUSR      可执行     1

S_IRWXU    可读,写,执行  6


如果是0,这表示没有权限!


示例代码:

file_creat.c

#include<stdio.h>#include<stdlib.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>          //注意这里不是fcnt1是fcuntl,不是数字1,是字母lvoid create_file(char *filename){if(creat(filename,0755) < 0){printf("creat file %s failure!\n",filename);exit(EXIT_FAILURE);}else{printf("create file %s success!\n",filename);}}int main(int argc,char *argv[]){int i;if(argc<2){perror("you haven't input the filename,please try again!\n");exit(EXIT_FAILURE);}for(i = 1; i < argc; i++){create_file(argv[i]);}exit(EXIT_SUCCESS);}


 系统调用-打开

int open(const char *pathname,int flags);int open(const char *pathname, int flags, mode_t mode);

pathname:要打开的文件名(包含路径,缺省为当前路径)
flags:打开标志

常见的打开标志:
O_RDONLY     只读方式打开
O_WRONLY    只写方式打开
O_RDWR         读写方式打开
O_APPEND     追加方式打开
O_CREAT        创建一个文件
O_NOBLOCK  非阻塞方式打开


O_CREAT 如果打开文件不存在就会创建一个文件;
如果使用O_CREAT就要使用3个参数的OPEN,需要指定mode来表示文件的访问权限。

示例代码:
open.c

#include<stdio.h>#include<stdlib.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>  int main(int argc , char *argv[]){int fd;if(argc < 2){puts("please input the open file pathname\n");exit(1);}//如果flag参数里有O_CREAT表示,该文件如果不存在,系统则创建该文件,该文件的权限由第三个参数指定//如果没有O_CREAT参数,则不需要第三个参数,没有文件会报错。//fd = open(argv[1],O_CREAT|O_RDWR) 仅仅只是打开指定文件。if(fd = open(argv[1],O_CREAT|O_RDWR, 0755) < 0){perror("open file failure\n");exit(1);}else{printf("open file %d success!\n",fd);}close(fd);exit(0);}



系统调用----关闭文件:

int close(int fd);

fd是open函数的返回值。



系统调用----读:

int read(int fd, const void *buf, size_t length)
功能:
从文件描述符fd所指定的文件中读取
length个字节到buf所指向的缓冲区中,
返回值为实际读取的字节数。



系统调用----写:
int write(int fd, const void *buf, size_t length)
功能:
把length个字节从buf指向的缓冲区中写
到文件描述符fd所指向的文件中,返回
值为实际写入的字节数。


系统调用----定位:
int lseek(int fd, offset_t offset, int whence)
功能:
将文件读写指针相对whence移动offset
个字节。操作成功时,返回文件指针相
对于文件头的位置。


whence可使用下述值:
SEEK_SET:相对文件开头
SEEK_CUR:相对文件读写指针的当前位置
SEEK_END:相对文件末尾
offset可取负值,表示向前移动。例如下述调用
可将文件指针相对当前位置向前移动5个字节:
lseek(fd, -5, SEEK_CUR)


lseek(fd,0,SEEK_END) 用这个语句的返回值可以检测出fd指向的文件的长度。


有时我们需要判断文件是否可以进行某种操作(读,写
等),这时可以使用access函数:
int access(const char*pathname,int mode)
pathname:文件名称
mode:要判断的访问权限。可以取以下值或者是他们的
组合。R_OK:文件可读,W_OK:文件可写,
X_OK:文件可执行,F_OK文件存在。
返回值:当我们测试成功时,函数返回0,否则如果一个条
件不符时,返回-1。





原创粉丝点击