系统调用:write、open、read

一、open

     简单来说,open建立了一条到文件或设备的访问路径。如果调用成功,它则返回一个可以被read、write和其他系统调用使用的文件描述符。这个文件描述符是惟一的,它不会与其他任何运行中的进程共享,如果两个程序同时打开同一个文件,他们会分别得到两个不同的文件描述符。如果他们都对文件进行写操作,那么它们会各写各的,它们分别接着上次离开的位置继续往下写。它们的数据不会交织在一起,而是彼此互相覆盖。两个程序对文件的读写位置(偏移量)不同。可以通过使用文件锁功能来防止冲突。

       open系统调用执行成功是返回一个文件描述符,调用失败返回-1

   open系统调用的原型:

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

/*
path:要访问的文件路径
oflags:访问方式
mode:当访问方式为O_CREAT时,通过mode来设置文件权限
*/
int open(const char *path, int oflags);
int open(const char *path, int oflags, mode_t mode);

示例:

# include <stdio.h>
# include <unistd.h>
# include <fcntl.h>
# include <stdlib.h>

int main()
{
    int fd = open("/home/FUJIA/cy1706/practice/text",O_RDONLY);
    if(fd != -1)
    {
        printf("open success");
        }
        else
        {
            printf("open error");
            }
    exit(0);
    }

二、write

      系统调用write的作用是把缓冲区buf的前nbytes个字节写入与文件描述符fildes关联的文件中。它返回实际写入的字节数。如果文件描述符有错或者底层的设备驱动程序对数据块长度比较敏感,改返回值可能小于nbytes。如果返回值为0,则表示未写入数据;如果返回值是-1,就表示在write调用过程中出现了错误。

    write系统调用的原型:

# include <unistd.h>

size_t write(int fildes, const void *buf, size_t nbytes);

示例:

# include <stdio.h>
# include <unistd.h>
# include <fcntl.h>


int main()
{
    int fd = open("/home/FUJIA/cy1706/practice/text",O_WRONLY);
    char buf[] = "hello";

    write(fd, buf, 5);
    close(fd);
    return 0;
    }

三、read

    系统调用read的作用是:从与文件描述符fildes相关的文件里读入nbytes个字节数据,并把它们放在数据区buf中,它返回实际读入的字节数,这可能会小于请求的字节数。如果read调用返回0,表示未读入任何数据,如果返回-1,则调用出错。

read系统调用原型:

# include <unistd.h>

size_t read(int fildes, void *buf, size_t nbytes);

示例:

# include <stdio.h>
# include <unistd.h>
# include <fcntl.h>


int main()
{
    int fd = open("/home/FUJIA/cy1706/practice/text",O_RDONLY);
    char buf[20] = {0};

    read(fd, buf, 6);
    printf("%s",buf);
    close(fd);
    return 0;
    }

猜你喜欢

转载自blog.csdn.net/qq_41727218/article/details/81280812