目录
在windows中如何编写一个文件呢?
步骤:打开/新建文档---->编辑文档---->保存文档---->关闭文档。
那在Linux中如何编写一个文件呢?
步骤:打开(open)---->读写(read/write)---->关闭(close)
在Linux系统中的文件编程如下
1、打开/创建文件:open()函数
#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);
const char *pathname 指打开文件的路径;
int flags 指打开文件的模式;
打开文件的模式有三种,如下:
O_RDONLY(可读)
O_WRONLY(可写)
O_RDWR(可读可写)
open的返回值是一个文件描述符,是一个非负整数
什么是文件描述符:对于内核而言,所有打开文件都由文件描述符引用。文件描述符是一个非负整数。当打开一个现存文件或者创建一个新文件时,内核向进程返回一个文件描述符
open函数打开文件,打开成功返回一个文件描述符,打开失败,则返回-1
下面用代码举例
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int fd;//定义一个文件描述符
fd = open("./file1",O_RDWR);//打开一个文件,然后返回一个文件描述符
printf("fd = %d\n",fd);//打印文件描述符,要是本地中有file1文件,则返回3,否则返回-1
return 0;
}
若本地文件中有file1文件时,文件描述符的返回值
若本地文件中没有file1文件时,文件描述符的返回值
在文件有三种打开模式后,还能在后面添加几种模式
O_CREAT:若文件不存在则创建它
O_EXCL:如果同时指定了OCREAT,而文件已经存在,则返回-1
O_APPEND:每次写时都加到文件的尾端
O_TRUNC:去打开文件时,如果原文件中有内容,则把原文件中的内容清零,再写入新文件
举例:O_CREAT:若文件不存在则创建它
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int fd;
fd = open("./file1",O_RDWR);
if(fd == -1){
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("create file1 success!\n");
}
}
return 0;
}
#O_CREAT 指若文件不存在,则创建它
#0600 指新创建文件的权限,可读可写
O_EXCL:如果同时指定了OCREAT,而文件已经存在,则返回-1
#include <stdio.h>
#include <sys/types.h>
#include <