C: 多个 pthread 期间 fgets 错误

标签 c multithreading file pthreads fgets

我的程序的总体目标是从文件中读取数据( float 或字母)并使用互斥体更改我的全局常量。 (我到现在还没应用过)

但在我做到这一点之前,我只是想创建一个基本程序来读取文件的全部内容并打印到屏幕上。 目前,我的程序无法做到这一点。它只是读取文件的第一个字符并退出文件。
我提供了我的代码以及错误。任何帮助都会非常有帮助。

#include <stdio.h>
#include <pthread.h>
#include <string.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char *files[] = {"one.in", "two.in", "three.in", "four.in", "five.in"};

void* thread( void * arg )
{
    char * file = (char *) arg;
    // open the file and read the content
    FILE *fp = fopen(file,"r");
    char line[1024];
    int len;

    printf("Thread id is %s enter\n",file);
    if( !fp)
    {
        printf("%s file open failed\n", file);
        return 0;
    }
    else
        printf("%s File open success %p %d\n", file, fp, ftell(fp));
    // dump the file content with thread id (file name)
    while (fgets(line,len, fp))
    {
        printf("%s %s", file, line);
    }
    printf("Thread id is %s %d exit\n",file, ftell(fp));
    fclose(fp);
    return 0;
}

int main( void )
{
    int i = 0;

    if (pthread_mutex_init(&mutex, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        return 1;
    }
    for(i = 4; i >= 0; i--)
    {
        pthread_t  id;
        pthread_create( &id, NULL, &thread, files[i] );
        pthread_detach(id);
    }
    printf("Main thread exit\n");
    pthread_exit(0);
    printf("Main thread real exit\n");
    return 0;
}
<小时/>

错误

Thread id is five.in enter
five.in File open success 0x7fff7a2e7070 0
Thread id is five.in 0 exit
Thread id is four.in enter
four.in File open success 0x7fff7a2e7070 0
Thread id is four.in 0 exit
Thread id is three.in enter
three.in File open success 0x7fff7a2e7070 0
Thread id is three.in 0 exit
Thread id is two.in enter
two.in File open success 0x7fff7a2e7070 0
Thread id is two.in 0 exit
Thread id is one.in enter
one.in File open success 0x7fff7a2e7070 0
Thread id is one.in 0 exit
Main thread exit
<小时/>

文件格式

R
1
2
3
-4
-5
4
W

最佳答案

问题是对 fgets() 的调用:

while (fgets(line,len, fp))

len 未初始化。这在技术上是undefined behaviour .

您想要的是使用的大小:

while (fgets(line, sizeof line, fp))

关于C: 多个 pthread 期间 fgets 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33050255/

相关文章:

c - 删除结构体的设置间隔

c - 如何在 C 中使用 scanf 设置部分默认输入?

c - 黑客攻击 : how to perform buffer overflow attack?

c++ - 如何在循环线程中使用 wait_for?

关于全局空间默认返回类型的说明

C#——多线程

javascript - CasperJS 可以在同一进程中运行多个实例吗?

java - 如何从java中的txt文件生成连续字符频率矩阵?

linux - 在 Linux 中编写由多个文件组成的环回设备

Android Studio 从 Gallery Intent 获取文件