KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have seen many posts but didn't find something like i want. I am getting wrong output : ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ...... // may be this is EOF character Going into infinite loop. My algorithm: Go to end of file. decrease position of pointer by 1 and read character by character. exit if we found our 10 lines or we reach beginning of file. now i will scan the full file till EOF and print them //not implemented in code. code: #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; } UPD 1: changed code: it has just 1 error now - if input has lines like 3enil 2enil 1enil it prints 10 lines only line1 line2 line3ÿine1 line2 line3ÿine1 line2 line3ÿine1 line2 line3ÿine1 line2 PS: 1. working on windows in notepad++ this is not homework also i want to do it without using any more memory or use of STL. i am practicing to improve my basic knowledge so please don't post about any functions (like tail -5 tc.) please help to improve my code.
Tags (comma-separated)
Save Edits
Cancel