As most of the respondents have already pointed out - you should be quite ok
with plain fopen(). _sopen() is primarily for file sharing (at least this
is what I remember doing in the past) among processes.
Anyway, are you sure that your problems are not related to rendering of data
(e.g. displaying, writing, etc.) instead of reading? Please see the code
below that demonstrates fopen() in a multithreaded environment. The program
first creates a file and then launches a number of threads (specified on a
command line) to read from it. Note that I 'protect' rendering of data being
read by a critical section - this is just to make sure that this look ok on
the screen. You can redirect the output to another file if you like.
Bogdan
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <windows.h>
#define LINE_LEN 4
long offsets[] = {0, 4, 8, 12, 16, 20, 24, 28, 32};
const char* fname = "threadfp.txt";
CRITICAL_SECTION cs;
int num_reads = 100;
int createFile(char* fname)
{
FILE* fp = fopen(fname, "wb");
if (NULL == fp) {
printf("Failed to create %s\n", fname);
return errno;
}
for (int i = 0; i < sizeof(offsets) / sizeof(offsets[0]); i++) {
char c = i + '0';
for (int j = 0; j < LINE_LEN; j++) {
fwrite(&c, 1, 1, fp);
}
}
fclose(fp);
return 0;
}
void readFile(void* param)
{
char buf[LINE_LEN];
int i;
FILE* fp = fopen((const char*) param, "rb");
DWORD tid = ::GetCurrentThreadId();
srand((unsigned int) tid);
if (NULL != fp) {
for (int n = 0; n < num_reads; n++) {
i = rand() % (sizeof(offsets) / sizeof(offsets[0]));
if (0 == fseek(fp, offsets[i], SEEK_SET)) {
if (sizeof(buf) == fread(buf, 1, sizeof(buf), fp)) {
EnterCriticalSection(&cs);
printf("[tid=%04X, offset=%2ld]", tid, offsets[i]);
for (int i = 0; i < sizeof(buf); i++) {
printf("%c", buf[i]);
}
printf("\n");
fflush(stdout);
LeaveCriticalSection(&cs);
}
}
::Sleep(500);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
if (argc > 2 && 0 == createFile(argv[1])) {
if (argc > 3) {
num_reads = atoi(argv[3]);
}
InitializeCriticalSection(&cs);
int n = atoi(argv[2]);
for (int i = 0; i < n; n++) {
_beginthread(readFile, 0, argv[1]);
}
while (1) {
::Sleep(1000);
}
}
return 0;
}
"noleander" <no*******@discussions.microsoft.com> wrote in message
news:10**********************************@microsof t.com...
I've got two threads reading from one disk file (I'm using the Pthread
library).
I need each thread to have its own file seek pointer, so they can read
from
independent parts of the file.
I tried using _sopen() once (for the entire process) then using fdopen()
in
each thread to get unique file seek pointers, but it is not working well.
Any suggestions?