【C语言基础】文件中任意位置插入写操作的实现/Implementation For File Insertion Operation based on C standard lib.

最近因工作要求,需要实现简单的文本插入功能。该功能虽然简单,但是c语言标准库并未实现之。因此我花一点点时间,基于标准库的文件操作接口,简单实现了一个在文件中任意位置插入指定字符串的子函数。


static int finsert(FILE *fp, char *file_name, char *content_to_insert, unsigned int content_size)
{
	char *buffer;
	long current_position, file_size, remainder;
	FILE *temp = fopen("temp.txt", "wb+");

	//1. memory allocation
	current_position = ftell(fp);
	fseek(fp, 0, SEEK_END);
	file_size = ftell(fp);
	remainder = file_size - current_position;
	buffer = (char *)malloc(file_size * sizeof(char));
	if (NULL == buffer)
	{
		return -1;
	}

	//2. Copy PART I
	fseek(fp, 0, SEEK_SET);
	fread(buffer, sizeof(char), current_position, fp);
	fwrite(buffer, sizeof(char), current_position, temp);

	//3. Insert new content
	fwrite(content_to_insert, sizeof(char), content_size, temp);

	//4. Copy PART II
	fseek(fp, current_position, SEEK_SET);
	fread(buffer, sizeof(char), remainder, fp);
	fwrite(buffer, sizeof(char), remainder, temp);

	//5. File replace
	fclose(fp);
	fclose(temp);
	if (0 != remove(file_name))
	{
		return -1;
	}
	if (0 != rename("temp.txt", file_name))
	{
		return -1;
	}

	//6. Open the new file
	fp = fopen(file_name, "rb+");
	fseek(fp, current_position + content_size, SEEK_SET);
	return 0;
}

int main(void)
{
	int input = 0;
	FILE *fp = fopen("test.txt", "rb+");
	char content[] = "hello world";

	fscanf(fp, "%d", &input);
	finsert(fp, "test.txt", content, sizeof(content));
	fscanf(fp, "%d", &input);
	fclose(fp);
	return 0;
}


  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值