将字符添加到文件中间而不覆盖C中的现有字符

时间:2014-09-09 15:37:22

标签: 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中实现这一点?

1 个答案:

答案 0 :(得分:1)

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

另外,我更喜欢流功能:fopen,fseek,fread。但文件描述符方法有效。