2016-12-12 4 views
0

Я пытаюсь создать программу, которая читает в двух файлах и записывает содержимое из обоих в отдельный файл. Моя программа уже считывает оба файла и отображает их статистику, и мне просто нужно заставить его записать его в новый выходной файл. Я думаю, что я почти там, мне просто нужна небольшая помощь, чтобы закончить его. Вот мой код: (поток выходного файла находится в конце кода)Прочитайте ввод из двух файлов и напишите их в другой файл в C

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <string.h> 

int main() { 

    // declaring variables 
    FILE *fp1; 
    FILE *fp2; 
    FILE *out; 
    int charcount = 0, wordcount = 0, linecount = 1, sentence = 0; 
    int charcount2 = 0, wordcount2 = 0, linecount2 = 1, sentence2 = 0; 
    int character; 
    char first[50]; 
    char second[50]; 
    char output[50]; 
    char ch[200]; 

    // asking the user for the file names and scanning the names they enter as txt files 
    printf(" Enter the first file name: "); 
    scanf("%s", first); 
    strcat(first, ".txt"); 

    printf(" Enter the second file name: "); 
    scanf("%s", second); 
    strcat(second, ".txt"); 

    printf(" Enter the output file name: "); 
    scanf("%s", output); 
    strcat(output, ".txt"); 

    // opening the file stream 
    fp1 = fopen(first, "r"); 

    // if the file cannot be reached, display error 
    if (fp1 == NULL) { 
     printf("File cannot be opened: %s\n", first); 
     return 0; 
    } 

    // reading and printing the file into the program 
    printf("\n---FIRST FILE---\n"); 
    while (!feof(fp1)) { 
     fgets(ch, 200, fp1); 
     fputs(ch, stdout); 
    } 

    // counting the characters, words and lines until the program is finished 
    fseek(fp1, 0, SEEK_SET); // sends the file pointer back to the start of the file 
    while ((character = fgetc(fp1)) != EOF) { 
     if (character == EOF) 
      break; 
     { 
      charcount++; 
     } 
     if (character == ' ' || character == '.') 
     { 
      wordcount++; 
     } 
     if (character == '\n') 
     { 
      linecount++; 
     } 
     if (character == '.') 
     { 
      sentence++; 
     } 
    } 

    // closing the stream 
    fclose(fp1); 

    // printing the number of characters, words and lines 
    printf("\n Characters: %d \n Words: %d\n Lines: %d\n Sentences: %d\n\n\n", charcount, wordcount, linecount, sentence); 

    //---------SECOND FILE----------// 

    // opening the stream 
    fp2 = fopen(second, "r"); 

    // reading and printing the file into the program 
    printf("\n---SECOND FILE---\n"); 
    while (!feof(fp2)) { 
     fgets(ch, 200, fp2); 
     fputs(ch, stdout); 
    } 

    // counting the characters, words and lines until the program is finished 
    fseek(fp2, 0, SEEK_SET); // sends the file pointer back to the start of the file 
    while ((character = getc(fp2)) != EOF) { 
     if (character == EOF) 
      break; 
     { 
      charcount2++; 
     } 
     if (character == ' ' || character == '.') 
     { 
      wordcount2++; 
     } 
     if (character == '\n') 
     { 
      linecount2++; 
     } 
     if (character == '.') 
     { 
      sentence2++; 
     } 
    } 

    // closing the stream 
    fclose(fp2); 

    // printing the number of characters, words and lines 
    printf("\n Characters: %d \n Words: %d\n Lines: %d\n Sentences: %d\n\n\n", charcount2, wordcount2, linecount2, sentence2); 

    out = fopen(output, "w"); 

    fgets(ch, 0, fp1); 
    fgets(ch, 0, fp2); 

    fclose(out); 



} 

ответ

1

Если вы можете распечатать его на терминал, то вы можете распечатать его в файл! printf("") - это просто особый способ сказать fprintf(stdout, ""). Итак, откройте новый указатель файла к файлу, который вы хотите распечатать, и установите его как цель вызова fprintf(). Например,

fp3 = fopen(<output file name>, "w") 
fprintf(fp3,<string you want to write>) 
fclose(fp3) 

EDIT: Я вижу, что вы использовали fputs для печати. Это тот же принцип, что и выше. Вместо того, чтобы прокладывать конвейер в stdout, откройте файл для записи и записи там.

+0

Хорошо, теперь я добавил это, и ему удаётся написать последнее предложение второго файла и ничего более ... сделать прогресс, хотя! вот что у меня есть: out = fopen (output, "w"); \t \t fprintf (out, ch); \t fclose (out); 'Я предполагаю, что мне нужно добавить указатель где-нибудь? – rozak

+0

@rozak Не открывать и закрывать файл. Откройте его один раз в начале, закройте его в конце и сделайте все записи в середине. – Barmar

+0

@Barmar, где именно я должен помещать 'fprintf'? как раз перед закрытием файловых потоков fp1 и fp2? Я не совсем понимаю, что вы подразумеваете под «посередине». – rozak