multithreading - C: fgets error during multiple pthread -
my overall goal of program read data (float or letter) file , change global constant using mutex. (i have not applied until now)
but before that, thought of creating basic program read entire content of file , print screen. currently, program unable so. reads first character of file , exits file.
providing code , error. assistance helpful.
#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 file , read content file *fp = fopen(file,"r"); char line[1024]; int len; printf("thread id %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 file content thread id (file name) while (fgets(line,len, fp)) { printf("%s %s", file, line); } printf("thread id %s %d exit\n",file, ftell(fp)); fclose(fp); return 0; } int main( void ) { int = 0; if (pthread_mutex_init(&mutex, null) != 0) { printf("\n mutex init failed\n"); return 1; } for(i = 4; >= 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; }
errors
thread id five.in enter five.in file open success 0x7fff7a2e7070 0 thread id five.in 0 exit thread id four.in enter four.in file open success 0x7fff7a2e7070 0 thread id four.in 0 exit thread id three.in enter three.in file open success 0x7fff7a2e7070 0 thread id three.in 0 exit thread id two.in enter two.in file open success 0x7fff7a2e7070 0 thread id two.in 0 exit thread id one.in enter one.in file open success 0x7fff7a2e7070 0 thread id one.in 0 exit main thread exit
file format
r 1 2 3 -4 -5 4 w
the problem call fgets()
:
while (fgets(line,len, fp))
len
uninitialized. thi technically undefined behaviour.
what want use size of line
:
while (fgets(line, sizeof line, fp))
Comments
Post a Comment