C++制作特定大小的文件
这是我当前的问题:我正在尝试用 C++ 创建一个 x MB 的文件。用户将输入文件名,然后输入 5 到 10 之间的数字作为他们想要创建的文件的大小。稍后在这个项目中,我将用它做其他事情,但我停留在创建该死的东西的第一步上。
我的问题代码(到目前为止):
char empty[1024];
for(int i = 0; i < 1024; i++)
{
empty[i] = 0;
}
fileSystem = fopen(argv[1], "w+");
for(int i = 0; i < 1024*fileSize; i++){
int temp = fputs(empty, fileSystem);
if(temp > -1){
//Sucess!
}
else{
cout<<"error"<<endl;
}
}
现在,如果我正确地进行数学计算,1 个字符就是 1 个字节。 1KB有1024字节,1MB有1024KB。因此,如果我想要一个 2 MB 的文件,我必须向该文件写入 1024*1024*2 字节。是的?
我没有遇到任何错误,但我最终得到了一个 0 字节的文件...我不确定我在这里做错了什么,所以任何帮助将不胜感激!
谢谢!
Here is my current problem: I am trying to create a file of x MB in C++. The user will enter in the file name then enter in a number between 5 and 10 for the size of the file they want created. Later on in this project i'm gonna do other things with it but I'm stuck on the first step of creating the darn thing.
My problem code (so far):
char empty[1024];
for(int i = 0; i < 1024; i++)
{
empty[i] = 0;
}
fileSystem = fopen(argv[1], "w+");
for(int i = 0; i < 1024*fileSize; i++){
int temp = fputs(empty, fileSystem);
if(temp > -1){
//Sucess!
}
else{
cout<<"error"<<endl;
}
}
Now if i'm doing my math correctly 1 char is 1byte. There are 1024 bytes in 1KB and 1024KB in a MB. So if I wanted a 2 MB file, i'd have to write 1024*1024*2 bytes to this file. Yes?
I don't encounter any errors but I end up with an file of 0 bytes... I'm not sure what I'm doing wrong here so any help would be greatly appreciated!
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
潜在的稀疏文件
这将创建大小为 300 MB 的
output.img
:请注意,从技术上讲,这将是触发文件系统对稀疏文件的支持的好方法。
密集文件 - 用 0 填充
功能与上面相同,但用 0 填充文件:
Potentially sparse file
This creates
output.img
of size 300 MB:Note that technically, this will be a good way to trigger your filesystem's support for sparse files.
Dense file - filled with 0's
Functionally identical to the above, but filling the file with 0's:
您的代码不起作用,因为您正在使用
fputs
它将空终止字符串写入输出缓冲区。但是您试图写入所有空值,因此当它查看字符串的第一个字节并最终什么也不写入时,它就会停止。现在,要创建特定大小的文件,您所需要做的就是调用
truncate
函数(或 Windows 的_chsiz
)一次并设置您想要的文件大小。祝你好运!
Your code doesn't work because you are using
fputs
which writes a null-terminated string into the output buffer. But you are trying to write all nulls, so it stops right when it looks at the first byte of your string and ends up writing nothing.Now, to create a file of a specific size, all you need to do is to call
truncate
function (or_chsiz
for Windows) exactly once and set what size you want the file to be.Good luck!
要制作 2MB 文件,您必须寻找
2*1024*1024
并写入0
字节。fput()
无论使用多少次空字符串都没有任何作用。并且字符串是空的,因为字符串以 0 结尾。To make a 2MB file you have to seek to
2*1024*1024
and write0
bytes.fput()
ting empty string will do no good no matter how many time. And the string is empty, because strings a 0-terminated.