Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Adding text data to the begining fo a file

Posted on 2002-03-25
Medium Priority
Last Modified: 2011-04-14
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?
Question by:ronandersen
LVL 22

Accepted Solution

cookre earned 200 total points
ID: 6895399
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)

Expert Comment

ID: 6895449
Cookre is right.
It's a pain, isn't it?
LVL 16

Expert Comment

by:Peter Kwan
ID: 6896465

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".
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Expert Comment

ID: 6921880
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 */


Expert Comment

ID: 6954696

  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,


Expert Comment

ID: 6979624

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.


Expert Comment

ID: 6980209
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.

Expert Comment

ID: 8279743
Force Accepted

Community Support Moderator @Experts Exchange

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
Suggested Courses

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question