Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7513899
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T00:19:43+00:00 2026-05-30T00:19:43+00:00

I am learning C, and I finally solved the following exercise, after couple of

  • 0

I am learning C, and I finally solved the following exercise, after couple of hours of struggle:

“Write a program that merges lines alternately from two files and writes the results
to stdout. If one file has less lines than the other, the remaining lines from the
larger file should simply be copied to stdout.”

However, I am not satisfied with the code. I feel that I over complicated it, and that there’s
a simpler solution.

How do I improve this code?

#include <stdio.h>
#include <stdbool.h>

int main (void)
{
    char file1[11], file2[11];
    FILE *input1, *input2;
    int c, d, i = 0;
    bool end_of_file1 = false, end_of_file2 = false;
    bool file1_newline = false, file2_newline = false;

    printf ("Enter the name of the two files to be merged,\
 separated by space: ");
    scanf ("%10s %10s", file1, file2);

    input1 = fopen (file1, "r");
    input2 = fopen (file2, "r");

    while ( end_of_file1 == false ) {
    if ( file1_newline == false )
        c = getc (input1);

    if ( end_of_file2 == true && end_of_file1 == false
                                         && i == 0 ) {
        putc ('\n', stdout);
        i = 1;
    }

    if ( c == '\n' && end_of_file2 == true )
        i = 0;

    if ( (c == '\n' && file1_newline == false) ||
               (c == EOF && file1_newline == false) ) {
        file1_newline = true;
        putc (' ', stdout);
    }

    if ( file1_newline == false )
        putc (c, stdout);

    if ( file1_newline == true )
        d = getc (input2);
    if ( d == EOF ) {
        end_of_file2 = true;
        if ( c == EOF )
        end_of_file1 = true;
    }
    if ( file1_newline == true && end_of_file2 == false )
        putc (d, stdout);
    if ( (d == '\n' && c != EOF) || end_of_file2 == true )
        file1_newline = false;
    }

    fclose (input1);
    fclose (input2);

    return 0;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T00:19:45+00:00Added an answer on May 30, 2026 at 12:19 am

    Algorithmic issues

    …Let’s look at the question, instead of the code…

    Write a program that merges lines alternately from two files and writes the results to stdout. If one file has fewer lines than the other, the remaining lines from the larger file should simply be copied to stdout.

    Given that you are supposed to be dealing with lines, it seems better to read whole lines. For that, you should use fgets() or perhaps getline() (though the latter is less widely available than the former).

    char line1[4096];
    char line2[4096];
    
    ...
    
    char *l1 = fgets(line1, sizeof(line1), input1);
    char *l2 = fgets(line2, sizeof(line2), input2);
    
    while (l1 != 0 && l2 != 0)
    {
        fputs(line1, stdout);
        fputs(line2, stdout);
        l1 = fgets(line1, sizeof(line1), input1);
        l2 = fgets(line2, sizeof(line2), input2);
    }
    
    /* One file has reached EOF */
    
    if (l1 != 0)
    {
        fputs(line1, stdout);
        while (fgets(line1, sizeof(line1), input1) != 0)
            fputs(line1, stdout);
    }
    if (l2 != 0)
    {
        fputs(line2, stdout);
        while (fgets(line2, sizeof(line2), input2) != 0)
            fputs(line2, stdout);
    }
    

    Nitpicking style

    Personally, I don’t like the way you have spaces around the parentheses on functions – K&R distinguish between operators such as if and for where there’s a space separating the keyword and the expression and function calls where there is no such space. It is a style issue, though, so very subjective.

    These lines of code give ample ammunition:

        bool end_of_file1 = false, end_of_file2 = false;
        bool file1_newline = false, file2_newline = false;
    
        printf ("Enter the name of the two files to be merged,\
     separated by space: ");
        scanf ("%10s %10s", file1, file2);
    
        input1 = fopen (file1, "r");
        input2 = fopen (file2, "r");
    

    Don’t combine multiple declarations on a single line, especially when they’re initialized.

    bool end_of_file1 = false;
    bool end_of_file2 = false;
    bool file1_newline = false;
    bool file2_newline = false;
    

    (But you get plus points for using suffixes 1 and 2 rather than ‘no suffix’ and 2.)

    Don’t split string literals across lines with backslashes. That is a very antique way to do it. Use string concatenation, standard since 1989 (and fix the grammar too). Note that among the many defects of the backslash-newline technique are that it screws up the indentation of the code and it is very vulnerable to editing errors.

    printf("Enter the names of the two files to be merged,"
           " separated by space: ");
    

    Consider a fflush(stdout); before reading. In practice, it isn’t usually necessary, but worth thinking about. Notice that the user can enter the two names on separate lines; that will also work. Limiting the file names to just 10 characters is rather parsimonious, I think; you should probably allow for at least 256 characters. It is good that you specified the size of the strings in format arguments, and did so correctly (at sizeof(array)-1, not sizeof(array)). A more useful design of program would probably take the file names from the command line arguments to the program, rather than prompting the user for the names.

    Always test the result of scanf():

    if (scanf("%10s %10s", file1, file2) != 2)
        ...something went wrong...
    

    Always test the result of fopen():

    if ((input1 = fopen (file1, "r")) == 0)
        ...something went wrong...
    if ((input2 = fopen (file2, "r")) == 0)
        ...something went wrong...
    

    More of your code

    while ( end_of_file1 == false ) {
    if ( file1_newline == false )
        c = getc (input1);
    
    if ( end_of_file2 == true && end_of_file1 == false
                                         && i == 0 ) {
        putc ('\n', stdout);
        i = 1;
    }
    

    Indent the body of your loop by one level (or, on StackOverflow, do not use tabs). You are correct to use int for c (and later d).

    The logic which follows in the loop is … obscure. It is not clear what you are up to. Generally, you want to head off EOF as soon as you can; you wait a while before doing that test. The body of the loop is inscrutable to me – very complex logic (well, it looks complex; I suspect the underlying logic is simple, but since there’s no explanation of what it does, it looks convoluted).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am staring to get used to MVC and after a couple little learning
After a long time learning python I finally managed to make some breakthroughs: I'm
I'm a Delphi, Ruby, and Javascript programmer that is finally learning C - starting
I'm finally getting used to Git and, after the initial steep learning curve, I
I am learning to use mysql for rails apps, and I finally have been
Learning a lot in my few years of programming that the best projects are
Learning xml, Can anyone help me? I have following XML code: **<book lang=en>name of
I'm finally learning regexps and training with ack . I believe this uses Perl
I have finally quit the idea of learning Zend and instead i find CakePHP
I started learning haskell yesterday and I got stuck on a problem. After a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.