size_t:无符号整数
头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//查询命令 man 2 open
函数
int open(const char *pathname,int flags)
int open(const char *pathname,int flags,mode_t mode)
:打开一个文件int create(const char* pathname,mode_t mode)
:创建一个文件- 这三个函数的返回值都是文件的描述符,只有拿着文件的描述符才可以对文件进行相关操作
pathname
为所需要打开/创建的文件的名称,
flags
:
O_RDONLY
:只读打开O_WRONLY
:只写打开O_RDWR
:可读可写打开- 以上三个只能制定一个,下列为可选
O_CREAT
:若文件不存在则创建它,此时需要制定mode
参数O_EXCL
:如果同时指定了OCREATE,而此文件已经存在,则出错O_APPEND
:每次写时,都加到文件的尾端O_TRUNC
:打开文件时,如果这个文件中本来是由内容的,而且为只读或只写成功打开,则将其长度截断为0,相当于清空了
Mode
:记录待创建的文件的访问权限
- 权限分为3中,读写执行:rwx对应421
- 而权限制定时,要指定当前人、同组者和其他组者
- 0600代表制定当前人具有rw权限,其他人无权限
- 对于create中的mode有具体的宏定义,以下
- S_IRUSR 4 可读
- S_IWUST 2 可写
- S_IXUSR 1 可执行
- S_IRWXU 7 可读可写可执行
打开一个文件,当文件不存在时创建
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fds = open("./file1",O_RDWR);
printf("%d\n",fds);
if(fds == -1){
fds = open("./file1",O_RDWR|O_CREAT,0600);
if(fds>0){
printf("open success\n");
}
}
return 0;
}
将数据写入文件中
头文件
#include <unistd.h>
#include <string.h>
//man 2 write
//man 2 close
//man strlen
函数
-
ssize_t write(int fd, const void *buf, size_t count);
:对fd
文件写入buf
中的count
长度的数据,return
写入数据的长度 -
int close(int fd)
:关闭文件fd
-
strlen(const char *s)
:获取s
的长度
#include <unistd.h>
#include <string.h>
int main()
{
int fds = open("./file1",O_RDWR);
char *buf = "huanghaibo 123456";
printf("%d\n",fds);
if(fds == -1){
fds = open("./file1",O_RDWR|O_CREAT,0600);
if(fds>0){
printf("open success\n");
}
}
write(fds,buf,strlen(buf));
close(fds);
return 0;
}
将数据从文件中读取出来
ssize_t read(int fd, void *buf, size_t count);
:读取count个字符填入到buf中,返回读取的字节数off_t lseek(int fd, off_t offset, int whence);
:移动根据whence偏移制定的offset,return 偏移量SEEK_SET
:将光标放到文件首SEEK_CUR
:以当前位置为基准,左为负,右为正SEEK_END
:将光标放到文件尾
实现CP指令
lude <string.h>
#include <stdlib.h>
int main(int argc,char** argv)
{
printf("%s\n",argv[0]);
printf("%s\n",argv[1]);
printf("%s\n",argv[2]);
//read src
int fds_src = open(argv[1],O_RDONLY);
int fds_src_size = lseek(fds_src,0,SEEK_END);
int fds_des = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);
printf("fds_des:%d\n",fds_des);
//move head
lseek(fds_src,0,SEEK_SET);
char* buf = (char*)malloc(sizeof(char)*fds_src_size);
read(fds_src,buf,fds_src_size);
write(fds_des,buf,fds_src_size);
close(fds_src);
close(fds_des);
return 0;
}
通过程序修改配置文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char** argv)
{
printf("%s\n",argv[0]);
printf("%s\n",argv[1]);
//read src
int fds_src = open(argv[1],O_RDWR);
int fds_src_size = lseek(fds_src,0,SEEK_END);
//move head
lseek(fds_src,0,SEEK_SET);
char* buf = (char*)malloc(sizeof(char)*fds_src_size);
read(fds_src,buf,fds_src_size);
lseek(fds_src,0,SEEK_SET);
char* p = strstr(buf,"two=");//匹配
p=p+strlen("two=");
*p='8';
write(fds_src,buf,fds_src_size);
close(fds_src);
return 0;
}