标准IO函数

本文详细介绍了C语言中的标准IO库,包括fopen()、fclose()等函数的使用,以及标准输入、输出和错误的文件指针。讨论了标准IO的读写操作,并通过示例展示了fread()和fwrite()的用法。文章还涵盖了文件位置的重新定位,如fseek()、ftell()和rewind()函数,并提供了实践示例。最后,文章讨论了printf()的输出特性,包括缓冲区管理和flush操作。
摘要由CSDN通过智能技术生成

一、标准IO。
1、标准IO有什么特点?
系统IO专门用于访问硬件设备的,标准IO专门用于访问普通文件。
标准IO中所有函数都是属于标准C库中的接口,所以标准IO的函数都是属于man手册中第3手册。

2、如何使用标准IO访问文件?
1)访问文件?  ->  fopen()  -> man 3 fopen
函数功能: stream open functions
头文件:#include <stdio.h>
原型:
    FILE *fopen(const char *path, const char *mode);
    
参数:
    path:需要打开的那个文件的路径  (绝对路径/相对路径)
    mode:操作权限  -> 字符串  例如:"r"

 r      Open text file for reading.  The stream is positioned at the beginning of the file.
    //以只读的方式来打开文件,文件的定位在最开头的。
    O_RDONLY

 r+     Open for reading and writing.  The stream is positioned at the beginning of the file.
    //以可读可写的方式来打开文件,文件的定位在最开头的。
    O_RDWR

 w      Truncate file to zero length or create text file for writing.  The stream is positioned at the beginning of the file.
    //以只写的方式打开文件,如果文件不存在就创建该文件,如果文件存在,则清空文件的内容,文件的定位在最开头的。
    O_WRONLY|O_CREAT|O_TRUNC

 w+     Open for reading and writing.  The file is created if it does not exist, otherwise it is truncated.  The  stream  is  positioned at the beginning of the file.
    //以可读可写的方式来打开文件,如果文件不存在就创建该文件,如果文件存在,则清空文件的内容,文件的定位在最开头的。
    O_RDWR|O_CREAT|O_TRUNC

 a      Open  for  appending  (writing at end of file).  The file is created if it does not exist.  The stream is positioned at the end of the file.
    //以只写追加的方式打开文件,写的话就在文件末尾开始写,文件不存在就会创建,文件的定位在末尾。
    O_WRONLY|O_APPEND

 a+     Open for reading and appending (writing at end of file).  The file is created if it does not exist.  The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
    //以可读可写和追加的方式打开文件,写的话就在文件末尾开始写,文件不存在就会创建,如果读,就从文件开头读,如果写,就从文件末尾开始写。
    O_RDWR|O_CREAT|O_APPEND

返回值:
    成功:文件流指针  FILE *
    失败:NULL

2)关闭文件。  -> fclose()  -> man 3 fclose
函数功能: fclose - close a stream
头文件:#include <stdio.h>
原型:
    int fclose(FILE *stream);

参数:
    stream: 需要关闭的那个文件的文件指针

返回值:
    成功:0
    失败:EOF

#define EOF -1

  练习1: 测试一下fopen()打开一个文件后,会不会占用一个文件描述符?
  练习2: 打开一个文件,测试fopen第二个参数,并关闭文件。

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

int main(int argc,char *argv[])
{
    FILE *fp = NULL;
    fp = fopen("./test.txt","w");
    if(fp == NULL)
        printf("fopen error!\n");  -> 3
    
    int fd = open("./kk.txt",O_RDONLY);
    print

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值