This example opens the file sample.dat and associates a stream with the file using fdopen. It then reads from the stream into the buffer.
#if (1 == __TOS_OS2__) #include <sys\stat.h> #include <io.h> #elseif (1 ==__TOS_WIN__) #include <io.h> #include <sys\stat.h> #endif
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main(void)
{
long length;
int fh;
char buffer[20];
FILE *fp;
memset(buffer, '\0', 20); /* Initialize buffer */
printf("\nCreating sample.dat.\n");
system("echo Sample Program > sample.dat");
if (-1 == (fh = open("sample.dat", O_RDWR|O_APPEND))) {
perror("Unable to open sample.dat");
return EXIT_FAILURE;
}
if (NULL == (fp = fdopen(fh, "r"))) {
perror("fdopen failed");
close(fh);
return EXIT_FAILURE;
}
if (7 != fread(buffer, 1, 7, fp)) {
perror("fread failed");
fclose(fp);
return EXIT_FAILURE;
}
printf("Successfully read from the stream the following:\n%s.\n", buffer);
fclose(fp);
return 0;
/***********************************************************
The output should be:
Creating sample.dat.
Successfully read from the stream the following:
Sample .
***********************************************************/
}