文件IO的详解

1.缓冲区

1.1如何验证缓冲区存在

使用_exit()函数,结束程序,不会清空IO的缓冲区

1.2缓冲区类型分类:全缓冲,行缓冲(stdin,stdout),无缓冲(stderr)

1.21行缓冲区(1024)

#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main(int argc , char *argv[ ])
{  int i;
  char buf[1024];
  for(i=0;i<1024;i++)
  {
    buf [i]='a';
  }
  fwrite(buf,1,1024,stdout);
  _exit(-1);
  return 0;
}

1.12全缓冲区字节数(4096)

#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main(int argc , char *argv[ ])
{int i;
  char buf[1024*4];
  for(i=0;i<1024*4;i++)
  {
    buf [i]='a';
  }
FILE  *fp=fopen("testfile","w");
if(fp)
  {
        fwrite(buf,1,sizeof(buf),fp);
  }
  _exit(-1);
  return 0;
}

1.2如何刷新缓冲区

(1)缓冲区满了,会自动刷新缓冲区;

(2)调用exit函数程序退出;

(3)函数return的时候;

(4)调用fclose;

(5)调用fflush;

(6)对于行缓冲,遇到“\n”会缓冲。

2.文件IO

2.1概述

2.11定义:类Unix操作系统提供的POSIX系统调用。

2.12.操作对象:文件描述符(一个大于等于0的整数,通过这个来操作文件)。

(1)0:stdin;

(2)1:stdout;

(3)2:stderr。

2.2文件IO操作

2.21.获取文件描述符

(1)open函数:不用creat

函数功能:打开文件

头文件:#include<sys/types.h>

              #include<sys/stat.h>

              #include<fcntl.h>

函数参数:char *pathname 带路径的文件名

                  int flags  打开的方式

                  mode_t mode  文件权限(八进制权限,例如:0777,0664)

(2)close函数:关闭文件

头文件:#include<unistd.h>

函数参数:int fd  文件描述符

(3)read函数

头文件:#include<unistd.h>

函数参数:int fd  文件描述符

                  void  *buf 存放读到数据的内存首地址

                  size_t count 想要读取到的字节数

(4)write函数

头文件:#include<unistd.h>

函数参数:int fd  文件描述符

                  void  *buf 存放写入数据的内存首地址

                  size_t count 想要读取到的字节数

(5)lseek函数

头文件:#include<unistd.h>

               #include<sys/types.h>

函数参数:int fd  文件描述符

                  off_t offset 相对于基准的偏移量

                  size_t count 基准

2.3代码段

//文件IO完成文本复制
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{  int i,j;
i=open(argv[1],O_RDONLY,0664);
j=open(argv[2],O_WRONLY | O_CREAT,0664);  

char buf[100];
while(1)
{
memset(buf,0,sizeof(buf));
int rr=read(i,buf,sizeof(buf));
if(rr>0)
{
   write(j,buf,rr);
}else if(rr==0){
            break;
        }
}
    close(i);
     close(j);
    return 0;
}
//文件IO完成图片加密

#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
int main(int argc,char *argv[])
{  int i;
i=open(argv[1],O_RDWR,0664);
char buf[10];
memset(buf,0,sizeof(buf));
int rr=read(i,buf,10);
if(rr==10)
{
    int i=0;
    for(i=0;i<5;i++)
    {
        char t=buf[9-i];
        buf[9-i]=buf[i];
        buf[i]=t;
        lseek(i,0,SEEK_SET);
    }    
}
   write(i,buf,rr);
   close(i);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值