I would like to read a file line by line in a thread that I have created, but for some reason, the result that I'm getting from fgets is just garbage. What is the cause of this problem and how would I go about fixing it?
Here is the problem area, which is contained in its own thread:
FILE *orders = fopen("orders.txt","r");
int numOrders;
numOrders = getNumLines(orders);
int orderLineSize = getMaxLineCount(orders);
char Line[orderLineSize];
fgets(Line,orderLineSize,orders); // This is the call that gives me a garbage output
printf("Line is: %s\n",Line);
This is what is contained in Line
: ;3+
. However, this changes every time I run the program
And this is what orders.txt
contains:
"I Could Pee on This: And Other Poems by Cats"|7.49|1|HOUSING01
"Across Islands and Oceans"|1.99|1|SPORTS01
"Soul Surfer"|7.99|3|SPORTS01
"The Immortal Life of Henrietta Lacks"|8.91|4|POLITICS01
"The Handbuilt Home: 34 Simple Stylish and Budget-Friendly Woodworking Projects for Every Room"|15.63|1|HOUSING01
"The History of Surfing"|31.5|2|SPORTS01
Here is getMaxLineCount:
int getMaxLineCount(FILE *filePtr)
{
char c;
int lineCount;
int maxCount;
lineCount = 0;
maxCount = 0;
while(c != EOF)
{
c = fgetc(filePtr);
lineCount++;
if((c == '\n') && (lineCount > maxCount))
{
maxCount = lineCount;
lineCount = 0;
}
}
rewind(filePtr);
return maxCount;
}
getNumLines:
int getNumLines(FILE *filePtr)
{
char c;
int lineCount;
int maxCount;
lineCount = 0;
maxCount = 0;
int peopleCount;
peopleCount = 0;
while(c != EOF)
{
c = fgetc(filePtr);
if(c == '\n')
peopleCount++;
}
rewind(filePtr);
return peopleCount;
}
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);
}