一、文件的基本概念:
1、设备文件(广义的文件)分类:
计算机硬件设备大体可分为字符设备、块设备、网络设备三类。
(1)、字符设备:
是指在I/O传输过程中,以字符为单位进行传输的设备。(例如:键盘、打印机等)
(2)、块设备:
是指在I/O传输过程中,以块为单位进行传输的设备。(例如:硬盘、软盘、闪存等)
(3)、网络设备:
是面向数据包的接收和发送而设计的硬件设备。(例如:集线器、交换机、网桥、路由器、网关、网卡等)
在计算机中,我们可以将每一个硬件设备看成是一个文件,对设备的操作即是对文件的操作。而字符设备与块设备的的根本区别在于:是否可以被随机访问。字符设备只能顺序读取(如键盘输入只能一个一个字符顺序数如),而块设备可以随机读取(如硬盘上txt文件可以随机读取)。
2、C语言文件基础:
(1)、高级I/O与低级I/O:
通常,文件的操作可以按操作方式分为:读、写、控制、关闭等。而文件操作也可以按处理的对象不同分为:内核中的文件操作(低级I/O)、基于OS的文件操作两种(高级I/O)。
(2)、文本文件与二进制文件:
文件按照存储形式可以分为:文本文件(以ASCII码形式存储)和二进制文件(以二进制形式存储)。我们一般操作的文件(狭义)基本都是文本文件,由于ASCII码中无-1,所以用-1作为文本文件结束标志,即结束标志EOF(#define EOF -1)。但无论是二进制文件还是文本文件都是流式文件。
(3)、流式文件:
呈现在用户面前的文件结构叫做文件的逻辑结构,逻辑结构分为两种:一种是记录式文件,另一种为流式文件。
记录文件:由若干逻辑记录组成,每条逻辑纪录又有相同的数据项组成。
流文件 :就是没有结构的文件,在C语言中对文件的记录是以字符(字节)为单位的。输入输出的数据流的开始和结束仅受程序控制而不受物理符号(如回车换行符)控制,我们把这种文件称为流式文件。
(4)、默认打开的三个流式文件:
在程序开始运行时,编译器会默认打开三个流式文件stdin、stdout、stderr。
#include<stdio.h>
FILE * stdin;//标准输入流,用0标识
FILE * stdout;//标准输出流,用1标识
FILE * stderr;//标准错误流,用2标识
如下代码中,直接调用stdin标准输入流,进行输入操作:
char passwd_input[20]={0};
fgets(passwd_input, 20, stdin);//类似于scanf("%s",passwd_input);
(5)、FILE类型为C标准stdio.h中定义的结构体类型:
struct _iobuf {
char *_ptr;//文件指针当前位置,缓冲区内马上读和写的位置。
int _cnt;//缓冲区内现有可以读的字符个数
char *_base;//缓冲区
int _flag;//文件流特征标志,如:读,写,读写,错误,文件结束,2进制文件等
int _file;//系统里文件属性,如:权限所属(用户,用户组,管理员)。
int _charbuf;//供ungetc()使用的缓冲存储单元
int _bufsiz;//已分配的缓冲区的大小
char *_tmpfname;//临时文件名
};
typedef struct _iobuf FILE;
二、文件打开与关闭函数:
1、fopen()函数:
(1)函数原型:
# include<stdio.h>
...
FILE * fopen(const char * path, const char * made);
...
(2)、返回值与参数:
返回值:
当打开文件正常,返回一个FILE *类型的指针;
打开失败,返回NULL,将接收指针赋为空,并设置全局变量errno来指示错误发生。
参数:
const char * path:要打开的文件位置及文件名,如"linux.txt"(默认为当前目录),又如"/etc/vimrc"等。
const char * made:要打开的方式,赋予文件的操作权限。可填参数为:
r//打开只读文件,只能从文件中读取数据,且文件必须存在,若不存在打开失败。
r+//打开可读写文件。
w//打开只写文件,只能向文件中写入数据,文件不存在则创建,存在则删除该文件重新创建。
w+//打开可读写文件。
a//打开只写文件,向文件尾增加新数据,文件不存在则创建直接写入。如文件存在,打开成功后便将文件指针移动到文件尾,开始增加新数据。
a+//打开可读写文件。
rw+//组合应用,可在规则内合理组合应用。
如果某文件的权限为“-r--”,便不能以除了r的任何方式打开,否则会打开失败,并设置并设置全局变量errno来指示错误发生。
2、fclose()函数:
#include<stdio.h>
...
int fclose(FILE * fp);
...
返回值:成功返回0,失败返回-1(EOF)并设置全局变量errno来指示错误发生。
参数:fp为文件指针,指向关闭的文件对象。
fopen与fclose的测试在perror中展示。
三、exit()函数:
(1)、函数原型:
#include<stdlib.h>.
...
void exit(int status);
...
(2)、返回值与参数:
我们通常会这样说exit()函数,exit(0)退出并且返回0。其实不够准确,因为exit()函数返回值类型为void。准确来说应该是:exit函数使程序正常终止,并且向父进程返回一个参数status。
参数status在C标准中有两个宏定义:
#define EXIT_FAILURE 0
#deinde EXIT_SUCCESS 1
对于这个宏中的参数值可以做修改:
#ifdef EXIT_SUCCESS
#undef EXIT_SUCCESS
#define EXIT_SUCCESS 2
#eddif
这样就可以将EXIT_SUCCESS的值修改为2
四、perror()函数:
1、errno是什么?
前面一直提到errno,而errno是个什么?errno其实是一个整形变量,用来记录最后一次错误代码,代码是一个int型值(0~133),在errno.h定义(/usr/include/errno.h)。
# include<errno.h>
...
int errno;
...
关于errno的错误表示的所有形式如下:
#define EPERM 1 /* Operation not permitted */
#define ENOENT 2 /* No such file or directory */
#define ESRCH 3 /* No such process */
#define EINTR 4 /* Interrupted system call */
#define EIO 5 /* I/O error */
#define ENXIO 6 /* No such device or address */
#define E2BIG 7 /* Argument list too long */
#define ENOEXEC 8 /* Exec format error */
#define EBADF 9 /* Bad file number */
#define ECHILD 10 /* No child processes */
#define EAGAIN 11 /* Try again */
#define ENOMEM 12 /* Out of memory */
#define EACCES 13 /* Permission denied */
#define EFAULT 14 /* Bad address */
#define ENOTBLK 15 /* Block device required */
#define EBUSY 16 /* Device or resource busy */
#define EEXIST 17 /* File exists */
#define EXDEV 18 /* Cross-device link */
#define ENODEV 19 /* No such device */
#define ENOTDIR 20 /* Not a directory */
#define EISDIR 21 /* Is a directory */
#define EINVAL 22 /* Invalid argument */
#define ENFILE 23 /* File table overflow */
#define EMFILE 24 /* Too many open files */
#define ENOTTY 25 /* Not a typewriter */
#define ETXTBSY 26 /* Text file busy */
#define EFBIG 27 /* File too large */
#define ENOSPC 28 /* No space left on device */
#define ESPIPE 29 /* Illegal seek */
#define EROFS 30 /* Read-only file system */
#define EMLINK 31 /* Too many links */
#define EPIPE 32 /* Broken pipe */
#define EDOM 33 /* Math argument out of domain of func */
#define ERANGE 34 /* Math result not representable */
#define EDEADLK 35 /* Resource deadlock would occur */
#define ENAMETOOLONG 36 /* File name too long */
#define ENOLCK 37 /* No record locks available */
#define ENOSYS 38 /* Function not implemented */
#define ENOTEMPTY 39 /* Directory not empty */
#define ELOOP 40 /* Too many symbolic links encountered */
#define EWOULDBLOCK EAGAIN /* Operation would block */
#define ENOMSG 42 /* No message of desired type */
#define EIDRM 43 /* Identifier removed */
#define ECHRNG 44 /* Channel number out of range */
#define EL2NSYNC 45 /* Level 2 not synchronized */
#define EL3HLT 46 /* Level 3 halted */
#define EL3RST 47 /* Level 3 reset */
#define ELNRNG 48 /* Link number out of range */
#define EUNATCH 49 /* Protocol driver not attached */
#define ENOCSI 50 /* No CSI structure available */
#define EL2HLT 51 /* Level 2 halted */
#define EBADE 52 /* Invalid exchange */
#define EBADR 53 /* Invalid request descriptor */
#define EXFULL 54 /* Exchange full */
#define ENOANO 55 /* No anode */
#define EBADRQC 56 /* Invalid request code */
#define EBADSLT 57 /* Invalid slot */
#define EDEADLOCK EDEADLK
#define EBFONT 59 /* Bad font file format */
#define ENOSTR 60 /* Device not a stream */
#define ENODATA 61 /* No data available */
#define ETIME 62 /* Timer expired */
#define ENOSR 63 /* Out of streams resources */
#define ENONET 64 /* Machine is not on the network */
#define ENOPKG 65 /* Package not installed */
#define EREMOTE 66 /* Object is remote */
#define ENOLINK 67 /* Link has been severed */
#define EADV 68 /* Advertise error */
#define ESRMNT 69 /* Srmount error */
#define ECOMM 70 /* Communication error on send */
#define EPROTO 71 /* Protocol error */
#define EMULTIHOP 72 /* Multihop attempted */
#define EDOTDOT 73 /* RFS specific error */
#define EBADMSG 74 /* Not a data message */
#define EOVERFLOW 75 /* Value too large for defined data type */
#define ENOTUNIQ 76 /* Name not unique on network */
#define EBADFD 77 /* File descriptor in bad state */
#define EREMCHG 78 /* Remote address changed */
#define ELIBACC 79 /* Can not access a needed shared library */
#define ELIBBAD 80 /* Accessing a corrupted shared library */
#define ELIBSCN 81 /* .lib section in a.out corrupted */
#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
#define ELIBEXEC 83 /* Cannot exec a shared library directly */
#define EILSEQ 84 /* Illegal byte sequence */
#define ERESTART 85 /* Interrupted system call should be restarted */
#define ESTRPIPE 86 /* Streams pipe error */
#define EUSERS 87 /* Too many users */
#define ENOTSOCK 88 /* Socket operation on non-socket */
#define EDESTADDRREQ 89 /* Destination address required */
#define EMSGSIZE 90 /* Message too long */
#define EPROTOTYPE 91 /* Protocol wrong type for socket */
#define ENOPROTOOPT 92 /* Protocol not available */
#define EPROTONOSUPPORT 93 /* Protocol not supported */
#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
#define EPFNOSUPPORT 96 /* Protocol family not supported */
#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
#define EADDRINUSE 98 /* Address already in use */
#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
#define ENETDOWN 100 /* Network is down */
#define ENETUNREACH 101 /* Network is unreachable */
#define ENETRESET 102 /* Network dropped connection because of reset */
#define ECONNABORTED 103 /* Software caused connection abort */
#define ECONNRESET 104 /* Connection reset by peer */
#define ENOBUFS 105 /* No buffer space available */
#define EISCONN 106 /* Transport endpoint is already connected */
#define ENOTCONN 107 /* Transport endpoint is not connected */
#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
#define ETOOMANYREFS 109 /* Too many references: cannot splice */
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */
#define EHOSTUNREACH 113 /* No route to host */
#define EALREADY 114 /* Operation already in progress */
#define EINPROGRESS 115 /* Operation now in progress */
#define ESTALE 116 /* Stale NFS file handle */
#define EUCLEAN 117 /* Structure needs cleaning */
#define ENOTNAM 118 /* Not a XENIX named type file */
#define ENAVAIL 119 /* No XENIX semaphores available */
#define EISNAM 120 /* Is a named type file */
#define ENOKEY 126 /* Required key not available */
#define EKEYEXPIRED 127 /* Key has expired */
#define EKEYREVOKED 128 /* Key has been revoked */
#define EKEYREJECTED 129 /* Key was rejected by service */
#define EOWNERDEAD 130 /* Owner died */
#define ENOTRECOVERABLE 131 /* State not recoverable */
#define ERFKILL 132 /* Operation not possible due to RF-kill */
#define EHWPOISON 133 /* Memory page has hardware error */
关于这些宏定义可以在以下两个文件中查看;
/usr/include/asm-generic/errno.h
/usr/include/asm-generic/errno-base.h
2、perror函数:
(1)、函数原型:
# include<stdio.h>.
...
void perror(const char *s);
...
作用:输出指针s指向的字符串(类似于printf函数的字符串输出功能),并且输出上一个函数发生的错误信息errno原因到标准设备stderr(标准错误流),如果上一个函数没有出错,就输出s的字符串及SUCCESS(因为errno未修改之前的信息就是SUCCESS,修改之后,才会变成No such file or directory之类的相关错误原因)。
(2)、测试举例:
测试代码:
# include<stdio.h>
# include<stdlib.h>
int main(void)
{
FILE * fp = fopen("./a.txt","r");
if(fp == NULL){
perror("OPEN FALSE!\n");
exit(EXIT_FAILURE);
}
else{
perror("OPEN SUCCESS!\n");
}
fclose(fp);
return 0;
}
测试结果:
最开始,当前目录下无a.txt文件,运行程序后输出OPEN FALSE ,并将errno设置为ENOENT,所以,以perror()函数输出OPEN FALSE时还会输出错误信息:“No such file or directory”,即原因是不存在所谓的要打开的文件,打开失败。
而当touch一个a.txt文件以后,当前目录下存在a.txt文件,故而成功打开,errno的值依然是0(SUCCESS),用perror()函数输出时,输出了OPEN SUCCESS,并且输出错误标志的信息:SUCCESS,即无错误,上一个函数(fopen())调用成功。