欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Linux文件

Linux文件

2025/3/20 6:17:15 来源:https://blog.csdn.net/2202_75840803/article/details/146339797  浏览:    关键词:Linux文件

1.Open函数

高频使用的Linux系统调用:open write read close
Linux自带的工具:man手册:
man 1是普通的shell命令,比如ls
man 2是系统调用函数,比如open,write说明
在Linux系统库的定义:

int open(const char *pathname, intflags); /* 比较常用*/
int open(const char *pathname, intflags, mode_tmode);
//包含的头文件:
#include <sys/types.h>//这里提供类型pid_t和size_t的定义
#include <sys/stat.h>
#include <fcntl.h>
返回值:
成功,返回句柄,我们后面对于文件的读写,关闭等都通过句柄来操作。
失败,返回-1
参数说明:
grep -nr "xxxx"./
pathname:文件的路径名,如果只写文件名,就默认当前目录,如果在文件名加上路径,就按照绝对路径来
打开文件。
flags:表示打开文件后用的操作

底层是一个宏,它可能以十六进制的形式存放。
O_RDONLY:只读模式 0x 0000 0000
O_WRONLY:只写模式 0x 00000001
O_RDWR:可读可写 0x 00000002     是文件存在的轻快下可读可写
gcc test.c
int open(const char *pathname, intflags); /* 比较常用*/
int open(const char *pathname, intflags, mode_tmode);
//包含的头文件:
#include <sys/types.h>//这里提供类型pid_t和size_t的定义
#include <sys/stat.h>
#include <fcntl.h>
参数说明

参数说明
O_APPEND 表示追加,如果原来文件里面有内容,则这次写入会写在文件的最末尾。0x00002000
O_CREAT 表示如果指定文件不存在,则创建这个文件 0x0000 0100
O_EXCL 表示如果要创建的文件已存在,则出错,同时返回-1,并且修改errno 的值。
O_TRUNC 表示截断,如果文件存在,并且以只写、读写方式打开,则将其长度截断为0。
O_NOCTTY 如果路径名指向终端设备,不要把这个设备用作控制终端

grep -nr "xxxx"./      -n文件名  r是递归


  

比如我们输入mam   ls   它就会打开这个文件

vi hello.c 建立一个文件,然后编写

#include <stdio.h>

{

return 0;

}

i 切换模式,:wq保存退出

man 2 open

复制

       #include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>

ctrl+shift+v粘贴

2.close函数

参数说明
在Linux系统库的定义:

int close(int fd);
包含的头文件:

#include <unistd.h>

功能就是简单的关闭文件

3.文件的权限属性

ls -l查看文件的属性

open("mm",O_RDWR|O_CREAT);因为mm文件不存在所以会自己创建mm文件,但是创建的文件不是可读可执行的,O_RDWR这个指令是在文件存在的情况下可读可写可执行。

Linux 系统中采用三位十进制数表示权限,如0755, 0644.

open("mm",O_RDWR|O_CREAT,0755),加上0755给了创建的文件可读可写可执行的权限。

4.write写入一个字符串到文件

从打开的fd设备或文件中读取count个字节到buf中

ssize_tread(int fd,void * buf, size_tcount);


fd: 文件描述符
*buf: 读入数据的首地址
count: 读入数据的个数
返回值:成功返回读取的字节数,出错返回-1并设置errno,如果在调read之前已到达文件末尾,则这次read返回0

cat +文件名  查看文件中代码

下面是使用write函数写入字符串到文件mm中的代码,可以通过cat mm  查看mm文件中内容是否是写入的字符串。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>   //使用strcpy函数需要添加// int open(const char *pathname, int flags);// int open(const char *pathname, int flags, mode_t mode);       函数原型// ssize_t write(int fd, const void *buf, size_t count);int main()
{int fd;char writeBuff[128]={0};    //定义一个数组char *test ="hello world";    字符指针strcpy(writeBuff,test);   //将字符写到数组中fd=open("mm",O_RDWR|O_CREAT,0755);   //查询是否存在mm文件,没有就建立一个可读可写可执行的mm文件if(fd==-1){printf("open file failed!\n");perror("why");//print  reasion return -1;}printf("open file successed!\n");write(fd,&writeBuff[0],11);   //将数组中的数据写到fd文件中,也就是mm文件close(fd);return 0;
}
~                

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com