linux文件操作

1.open

需要的头文件

前三个是open()

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

close()
#include<unistd.h>

perror()
#include<stdio.h>

打开以存在的文件:int open(const char *pathname, int flags);

当文件不存在时返回-1,pathname 表示文件的路径,flags表示需要的操作,O_RDONLY只读(read-only)O_WRONLY 只写(write-only), O_RDWR读写(read/write)

在当前目录下打开a.txt文件,若改文件不存在输出 open:,若存在则输出文件描述符

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

int main()
{
    int fd = open("a.txt",O_RDONLY);    
    if(fd == -1){
        perror("open");
    }

printf("%d \n",fd);
    close(fd);
    return 0;
}

创建文件:int open(const char *pathname, int flags, mode_t mode);

O_CREAT  表示创建一个新文件

mode 表示创建的文件的权限,传入的需要是八进制的值,umask默认值为0002,权限的最终由mode和umask确定

(mode & ~umask)

 创建的text.txt文件被赋予了可执行的权限,可以通过调节umask的值来控制文件的权限

 

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

int main()
{
    int fd = open("text.txt",O_RDONLY | O_CREAT,0777);
    if(fd == -1){
        perror("open:");
}
    printf("%d\n",fd);
    close(fd);
    return 0;
}
 

ssize_t read(int fd, void *buf, size_t count);

fd:读取文件描述符,

buf:需要读取数据存放的地方,数组的地址(传出参数)
count:指定的数组的大小

返回值:-1 读取失败;

                0 达到文件末尾

                > 0 读取的字节数;

ssize_t write(int fd, const void *buf, size_t count);

fd:写入文件描述符,

buf:需要写入的数据,
count:要写的数据的实际的大小

成功:实际写入的字节数

 失败:返回-1

将source.txt文件的内容复制到cpy.txt中

#include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int srcfd = open("source.txt",O_RDONLY);
    if(srcfd == -1)
    {
        perror("open source.tex: ");
        exit(-1);
    }
    int copyfd = open("cpy.txt", O_WRONLY | O_CREAT, 0664);
    if(copyfd == -1)
    {
        perror("open:");
        exit(-1);
    }
    char buf[1024] = {0};
    int len = 0;
    while((len = read(srcfd,buf,sizeof(buf))) >0)
    {
        write(copyfd,buf,len);
    }
    close(srcfd);
    close(copyfd);
    return 0;
}
 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值