Would it be possible to create a function that reads half a text file ... ?
To read half the file, read a byte - skip a byte.
int ch;
while((ch = fgetc(myFile)) != EOF) {
putchar(ch);
fseek(myFile, 1, SEEK_CUR);
}
To print every other line, use the return value of fgets()
and toggle a flag print
.
bool print = true;
while(fgets(line, sizeof line, myFile)) {
if (print) {
fputs(line, stdout);
}
print = !print;
}
... is there a way I could get just the first or second half of the file to be read?
Awww, that does not look like much fun to add that condition at the end of the the post.
First find file length:
How can I get a file's size
How do you determine the size of a file
On Linux, I would use stat64();
long size = foo(); // from one of above 3 ideas
To read the first half:
rewind(myFile);
int ch;
while(size-- > 0 && (ch = fgetc(myFile)) != EOF) {
putchar(ch);
}
To read the 2nd half:
fseek(myFile, size/2, SEEK_SET);
int ch;
while((ch = fgetc(myFile)) != EOF) {
putchar(ch);
}
Heres is a fun idea to print the first half, just write a few queue functions.
queue *q = q_init();
int ch;
// Read 2 bytes, save, write earliest byte
while((ch = fgetc(myFile)) != EOF) {
q_append(q, ch);
ch = fgetc(myFile);
if (ch != EOF) q_append(q, ch);
ch = q_get(q);
putchar(ch);
}
q = q_uninit(q);