// Readorwritetextline. cpp: defines the entry point of the console application.
//
# Include "stdafx. H"
# Include <iostream>
# Include <fstream>
# Include <string>
Using namespace STD;
// Empty output line
Void outputanemptyline ()
{
Cout <"\ n ";
}
// Read method: Read by word, separated by Spaces
// Read data from the file, word by word
// When used in this manner, we'll get space-delimited bits of text from the file
// But all of the whitespace that separated words (including newlines) was lost.
Void readdatafromfilewbw ()
{
Ifstream fin ("C: \ data.txt ");
String S;
While (Fin> S)
{
Cout <"read from file:" <S <Endl;
}
}
// Read method: Read rows by row, read rows into character arrays, and use carriage return to line feed to distinguish between rows
// If we were interested in preserving whitespace,
// We cocould read the file in line-by-line using the I/O Getline () function.
Void readdatafromfilelblintochararray ()
{
Ifstream fin ("C: \ data.txt ");
Const int line_length = 100;
Char STR [line_length];
While (Fin. Getline (STR, line_length ))
{
Cout <"read from file:" <STR <Endl;
}
}
// Read method: Read rows by line, read rows into strings, and use carriage return to line feed to distinguish between rows
// If you want to avoid reading into character arrays,
// You can use the C ++ string Getline () function to read lines into strings
Void readdatafromfilelblintostring ()
{
Ifstream fin ("C: \ data.txt ");
String S;
While (Getline (FIN, S ))
{
Cout <"read from file:" <S <Endl;
}
}
// Read method with Error Detection
// Simply evaluating an I/O object in a Boolean context will return false
// If any errors have occurred
Void readdatawitherrchecking ()
{
String filename = "C :\\ datafunny.txt ";
Ifstream fin (filename. c_str ());
If (! Fin)
{
Cout <"error opening" <FILENAME <"for input" <Endl;
// Exit (-1 );
}
}
Int _ tmain (INT argc, _ tchar * argv [])
{
Readdatafromfilewbw (); // read strings one by one
Outputanemptyline (); // empty output line
Readdatafromfilelblintochararray (); // read the character array one by one
Outputanemptyline (); // empty output line
Readdatafromfilelblintostring (); // read strings one by one
Outputanemptyline (); // empty output line
Readdatawitherrchecking (); // read with detection
Ofstream o_file;
// Write
O_file.open ("C: \ data.txt", IOS: Out | IOs: app | IOs: Binary );
For (INT I = 1; I <= 10; I ++)
{
O_file <"no." <I <"line \ n"; // write the content to a text file.
}
O_file.close ();
System ("pause ");
}
/*
# Include <iostream>;
# Include <string>;
Char filename [] = "C: \ test.txt ";
Ifstream in (filename );
String line;
While (Getline (line, in )){
Cout <line <Endl;
}
*/