read と write によるファイルへの入出力
#include <stdio.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
double x1 = 10.5;
double x2;
long k1 = 21;
long k2;
int disk;
char *buf;
/*
ディスクへの出力
*/
disk = open("data", O_WRONLY|O_CREAT, S_IREAD);
buf = (char *)(&x1);
write(disk, buf, 8);
buf = (char *)(&k1);
write(disk, buf, 4);
close(disk);
/*
ディスクからの入力
*/
disk = open("data", O_RDONLY);
buf = (char *)(&x2);
read(disk, buf, 8);
buf = (char *)(&k2);
read(disk, buf, 4);
close(disk);
/*
出力
*/
printf("x2 %5.1f k2 %3ld\n", x2, k2);
return 0;
}
(出力)
x2 10.5 k2 21
ファイルのコピー
#include <stdio.h>
#include <stdlib.h>
#include <sys\types.h>
#include <sys\uio.h>
#include <unistd.h>
#include <sys\stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char *argv[])
{
long count;
int source, target, ch;
char *buf;
struct stat filestat;
if(argc < 3) {
printf("***error use: test file1 file2\n");
exit(1);
}
/*
ファイルのオープン
*/
if((source = open(argv[1], O_BINARY|O_RDONLY)) == -1) {
printf("***error ファイル %s をオープンできません\n", argv[1]);
exit(1);
}
target = open(argv[2], O_BINARY|O_WRONLY|O_CREAT|O_EXCL,
S_IREAD|S_IWRITE);
if (target == -1) {
if(errno == EEXIST) {
printf("Target exists. Overwrite? ");
ch = getchar();
if((ch == 'y') || (ch == 'Y'))
target = open(argv[2], O_BINARY|O_WRONLY|O_CREAT|O_TRUNC,
S_IREAD|S_IWRITE);
}
else {
printf("***error ファイル %s をオープンできません\n", argv[2]);
exit(1);
}
}
/*
バッファ領域の確保
*/
fstat(source, &filestat);
count = filestat.st_size;
if((buf = (char *)malloc((size_t)count)) == NULL) {
printf("***error no memory\n");
exit(1);
}
/*
コピー
*/
if ((count = (long)read(source, buf, (int)count)) == -1) {
printf("ファイルの読込に失敗しました\n");
exit(1);
}
if ((count = (long)write(target, buf, (int)count)) == -1) {
printf("ファイルの書き込みに失敗しました\n");
exit(1);
}
/*
ファイルのクローズと領域の開放
*/
close(source);
close(target);
free(buf);
printf("Copy successful\n");
return 0;
}