Linux file reading and writing

Library Functions:

#include <unistd.h>

File reading:

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

Return value : The return value is the number of bytes actually read. If it returns 0, it means that the end of the file has been reached or there is no data to read. If the parameter count is 0, then read() has no effect and returns 0. If an error occurs, it returns -1

File writing:

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

Return value : If successful, write() will return the number of bytes actually written. When an error occurs, it returns -1, and the error code is stored in errno. 

fd   : file descriptor (0: combined with the standard input of the process, 1: combined with the standard output of the process, 2: combined with the standard error)

buf : points to the buffer area holding the data being written, or an empty buffer area where new data is placed

count : the size of the data requested to be read or written

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-3
        fd = 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);

        //读取文件的内容到缓存区 readBuf
        int n_read = read(fd,readBuf,n_write);
        printf("readBuf = %s\n",readBuf);
        printf("n_read = %d\n",n_read);
        close(fd);

        return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_49472648/article/details/108786551