linux---基础IO

在标准库中我们学习了printf,fprintf,sprintf,snprintf等等相关的函数,接下来是我们的系统I/O调用接口
open

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

       int open(const char *pathname, int flags);
       int open(const char *pathname, int flags, mode_t mode)

此时我们打开一个文件就需要使用open函数,需要包含sys/types.h和sys/stat.h和fcntl.h三个头文件。
参数:

  • pathname:文件名字

  • flags:这里我们把它叫做参数选项

      O_RDONLY:以只读的方式打开
      O_WRONLY:以只写的方式打开
      O_RDWR:以读写的方式打开
      O_CREAT:如果文件不存在就创建一个新的文件
      O_APPEND:向文件末尾追加内容
      O_TRUNC:截断文件,(清空原有的数据)
      ...
    
  • mode:设置文件权限

返回值:

  • 成功:返回0
  • 失败:返回-1

write

       #include <unistd.h>

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

参数列表:

  • fd:open函数打开时返回的文件描述符
  • buf:缓冲区的名字
  • count:缓冲区中字节数的大小(一般使用strlen()计算)

返回值:

  • 成功:返回所写入的字节数(若为零则表示没有写入数据).
  • 错误:时返回-1,并置errno为相应值.
  • 若count为零,对于普通文件无任何影响,但对特殊文件 将产生不可预料的后果
    我们在后面再讨论出现0的情况

read

       #include <unistd.h>

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

read()从文件描述符fd中读取count字节数据并放入从buf开始的缓冲区中,如果count为0,read()返回0,不执行其他任何操作,如果count大于SIZE_MAX,那么结果将不可预料
参数:

  • fd:文件描述符
  • buf:缓冲区名字
  • count:读取的字节数,一般使用缓冲区的大小。

返回值:

  • 成功时返回读取到的字节数(为0表示读到文件描述符)此返回值守文件剩余字节数限制,当返回值小于制定的字节数时并不意味这错误,这可能是因为当前可读取的字节数小于指定的字节数(比如已经接近文件末尾,或者正在从管道或者中断读取数据,或者read()被信号中断)
  • 失败返回-1,并使errno为相应值,在这种情况下无法得知文件偏移位置是否有变化。

lseek

       #include <sys/types.h>
       #include <unistd.h>
       off_t lseek(int fd, off_t offset, int whence);

参数列表:

  • fd:文件描述符

  • offset:偏移量

  • whence:偏移位置

       SEEK_SET:文件的开始位置
       SEEK_CUR:当前光标的位置
       SEEK_END:文件结束的位置
    

返回值:

  • 成功返回文件开始到最后光标位置的字节数的大小
  • 失败返回-1,并设置errno的值

lseek可以用来计算我们文件的大小

例子:

  1 #include <stdio.h>                                                          
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <fcntl.h>
  5 #include <unistd.h>
  6 #include <string.h>
  1 #include <stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <fcntl.h>
  5 #include <unistd.h>
  6 #include <string.h>
  7 int main(){
  8 
  9     int fd = open("te.txt",O_RDWR|O_CREAT,664);
 10     if(fd == -1){
 11         perror("open error\n");
 12     }
 13     char buf[1024];
 14     char str[] = "你好啊同学!!!";
 15     int ret = write(fd,str,sizeof(str));
 16     if(ret == -1){
 17         perror("write error");
 18     }
 19     ret = read(fd,buf,sizeof(buf));
 20     if(ret == -1){
 21         perror("read error");
 22     }
 23     printf("读取到的内容%s",buf);
 24     ret = lseek(fd,0,SEEK_END);
 25     if(ret == -1){
 26         perror("lseek erro");
 27     }
 28     printf("文件大小%d",ret);
 29     return 0;
 30 } 

猜你喜欢

转载自blog.csdn.net/boke_fengwei/article/details/89278553