Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7889767
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T06:10:58+00:00 2026-06-03T06:10:58+00:00

Today’s problem is that I need to write an array of numbers in a

  • 0

Today’s problem is that I need to write an array of numbers in a binary file at a starting position. I have the position where it should start, and I don’t want to overwrite values after that, just want to insert the array at the starting position in the file. E.g:

12345

Let’s push 456 at position 2:

12456345

I know that probably I’ll have to implement it by myself, but I want to know what’s your opinion on how to implement that as efficiently as possible.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T06:10:59+00:00Added an answer on June 3, 2026 at 6:10 am

    Here’s a function extend_file_and_insert() that does the job, more or less.

    #include <sys/stat.h>
    #include <unistd.h>
    
    enum { BUFFERSIZE = 64 * 1024 };
    
    #define MIN(x, y) (((x) < (y)) ? (x) : (y))
    
    /*
    off_t   is signed
    ssize_t is signed
    size_t  is unsigned
    
    off_t   for lseek() offset and return
    size_t  for read()/write() length
    ssize_t for read()/write() return
    off_t   for st_size
    */
    
    static int extend_file_and_insert(int fd, off_t offset, char const *insert, size_t inslen)
    {
        char buffer[BUFFERSIZE];
        struct stat sb;
        int rc = -1;
    
        if (fstat(fd, &sb) == 0)
        {
            if (sb.st_size > offset)
            {
                /* Move data after offset up by inslen bytes */
                size_t bytes_to_move = sb.st_size - offset;
                off_t read_end_offset = sb.st_size; 
                while (bytes_to_move != 0)
                {
                    ssize_t bytes_this_time = MIN(BUFFERSIZE, bytes_to_move);
                    ssize_t rd_off = read_end_offset - bytes_this_time;
                    ssize_t wr_off = rd_off + inslen;
                    lseek(fd, rd_off, SEEK_SET);
                    if (read(fd, buffer, bytes_this_time) != bytes_this_time)
                        return -1;
                    lseek(fd, wr_off, SEEK_SET);
                    if (write(fd, buffer, bytes_this_time) != bytes_this_time)
                        return -1;
                    bytes_to_move -= bytes_this_time;
                    read_end_offset -= bytes_this_time; /* Added 2013-07-19 */
                }   
            }   
            lseek(fd, offset, SEEK_SET);
            write(fd, insert, inslen);
            rc = 0;
        }   
        return rc;
    }
    

    (Note the additional line added 2013-07-19; it was a bug that only shows when the buffer size is smaller than the amount of data to be copied up the file. Thanks to malat for pointing out the error. Code now tested with BUFFERSIZE = 4.)

    This is some small-scale test code:

    #include <fcntl.h>
    #include <string.h>
    
    static const char base_data[] = "12345";
    typedef struct Data
    {
        off_t       posn;
        const char *data;
    } Data;
    static const Data insert[] =
    {
        {  2, "456"                       },
        {  4, "XxxxxxX"                   },
        { 12, "ZzzzzzzzzzzzzzzzzzzzzzzzX" },
        { 22, "YyyyyyyyyyyyyyyY"          },
    };  
    enum { NUM_INSERT = sizeof(insert) / sizeof(insert[0]) };
    
    int main(void)
    {
        int fd = open("test.dat", O_RDWR | O_TRUNC | O_CREAT, 0644);
        if (fd > 0)
        {
            ssize_t base_len = sizeof(base_data) - 1;
            if (write(fd, base_data, base_len) == base_len)
            {
                for (int i = 0; i < NUM_INSERT; i++)
                {
                    off_t length = strlen(insert[i].data);
                    if (extend_file_and_insert(fd, insert[i].posn, insert[i].data, length) != 0)
                        break;
                    lseek(fd, 0, SEEK_SET);
                    char buffer[BUFFERSIZE];
                    ssize_t nbytes;
                    while ((nbytes = read(fd, buffer, sizeof(buffer))) > 0)
                        write(1, buffer, nbytes);
                    write(1, "\n", 1);
                }
            }
            close(fd);
        }
        return(0);
    }
    

    It produces the output:

    12456345
    1245XxxxxxX6345
    1245XxxxxxX6ZzzzzzzzzzzzzzzzzzzzzzzzZ345
    1245XxxxxxX6ZzzzzzzzzzYyyyyyyyyyyyyyyYzzzzzzzzzzzzzzZ345
    

    It should be tested on some larger files (ones bigger than BUFFERSIZE, but it would be sensible to test with a BUFFERSIZE a lot smaller than 64 KiB; I used 32 bytes and it seemed to be OK). I’ve only eyeballed the results but the patterns are designed to make it easy to see that they are correct. The code does not check any of the lseek() calls; that’s a minor risk.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

today i have direct a problem :P i just need some ideas... how do
Today I have encountered a problem that required me to determine the maximum index
Today I realized that I no longer have a Web Content Form option (where
today i'm having a little problem, that probably is nothing for pros here :)
today i need your help to get an specific sql select query. i have
Today, I have a problem with hosting my custom service host using custom binding
today i need help with some jquery, which I really do not have much
Today at work someone tried to convince me that: {$obj->getTableInfo()} is fine for smarty/mvc/templating
Today I'm playing with localization. I have a winforms app where I've set localizable
Today I came across this question: you have a code static int counter =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.