Quite simply, I/O is a shortening of Input/Output. You should see this initialism used a fair bit when it comes to computers.
The next thing to realise about C and C++ I/O methods is that they all write to or read from a file. The main thing to realise here is that the keyboard is a special file, STDIN. The screen is another special file, STDOUT. Finally, there is also a special error file, STDERR. By default, this is routed to the screen, but you can change all of this behaviour.
In C, the file that you're reading to or writing from is of type "FILE" - just like an integer is of type "int".
Furthermore, as explained in our below post about pointers, we like to use FILE* instead of FILE. Life is just so much simpler this way.
To declare a FILE*, it's as simple as this:
FILE *in;
FILE *out;
Of course, I've used the names "in" and "out" because these, obviously, will represent the location in memory of our input and output files (again, this memory thing is because of our pointers. Seriously, re-read that other post).
However, there is a problem with this. If you understood/read anything about variables, you'd understand that just randomly declaring a pointer does nothing useful. We want *in to be talking about a file. Same goes for *out.
Thus, we can do this:
in = fopen("inputfile", "r");
out = fopen("outputfile", "w");
Of course, common sense tells us that "r" means read and "w" means write. Common sense is right.
This takes the file "inputfile" (it would usually be a .txt, but it can be anything, really. If the file was called "yourMum.txt", change the word "inputfile" to "yourMum.txt") and opens it in reading mode. Make sure the file exists; if it doesn't the universe explodes.
It then creates the file "outputfile", and makes it writeable. If "outputfile" already exists, it'll delete it first.
Now, we can print!
Unlike printing/reading to/from stdout/stdin, we can't use printf() or scanf(). These are specially-designed functions just for printing to/reading from the screen/keyboard. Instead, we need fprintf() or fscanf() - i.e. the printing/reading functions for files.
They both work with only a small change.
First inside the brackets is the file you're printing to. Then, you just copy-paste what you would've put inside printf().
For instance,
fprintf(out, "%d\n", 9000+1);
fscanf(in, "%d", &n);
Or, for a more complete example:
#include <cstdio>
int main(){
FILE* in = fopen("inputfile", "r");
FILE* out = fopen("outputfile", "w");
fscanf (in, "%c %d\n", &letter, &number); // read in data
fprintf (out, "%c %d\n", letter, number); // write data
return 0;
}
That's it for now. Any questions, either jump on #dlspc via http://webchat.freenode.net/ or ask us on Thursday.
PS If you felt like you weren't getting enough attention last week, don't worry. We'll all be in the one pod this week.
No comments:
Post a Comment