ReallyGoodPie ReallyGoodPie - 17 days ago 4x
C Question

Having trouble checking for newline when reading file

I'm trying to write a program to read a file of an unknown size / line size but I'm having some issues detecting the new line character.

When I run the program, it never reaches the end of the line point within the while loop in

and will just run constantly. If I run print each character, it prints out some unknown char.

I've tried setting
to be an int value and typecasting to char for
comparison. It's not reaching the
condition either so I'm not sure what is going on.


void readFile(FILE* file)
int endOfFile = 0;
while (endOfFile != 1)
endOfFile = readLine(file);
printf("%d\n", endOfFile);

int readLine(FILE* file)
static int maxSize = LINE_SIZE;
int currentIndex = 0;
int endOfFile = 0;
char* buffer = (char*) malloc(sizeof(char) * maxSize);
char ch;

ch = fgetc(file);
if ((ch != EOF) || (ch != '\n'))
buffer[currentIndex] = (char) ch;
currentIndex += 1;

if (currentIndex == maxSize)
printf("Reallocating string buffer");
maxSize *= 2;
buffer = (char*) realloc(buffer, maxSize);
} while ((ch != EOF) || (ch != '\n'));

if (ch == EOF)
endOfFile = 1;


return endOfFile;

If someone could help me that would be greatly appreciated because I have been stuck on this issue for quite some time. Thanks in advance.

(ch != EOF) || (ch != '\n')

This is always true.

You want an && (AND) here, both in your if and while, otherwise it will never stop.