自学内容网 自学内容网

Linux-标准IO常用函数

一、函数

1、文件的打开与关闭

1.1 fopen

函数原型:FILE *fopen(const char *pathname, const char *mode);

重要入参:mode

        r,r+,w,w+,a,a+,x(谨慎模式)

返回值:     

        成功:返回FILE*类型的变量

        失败:返回NULL,并将错误编码设置到系统的errno变量中

1.2 fclose

函数原型:int fclose(FILE *stream);
返回值

        成功:0

        失败:EOF。PS:使用fclose关闭一个已经关闭的文件流,可能导致不可预测的行为:可能相安无事,也有可能程序崩溃(free(): double free detected in tcache 2 Aborted (core dumped))

2、读写函数

2.1、字节读写函数

2.1.1 fgetc

函数原型:int fgetc(FILE *stream);

返回值

        成功:returns it as an unsigned char cast to an int

        失败或文件结束:EOF on end of file or error

2.1.1 fputc

函数原型:int fputc(int c, FILE *stream);

重要参数:writes the character c, cast to an unsigned char, to stream

返回值

        成功:returns it as an unsigned char cast to an int

        失败或文件结束:EOF on end of file or error

        PS:也就是说,写入成功,返回的一定是一个正数

2.2、字符串读写函数

2.2.1 fgets

函数原型:char *fgets(char *s, int size, FILE *stream);

重要参数:reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.  Reading stops after an EOF or a newline.  If a newline is read,  it
is  stored into the buffer.  A terminating null byte ('\0') is stored after the last character in the buffer.

1)读出的s,都有'\0';

2)文件结束或文件中遇到新行或超过s的size,会结束本次fgets

返回值

        成功:返回s

        失败或文件尾:返回NULL。NULL on error or when end of file occurs while no charac‐
ters have been read

2.2.2 fputs

函数原型: int fputs(const char *s, FILE *stream);

重要参数:writes the string s to stream, without its terminating null byte ('\0').

返回值:return a nonnegative number on success, or EOF on error

        成功: 非负

        失败: EOF(-1)

2.3、格式化读写函数

2.3.1 fscanf

函数原型:int fscanf(FILE *stream, const char *format, ...);

重要参数

返回值

        On success, these functions return the number of input items successfully  matched  and  assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.

        The value EOF is returned if the end of input is reached before either the first  successful conversion  or  a  matching failure occurs.  EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno  is  set  to indicate the error.

PS:是不是用fscanf或sscanf来解析外部传过来的报文会很危险,特别是处理一些异常报文的时候。

2.3.2 fprintf

函数原型:int fprintf(FILE *stream, const char *format, ...);

2.4、模块化读写函数

2.4.1 fread

函数原型:size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

重要参数

        size_t: 单个对象的大小

        nmemb:对象的数量

返回值

       On  success,  fread()  and fwrite() return the number of items read or written.  This number equals the number of bytes transferred only when size is 1.  

        If an error occurs, or the  end of the file is reached, the return value is a short item count (or zero).

        fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.

PS!!!

       成功一定会返回一个大于0的值,但是即便返回了大于0的值,也不一定是正确的读取。因此,不能简单的使用fread的函数的返回值来判读读取是否正常或读取到文件末尾,需要和ferror和feof结合判断。feof和ferror函数建第4小节

  • 使用fread函数完全读取一个文件内容的示例如下(我自己写的)
while((cntRead=fread(buf,1,1024,fp)) >0){
if(ferror(fp) != 0){
perror("读取的过程中发生了异常");
break;
}
//处理内容
//TODO
int ret2=fwrite(buf,1,cntRead,dest);

//文件是否到结尾
int ret=feof(fp);
printf("feof:[%d],cntRead=[%d],ret2=[%d]\n", ret, cntRead,ret2);
//读完后文件是否已经到末尾了
if(feof(fp)){
break;
}
}

使用fread任意文件,简化下,可写成

while(feof(fp)==0 && (cntRead=fread(buf,1,1024,fp)) >0){
if(ferror(fp) != 0){
perror("读取的过程中发生了异常");
break;
}
//TODO 处理内容
int ret2=fwrite(buf,1,cntRead,dest);
}
2.4.2 fwrite

函数原型:size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);

其他同fread

3、文件光标的操作

三个函数:fseek、ftell、rewind

3.1 fseek

函数原型:int fseek(FILE *stream, long offset, int whence);

重要参数

        whence

                SEEK_SET:文件头

                SEEK_CUR:当前位置 

                SEEK_END:文件末尾

        offset:

                可为正,也可为负,单位是字节。

返回值

        成功:0

        失败:-1

        

3.2 ftell

函数原型:long ftell(FILE *stream);

重要参数

返回值

        成功:返回当前位置

        失败:-1

3.3 rewind

函数原型:void rewind(FILE *stream);

重要参数

返回值:The rewind() function returns no value

4、辅助判断函数:feof与ferror函数

4.1 feof

函数原型:int feof(FILE *stream);

返回值:The function feof() tests the end-of-file indicator for the stream pointed to  by  stream,  returning nonzero if it is set.  The end-of-file indicator can be cleared only by the function clearerr().

        1)如果到文件结尾了,返回 真值(非0)

        2)否则,返回0

4.2 ferror

函数原型:int ferror(FILE *stream);

返回值:he  function  ferror() tests the error indicator for the stream pointed to by stream, returning nonzero if it is set.  The error indicator can be reset only by the clearerr() function.

        1) 0--没有错误;

        2)非0--有错误信息。

5、time与localtime函数

5.1 time

函数原型:time_t time(time_t *tloc);

重要参数

       If tloc is non-NULL, the return value is also stored in the memory pointed to by tloc.

返回值:time()  returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000(UTC).

5.2 localtime

函数原型:struct tm *localtime(const time_t *timep);

重要参数

返回值

          struct tm {
               int tm_sec;    /* Seconds (0-60) */
               int tm_min;    /* Minutes (0-59) */
               int tm_hour;   /* Hours (0-23) */
               int tm_mday;   /* Day of the month (1-31) */
               int tm_mon;    /* Month (0-11) */
               int tm_year;   /* Year - 1900 */
               int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
               int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
               int tm_isdst;  /* Daylight saving time */
           };

6、fflush函数

6.1 fflush

函数原型:int fflush(FILE *stream);

重要参数

返回值:Upon successful completion 0 is returned.  Otherwise, EOF is returned and errno  is  set  to indicate the error.

二、三组重要的流

1、stderr

不缓存,fd:2

2、stdin、stdout

默认缓存大小为:1024,fd:0和1

3、FILE(重点)

默认缓存大小为:4096,fd:从3开始分配,尽可能小原则

疑问:

1、fwrite和fread,跨硬件的大小端文件写读的问题

2、json、xml、csv等一些较为复杂的文件格式如何实现


原文地址:https://blog.csdn.net/tjzhuorui/article/details/142986118

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!