C语言的C库提供了文件流的各种操作方法,在这里介绍一些操作常识与限制。
示例:
/*@brief what's the limits of stream? show you here@author wen`xuanpei@email 15873152445@163.com(query for any question here)
*/
#include <stdio.h>//<cstdio>//NULL,EOF,_IO_LINE_BUF,(_IO_|)BUFSIZ, _IO(NBF|LBF|FBF), (TMP|FOPEN|FILENAME)_MAX,std(in|out|err),fileno,printf
#include <unistd.h>//sleep/*need sleep or not?*/
#if 1
# define NO_SLEEP//
#endif
#ifdef NO_SLEEP
# define sleep(x)//
#endif
#define TEST_BEGIN_GAP (5)//how long to sleep seconds when after test begin?
#define TEST_END_GAP (5)//how long to sleep seconds when after test end?/*main frame here*/
int main(){printf("\ntest stream limits begin:\n");sleep(TEST_BEGIN_GAP); printf(/*default opened stream*/"stdin :%p, fd(stdin ):%d\n""stdout:%p, fd(stdout):%d\n""stderr:%p, fd(stderr):%d\n", stdin , fileno(stdin), stdout, fileno(stdout), stderr, fileno(stderr));sleep(1);printf("NULL:%d\n"//empty address"EOF:%d\n"//end of file(stream)"BUFSIZ:%d\n"//buffer size"L_tmpnam:%d\n"//minimum length for temporary file name"TMP_MAX:%d\n"//number of temporary files, NULL, EOF, BUFSIZ, L_tmpnam, TMP_MAX);sleep(1);printf("FOPEN_MAX:%lu\n"//max times of fopen()"FILENAME_MAX:%lu\n"//max length of filename"_IO_LINE_BUF:%lu\n"//max length of line"_IO_BUFSIZ:%lu\n"//max length of file buffer, FOPEN_MAX, FILENAME_MAX, _IO_LINE_BUF, _IO_BUFSIZ);sleep(1);printf("macro for setvbuf():\n""_IONBF:%d\n""_IOLBF:%d\n""_IOFBF:%d\n", _IONBF, _IOLBF, _IOFBF);sleep(1);printf("macro for fseek():\n""SEEK_SET:%d\n""SEEK_CUR:%d\n""SEEK_END:%d\n", SEEK_SET, SEEK_CUR, SEEK_END);sleep(1);printf("\ntest stream limits end:\n");sleep(TEST_END_GAP);return 0;
}
小结:
1)程序(进程)启动后,自动打开三个文件流stdin, stdout,stderr, 进程退出后自动关闭
2)用户态的流文件操作可以转换为内核态的系统文件操作
3)文件指针没有被用到前尽量置为NULL, 使用完了关闭流,然后也尽量置为NULL
4)读取操作到了文件末尾,会读取到EOF字符
5)文件流有不同的缓冲区模式:
无缓冲区-如stderr(缓冲区大小默认为0)
行缓冲区-如stdin,stdout(缓冲区大小默认为_IO_LINE_BUF)
块缓冲区-如文件流(缓冲区大小默认为BUFSIZ或_IO_BUFSIZ)
6)文件流的缓冲模式可以被变更,相关方法及标识:setvbuf, _IONBF, _IOLBF, _IOFBF
7)打开临时文件最大数量限制为:TMP_MAX
8)打开文件流最大数量限制为:FOPEN_MAX
9)文件路径长度最大限制为:FILENAME_MAX
10)文件流的访问可以是随机的,相关方法及标识:fseek, SEEK_SET, SEEK_CUR, SEEK_END