A string in C is only an array of characters with the "null"
character '\0' (backslash zero, not to be confused
with the null pointer). What does the following output?
#include <string.h>
char hello[] = "Hello, world\n"; /* null is implicit */
char world[14] = {'H', 'e', 'l', 'l', 'o', ',', ' ',
'w', 'o', 'r', 'l', 'd', '\n', '\0'};
char mychars[20]; /* NOT a string yet, just an array of char */
printf("%s", hello);
printf("%s", world);
/* strcmp: return value is
< 0 : if first < second
0 : if first == second
> 0 : if first > second. */
printf("%d\n", strcmp(hello, world));
hello[1] = 'u';
printf("%d\n", strcmp(hello, world));
hello[1] = 'a';
printf("%d\n", strcmp(hello, world));
/* strcpy: note that the SECOND argument is the source.
Think, "I strcpy TO mystr FROM world." */
strcpy(mychars, world);
printf("%s", mychars);
/* strlen: note that the length DOES NOT include the null
character or anything after it. */
printf("%d\n", strlen(world));
printf("%d\n", strlen(mychars));
Files are represented by a struct that typically contains some hairy operating system information, like a pointer to a list of disk blocks, a pointer to buffer memory, etc.
Fortunately, we don't have to worry about it, because all file functions operate on pointers to FILE structs. This is an example of a "handle" or "magic cookie", which is frequently used to provide modular programming interfaces to C libraries.
#include <stdio.h>
FILE *infile, *outfile;
char c;
infile = fopen("in.txt", "r"); /* Open filehandles */
outfile = fopen("out.txt", "w");
if (infile != NULL && outfile != NULL) { /* If open successful, */
while ( fscanf(infile, "%c", &c) != EOF ) /* read until EOF, */
fprintf(outfile, "%c", c); /* writing the character */
}
fclose(infile);
fclose(outfile);
Recall the NAW server example we did, so long ago. Let's say we wanted to make the GET print a file's contents, like a real web server, instead of hardcoded strings. How would we do it?
void HandleGet(void) {
/* declarations */
/* Get page name from user; need string input. */
printf("Enter page name: ");
/* Print selected page: need to open a file, and print its
contents. */
}
So far, you have learned mostly the mechanics of programming: control structures and primitive data types. However, the purpose of programming is to solve actual problems with these building blocks.
To solve actual problems, we use algorithms. Sorting is one problem frequently taught in introductory courses because it is a simple proble, with (mostly) simple algorithms.
You did SelectSort in lecture. Here are some other sorting algorithms, in order of increasing speed:
If we liken programming to literature, right now you're at the stage where you can read "See Spot run. Good Spot!" This is fun for a while but gets boring eventually. Fortunately, things only get much more interesting from here on out.