如何在特定位置写文件?

时间:2016-05-26 03:57:20

标签: c

我在C中创建了一个使用Unix命令dd创建文件的文件:
    dd if=/dev/zero of=file.data bs=8 count=32

这有效并创建了大小为file.data的{​​{1}},如果我打开该文件,我可以看到它是空的。

现在我想使用256 bytesfseek写入此文件中的特定位置,但每当我尝试写入不同于0的位置时,它什么都不做。

例如,如果我想写入位置2,我还必须写入位置0和1.

fwrite

一些例子

输入:

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);
}

输入:

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

output > 012

输入:

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

output > 012

有没有办法写入文件而不必写入以前的位置?

1 个答案:

答案 0 :(得分:1)

你不必做任何特别的事情。您的代码有效,只要您知道如何证明它有效。这是一个温和的扩展版本:

#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;
}

odx命令是十六进制转储程序;您可以改用od -cxxd -g1

示例输出为:

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:

前三行来自dd。我不相信使用dd是必要的,但它并没有太大的危害。接下来的三行表示文件中的前16个字节都是零字节,并且该模式重复15行,然后在偏移0x100(256 10 )处达到EOF。接下来的四行显示有2个空字节,然后是三个数字012,然后是文件末尾的所有空字节。