从单独的线程调用时,如何从fgets获得正确的输出?

时间:2014-04-17 17:01:10

标签: c multithreading fgets

我想在我创建的一个线程中逐行读取一个文件,但由于某种原因,我从fgets获得的结果只是垃圾。这个问题的原因是什么?我将如何修复它?

这是问题区域,它包含在自己的线程中:

    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);

这是Line;3+中包含的内容。但是,每次运行程序时,这都会改变

这就是orders.txt包含的内容:

"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

这是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;
}

1 个答案:

答案 0 :(得分:1)

我的猜测是getMaxLineCount正在使用该文件,因此您必须回放它。

在致电fgets之前,请尝试添加

rewind(orders);

除非多个线程试图读取同一个文件,否则此问题应与线程无关。

更新:以下简短程序适用于我。

Update2:我已经修复了@chux提到的至少一些未定义的行为。

Update3:由chux更改为size_t。重新排序以允许最后一行测试,如果最长。移动lineCount = 0;(只有在找到新的最大值时才会发生。)

#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);
}