Briefly compare the truncate of function with the ftruncate of function in C language

  • 2020-04-02 03:18:08
  • OfStack

C truncate() function: changes file size
The header file:


#include <unistd.h>

Definition function:


int truncate(const char * path, off_t length);

Truncate () changes the file size specified by the parameter path to the size specified by the parameter length.

Return value: 0 on success, -1 on failure, error in errno.

Error code:
1. The file specified by the EACCESS parameter path cannot be accessed.
2. The file to be written by EROFS exists in the read-only file system.
3. The EFAULT parameter path pointer exceeds the accessible memory space.
4. The EINVAL parameter path contains illegal characters.
5. The ENAMETOOLONG parameter path is too long.
The path to ENOTDIR is not a directory.
7. The EISDIR parameter path points to a directory.
8. The file to which the ETXTBUSY parameter path refers is a Shared program and is being executed.
9. The ELOOP parameter path has too many symbolic connections.
EIO I/O access error.

C ftruncate() function: changes file size
The header file:


#include <unistd.h>

Definition function:


int ftruncate(int fd, off_t length);

Ftruncate () changes the file size specified by parameter fd to the size specified by parameter length. The fd parameter is an open file descriptor and must be opened in write mode. If the original file size is larger than the parameter length, the excess is deleted.

Return value: 0 on success, -1 on failure, error in errno.

Error code:
1. EBADF parameter fd file descriptor is invalid or the file has been closed.
2. EINVAL parameter fd to a socket is not a file, or the file is not opened in write mode.


Related articles: