Reputation: 21
I am currently working on files and I want to read a character from the file which the file pointer has already passed. Imagine file consists of these characters: 123456789
I want to print 3 characters forward and 1 character from back, output must be like: 123234345456567678789
I tried this but it didnt print anything. I also tried fseek function but still it didn't print anything.
while(c != EOF){
for(int i=0; i<=2; i++){
c = fgetc(fp);
printf("%c", c);
}
fp -= 1;
}
Upvotes: 2
Views: 4897
Reputation: 35560
fseek
does work, just make sure you subtract 2, not 1, since calling fgetc
will advance the file pointer once more.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int c = 0;
FILE* fp = fopen("test", "r");
int shouldBreak = 0;
while (c != EOF) {
for (int i = 0; i <= 2; i++) {
c = fgetc(fp);
if (c == EOF) {
shouldBreak = 1;
break;
}
printf("%c", c);
}
if (shouldBreak) {
break;
}
fseek(fp, -2, SEEK_CUR);
}
printf("\n");
return 0;
}
Upvotes: 0
Reputation: 23832
For the desired output you can use fseek
to reset the fp
file pointer.
Another thing that should be done is to place a first read ouside the loop otherwise, in the first evaluation, c
has yet to have read a character from the file, this can lead to undefined behaviour if c
is not yet initialized.
I also inverted the printf
and fgetc
statements otherwise EOF
will be printed.
#include <stdio.h>
int main() {
FILE *fp = fopen("file.txt", "r");
if(!fp)
return 1;
int c;
c = fgetc(fp);
while(c != EOF) {
for (int i = 0; i <= 2; i++) {
printf("%c", c);
c = fgetc(fp);
}
fseek(fp, -2, SEEK_CUR);
}
}
Upvotes: 0