库函数文件操作

库文件操作

  • remove
int remove(const char *pathname);

remove()删除文件或路径。

remove()  deletes a name from the filesystem.  It calls unlink(2) for files, and rmdir(2) for directories.
If the removed name was the last link to a file and no processes have the file  open,  the  file  is deleted and the space it was using is made available for reuse.
If  the  name was the last link to a file, but any processes still have the file open, the file will remain in existence until the last file descriptor referring to it is closed.
If the name referred to a symbolic link, the link is removed.
If the name referred to a socket, FIFO, or device, the name is removed, but processes which have the object open may continue to use it.

  • fopen
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);

mode参数是一个字符串,由rwatb+六个字符组合而成,其中t代表文本文件,b代表二进制文件。在unix系统中,二进制文件和文件文件没有区别,都是由一串字节组成。如果省略t和b,rwa+有6种组合:

"r"只读,文件必须存在

"w"只写,如果文件不存在则创建;如果文件已经存在,则把文件长度截断(Truncate)为0字节再重新写,也就是替换掉原来的文件内容。

"a"只能在文件末尾追加数据,如果文件不存在则创建。

"r+"允许读和写,文件必须存在。

"w+"允许读和写,如果文件不存在则创建;如果文件已经存在,则把文件长度截断(Truncate)为0字节再重新写,也就是替换掉原来的文件内容。

"a+"允许读和追加数据,如果文件不存在则创建。

  • fclose
int fclose(FILE *fp);

返回值:成功返回0,出错返回EOF(-1),并设置errno。

注:如果不调用fclose,在进程退出时系统会自动关闭文件。但常年累月运行的程序(服务器程序),会浪费很多资源。

  • 文件定位
#include <stdio.h>

int fseek(FILE *stream, long offset, int whence);

whence:SEEK_SET, SEEK_CUR, SEEK_END

offset可正可负,负值表示向前移动,正值表示向后移动,如果向前移动的字节数超过了文件开头则出错返回。如果向后移动的字节数超过了文件末尾,再次写入时将增大文件尺寸,从原来的文件末尾移动到fseek指定的位置之间的字节都是0.

返回值:成功返回0,出错返回-1并设置errno。

    long ftell(FILE *stream);

返回值:成功返回当前读写位置,出错返回-1并设置errno。

    void rewind(FILE *stream);

返回值:无

  • 以记录为单位的输入输出
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

返回值:读或写的记录数,成功时返回的记录数等于nmemb,出错或读到文件末尾时返回的记录数小于nmemb,也可能返回0。

fread和fwrite用于读写记录,这里的记录是指一串固定长度的字节,比如一个int,一个结构体或一个定长数组。参数size指定一条记录的长度,而nmemb指出要读或写多少条记录,这些记录在ptr指向的内存空间中连续存放。

  • 流状态操作
void clearerr(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);
int fileno(FILE *stream);

clearerr()清除文件结束end-of-file和error标识。

feof()测试是否设置文件结束标识,设置返回非0.

ferror()测试是否设置错误标识,设置返回非0.

fileno()返回文件描述符。错误返回-1设置EBADF.

原文地址:https://www.cnblogs.com/embedded-linux/p/5037381.html