CompOrg HW1 FAQ

Homework #1 FAQ

Question: When I run my program on the sample files under DOS (or cygwin on a windows machine) it stops after just a few lines. What's up with that?
Answer:

Chances are your code works fine under Unix. To fix the problem (so it works on a PC), open the file for reading in binary mode, like this:

f = fopen(filename,"rb");

Note the mode given to fopen is "rb" and not simply "r". This tells fopen to treat the file as binary data, not as a sequence of text characters (which might have a DOS end-of-file marker in the middle). This distinction has been abandoned on unix versions of fopen for quite some while... (this was a surprise to me!)


Question: Where can I get gcc for Windows?
Answer: You can find the compiler and a nice "Unix" environment (shell and utilities) that runs under Windows at: sources.redhat.com/cygwin

Question: My code works fine except when printing the 2 hex digit value of a byte whose value is greater than 127. What's the problem?
Answer:

The compiler assumes your single byte values are "signed". If you try to print a signed char as 2 hex digits and the value (when interpreted as a signed char) is negative - printf will insist on printing more than 2 hex digits.

Make sure you tell the compiler that the thing you want to print is "unsigned", so something like this:

  printf("%02x ",(unsigned char) x);
  

This will all make more sense once we cover the representation of integer values (signed and unsigned)...


Question: I get an extra line of 0s on the sample file - why?
Answer:

This probably means that you are not looking at the return value from fread(), and assuming that you always get 8 bytes. The problem is that for file sizes that are a multiple of 8 bytes, when the last 8 bytes are read in the EOF condition is still false - it won't be true until you try to read beyond the last byte in the file. fread() will tell you how many bytes (actually how many elements) were read - you need to pay attention to this number as well as to feof.

The above discussion assumes that you are using fread to read 8 bytes at a time...


Question: Should our program write to a file or to the screen?
Answer:

Your program should use printf to generate output that is sent to STDOUT. If you simply run the program without doing anything special - STDOUT is sent to the screen. If you "redirect" the output of your program you can have STDOUT sent to a file. Here is an example that sends the output of the program to a file named "foo". The '>' tells the shell to send STDOUT to the named file.

> hw1 sample1 > foo