-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path55_Writing_to_Files.cpp
More file actions
66 lines (54 loc) · 3.13 KB
/
55_Writing_to_Files.cpp
File metadata and controls
66 lines (54 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <fstream>
#include <iostream>
using namespace std;
int main(){
ofstream myFile("sample.txt"); //if the file exists, it's contents will be deleted.
if(myFile.fail()) {
cout << "Error: Unable to open!" << endl;
return 0;
}
//We can write to a txt file by using the insertion operator "<<" with the ofstream object
myFile << "AAAAA" << endl;
myFile << "BBBBB" << endl;
myFile << "CCCCC" << endl;
myFile.close();
//To modify (append a text) a file, we need to open the file in append mode.
ofstream myFile2("sample.txt", ios::app);
myFile2 << "DDDDD" << endl;
myFile2.close();
/*
Manipulators on insertion:
Chane the formatting of the data that is written to the file. Used with << as literal variables.
Some useful manipulators:
Manipulator Example Description
boolalpha myFile << boolalpha << false; Writes boolean values
dec myFile << dec << 12; Integers as decimal digits
oct myFile << oct << 12; Integers as octal digits
hex myFile << hex << 12; Integers as hexadecimal digits
showbase myFile << hex << showbase << 12; Prefixes the numbers (hex 0x, oct 0)
endl myFile << "text" << endl << "text"; Writes a Newline character
ends myFile << "text" << ends; Writes null terminating (\0)
fixed myFile << fixed << 3.14; Floating point numbers with a fixed number of decimal
showpoint myFile << showpoint << 12.0; Decimal point for floating point, even if it's not neeed
setprecision() myFile << setprecision(3) <<3.141 The precision of floating point numbers
setw() myFile << setw(5) << ... ; Padding from left (requires <iomanip>)
setfill() myFile << setfill(',') << setw(x) << 3.14; Choosing a character to use as padding (requires <iomanip>)
showpos myFile << showpos << 12; Plus (+) sign next to positive numbers
left myFile << setw(5) << left << "text"; Aligns output to right
right myFile << setw(5) << right << "text"; Aligns output to left
.
.
.
*/
/*
Some ofstream file object methods:
Method Example Description
write(str, n) myFile.write(myStr, 5) Writes n character of str into the file
put(character) myFile.put(c) Writes a specified character into the file
seekp(position) myFile.seekp(5) Moves the file pointer to a specified position relative to the beginning of the file
tellp() myFile.tellp() Returns the current position of the file pointer
.
.
.
*/
}