文章目录
前言
本文作为linux文件编程的代码笔记,作为日后复习资料。如有错误欢迎指出。逐步按照学习进度来在逐渐添加。
一、linux文件编程下常用函数?
1.open函数的使用,open函数作为打开文件的函数,范围值是整型数,作为文件的标识符。参数具体有文件名(*pathname)和操作属性(flags),以及对文件的操作权限(mode)。
用man open 可打开函数的参考。
二、open函数使用步骤
1.按读写进行读取文件(文件已存在否则fd返回-读取失败)
代码如下(示例):
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>//前三个文件必须包括作为使用open
#include <stdio.h>//C语言的输入输出库
int main(void)
{
int fd;//文件表示符
fd=open("./file1",O_RDWR);//O_RDWR 按读写的来读取,也有只可读,只可写的
printf("fd = %d \n",fd);
return 0;
}
2.读写文件不存在,可自动创建的
代码如下(示例):
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(void)
{
int fd;
fd=open("./file1",O_RDWR);
if(fd==-1)
{
printf("open file1 error\n");
fd = open("file1",O_RDWR|O_CREAT,0600);//利用上述open第二个函数(添加O_CREAT来是自动创建,0600是表示该创建文件具备读写的功能。)
if(fd>0)
{
printf("open success\n");
}
}
printf("fd = %d \n",fd);
return 0;
}
三、write函数使用步骤(含close,strlen)
1.write使用说明
2.close使用说明
3.strlen使用说明
4.代码示例
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>//以上三个是open所需
#include <unistd.h>//这个是write和close所需
#include <stdio.h>
#include <string.h>//strlen 所需的
int main()
{
int fd;
char *buf ="jjl is best\n";
fd =open("./file1",O_RDWR|O_CREAT,0600);//读写(可)创建
//ssize_t write(int fd, const void *buf, size_t count);//参数说明
//write(fd,buf,sizeof(buf));//这里注意sizeof是对指针的分配,不是所有指针的值都在,linux下是八个字节
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
总结
本文仅仅简单介绍了open,wirte(含close ,strlen)的使用.