1、使用Linux的系统接口进行文件的读写

1、所用的主要函数接口

open函数
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
返回值:成功返回新分配的文件描述符,出错返回-1并设置error
mode对应open函数来说,仅当创建新文件时才使用第三个参数

read函数
#include <unistd.h>
ssize_t read(int feleds, void *buff, size_t nbytes);
read函数从当前文件偏移量处读入指定的文件内容
read函数会把参数feleds所指的文件传送nbytes个字节到buff中
返回值:返回读到的字节数。若已到文件尾为0,若出错为-1.
		如果read成功,则返回读到的字节数。如已到文件末尾,则返回0。

write函数
#include <unistd.h>
ssize_t write(int feleds, const void *buff, size_t nbytes);
write函数会把buff所指的内存写入nbytes个字节到feleds所指的文件中。
返回值:若成功返回写的字节数,出错返回-1

2、例子

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

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

    int fd1 = open("newfile.txt", O_CREAT | O_WRONLY, 0644);
    if(fd1 == -1)
    {
        perror("open1");
        exit(1);
    }

    char buf[2 * 1024] = {0};
    ssize_t n = read(fd, buf, sizeof(buf));
    if(n == -1)
    {
        perror("read");
        exit(1);
    }
    while(n > 0)
    {
       ssize_t m =  write(fd1, buf, sizeof(buf));
       printf("write bytes %d\n", m);
       n = read(fd, buf, sizeof(buf));
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值