FileIO

=File IO=

Every programming language has some kind of output and input to a file that is very similar to IO to the console. Most programming languages have a format in common for input and output that has variable formatted into the line e.g. printf("%s is %d years old", name, age); The %s is replaced with name and the %d is replaced with age. 's' referring to a string and 'd' to an integer. These single character abbreviations is the important part in the function.


 * Character || data type || example output ||
 * %d || int, long, short, byte, char || 55 ||
 * %c || char || a ||
 * %s || *char, string || sample ||
 * %f || float, double || 5.55 ||
 * %e || float, double || 4.55e+5 ||
 * %p || *ptr || B800:0000 ||
 * %% || prints a percent || % ||

You can also set precision by adding a the max digits on the left side of the decimal, then a decimal followed by the max digits on the right. e.g: %4.2 for 3.141548 will print 3.14

Here are a few file IO methods I know off the top of my head.

In Java
Anything involving an external file or directory in java uses the File class.

Output
To write to a file in java you need to use a buffer. I went with FileWriter.

code format="java" import java.io.File; import java.io.BufferedWriter; import java.io.FileWriter;

public class Main{ public static void main(String[] args) throws Exception{ //these classes throw exceptions File myFile = new File("output.txt"); //this will read from the projects root directory BufferedWriter out = new BufferedWriter(new FileWriter(myFile)); out.write("Hello, file output."); out.close; } } code

Input
Just like for console input, this is where Java has options. You can go with streams or buffers, or maybe something I haven't heard of, either way you get the same result. I like to use the Scanner class it gets the job done, but some say its too slow, if this is you then go with a buffer.

code format="java" import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.util.Scanner;

public class Main{ public static void main(String[] args) throws Exception{ //don't forget these classes throw exceptions File myFile = new File("input.txt"); //scanner input Scanner in = new Scanner(myFile); int x = in.nextInt; in.close;

//buffered input BufferedReader bfIn = new BufferedReader(new FileReader(myFile)); String line = bfIn.readLine; bfIn.close; } } code

In C++
The primary method of file IO in C++ is through libraries. I know of two; stdio.h and ifstream.

Output
code format="cpp"
 * 1) include

int main{ File *out; out = fopen("output.txt", "w"); //'w' for write only

char[] key = "World!";

fprintf(out, "Hello, %s\n", key); //like printf but with the file to print to in first arg fclose(out); //don't forget to close the file

return 0; } code

Input
code format="cpp"
 * 1) include

int main{ File *in; in = fopen("input.txt", "r"); //'r' for read only

int x;   fscanf(in, "%d", &x); //read printf("I read %d.\n", x);

return 0; } code