关于文件分页时候的一些问题。以及解决方案。

 观察下面代码。 是一个以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;
}

希望大家能学点东西。哈哈!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值