对前面的一个补充说明及综述:
我们前面学了几种函数:
文件打开:
int open (const char * pathname, int flags);
int open (const char * pathname, int flags, mode_t mode);
int creat (const char * pathname, mode_t mode);
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
creat 详情见本文末;
文件写入:
ssize_t write (int fd, const void * buf, size_t count);
#include<unistd.h>
fd :文件描述符,上节课讲到,当打开一个文件的时候,会返回一个文件描述符,用此描述符来代表此文件;
buf :无类型指针,是个缓冲区,
count:写入文件的大小,
就是将缓冲区 buf 指针所指向的数据,取出 count 个字节,然后写入 fd 中
文件读取:
ssize_t read (int fd, void * buf, size_t count);
#include<unistd.h>
buf 为读取后内容在缓冲区的存放位置,
count 为读取的字节数
如果成功的话,读取的字节数会被返回(如果读到文件最后都没有读取到,则返回0)
如果读取失败则返回 -1
文件光标的移动
off_t lseek (int fd, off_t offset, int whence);
#include<sys/types.h>
#include<unistd.h>
作用: 将文件读写指针相对 whence 移动 offset 个字节
返回值:文件读写指针距文件开头的字节大小,出错,返回-1(可利用此来计算文件内容的字节数)
给出三个宏定义:
SEEK_SET 指向文件头
SEEK_CUR 指向当前位置
SEEK_END 指向文件尾
我们回过头来看 open 两个:
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_EXCL; O_CREAT; O_APPEND; O_TRUNC;
O_CREAT 若文件不存在就创建它,当O_CREAT 时,必须要写明权限 mode
O_TRUNC 当用O_TRUNC 打开文件时,如果这个文件中本来是有内容的,而且为只读或者只写那么当其成功打开时,将文件中内容截断为0(也就是全部删除)
O_EXCL 其实就是对 O_CREAT 的加注版,当 O_CREAT 要创立的文件已经存在时,就会出错,那么 open 函数就会返回 -1
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
int main(){
int fd;
fd = open("./file1",O_RDONLY|O_CREAT|O_EXCL,0600);
if (fd != -1){
printf("文件存在\n");
}
return 0;
}
如果在程序运行前创立了文件,那么就会打印出 文件存在
O_APPEND 每次写的时候,都加至文件的尾端 。 其实说白了,使用 write() 函数写入内容时,会从头开始写,就像SEEK_SET,这样的话,就会导致原文件中的内容被覆盖,所以在 open() 时,就提前使用 O_APPEND
关于 使用光标 lseek() 函数和在open中使用 O_APPEND 经过本人亲测,在Linux12.04中,运行以下代码
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int main(){
int fd;
fd = open("./file1",O_WRONLY);
if (fd > 0){
printf("file1 open success\n");
}
int off = lseek(fd,0,SEEK_END);
if(off != -1){
printf("文件光标 移动成功\n");
}
char * buf = "abcdefg";
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
文件 file1 中 原本为:12345678 王天潇全场最佳,
运行结束后显示为: 12345678 王天潇全场最佳abcdefg
而 O_APPEND 的运行结果则是:
12345678 王天潇全场最佳
abcdefg
说白了 O_APPEND 在file1 中是在文件的末尾处,另起一行进行写入
而 lseek(fd,0,SEEK_END); 则是直接从光标处开始向后写入
最后 creat 来啦
int creat (const char * filename,mode_t mode);
filename : 要创建的文件名(包含路径,缺省则为当前路径)
mode : 创建的模式(权限) // 可读可写可执行
常见的宏权限:
S_IRUSR 4字节 可读
S_IWUSR 2字节 可写
S_IXUSR 1字节 可执行
S_IRWXU 7字节 可读,写,执行
int main()
{
int fd;
char *buf = "test" ;
int creat(const char *pathname, mode_ t mode ) ; // 划重点
fd = creat( ”/home/CLC/file1" ,S_ IRWXU);
return 0;
}
划重点:注意这里的路径,是 /
转到 windows时,其实可以合Linux兼容,也就是使用 /
但 windows 系统本身的路径是 \ 但由于 \ 也是转义字符的起始符,所以规定在 C 语言中, 用 \\ 表示