我看了很多帖子,但没有找到我想要的东西。
我得到了错误的输出:
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ...... // may be this is EOF character
进入无限循环。
我的算法:
- 跳转到文件结尾。
- 将指针位置减1并逐个读取字符。
- 如果我们找到了10行或到达文件开头,则退出。
- 现在我将扫描整个文件直到EOF并打印它们 //代码未实现。
代码:
#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main()
{
FILE *f1=fopen("input.txt","r");
FILE *f2=fopen("output.txt","w");
int i,j,pos;
int count=0;
char ch;
int begin=ftell(f1);
// GO TO END OF FILE
fseek(f1,0,SEEK_END);
int end = ftell(f1);
pos=ftell(f1);
while(count<10)
{
pos=ftell(f1);
// FILE IS LESS THAN 10 LINES
if(pos<begin)
break;
ch=fgetc(f1);
if(ch=='\n')
count++;
fputc(ch,f2);
fseek(f1,pos-1,end);
}
return 0;
}
更新 1:
修改后的代码:现在只有一个错误 - 如果输入包含以下行
3enil
2enil
1enil
it prints 10 lines only
line1
line2
line3ÿine1
line2
line3ÿine1
line2
line3ÿine1
line2
line3ÿine1
line2
PS:
1. 在notepad++上在Windows上工作
这不是作业
我也想不使用更多的内存或STL来完成它。
我正在练习提高我的基础知识,所以请不要发布任何函数(如tail -5 tc.)
请帮助改进我的代码。
fgetc
函数会将文件位置指示器向前移动一个字符位置。 - jsalonenfseek(f1, pos-1, SEEK_SET);
和文件模式 bin。 - BLUEPIXYfstream
? - nkint