Adding text data to the begining fo a file

Posted on 2002-03-25
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 50 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".

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 */

The curse of the end user strikes again      

You’ve updated all your end user’s email signatures. Hooray! But guess what? They’re playing around with the HTML, adding stupid taglines and ruining the imagery. Find out how you can save your signatures from end users today.


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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Where is my core dump file in Ubuntu? 12 442
How to get time_t value that is a week old 6 163
valid enum? 6 73
Windows Updates failing due to Diskpart not configured correctly 8 104
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

911 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now