如何创建一个特定大小的文本文件c ++ [英] How to create a text file of specific size c++

查看:217
本文介绍了如何创建一个特定大小的文本文件c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个特定大小的文本文件,用户输入大小。所有我需要知道的是如何使文件更快。当前创建10mb文件大约需要15秒。我必须减少到最多5秒。我该怎么办?目前这是我创建我的文件

I have to create a text file of specific size, user enters the size. All I need to know is how to make a file faster. Currently creating a 10mb file takes about 15 seconds. I have to decrease this to max 5 seconds. How can I do that? Currently this is how I am making my file

void create_file()
{
    int size;
    cout<<"Enter size of File in MB's : ";
    cin>>file_size;
    size = 1024*1024*file_size;   // 1MB = 1024 * 1024 bytes
    ofstream pFILE("my_file.txt", ios::out);

    for(int i=0; i<size; i++)   //outputting spces to create file
        pFILE<<' ';

    pFILE.close();
}

更新,这是我现在使用,

Update, this is what I am using now, but I get garbage value written to the file as well,

void f_c()
{
int i, size;
cin>>size;
FILE * new_file = fopen("FILE TEST.txt", "w");
char buffer[1024];
memset(buffer,' ', 1024);
for(i = 0; i<1024 * size; i++)
    fputs(buffer, new_file);
getchar();
 }


推荐答案

一次。相反,您可以使用 new 分配更大的内存块,然后立即写入更大的块以加快进程。您可以在分配的内存上使用 memset ,以防止在内存中有字节字符。但也看看关于重复问题的评论,如果文件最初不需要具体的内容,还有更快的方法。

You are filling it one character at a time. Instead, you could allocate a larger chunk of memory using new and then write larger chunks at once to speed up the process. You could use memset on the allocated memory to prevent having bytes characters in the memory. But also look at the comment about the duplicate question, there are even faster methods if the file needn't have specific content initially.

这篇关于如何创建一个特定大小的文本文件c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆