您的位置:首页 > 其它

File Read Write

2012-11-28 15:00 302 查看
Reads information from the file and outputs it onto the screen

#include <fstream>
#include <iostream>
using namespace std;

int main ()
{
char data[80];
ofstream outfile;
outfile.open("file.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 80);
outfile << data << endl;
cout << "Enter your id: ";
cin >> data;
cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
cout << "Reading from the file" << endl;

infile.open("file.dat");
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
return 0;
}
Another example of read() and write() and illustrates the use of gcount( )

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
double doubleNumberArray[4] = {99.75, -34.4, 1776.0, 200.1};
int i;
ofstream out("numbers", ios::out | ios::binary);
if(!out) {
cout << "Cannot open file.";
return 1;
}
out.write((char *) &doubleNumberArray, sizeof doubleNumberArray);
out.close();
for(i=0; i<4; i++) // clear array
doubleNumberArray[i] = 0.0;

ifstream in("numbers", ios::in | ios::binary);
in.read((char *) &doubleNumberArray, sizeof doubleNumberArray);

cout << in.gcount() << " bytes read\n"; // see how many bytes have been read
for(i=0; i<4; i++) // show values read from file
cout << doubleNumberArray[i] << " ";
in.close();
return 0;
}


Opening Files for Read and Write

#include <fstream>
#include <iostream>

using namespace std;
int main()
{
char buffer[255];

ofstream fout("text.txt");
fout << "This line written directly to the file...\n";
cout << "Enter text for the file: ";
cin.ignore(1,'\n');
cin.getline(buffer,255);

fout << buffer << "\n";
fout.close();

ifstream fin("text.txt");
char ch;
while (fin.get(ch))
cout << ch;

fin.close();
return 0;
}


Use get() and getline() to read characters.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
char ch;
char str[256];

ofstream fout("test.dat");
if(!fout) {
cout << "Cannot open file for output.\n";
return 1;
}

fout << "This is a line of text.\n";
fout << "This is another line of text.\n";
fout << "This is the last line of text.\n";

fout.close();
if(!fout.good()) {
cout << "An error occurred when writing to the file.\n";
return 1;
}

ifstream fin("test.dat", ios::in);
if(!fin) {
cout << "Cannot open file for input.\n";
return 1;
}

cout << "Use get():\n";

cout << "Here are the first three characters: ";
for(int i=0; i < 3; ++i) {
fin.get(ch);
cout << ch;
}
cout << endl;

fin.get(str, 255);
cout << "Here is the rest of the first line: ";
cout << str << endl;

fin.get(ch);

cout << "\nNow use getline():\n";

fin.getline(str, 255);
cout << str << endl;
fin.getline(str, 255);
cout << str;

fin.close();
if(!fin.good()) {
cout << "Error occurred while reading or closing the file.\n";
return 1;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: