Java Reference
In-Depth Information
The C program in
Example 10-10
writes the file
random.dat
that we read in
Seeking to a
Position within a File
.
It uses the network byte order macros to make sure that the long in-
teger (32 bits on most C compilers) is in the correct order to be read as an
int
in Java:
Example 10-10. src/main/java/io/WriteRandom.c
/* C Program to create the random-access file for the RandomAccessFile example
* Ian F. Darwin, http://www.darwinsys.com/
*/
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <machine/endian.h>
const
const
off_t
off_t
OFFSET
=
1234
;
// off_t is a C "typedef", usually == long integer
const
const
char
char
*
FILENAME
=
"random.dat"
;
const
const
int
int
MODE
=
0644
;
const
const
char
char
*
MESSAGE
=
"Ye have sought, and ye have found!\r\n
\r\n"
;
int
int
main
(
int
int
argc
,
char
char
**
argv
) {
int
int
fd
;
int
int
java_offset
;
iif
((
fd
=
creat
(
FILENAME
,
MODE
))
<
0
) {
perror
(
FILENAME
);
return
return
1
;
}
/* Java's DataStreams etc. are defined to be in network byte order */
java_offset
=
htonl
(
OFFSET
);
iif
(
write
(
fd
,
&
java_offset
,
sizeof
sizeof
java_offset
)
<
0
) {
perror
(
"write"
);
return
return
1
;
}
iif
(
lseek
(
fd
,
OFFSET
,
SEEK_SET
)
<
0
) {
perror
(
"seek"
);
return
return
1
;
}
iif
(
write
(
fd
,
MESSAGE
,
strlen
(
MESSAGE
))
!=
strlen
(
MESSAGE
)) {