观察下面代码。 是一个以10个字节来分隔页的代码,按2 可以上翻,按8下翻页。
#include "stdafx.h"
#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// C++ standard file operation
int _tmain(int argc, _TCHAR* argv[])
{
fstream fin("1.txt");
if(!fin)
{
cout << "Cannot open the file 1.txt";
return -1;
}
int key = 2;
char page[11];
// every 10 bytes composite a page
memset(page,0,11);
LOOP:
{
cout << "Please input your key" << endl;
cin >> key;
switch(key)
{
case 2: // page up function;
fin.clear();
if(fin.read(page,10))
{
cout << page <<endl;
cout << fin.tellg() << endl;
}
else
{
cout << "invalidate file operation" << endl;
fin.seekg(0,ios::beg);
}
break;
case 8: // page down function;
fin.clear();
fin.seekg(-20,ios::cur);
if(fin.read(page,10))
{
cout << page <<endl;
cout << fin.tellg() << endl;
}
else
{
cout << "invalidate file operation" << endl;
fin.seekg(0,ios::beg);
}
break;
case 0:
return 0; // exit the application.
default:
break;
}
}
goto LOOP;
return 0;
}
但是当读到一行的末尾的时候,就将字节多读一个。这样使得数据的上下翻页出问题。
eg 1.txt 的内容如下。
A leading classical
.......
当文件指针知道 一行末尾的时候 就会有问题,原因是在window 系统下 存在两个字节 /r /n 这样就多读了。 所以会出问题,
可想而知,一种方法是替代/r/n 为 /n 这个方法不好。原因是重复操作文件一次不划算。那么下面这个方法可以避免。
头文件已在上面的例子中包含了。
int _tmain(int argc, _TCHAR* argv[])
{
int fileHandle = _open("1.txt",_O_RDONLY ,0700);
if(fileHandle == -1)
{
cout << "Cannot open the file 1.txt";
return -1;
}
char data[11];
int key;
long pos = -1L;
memset(data,0,11);
LOOP:
{
cout << "Please input your key" << endl;
cin >> key;
switch(key)
{
case 2: // page up function;
pos = _lseek( fileHandle, 0L, SEEK_CUR );
if( pos == -1L )
{
perror( "_lseek to current position failed" );
pos = _lseek( fileHandle, 0L, SEEK_SET );
break;
}
_read(fileHandle,data,10);
cout << data << endl;
cout << _tell(fileHandle)<< endl;
break;
case 8: // page down function;
pos = _lseek(fileHandle,-20,SEEK_CUR);
if(pos == -1L)
{
cout << "_lseek to current position failed" << endl;
cout << "restart from the file head" << endl;
pos = _lseek( fileHandle, 0L, SEEK_SET );
break;
}
_read(fileHandle,data,10);
cout << data << endl;
cout << _tell(fileHandle) << endl;
break;
case 0:
return 0; // exit the application.
default:
break;
}
}
goto LOOP;
return 0;
}
希望大家能学点东西。哈哈!!