当前位置: 代码迷 >> 综合 >> Linux 文件的读取与写入
  详细解决方案

Linux 文件的读取与写入

热度:72   发布时间:2024-02-22 16:48:23.0

库函数:

#include <unistd.h>

文件的读取:

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

返回值:返回值为实际读取到的字节数, 如果返回0, 表示已到达文件尾或是无可读取的数据。若参数count 为0, 则read()不会有作用并返回0。 

文件的写入:

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

返回值:成功则write()会返回实际写入的字节数。当有错误发生时则返回-1,错误代码存入errno中。 

fd  :文件描述符

buf:指向持有被写入数据的缓存区, 或者放入新数据的空缓存区

count: 请求读取或写入的数据大小

代码(code):

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>int main()
{int fd;char *buf = "Read and write files";//打开文件 file-3fd = open("./file-3",O_RDWR|O_CREAT,0600);printf("fd = %d\n",fd);//将缓存区 buf 的内容写入文件 file-3 int n_write = write(fd,buf,strlen(buf));printf("n_write = %d\n",n_write);char *readBuf;readBuf = (char *)malloc(sizeof(char) * n_write);//将光标移动到文件开头的位置(read读取的是光标后面的内容)lseek(fd,0,SEEK_SET);//读取文件的内容到缓存区 readBufint n_read = read(fd,readBuf,n_write);printf("readBuf = %s\n",readBuf);printf("n_read = %d\n",n_read);close(fd);return 0;
}