分而治之。
写作部分:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int const a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int const out { open( "testnums.out",
O_WRONLY | O_CREAT, S_IWRITE | S_IREAD) };
if(out==-1) {
perror("Cannot open file");
return 1;
}
ssize_t const written { write( out, a, sizeof(a) ) };
if(written<0) {
perror("Write error");
}
close( out );
return 0;
}
编译并执行时:
$ g++ -std=c++0x -Wall -Wextra tout.cc
$ ./a.out
它写出'a'数组:
$ hexdump testnums.out
0000000 0001 0000 0002 0000 0003 0000 0004 0000
0000010 0005 0000 0006 0000 0007 0000 0008 0000
0000020 0009 0000 000a 0000
0000028
请注意,这不是可移植的——每个编译器/体系结构在这里可能有一些不同的输出。
这是再次读入并将其写入标准输出的部分:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main() {
int const in { open( "testnums.out", O_RDONLY ) };
if(in==-1) {
perror("Cannot open file");
return 1;
}
int a[10];
ssize_t const r { read( in, a, sizeof(a) ) };
if(r!=sizeof(a)) {
fprintf(stderr, "Could not read complete array.");
return 1;
}
if(r<0) {
perror("Read error");
close(in);
return 1;
}
close(in);
for(unsigned int i(0); i<sizeof(a)/sizeof(int); ++i) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
编译并执行:
$ g++ -std=c++0x -Wall -Wextra tin.cc
$ ./a.out
1 2 3 4 5 6 7 8 9 10
一般:在你的代码中有很多小问题(比如:检查返回值完全缺失,没有包括所有需要的头文件,写入错误的字节数,......)你可能想阅读不同的人像这样的页面
$ man 2 open
$ man 2 read
$ man 2 write
$ man 2 close