tags:

views:

375

answers:

4

I was writting a program that can read a set of numbers file called dog.txt; and also writes to two file separating odd and even. i was able to compile my program however, the output expected is not the same which was supposed to be even numbers in one file called EVEN, odd numbers in file odd.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
  int i;
  int even,odd;
  int num;

  if (argc != 4) {
    printf("Usage: executable in_file  output_file\n");
    exit(0);
  }

  FILE *dog = fopen(argv[1], "r");
  FILE *feven= fopen(argv[2], "w");
  FILE *fodd= fopen (argv[3], "w");
  while (fscanf(dog, "%d", &num) != EOF)
    {
      if (0==i%2){
        i++;
         printf("even= %d\n", num);
         }
      else if(i!=0){
       i++;
       printf("odd= %d\n", num);
      }
    }
  fclose(feven);
  fclose(fodd);
  fclose(dog);

  return 0;
}

output:

even= 1
odd= 2
even= 34
odd= 44
even= 66
odd= 78
even= 94
odd= 21
even= 23
odd= 54
even= 44
odd= 65
even= 78
odd= 68
even= 92
A: 

The code contains no instructions to write into the output files. It only writes to stdout.

wallyk
+4  A: 

You're checking i % 2, not num % 2. I'm not even sure what i does in this example—perhaps you're planning on using it later.

while (fscanf(dog, "%d", &num) != EOF) {
    if (num % 2 == 0) {
        printf("even = %d\n", num);
    }
    else if(num != 0) {
        printf("odd = %d\n", num);
    }
}

I imagine the code to write these numbers to the files will come later, once you've fixed this bug.

Samir Talwar
`i` isn't even initialized properly.
Felix Kling
A: 

The printf function writes to the screen (more correctly, it writes to "standard output", but that is usually the screen). You want to write to a file. You have opened files called feven and fodd. To write to them, you would use the fprintf call, which works like printf except it takes an extra (left-most) argument, which is the FILE* that you want to write to, e.g.

FILE *fmyfile = fopen("myfile.txt", "w");
fprintf(fmyfile, "The magic number is %d!", 3);

Also, your results are incorrect, but that's an unrelated problem.

Tyler McHenry
A: 

In addition to the printf/fprintf problem, in any decent modern compiler, that code should be generating a warning that you're not assigning any initial value to i.

T.J. Crowder
Uninitialized variables are not a compile-time error in C or C++, they just have an arbitrary value (whatever used to be in the memory that they're using) until you do initialize them. A good compiler should warn, though.
Tyler McHenry
@Tyler: Quite true, good point. Heck, the compilers I was using *twenty years ago* included those sorts of lint features. I suppose it should *compile*, just with warnings. But still, ignore warnings at your peril. :-)
T.J. Crowder