2013-12-15 5 views
1

Итак, я хочу объединить несколько файлов в один. Проблема в том, что окончательный файл пуст. Я хочу знать, как я могу писать материал в файл без перезаписи и так далее. Вот мой код. Спасибо заранее!Объединение нескольких файлов в один

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(); 
} 
+0

введите код здесь? – ldrumm

+0

Извините, я не совсем знал, как это сделать xd. – user3105558

+0

О, я вижу. Вы редактировали. Не стоит беспокоиться – ldrumm

ответ

3

Снимите 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() снова.

Смежные вопросы