• C

Adding text data to the begining fo a file

Openning a text file with "a" will append data to the end of a text file. How would you add records to the beginning of a file?
Who is Participating?
cookreConnect With a Mentor Commented:
The way it's been done for decades:
1) Create temp file
2) Write new stuff to temp file
3) Copy over old stuff
4) Close both
5) Delete original
6) Rename temp

If the file isn't too big and you can malloc up enough RAM to hold the entire file:
1) Open file in truncate mode
2) Load into RAM
3) Write new stuff
4) Write old stuff

Or, you could be lazy:
1) Create temp file with new stuff
2) Shell out to a copy temp+old  old
(If this actually works, it was probably because it was done like the first method mentioned above)
Cookre is right.
It's a pain, isn't it?
Peter KwanAnalyst ProgrammerCommented:

1. Rename your original file (say "file1") to another name (say "file2")
2. Create a new file with the name "file1"
3. Write some stuff to "file1"
4. Open your "file2" and append the content to the "file1".
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

When I had this problem on machines that lacked the hard disk space for temp files and the memory for reading the whole file at once, I would use an allocated buffer that was twice the size of what was to be added, and I would read ahead so I wouldn't overwrite file data.

This is not terribly efficient, but it was designed to work around certain hardware limitations.

For example, the program below will add however many '\0' characters you want to a file at a given location, but it does not use temp files, and it only allocates twice as much memory as the number of characters to add.

So, if you want to add 5 '\0' characters to the beginning of the file, you would run the program as:

prgmName fileName 0 5

You could easily change this to add what you want and where, but this gives you an idea of how to do it.


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
    FILE *f;
    long writeTo;
    long bytesToAdd;
    long temp;
    char *ptr;
    long bufSize;

    if ( argc != 4 ) {
        printf("Usage: %s <file> <writeTo> <bytesToAdd>\n", argv[0]);
        return -1;
    if ( (f = fopen(argv[1], "r+b")) == NULL )
        return -2;
    if ( (writeTo = atol(argv[2])) < 0 )
        return -3;
    if ( (bytesToAdd = atol(argv[3])) <= 0 )
        return -4;
    if ( (ptr = (char*)malloc(2*bytesToAdd)) == NULL )
        return -5;

    fseek(f, writeTo, SEEK_SET);
    bufSize = fread(ptr, sizeof(char), bytesToAdd, f);
    fseek(f, writeTo, SEEK_SET);

    memset(ptr+bytesToAdd, 0, bytesToAdd);
    fwrite(ptr+bytesToAdd, sizeof(char), bytesToAdd, f);

    while ( bufSize > 0 ) {
        if ((temp = fread(ptr+bytesToAdd, sizeof(char), bytesToAdd, f)) > 0)
            fseek(f, -temp, SEEK_CUR);
        fwrite(ptr, sizeof(char), bufSize, f);
        memmove(ptr, ptr+bytesToAdd, bytesToAdd);
        bufSize = temp;

    return 0;
} /* main */


  There is no way you can say append at the begining of the file in an open statement. However, this could be done programatically.

  Writing to a different file
     Open you file for reading.
     Open another file for writting.
     Read the contents of the original file.
     Write your new records to the New file.
     Write the old records to the New file.

  Doing the same thing to the same file.
     Open the file for reading.
     Read file contents into memory.
     Delete the file.
     Open the same file for writting.
     Write the New Records.
     Write the Old Records.

  If you are not sure of the way to do this. Let me know and I will write the code.

Hope this helps,


It is possible. You open a file as append mode. you initialize ypu file pointer at NULL. You may write here. This is the best possible way.

Hi tapasmondal, welcome to EE.

All of the experts here, for the most part have learn from other experts as to the proper etiquette
for posting answers.

Please don't lock questions especialy when the questioner has asked that the question not be locked.

An answer should not be posted as an answer, if other experts have previously posted possible answers
as comments, and/or have already made contributions to the question.

There are many experts who never post answers as answer.  Instead, they post their answers as comments.

If you read the following link, you'll see why this is the preferred method for many of our valued experts,
including myself.


Hi ronandersen:
Feel free to click the [Reject Answer] button near tapasmondal's response, even if it seems like
a good answer.
Doing so will increase your chance of obtaining additional input from other experts.  Later, you can
click the [Select Comment as Answer] button on any response.
Force Accepted

Community Support Moderator @Experts Exchange
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.