We've covered a lot of ground with C so far. The big problem here is that we've not yet covered one of the most common tasks on a UNIX system. We have not covered files. So, let's look at files. For file I/O in C, you need a file pointer. We declare a file pointer like so:
FILE *thisisafilepointer;
There are then a series of common file commands: fopen, fclose, fprintf, fscanf, fgetc, fputc, fread, fwrite, feof. So, let's open a file:
FILE *thisisafilepointer;
thisisafilepointer=fopen("/home/bradford/ctut.txt","r");
This opens ctut.txt for reading. That's what the "r" is. There are many other modes with which we can open a file.
r open a file for reading
w open a file for writing
a open a file for appending
r+ open for reading/writing, start a beginning
w+ open for reading/writing, overwriting file
a+ open for reading/writing, append
If opening a file fails, fopen will return a NULL pointer. Whatever is opened needs to be closed, so:
fclose(thisisafilepointer);
So, let's move on to actually reading and writing data.
FILE *fp;
fp=fopen("/home/bradford/c13.md", "w");
fprintf(fp, "###An Introduction to C (Part XIII)\n");
fclose(fp);
So, there, we just wrote to a file. For our next trick, let's read from a file and print to stdout.
#include <stdio.h>
#include <stdlib.h>
main() {
FILE* fp;
int i;
fp = fopen("/home/bradford/c13.md", "r");
while ((i = fgetc(fp)) != EOF) {
fputc(i, stdout);
} // end while
fclose(fp);
} // end main
See? That was easy. So, let say that you have a file that contains a list of IPs and how many hits those IPs have on you server, you could scan those likes this:
while (!feof(fp)) {
if (fscanf(fp, "%s %d", ip, hits) != 2) {
break;
} // end if
fprintf(stdout, "%s %d", ip, hits);
} // end while
It is important to note that you always have stdin, stdout, and stderr available as file handles.