Thursday, September 13, 2012

Re: The simplest Assembler

I had to refresh my C programming skills. I used these codes copied
outright, and some modified from the internet sources. Sorry, I cannot
locate them partly because of the lack of copyright notices within the
codes. These are simple testing codes anyway.
Copied to my blog on programming. Hopefully I will not forget it next
time.

I thought I don't need it because I am supposed to be able to remember
it easy. I was wrong. You need it to test your C installation.
helloworld.c
#include <stdio.h>
main()
{
printf("hello, world");
}

Reading manuals just boring and time consuming. Testing is better.

/* Testing main() */
#include <stdio.h>
int main(int argc, const char* argv[])
{
int i;
printf("argc=%d\n",argc);
for(i=0; i<argc; i++){
printf("i=%d, argv=%s\n",i,argv[i]); };
}

The original was from a C tutorial site, but I modified it so that I
can use arguments to put the file names, instead of embedding the
filenames in the source codes.
You can have stdin(your text screen) for input, or stdout(for screen
output). These work in console, or text screen of Windows.


// copy file from first argument to second argument
#include <stdio.h>
int main(int argc, const char* argv[]) {
FILE *fin;
FILE *fout;
int c;
fin =fopen(argv[1], "r"); fout =fopen(argv[2],"w");

if (fin != NULL) {
if (fout != NULL) {
c = fgetc (fin);
while (c >= 0) {
fputc (c, fout);
c = fgetc (fin);
}
fclose (fout);
} else {
fprintf (stderr, "Cannot write to output file");
}
fclose (fin);
} else {
fprintf (stderr, "Cannot read from input file");
}
}

With all these test files, I was able to improve Bison examples so
that it can read from files instead of just stdin, as interpreters. It
took a week of my time.
Gnu does not make this source available. In order to save people's
time, I shall upload it in this thread, and copied to my
microprocessor development blog.

No comments:

Post a Comment