well, just to add to javathehut's solution ...
- if you insist on using C for IO, at least use stat(...) to get the info about the file size and its existance ( rather than opening, and fseeking )
- if you allocate with _builtin_vec_new [] you should delete with [] ( delete [] szBuffer; )
- rather than looping several times through the file, make a vector<int> int which you dump the new line positions, when counting the line feeds, that way when you go write it out, you'll simple dump the buffer in two chunks ( from 0 to first LF poition and secod LF position to EOF )
basically it would look something like this
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
int main(int argc, char* argv[])
{
struct stat stbuf;
FILE* fp;
char* buf;
size_t sz, j;
vector<int> vc;
size_t range[] = { 0 , 0 };
if(stat(argv[1], &stbuf) != 0) {
perror("stat failed");
return 1;
}
if((fp = fopen(argv[1], "r")) == NULL) {
perror("fopen failed");
return 1;
}
buf = (char*)malloc(sizeof(char)*stbuf.st_size);
sz = read(fileno(fp), buf, stbuf.st_size);
vc.push_back(0);
for(j = 0; j<sz; j++) {
if(buf[j] == '\n')
vc.push_back(j+1);
}
fclose(fp);
if((fp = fopen(argv[2], "w")) == NULL) {
perror("fopen failed");
return 1;
}
printf("total lines: %d\n> ", vc.size( )-1);
scanf("%d %d", &range[0], &range[1]);
if(range[0] > 0 && range[1] < vc.size( ) && range[0] <= range[1]) {
fwrite(buf, sizeof(char), vc[range[0]-1], fp);
fwrite(buf+vc[range[1]], sizeof(char), sz-vc[range[1]], fp);
}
else {
fprintf(stderr, "invalid parameters\n");
return 1;
}
fclose(fp);
free(buf);
return 0;
}
edit: [ i ] got swallowed by the page parser :|