【C语言基础】文件中任意位置插入写操作的实现/Implementation For File Insertion Operation based on C standard lib. 您所在的位置:网站首页 c语言往文件中写数据怎么写 【C语言基础】文件中任意位置插入写操作的实现/Implementation For File Insertion Operation based on C standard lib.

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

2023-08-24 03:45| 来源: 网络整理| 查看: 265

最近因工作要求,需要实现简单的文本插入功能。该功能虽然简单,但是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; }



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有