ofstream outfile; outfile.open("afile.dat");
cout << "Writing to the file" << endl; cout << "Enter your name: ";
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your age: ";
cin >> data; cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
return 0;}
当上面的代码被编译和执行时,它会产生下列输入和输出:
$./a.outWriting to the fileEnter your name: ZaraEnter your age: 9Reading from the fileZara9
上面的实例中使用了 cin 对象的附加函数,比如 getline()函数从外部读取一行,ignore() 函数会忽略掉之前读语句留下的多余字符。
文件位置指针
istream 和 ostream 都提供了用于重新定位文件位置指针的成员函数。这些成员函数包括关于 istream 的 seekg("seek get")和关于 ostream 的 seekp("seek put")。
seekg 和 seekp 的参数通常是一个长整型。第二个参数可以用于指定查找方向。查找方向可以是 ios::beg(默认的,从流的开头开始定位),也可以是 ios::cur(从流的当前位置开始定位),也可以是 ios::end(从流的末尾开始定位)。
文件位置指针是一个整数值,指定了从文件的起始位置到指针所在位置的字节数。下面是关于定位 "get" 文件位置指针的实例:
fileObject.seekg( n );
fileObject.seekg( n, ios::cur );
fileObject.seekg( n, ios::end );
fileObject.seekg( 0, ios::end );
xiaoke
lkj***9@163.com
读写&复制实例
下面的 C++ 程序以读写模式打开一个文件。
file_wr() 在向文件 test.txt 写入用户输入的信息之后,程序从文件读取信息,并将其输出到屏幕上;
file_copy()将文件test.txt里的数据读取出来后,再写入test_1.txt中。
#include "iostream"#include "fstream"using namespace std;//向文件内部写入数据,并将数据读出void file_wr(void){ char data[100]; //向文件写入数据 ofstream outfile; outfile.open("test.txt"); cout << "Write to the file" << endl; cout << "Enter your name:" << endl; cin.getline(data, 100); outfile << data << endl; cout << "Enter your age:" << endl; cin >> data; cin.ignore(); outfile << data << endl; outfile.close(); //从文件读取数据 ifstream infile; infile.open("test.txt"); cout << "Read from the file" << endl; infile >> data; cout << data << endl; infile >> data; cout << data << endl; infile.close();}//将数据从一文件复制到另一文件中void file_copy(void){ char data[100]; ifstream infile; ofstream outfile; infile.open("test.txt"); outfile.open("test_1.txt"); cout << "copy from test.txt to test_1.txt" << endl; while (!infile.eof()) { infile >> data; cout << data << endl; outfile << data << endl; } infile.close(); outfile.close();}//测试上述读写文件,与文件数据复制int _tmain(int argc, _TCHAR* argv[]){ file_wr(); file_copy(); return 0;}当上面的代码被编译和执行时,它会产生下列输入和输出:
xiaoke
lkj***9@163.com
wupa
100***5122@qq.com
参考地址
关于 cin.ignore() ,完整版本是 cin.ignore(int n, char a), 从输入流 (cin) 中提取字符,提取的字符被忽略 (ignore),不被使用。每抛弃一个字符,它都要计数和比较字符:如果计数值达到 n 或者被抛弃的字符是 a,则 cin.ignore()函数执行终止;否则,它继续等待。它的一个常用功能就是用来清除以回车结束的输入缓冲区的内容,消除上一次输入对下一次输入的影响。比如可以这么用:cin.ignore(1024,' '),通常把第一个参数设置得足够大,这样实际上总是只有第二个参数 起作用,所以这一句就是把回车(包括回车)之前的所以字符从输入缓冲(流)中清除出去。