My guess is that getMaxLineCount
is consuming the file, so you have to rewind it.
Before the call to fgets
, try adding
rewind(orders);
Unless multiple threads are trying to read the same file, this issue should have nothing to do with threading.
Update: The following short program works fine for me.
Update2: I have fixed at least some of the undefined behavior mentioned by @chux.
Update3: by chux changed to size_t
. Re-order to allow last line to be tested if longest. Move lineCount = 0;
(it had only happened when a new max was found.)
#include <stdio.h>
#include <stdlib.h>
size_t getMaxLineCount(FILE *filePtr)
{
int c; // Changed `char` to int
size_t lineCount;
size_t maxCount;
lineCount = 0;
maxCount = 0;
while(1)
{
c = fgetc(filePtr);
if (c == EOF) break;
lineCount++;
if (c == '\n')
{
if (lineCount > maxCount) maxCount = lineCount;
lineCount = 0;
}
}
if (lineCount > maxCount) maxCount = lineCount;
rewind(filePtr);
return maxCount;
}
int main(){
FILE *orders = fopen("orders.txt","r");
size_t orderLineSize = getMaxLineCount(orders);
char Line[orderLineSize+1]; // Extra space for the buffer.
fgets(Line,orderLineSize,orders); // This works fine for me.
printf("Line is: %s\n",Line);
}