Linux系统编程——文件编程(三)文件的读出和写入

1、写入(write)

头文件

#include <unistd.h>

函数原型

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

参数:
int fd :文件描述符
const void *buf :字节缓冲区,buf为要写入的字符串,(buf为void的指针)
size_t count:文件描述符写入字符串的大小
write:在缓冲区buf中取count个字节写入到文件描述符fd指向的文件里面

返回值

写入成功:返回一个整型数,大小就是写入的字节个数
写入失败:返回 -1

例如

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
	int fd;
    char* buf = "hello world!";
    fd = open("./file2",O_RDWR);   //先打开文件
    if(fd == -1){                  //没有就创建文件
    	printf("open file fail\n");
        fd = open("./file2",O_RDWR | O_CREAT,0600);  //创建文件
        if(fd > 0){         //表示成功创建文件
        	printf("creat success\n");
        }
	}
    printf("creat file2 success %d\n",fd);
    write(fd,buf,strlen(buf));       //将字符串buf写入到fd指向的文件中,大小为字符串的大小
    close(fd);                       //注意要关闭文件
    return 0;
}

在这里插入图片描述
file2中
在这里插入图片描述
首先通过open函数打开文件file2,发现没有file2,打印了 open file fail 然后创建了一个file2文件,打印 creat success ,再将file2的文件描述符打印出来,可以看到file2 的文件描述符为非负整数 3 ,说明创建成功,最后成功的将buf中的数据写入到file2中。

2、读出(read)

头文件和write一样

#include <unistd.h>

函数原型

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

参数:
int fd :文件描述符
const void *buf :字节缓冲区,buf为要读入的字符串,(buf为void的指针)
size_t count:读出字符串的大小
read:将文件描述符 fd 指向的文件读取count个字节放入字节缓冲区 buf 中

返回值

读出成功:返回一个整型数,大小就是读出的字节个数
读出失败:返回 -1

例如

#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 fd;
    char* buf = "hello world!";
    char* readBuf = NULL;

    fd = open("./file2",O_RDWR);                                                                                             
    printf("creat file2 success %d\n",fd);

    int n_write = write(fd,buf,strlen(buf));        
    printf("write %d\n",n_write);          //打印写入到file2的字节个数

    close(fd);                                //关闭文件
    fd = open("./file2",O_RDWR);      //重新打开,让光标回到头,不然读不到数据
    readBuf = (char*)malloc(sizeof(char) * n_write); //为readBuf开辟空间 
    int n_read = read(fd,readBuf,n_write);            //fd指向的文件读到readBuf中
    printf("readNum %d n_read = %s\n",n_read,readBuf); //打印读取到的字节个数和读到的数据

    close(fd);
    return 0;
}

在这里插入图片描述
因为上面写操作已将将file2文件创建了,所以下面直接打开重新写入,在这里应该要注意这两条代码

close(fd);                                //关闭文件
fd = open("./file2",O_RDWR);      //重新打开,让光标回到头,不然读不到数据

这是关于光标移动的问题,可参考光标移动(lseek)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值