File Input/Output
C++:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
ofstream ofile("example.txt");
ofile << "Sample line 1" << endl;
ofile << "Sample line 2" << endl;
ofile.close();
ifstream ifile("example.txt");
string line;
while (getline(ifile, line))
{
cout << line << endl;
}
ifile.close();
return 0;
}
Rust :
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
fn main()
{
let mut ofile = File::create("example.txt").unwrap();
ofile.write_all("Sample line 1\n".as_bytes());
ofile.write_all("Sample line 2\n".as_bytes());
ofile.flush();
let ifile = File::open("example.txt").unwrap();
let ifile = BufReader::new(ifile);
for line in ifile.lines()
{
println!("{}", line.unwrap());
}
}
Similar to the chapter "Console Input/Output", you should ignore warning messages regarding error handling in this program. You can read about how I/O errors are handled in the official tutorials.