c# - 如何通过C++或C或C#在Windows中创建指定大小的空文件?

标签 c# c++ c windows

<分区>

如何在Windows中用C++或C或C#创建一个指定大小的空文件?

这个文件不占用磁盘空间,打开文件,没有任何东西。 但是文件在文件属性中有字节数。

For example--

enter image description here

最佳答案

在 C++ 中你可以这样做:

#include <iostream>
#include <fstream>
#include <vector>

int main()
{
    std::vector<char> empty(1024, 0);
    std::ofstream ofs("ouput.img", std::ios::binary | std::ios::out);

    for(int i = 0; i < 1024*300; i++)
    {
        if (!ofs.write(&empty[0], empty.size()))
        {
            std::cerr << "problem writing to file" << std::endl;
            return 255;
        }
    }
}


在 C# 中:制作 2GB 的文件: 简单地创建文件,寻找一个适当大的偏移量,然后写入一个字节:

FileStream fs = new FileStream(@"c:\tmp\huge_dummy_file", FileMode.CreateNew);
fs.Seek(2048L * 1024 * 1024, SeekOrigin.Begin);
fs.WriteByte(0);
fs.Close();

关于c# - 如何通过C++或C或C#在Windows中创建指定大小的空文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172752/

相关文章:

c# - 将 ObservableCollection 的所有元素绑定(bind)到 TextBlock

c# - 如何使用 Entity Framework 6 将数据列表传递给存储过程

c# - 根据范围数据查找值

c - 编译 C 时出现奇怪的错误

c# - 获取 IP 地址而不是 MAC 地址

php - 捕获与 PHP exec() 分开的输出参数

c++ - 什么是 "cerr"和 "stderr"?

c++ - 使用C++模板编程提取任意结构的字段类型

python - 从树莓派上传文件到谷歌驱动器

c++ - 英特尔线程 C API