一.改变文件大小
1.1.ftruncate函数原型
#include <unistd.h>
int ftruncate(int fd, off_t length);
- 说明
- 函数ftruncate会将参数fd指定的文件大小改为参数length指定的大小。
- 参数fd为已打开的文件描述词,而且必须是以写入模式打开的文件。
- 如果原来的文件大小比参数length大,则超过的部分会被删去。
- 返回值 执行成功则返回0,失败返回-1。
1.2.例子
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <strings.h>
#include <fcntl.h>
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
int fd = open(argv[1], O_WRONLY);
if(-1 == fd)
{
perror("open fail\n");
return -1;
}
int ret = ftruncate(fd,3);//改变文档大小,字节
if(-1 == ret)
{
cout << "fruncate failed" << endl;
return -1;
}
close(fd);
return 0;
}
二.文件定位
2.1.lseek函数原型
//函数lseek将文件指针设定到相对于whence,偏移值为offset的位置
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);//fd文件描述符
- 说明
whence 可以是下面三个常量的一个
- SEEK_SET 从文件头开始计算
- SEEK_CUR 从当前指针开始计算
- SEEK_END 从文件尾开始计算
利用该函数可以实现文件空洞(对一个新建的空文件,可以定位到偏移文件开头1024个字节的地方,在写入一个字符,则相当于给该文件分配了1025个字节的空间,形成文件空洞)通常用于多进程间通信的时候的共享内存。
2.2.lseek例子
#include <iostream>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
int fd = open(argv[1], O_WRONLY|O_CREAT);
if(-1 == fd)
{
perror("open");
return -1;
}
int ret = lseek(fd, 1024, SEEK_SET);
if(-1 == ret)
{
perror("lseek");
close(fd);
return -1;
}else
{
cout << "lseek success" << endl;
}
ret = write(fd, "ss", sizeof("ss"));
if(-1 == ret)
{
perror("write");
close(fd);
return -1;
}
close(fd);
return 0;
}
//此时文件大小为1024+,即1k以上,