#include #include // read #include //read #include //read #include // lseek #include // errno, #include // strerror const char * FILE_NAME = "seekData"; const int POSITIONS = 10; using namespace std; // for clarity I will assume no errors on read/write. void MyError(int errmsg, string message) { cerr << message << endl; cerr << strerror(errmsg) << endl; return; } int main() { int fd; char data; int i; int location; int offset; int pos; int realPos; bool done = false; // open the file, read write // make it if it does not exist // and wipe it out to boot. fd = open(FILE_NAME, O_RDWR|O_CREAT|O_TRUNC, S_IRWXU | S_IRGRP | S_IROTH ); if (-1 == fd) { string message = FILE_NAME; message = "Could not open" + message; MyError(errno, message); } data = 'X'; // first fill the file with X for(i=0;i "; cin >> location; if (-1 == location) { done = true; } else if (location >= POSITIONS or location < 0) { cout << location << "is not a valid position" << endl; } else { // data to write. cout << "Enter a character to write at position " << location; cout << "=> "; cin >> data; // calculate the offset and give some information offset = location - pos; cout << "\tCurrently at " << pos << endl; cout << "\tGoing to " << location << endl; cout << "\tThe offset is " << offset << endl; // seek the location realPos == lseek(fd, offset, SEEK_CUR); if (-1 == realPos) { // argh, we failed. MyError(errno, "lseek failed"); done = true; } else { // the sweet smell of success cout << "\tLseek reports that we have moved to " << realPos << endl; cout << "\tWriting a " << data << " at location " << location << endl; cout << endl; write(fd, &data, 1); pos = location + 1; } } } close(fd); return 0; }