0

Ok so i am writing a C program. The program is simple enough, when i run the program i give it a few parameter Ex ./proj1 cat hat bat, so then it asks me to input a list of words the program gives counts of how many times "cat", "hat", and "bat" occurs in that list. I have the program working great.

Example 
./pro1 cat hat bat
cat
.

(the program recognized a "." as the end of input)

Result:
cat:1
hat:0
bat:0

ok so my program runs perfectly in every test case i can think of, but I have to pass a series of tests that my professor has mas made. here is the code of that test.

char *args[] = {"./main", "cat", "hat","bat",NULL};
char *result[] = {"Looking for 3 words\n",
  "Result:\n",
  "cat:1\n",
  "hat:0\n",
  "bat:0\n"};
FILE *out;
FILE *test;
test=fopen("test","w");
int i;
char *buffer=malloc(100*sizeof(char));

out = fopen("smp0.in", "w");
fprintf(out, "cat\n");
fprintf(out, ".\n");
fclose(out);

freopen("smp0.in", "r", stdin);


freopen("smp0.out", "w", stdout);

quit_if(main(4, args) != EXIT_SUCCESS);

fclose(stdin);
fclose(stdout);

out = fopen("smp0.out", "r");


for (i = 0; i < 5; i++) {
    quit_if(fgets(buffer, 100, out) == NULL);
    quit_if(strcmp(buffer, result[i]));
}


fclose(out);
return EXIT_SUCCESS;
 }

ok so sending the quit_if() is the method that makes it fail. specifically

   quit_if(strcmp(buffer, result[i]));

My output when i run the program is exactly as described. But between freopen() diverting stdout to a file and then reading it back it has changed somehow.

  Result:
  cat:1
  hat:0
  batÿ:0

is what the output becomes, but it is not like that before the file write and read, and for some reason it is always that weird y character.

any advice would be greatly appreciated. Sorry for not posting more code but it's because it is a school project. I am confident that it is the test that is wrong in some way and not my code, fixing the test is part of the project as well.

mingle
  • 580
  • 2
  • 6
  • 24
  • Use a hex file editor and see what hex byte value makes the wierd y character. That might give you a clue as to the issue. – Lee Meador Feb 01 '13 at 22:29
  • possible duplicate of [Why do I get a 'ÿ' char after every include that is extracted by my parser? - C](http://stackoverflow.com/questions/4906341/why-do-i-get-a-y-char-after-every-include-that-is-extracted-by-my-parser-c) – ecatmur Feb 01 '13 at 22:31

1 Answers1

2

See this answer to a previous question:

https://stackoverflow.com/a/4906442/2009431

It seems that when the dot is read back in from your stdin file, it has an EOF token appended (makes sense) that would not normally be part of the user's input. Then, somehow (not sure since we can't see your code) your main() function is appending that EOF character onto "bat" in the form of that weird y character (see linked answer for details on why).

If I'm right, maybe this could be considered a bug in the test?

Community
  • 1
  • 1
mdunsmuir
  • 492
  • 2
  • 8