用C创建固定长度的文本文件?

时间:2014-07-02 08:10:52

标签: c file-io

在C中创建给定长度的空文本文件的最佳方法是什么?写作空间或任何特殊字符不是一种选择。我的意思是它应该直接创建文件而不需要迭代到文件长度等。

3 个答案:

答案 0 :(得分:4)

这样做非常简单。你所要做的就是找到预期的位置然后写点东西:

#include <stdio.h>

const unsigned int wanted_size = 1048576;

int main(int argc, char **argv) {
    FILE *fp = fopen("test.dat", "w+");
    if (fp) {
        // Now go to the intended end of the file
        // (subtract 1 since we're writing a single character).
        fseek(fp, wanted_size - 1, SEEK_SET);
        // Write at least one byte to extend the file (if necessary).
        fwrite("", 1, sizeof(char), fp);
        fclose(fp);
    }
    return 0;
}

上面的示例将创建一个长度为1 MB的文件。请记住,实际空间将立即分配,而不仅仅是保留。

这也允许您分配大于系统内存的文件。使用上面的代码,我能够立即(<1毫秒)在Raspberry Pi(只有512 MB RAM)上保留1 GB大文件,而无需使用任何类型的迭代。

您还可以使用任何其他方式将数据写入该位置(如fputs()),实际编写内容非常重要。调用fputs("", fp);不一定会按预期扩展文件。

答案 1 :(得分:1)

在Windows上使用SetFilePointerSetEndOfFile,在Linux上使用truncate(也会增加)。

答案 2 :(得分:1)

这就是我想出来的。

// hello.c
#include <stdio.h>

int CreateFileSetSize(const char *file, int size)
{
    FILE *pFile;
    pFile = fopen(file, "w");
    if (NULL == pFile)
    {
        return 1;
    }
    fseek(pFile, size, SEEK_SET);
    fputc('\n', pFile);
    fclose(pFile);
    return 0;
}

int main(int argc, const char *argv[])
{
    const char *fileName = "MyFile.txt";
    int size = 1024;
    int ret = 0;
    if (3 == argc)
    {
        fileName = argv[1];
        size = atoi(argv[2]);
    }
    ret = CreateFileSetSize(fileName, size);
    return ret;
}

我显然不是唯一一个提出这个解决方案的人。我碰巧在Stack Overflow上找到了以下问题。

如何创建“x”大小的文件? How to create file of "x" size?

相关问题