c++ - 将多个文件合并为一个

标签 c++ file concatenation

好的,所以我想将多个文件连接成一个。问题是最终文件是空的。我想知道如何在不覆盖的情况下将内容写入文件等等。这是我的代码。 提前致谢!

    void concatenate()
{
    fstream fileToConcatenate, result;
    unsigned numberOfFiles = 0;
    char fileName[MAX], finalFileName[MAX];
    puts("Please tell me how many files you want to concatenate.");
    cin >> numberOfFiles;
    puts("Please tell me data for the resulted file.\n*Hint: full path followed by the file name.\n*E.g:C:\\Users\\IoanaAlexandra\\test.txt");
    cin >> finalFileName;
    result.open(finalFileName, ios::out|ios::ate);
    for (unsigned i = 0; i < numberOfFiles; i++)
        {
            switch (i)
            {
            case 0:puts("Please tell me the file data for the first file to be concatenated.\n*Hint: full path followed by the file name.\n*E.g:C:\\Users\\IoanaAlexandra\\test.txt"); break;
            case 1:puts("Please tell me the file data for the second file."); break;
            case 2:puts("Please tell me the file data for the third file."); break;
            default:cout << "Please tell me the file data for the " << i << "th file."; break;
            }
            cin >> fileName;
            fileToConcatenate.open(fileName, ios::in);
            if (result.is_open())
            {
                if (fileToConcatenate.is_open())
                {
                    result << fileToConcatenate.rdbuf();
                }
                else
                {
                    puts("The file you are trying to concatenate from doesn't exist!Try again!");
                    concatenate();
                }
            }
            else
            {
                puts("The result file could not be created! Try again!");
                concatenate();
            }
        }
    fileToConcatenate.close();
    result.close();
}

最佳答案

从循环外部移除 result.open() 并尝试将您的代码更改为如下内容:

 fileToConcatenate.open(fileName, ios::in);
 if (fileToConcatenate.is_open())
 {
      // open output file
      result.open(finalFileName, ios::out|ios::ate);
      // you should check so the output file really was opened correctly here
      result << fileToConcatenate.rdbuf();
      // close the input file
      fileToConcatenate.close();
      // close output file
      result.close();
 }
 else
 {
      puts("The file you are trying to concatenate from doesn't exist!Try again!");
      concatenate();
 }

如果 fileToConcatenate 在再次调用 concatenate() 之前打开,您还应该关闭它。

关于c++ - 将多个文件合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20601086/

相关文章:

c++ - 尝试打开显示设备句柄以使用 C++ 在 Windows XP 上更改亮度

c++ - 我的动态数组出现问题-线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x0)

Java NIO 在目录中搜索文件

java - 在java中打开文件无法正常工作

java - 当我使用 AES 加密或解密文件时,文件末尾有奇怪的字符,这可能是缓冲区问题还是 AES 问题?

javascript - AngularJS:在 HTML 属性中连接 Angular 变量

python - 将单个数据帧中的多个列合并到单个数据帧中

c++ - 通过指针更改 const 值 C++

C++在不创建新对象的情况下获取类成员的默认值

java - 如何连接int和string