Documente Academic
Documente Profesional
Documente Cultură
CHAPTER 9
ICT1103 Structured Programming
Topics
cout << "Now writing the data to the file" << endl;
dataFile << "Jonas\n";
dataFile << "Smith\n";
dataFile << "Willis\n";
dataFile << "Davis\n";
return 0;
}
if (nameFile)
{
getline(nameFile, input);//read item from the file
while (nameFile)
{
cout << input << endl;
getline(nameFile, input);
}
nameFile.close();
}
else
{
cout << "ERROR:Cannot open file\n";
}
return 0;
} 2000 Prentice Hall, Inc.
All rights 13
reserved.
The get() function
■ It reads a single character from the file.
int main()
{
string fileName;
char ch;
fstream file;
cout << "Enter a file name:";
cin >>fileName;
file.open(fileName, ios::in);
if (file)//if filename successfully open
{
file.get(ch);
while (file)
{cout << ch;
file.get(ch);}
file.close();
}
else
{cout << fileName << " could not be opened.\n“;}
return 0;
2000 Prentice Hall, Inc.
}
All rights 14
reserved.
The put() function
■ The put member function writes a single character to the file.
int main()
{
char ch;
fstream dataFile("sentence.txt");
cout << "Type a sentence and be sure to end it with a period.\n";
cin.get(ch);
while (ch != '.')
{
dataFile.put(ch);
cin.get(ch);
}
dataFile.put(ch);
dataFile.close();
return 0;
}
■ Example:
Sample.dat
This is line 1
This is line 2
This is line 3
This is line 4
is line 1
line 2
his is line 4