1

I want to write a C program, which could insert one line into the head of file.

However, if the file is very big, I need to read() all the file content, then add one line in the head, then write() them back.

Is there some way could be more effiency??

My Program is like below

int main(int argc, char **argv)
{
   char buffer[MAX_LENGTH];
   const char *line = argv[1];
   int fd = open("bigfile.txt", O_RDWR);
   read(fd, buffer, MAX_LENGTH);
   write(fd, line, strlen(line));
   write(fd, buffer, strlen(buffer));   //really low efficient, I need to rewrte the whole file every time
}
billzhao
  • 27
  • 2
  • You can rewind the file and write to the beginning. But this could overwrite some data – ForceBru Jul 07 '15 at 11:29
  • 4
    There's no filesystem on linux (Or any other ordinary operating system) that allows you to insert data in a file - only overwriting, appending, truncation can be done. – nos Jul 07 '15 at 11:31
  • The simple answer is "No, you just can't do that." You have to rewrite the file, it's the only way. Adding a line at the beginning of a file would be kind of like taking a 100-story building, and trying to add one more floor, but at the bottom, not at the top. It's so much work it's not worth it. – Steve Summit Jul 07 '15 at 13:49
  • Assuming a non-record-based filesystem (such as NTFS or ext3 or something like that), it's *far* easier and safer to create a new file, write your new content to that file, and then append the contents of the original file to the new file. Trying to rearrange data in place is a bit of work and you risk damaging the file data. – John Bode Jul 07 '15 at 14:55

1 Answers1

0

You can prepend in-place by rewriting. You just need to make sure you're already read what you're rewriting so that you don't lose any information.

You can take a look at my more general (it allows you to rewrite each line in-place, sed-style, instead of limiting itself to prepending) ruby answer at Prepend a single line to file with Ruby for inspiration if you really want to do it in C.

Community
  • 1
  • 1
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142