How to read file until certain character or EOF?

2019-03-06 08:12发布

问题:

I have small problem with my C code. I want to read file until I hit certain character or EOF (from parameter as seen now). char *readUntil(FILE *stream, char character, size_t *length)

I used this loop:int i = 0 while((i = fgetc(stream)) != character || i != EOF){} to read it until stream ends or character is matched. However it doesnt seem to be working. What's the problem and how to fix it?

回答1:

This line

while((i = fgetc(stream)) != character || i != EOF){}

will loop forever as either

i = fgetc(stream)) != character

or

i != EOF

will be true.

Try

while((i = fgetc(stream)) != character && i != EOF){}


标签: c file char fgetc