0

我正在尝试将一个大数据文件拆分为几个小文本文件。以下代码每次打开和关闭一个新文件,这是不可行的。有没有其他方法可以做到这一点?

ifstream infile(file_name);

if(infile)
{
    char val;
    while(!infile.eof())
    {
        ofstream ofile (ofile_name);
        infile >> val;
        ofile << val;
        if( infile.peek() == '\n' )// last entry on the line has been read
        {
            row_counter++;
            if (row_counter == win_size)
                // generate new ofile_name
        }
        ofile.close();
    }
    infile.close();
}
4

1 回答 1

1

如果不打开和关闭输出文件,您将无法创建多个输出文件。

原因是,每个输出文件都应该有一个唯一的名称。您必须为输出文件生成有用的名称。文件(内容)和文件名之间的连接将在 open 调用(或 ofstream 构造函数)中完成。

编辑

为了避免每个字符的打开和关闭,您需要状态变量。在您的示例row_counter中可用于它。您需要以下步骤:

  • 在您的 while(!infile.eof()) 循环之前打开初始文件
  • 关闭您的文件,生成下一个名称并打开您写的新位置// generate new ofile_name
  • 最后在循环后关闭你的文件。

这可以通过这种方式完成:

if(infile)
{
    char val;

    row_counter = 0;
    ofstream ofile (ofile_name);

    while(!infile.eof())
    {
        infile >> val;
        ofile << val;

        if( infile.peek() == '\n' )// last entry on the line has been read 
        { 
            row_counter++; 

            if (row_counter == win_size) 
            {   
               row_counter = 0;
               ofile.close();
               // generate new ofile_name 
               ofile.open(ofile_name); // you might change the nMode parameter if necessary
            }
        } 
    } 

    ofile.close(); 
    infile.close(); 
} 
于 2012-06-18T10:51:48.110 回答