seekg function --- plese help
hi all
this is my code
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
char a ;
int length ;
ifstream infile ;
ofstream outfile ;
infile.open("hm.txt",ios::in) ;
outfile.open("output.txt" , ios::out);
infile.unsetf(ios::skipws);
int a1;
cout << " please enter the ID " <<endl;
cin>> a1;
infile>> a ;
while ( ! infile.fail())
{
outfile<< a;
infile.seekg(0,ios::cur);
infile >> a ;
}
infile.close();
outfile.close();
}
i have this text file with users and if from 1 to 10 , and all the name is in same length
Code:
1 ken1
2 ken2
3 ken3
4 ken4
5 ken5
6 ken6
7 ken7
8 ken8
9 ken9
10ken10
the user should enter an ID from 1 to 10 and then the app should search for the id and if it found some thing it should print the user of the ID without without id ..
how i can do it ?????
thanks in advance
Re: seekg function --- plese help
Your names do not all have the same length unless the kens before ken10 have a space at the end of the line which of course is invisible in the listing.
AFAIK seekg() does not work reliably with files opened in text mode, so you may want to open the file in binary mode. However, in binary mode the >> operator may not work correctly, so you may need to use read() instead.
To get the offset to seek to, you need to multiply the ID minus 1 (assuming one-based IDs) with the record length. The record length in this file is 9 (assuming Windows line breaks and one space at the end of each line containing a ken before 10).
EDIT: Oh, and of course a char is not enough to hold all possible IDs (the ID may be 10) or even an entire record from the file.