1
Well, I’m trying to read from a file, and create a loop so I can go through all the characters until I find '<' character. After finding this character, the program must read and save the handle information until finding a ' n', to be processed later, and until then everything happens well.
The problem happens if before these actions occur I insert a while((ch = fgetc(in_file)) != EOF)
intended to start reading the text again until it finds the next character '<' to perform the operation again, and stop only at the end of the file.
With while included, I get a Segmentation fault. I’ve tried to create a temporary variable to store the variable position ch
, but the Segmentation fault continues to occur.
How can I solve this problem?
#include <stdio.h>
int main(void) {
int i = 0;
char s[100];
char ch;
FILE *in_file = fopen("name_of_file", "r");
while((ch = fgetc(in_file)) != EOF){ //aqui acontece o erro. sem essa tentativa de loop, os 2 for's que se seguem ocorrem sem erros
for(ch = fgetc(in_file);ch != '<';ch = fgetc(in_file)){
}
i=0;
for(ch = fgetc(in_file);ch != '\n';ch = fgetc(in_file)){
s[i] = ch;
i++;
}
s[i] = '\0';
}
return 0;
}
EOF returns when you reached the end of the file, or some error happened. What happens if while you’re in 1st or 2nd you don’t find any '<' or ' n' it will read endlessly. You need to check if you have reached the end of the file while reading it. while will only test this, when the two Fors finish their execution by their own tests.
– sgtcortez
You should just use a loop, testing on that if you get to the
<
or to the\n
or at the end of the file. This change of logic solves the problem that has in its entirety.– Isac