文件IO和标准IO

2015.2.26

星期四,阴天

今天的内容主要是文件IO

man 手册的分册:

man -f open 查看那些分册中有open
man 1 -- 普通的命令程序
man 2 -- 系统调用
man 3 -- 库函数

文件:操作系统将硬件抽象成文件
输入:将设备中的数据写进到内存
输出:将内存中的数据写出到设备

Linux的文件系统由两层结构构成:第一层是虚拟文件系统(VFS),第二层是各种不同的具体的文件系统

posix:可移植操作系统接口规范
API:用户编程接口

应用通过POSIX和GNU C LIB 变成 系统调用(可以访问系统):称这个接口为库函数

应用直接访问系统:系统调用

上层要访问系统需要先通过系统调用,

出错处理:

strerror():映射errno对应的错误信息:strerror(errno) ,error是全局变量
prerror();输出用户信息及errno对应的错误信息

printf("file to open:%s ", strerror(error))
perror("file to open:")
上面两条语句的功能想同:file to open: no such file directory (后面的提示语句和程序功能相关)


Linux中文件主要分为6种:普通文件,目录文件,符号链接文件,管道文件,套接字文件和设备文件。

不带缓存的IO:文件IO
带缓存的IO:标准IO
写出去:Output
读进来:Input(相对于程序而言)


open();read();write():
需要包含下面几个头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

标准IO:封装了文件描述符和缓存机制

fseek和ftell == lseek;

文件IO的函数:
open(),read(),write(),lseek(),close();

当总字节数大于每次读写的字节数的时候,判断是否读写完成有两种简单的判别方法;
1.累加:(设总字节数=MAX)

while((nbyte = write(fd, buf, N)) > 0)
{
sum += nbyte;
if(sum == MAX)
{
break;
}
}

2.判读实际读到的字节数和设置的读字节数是否相等

while(1)
{
i = read(fd, buf, N);
write(fd, buf, i);
if(i != N)
{
break;
}
}

off_t lseek(int fd, off_t offset, int whence)

offset:相对于基点whence的偏移量,以字节为单位,正数表示向前移动,负数表示向后移动

获得文件的长度:
length = lseek(fd, 0, SEEK_END)//备注几个宏(SEEK_SET , SEEK_CUR , SEEK_END)

标准IO;
fopen(),fread(),fwrite(),fseek(),ftell(),fprintf(),fclose();

求文件的长度:fseek()和ftell()两个函数组合的程序功能相当于lseek();
FILE *fp;
if(fseek(fp, 0, SEEK_END) < 0)
{
perror("fseek error");
fclose(fp);
retrn 1;
}
length = ftell(fp);

求文件长度完整程序:

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>

int main(int atgc, char *argv[])
{
FILE *fp;
long length;

if(argc < 2)
{
fprintf(stdout,"usage: %s filename ",argv[0]);
return 1;
}

if((fp = fopen(argv[1],"r")) == NULL)
{
fprintf(stderr,"fopen error: %s",strerror(erron));
return 1;
}

if(fseek(fp, 0, SEEK_END) < 0)
{
perror("fseek error");
fclose(fp);
return 1;
}

lingth = ftell(fp);

printf("the fiel size is %ld ",length);

fclose(fp);
return 0;
}


***************************************************************************************************************************************************************
***************************************************************************************************************************************************************
**************************o*************************************************************************************************************************************
***************************************************************************************************************************************************************

原文地址:https://www.cnblogs.com/cnlg/p/4302542.html