warty
warty

Reputation: 49

How to write file at specific position?

I made a function in C to create a file using Unix command dd:
dd if=/dev/zero of=file.data bs=8 count=32

This works and created file.data with size 256 bytes and if I open the file I can see it's empty.

Now I want to write to a specific position in this file using fseek and fwrite, but whenever I try to write to a position different from 0, it does nothing.

For example, If I want to write to position 2, I must also write to position 0 and 1.

void createFile() {
    char command[100];
    sprintf(comando, "dd if=/dev/zero of=file.data bs=8 count=32");
    system(command);
}

void writeFile(int position, char * data) {
    FILE * file = fopen("file.data", "r+");
    fseek(file, position, SEEK_SET);
    fwrite(data, strlen(data), 1, file);
    fclose(file);
}

Some examples

Input:

writeFile(0, "0");
writeFile(1, "1");  
writeFile(2, "2");

output > 012

Input:

writeFile(2, "2");
writeFile(1, "1");
writeFile(0, "0");

output > 012

Input:

writeFile(1, "1");
writeFile(2, "2");

output > empty

Is there some way to write into the file without having to write into the previous positions also?

Upvotes: 0

Views: 3923

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 755034

You don't have to do anything special. Your code works, as long as you know how to demonstrate that it works. Here's a mildly extended version of it:

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

static void createFile(void)
{
    char command[100];
    sprintf(command, "dd if=/dev/zero of=file.data bs=8 count=32");  // Typo fixed!
    system(command);
}

static void writeFile(int position, char *data)
{
    FILE *file = fopen("file.data", "r+");
    fseek(file, position, SEEK_SET);
    fwrite(data, strlen(data), 1, file);
    fclose(file);
}

int main(void)
{
    createFile();
    system("odx file.data");
    writeFile(2, "012");
    system("odx file.data");
    return 0;
}

The odx command is a hex dump program; you could use od -c or xxd -g1 instead.

The sample output is:

32+0 records in
32+0 records out
256 bytes transferred in 0.000109 secs (2349544 bytes/sec)
0x0000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................
* (15)
0x0100:
0x0000: 00 00 30 31 32 00 00 00 00 00 00 00 00 00 00 00   ..012...........
0x0010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................
* (14)
0x0100:

The first three lines are from dd. I'm not convinced that using dd is necessary, but it does no great harm. The next three lines indicate that the first 16 bytes in the file are all zero bytes, and that this pattern repeats for 15 more lines, and then you reach EOF at offset 0x100 (25610). The next four lines show that there are 2 null bytes, then the three digits 012, then all null bytes to the end of file.

Upvotes: 1

Related Questions