Liunx C 语言文件编程
打开创建文档->编辑文档->保存文档->关闭文档
操作系统提供了一系列的API:
打开 open 、
读写 write/read、
光标定位 lseek、
关闭 close
以上均为系统IO,操作文件是无缓存的
一 . 打开 / 创建文件
1 . 涉及函数
【打开/创建api】
相关头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
函数含义:打开或创建文件
int open(const char *pathname,int flags);
int open(const char *pathname,int flags,mode_t mode);
参数解释 :
pathname:
要打开的文件名(含路径,缺省为当前路径, 缺省示例:./file代表当前路径下的file文件 )
flags:
O_RDONLY 只读打开
O_WRONLY 只写打开
O_RDWR 可读可写打开
下列为可配置选项
O_CREAT 若文件不存在则创建它,在使用此选项时,需要同时说明第三个参数mode,用其来说明该新文件的存取许可权限
O_EXCL 和O_CREAT同时指定时,但如果文件存在则出错
O_APPEND 每次写时都加在文件的尾端
O_TRUNC 如果这个文件中本来是有内容的,而且为只读或只写成功打开,则将其长度截短为0
mode:
一定是在flags中使用了O_CREAT标志才需要设置mode,mode记录待创建文件的访问权限0600为可读可写 ,4可读 2可写 1可执行 所以0600为可读可写权限
返回值:成功返回文件描述符fd(非负整数),失败返回-1
----------------------------------------------------------------------------------------
【创建文件api】
相关头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
函数含义: 创建文件
int creat(const char *pathname, mode_t mode);
参数解释:
pathname:
要打开的文件名(含路径,缺省为当前路径,缺省示例:./file代表当前路径下的file文件)
mode:
S_IRUSR 可读
S_IWUSR 可写
S_IXUSR 可执行
S_IRWXU 可读可写可执行
返回值:成功返回文件描述符(非负整数),失败返回-1
2 . 示例代码
2-1 文件打开
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int ds = -1 ;
ds = open("./test.txt",O_RDWR);
if(ds != -1 ){
printf("file test.txt open success ! \r\n");
}else{
printf("file test.txt open fail !\r\n");
}
return 0 ;
}
2-2 文件创建与打开
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// 文件打开失败就创建文件,文件权限为 4 + 2 可读可写
int main(){
int ds = -1 ;
// 文件打开失败就创建文件,文件权限为 4 + 2 可读可写
ds = open("./new.txt",O_RDWR|O_CREAT,0600);
if(ds == -1 ){
ds = open("./new.txt",O_RDWR);
if(ds != -1 ){
printf("file test.txt open success 2 ! \r\n");
}else{
printf("file test.txt open fail ! \r\n");
}
}else{
printf("file test.txt open suc 1 ! \r\n");
}
return 0 ;
}
2-3 文件创建
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(){
int ds = creat("./creat.txt",0600);
if(ds != -1 ){
printf("creat file success ! \r\n");
}
return 0 ;
}
二 . 文件的写入与读取
1. 涉及函数
写入文件
头文件:
#include <unistd.h>
函数含义: 向文件中写入数据
ssize_t write(int fd,const void *buf,size_t count);
参数解释