c - 在文件中间添加字符而不覆盖C中现有的字符

标签 c pointers file-io system-calls

一般来说,我对 C 语言、系统调用和指针相当生疏,所以这是一个很好的复习练习,可以让我回到正轨。我需要做的就是给定一个这样的文件:

YYY.txt: "somerandomcharacters"

将其更改为这样:

YYY.txt: "somerandomabcdefghijklmnopqrstuvwxyzcharacters"

所以所做的只是在文件中间添加一些字符。显然,这非常简单,但在 C 中,您必须在添加附加字符之前提前跟踪和管理文件的大小。

这是我天真的尝试:

//(Assume a file called YYY.txt exists and an int YYY is the file descriptor.)
char ToBeInserted[26] = "abcdefghijklmnopqrstuvwxyz";
//Determine the current length of YYY
int LengthOfYYY = lseek(YYY, 0, 2);
if(LengthOfYYY < 0)
  printf("Error upon using lseek to get length of YYY");
//Assume we want to insert at position 900 in YYY.txt, and length of YYY is over 1000.

//1.] Keep track of all characters past position 900 in YYY and store in a char array.
lseek(YYY, 900, 0); //Seeks to position 900 in YYY, so reading begins there.
char NextChar;
char EverythingPast900[LengthOfYYY-900];
int i = 0;
while(i < (LengthOfYYY - 900)) {
    int NextRead = read(YYY, NextChar, 1); //Puts next character from YYY in NextChar
    EverythingPast900[i] = NextChar;  
    i++;
}

//2.] Overwrite what used to be at position 900 in YYY:
lseek(YYY, 900, 0); //Moves to position 900.
int WriteToYYY = write(YYY, ToBeInserted, sizeof(ToBeInserted));
if(WriteToYYY < 0)
  printf("Error upon writing to YYY");

//3.] Move to position 900 + length of ToBeInserted, and write the characters that were saved.
lseek(YYY, 926, 0);
int WriteMoreToYYY = write(YYY, EverythingPast900, sizeof(EverythingPast900));
if (WriteMoreToYYY < 0) {
  printf("Error writing the saved characters back into YYY.");
}

我认为逻辑大部分是合理的,尽管有更好的方法可以用 C 实现。基本上,我需要有关 C 指针以及 UNIX 系统调用的帮助。有人介意指导我如何在 C 中正确实现这个吗?

最佳答案

这就是基本思想。如果您必须真正节省 RAM 并且文件要大得多,您可能会希望以相反的顺序逐 block 复制。但更简单的方法是将整个内容读入内存并重写整个文件。

另外,我更喜欢流函数:fopen、fseek、fread。但文件描述符方法是有效的。

关于c - 在文件中间添加字符而不覆盖C中现有的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25748721/

相关文章:

c++ - 人口增长模式与预期不符

C : using strlen for string including\0

c - C中输入三个整数的函数

c - 结构和代码解释

在 C 中复制链表

c - 指针游戏数组不知道如何将指针向后移动

windows - Lua - io.open() 最多只有 2 GB?

C++,根据用户确认不断向文件添加记录

c++ - 将 struct 写入文件时写入了太多字节

c - 在c程序中包含tk.h和tcl.h