1

I currently have to add, and make it so it goes in an order like this

content of file 1
content of file 2
content of file 1
content of file 2

its currently only writing the contents of one text file into the output file, i cant see where i'm going wrong so any help is greatly appreciated.

**** Edit, hi done some digging and found that this exact question has already been answered, didnt want to get in trouble with mods and couldnt delete, thanks all

Adam
  • 21
  • 5
  • Please post the [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that shows the problem. What you have shown is incomplete and begs questions that should not need to be asked. – Weather Vane Dec 12 '16 at 20:17
  • What happened to the `OpenFile` - `OpenFile2` assignments? – Eugene Sh. Dec 12 '16 at 20:17
  • @WeatherVane I afraid the full code won't answer this question.. or will answer "they don't exist". – Eugene Sh. Dec 12 '16 at 20:19
  • @EugeneSh. perhaps but is still better. Maybe if the MCVE is posted we won't see `file3` opened twice. – Weather Vane Dec 12 '16 at 20:21
  • @EugeneSh. i only provided the part of my code that merges the two text files into the output file – Adam Dec 12 '16 at 20:21
  • I see in this part that you `fopen` 3 files discarding the handles they return. It won't do any good to anyone. – Eugene Sh. Dec 12 '16 at 20:22
  • It is still unclear whether you want to alternate the bytes from each file, or alternate the lines of text. Please show a simple example of file 1 and file 2 and what you expect file 3 to contain. Please make the source files unequal in length, to show what must be done with any remainder. – Weather Vane Dec 12 '16 at 20:27
  • @WeatherVane okay so i need the files to be unequal, or equal to in length. If it is unequal then the longer file will carry on beneath the shorter file in the merged output file. The two files contain lines of text in them, and i need to combine these into one output file in an order that goes file 1, then the next line file 2, then the next line file 1 again etc until it reaches the end of either file, and if one is longer it just carries on – Adam Dec 12 '16 at 20:31
  • Possible duplicate of [How to append text to a text file in C++?](http://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c) – Adam Dec 12 '16 at 21:34
  • `str[word][position] = (char)("\n");` should be `str[word][position] = '\0';` – chqrlie Dec 12 '16 at 23:41
  • `isupper(read_char) || islower(read_char)` should be `isalpha((unsigned char)read_char)` – chqrlie Dec 12 '16 at 23:42

3 Answers3

1

You are not storing the stream pointers returned by fopen() and you are not interleaving lines from file1 and file2. Here is how to fix these issues:

    ...
    // file 3
    printf("Please enter the name of the output file : ");
    if (scanf("%s", file3) != 1) {
        printf("input error\n");
        exit(1);
    }    
    FILE *OpenFile = fopen(file1, "r");
    FILE *OpenFile2 = fopen(file2, "r");
    FILE *OpenFile3 = fopen(file3, "w");

    if (OpenFile == NULL || OpenFile2 == NULL || OpenFile3 == NULL) {
        perror("Error opening files");
        printf("Press any key to exit!\n");
        exit(1);
    }

    int c1 = 0, c2 = 0;
    while (c1 != EOF || c2 != EOF) {
        if (c1 != EOF) {
            /* copy a line from file1 */
            while ((c1 = fgetc(OpenFile)) != EOF && c1 != '\n') {
                fputc(c1, OpenFile3);
            }
            fputc('\n', OpenFile3);
        }
        if (c2 != EOF) {
            /* copy a line from file2 */
            while ((c2 = fgetc(OpenFile)) != EOF && c2 != '\n') {
                fputc(c2, OpenFile3);
            }
            fputc('\n', OpenFile3);
        }
    }

    printf("The two files were successfully merged into %s\n", file3);

    fclose(OpenFile);
    fclose(OpenFile2);
    fclose(OpenFile3);
    return 0;
chqrlie
  • 98,886
  • 10
  • 89
  • 149
  • this works perfectly, it doesn't seem to append it still in the correct order line per line – Adam Dec 12 '16 at 20:50
  • @Adam: the specification was incomplete, I shall update the code. – chqrlie Dec 12 '16 at 23:29
  • its fine now i have a working code so no need to worry about it! I just need to find a way to reverse it now aha, thanks for the help anyway – Adam Dec 12 '16 at 23:32
0

You need to alternate your fgetc calls, not do each loop all at once.

int file2_ok = 1, file_ok = 1;
while (file_ok && file2_ok) {
    if (file2_ok) {
        c = fgetc(OpenFile2);
        if (c == EOF) {
            file2_ok = 0;
        } else {
            fputc(c, OpenFile3);
        }
    }
    if (file_ok) {
        c = fgetc(OpenFile);
        if (c == EOF) {
            file_ok = 0;
        } else {
            fputc(c, OpenFile3);
        }
    }
}

This assumes that the two files have the same number of characters. The question doesn't indicate how they should be merged if they don't match up evenly.

Barmar
  • 596,455
  • 48
  • 393
  • 495
  • if one of the merging files is shorter than the other, it is supposed to just carry on and add it below to the merged file – Adam Dec 12 '16 at 20:27
  • @Adam that's your call. – Weather Vane Dec 12 '16 at 20:31
  • I've added code that keeps reading until both files have been finished. Instead of using `break` to exit the loop, it sets a variable. – Barmar Dec 12 '16 at 20:33
  • @Barmar this now prints them, but not how the text originally was and in a weird order, would it be easier to post my whole code so you can try and see yourself, or output and original files? – Adam Dec 12 '16 at 20:38
  • Not sure what you mean. This alternated character by character, like the code in your question. Did you want it line by line instead of character by character? – Barmar Dec 12 '16 at 20:43
  • If you want lines, use `fgets()` instead of `fgetc()`. – Barmar Dec 12 '16 at 20:44
  • @Barmar it seems to throw up an error when i change it from fgetc() to fgets() C is a char and it seems to die when i change it to fgets – Adam Dec 12 '16 at 20:47
  • You can't just replace `fgetc` with `fgets`. You need to change the variable type, you need to call the function with the proper arguments, you need to print the result differently. This is all basic stuff, you should read your C textbook to see the proper way to read lines from a file. – Barmar Dec 12 '16 at 20:51
  • @Barmar this is for a assignment so i dont really know what im doing, i also didnt get given a textbook to read from just a few lecture notes – Adam Dec 12 '16 at 20:53
  • The documentation of `fgets` is available online, google it. – Barmar Dec 12 '16 at 20:54
  • @Barmar i tried googling it but couldn't find how to go about swapping the two, thanks for all your help anyway! – Adam Dec 12 '16 at 21:04
0

This merges alternates lines of two text files. The input files and the output file are program arguments.

#define _CRT_SECURE_NO_WARNINGS

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

int main(int argc, char *argv[]){
    FILE *OpenFile;
    FILE *OpenFile2;
    FILE *OpenFile3;
    char buffer[10000];                     // hopeful
    int finished = 0;

    if(argc < 4) {
        exit(1);
    }
    OpenFile  = fopen(argv[1], "rt");       // "t" is for MSVC
    OpenFile2 = fopen(argv[2], "rt");
    OpenFile3 = fopen(argv[3], "wt");
    if(OpenFile == NULL || OpenFile2 == NULL || OpenFile3 == NULL) {
        exit(1);
    }

    while(finished != 3) {
        if(fgets(buffer, sizeof buffer, OpenFile) != NULL) {
            fputs(buffer, OpenFile3);
        }
        else {
            finished |= 1;
        }

        if(fgets(buffer, sizeof buffer, OpenFile2) != NULL) {
            fputs(buffer, OpenFile3);
        }
        else {
            finished |= 2;
        }
    }

    fclose(OpenFile);
    fclose(OpenFile2);
    fclose(OpenFile3);
    return 0;
}

Input file 1:

File 1 line 1
File 1 line 2
File 1 line 3
File 1 line 4

Input file 2:

File 2 line 1
File 2 line 2

Output file 3:

File 1 line 1
File 2 line 1
File 1 line 2
File 2 line 2
File 1 line 3
File 1 line 4

The solution could be more efficient if it took notice of the finished status instead of calling fgets after any file has reached EOF.

Weather Vane
  • 31,226
  • 6
  • 28
  • 47
  • oh, this was already part of a programme so i don't need to declare the file stream etc, however using this code didn't seem to work for me? It just threw up loads of errors? Would it be easier to include all of my code? – Adam Dec 12 '16 at 20:57
  • What errors did it throw up? Give an example please. Include all of your code? That is what I asked in the very first comment. – Weather Vane Dec 12 '16 at 20:58
  • For simplicity the file names are supposed to be entered here as program arguments. Please try this, it is not supposed to be "part of your code where you already declared...." It is a complete program which is supposed to show you how to do it. – Weather Vane Dec 12 '16 at 21:02
  • i added all of the code to my program into the original post – Adam Dec 12 '16 at 21:07
  • So I added the warning suppression. What are the "loads of errors"? – Weather Vane Dec 12 '16 at 21:08
  • i cant remember off by heart, but there was at least 15 i believe some expression errors, incompatible types etc. I feel like why it isn't working is because you wrote it as a separate programme, when it is meant to be apart of my program that i already have written – Adam Dec 12 '16 at 21:13
  • Come now, I have spent a half hour providing code that generates no MSVC compiler warnings or errors, and produces the output that I have shown. Please try my code, exactly like I wrote it. – Weather Vane Dec 12 '16 at 21:15
  • i just cant seem to integrate your code with my code. I need to integrate it under the comment "//File 3" and when i try it throws errors – Adam Dec 12 '16 at 21:18
  • Do not try to integrate it. Run it first, and then adapt your program accordingly. You only just took earlier advice to show your whole program, and I am not going to rewrite it to suit what you only just supplied. This is "example code". Yours, angrily. – Weather Vane Dec 12 '16 at 21:20
  • The main difference between your progam and mine is the way we get the file names. Although this is a complete solution, I did not want to write a "pat" answer that you could just copy/paste, as this smells like homework. – Weather Vane Dec 12 '16 at 21:37
  • after reading your comment i realised i was being stupid and its now working so thank you very much, and im sorry. Im now worried ill get done for plagiarism though aha, thanks for the help! – Adam Dec 12 '16 at 21:39