c++ fstream write to file code example
Example 1: read a file c++
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Example 2: obj c write file
-(void)write:(NSString *)dir file:(NSString *)ff{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:[@"%@/" stringByAppendingString:dir],
documentsDirectory];
NSString *content = ff;
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
Example 3: how to read and write in a file c++
using namespace std;
ifstream file_variable;
file_variable.open("input.txt");
file_variable.close();
_____________________________________________________
while (cin >> name >> value)
{
cout << name << value << endl;
}
_____________________________________________________
ofstream out_file;
out_file.open("output.txt");
out_file << "Write this scentence in the file" << endl;
Example 4: write to file in C++
ofstream myfile;
myfile.open("file.txt");
myfile << "write this to file"