File Stream
File Stream
Unit V
C++ Files and Streams
• In C++ programming we are using the iostream standard
library, it provides cin and cout methods for reading
from input and writing to output respectively.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome \n";
filestream << "C++ Tutorial.\n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}
C++ FileStream example: reading from a file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}
C++ getline()
Return value
This function returns the input stream object, which is passed as a
parameter to the function.
Example
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string profile; // variable declaration
std::cout << "Enter your profile :" << std::endl;
getline(cin,profile,' '); // implementing getline() function with a
delimiting character.
cout<<"\nProfile is :"<<profile;
}
Output
• In the above code, we take the user input by
using getline() function, but this time we also
add the delimiting character('') in a third
parameter. Here, delimiting character is a space
character, means the character that appears
after space will not be considered.
• Output
• Enter your profile : Software Developer
• Profile is: Software
Delimiter
• A delimiter is a sequence of one or more characters
for specifying the boundary between separate,
independent regions in plain text, mathematical
expressions or other data streams.
• An example of a delimiter is the comma character,
which acts as a field delimiter in a sequence of
comma-separated values.
• Delimiters are used as separators between the
characters or words in a string so that different
results can get separated by the delimiter.