ftruncate函数的使用

来源:互联网 发布:潍坊医学院网络课程 编辑:程序博客网 时间:2024/05/17 02:15

定义:

定义函数 int ftruncate(int fd,off_t length);

作用:

ftruncate会将参数fd指定的文件大小改为参数length指定的大小。

说明:

man ftruncate看一下:

DESCRIPTION
       The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.
       If the file previously was larger than this size, the extra data is lost.  If the file previously was shorter, it is extended,  and  the extended part reads as null bytes ('\0').
       
The file offset is not changed.(文件偏移量不变)

ftruncate()会将参数fd指定的文件大小改为参数length指定的大小。参数fd为已打开的文件描述词,而且必须是以写入模式打开的文件。如果原来的文件大小比参数length大,则超过的部分会被删去。

所以如果在用ftruncate函数设置某文件(原来存有十个字节的字符串)的大小为0时,此时该文件的指针指向的位置还是原来字符串的结尾处,即从头开始的第十一个字节处,如果想再次向文件中写入数据,需要调整该文件的文件指针的位置到开头处,可以用lseek()或者rewind()。这样就不会出错了!(自己可以写个小程序,这里就不赘述了)
返回值
执行成功则返回0,失败返回-1,错误原因存于errno。
错误代码
EBADF 参数fd文件描述词为无效的或该文件已关闭。
EINVAL 参数fd 为一socket 并非文件,或是该文件并非以写入模式打开。







0 0
原创粉丝点击