|
通过前面的简单概念和基本系统IO接口的介绍,可以尝试写一个简单程序,需求如下: 创建文件testA,向testA写入123456,创建文件testB,将testA中3后面的2字节长度内容拷贝到文件B中。 1.示例 #include #include #include //strlen的头文件 #include #include #include #include
int main() { int fda, fdb; char msg[3]; //虽然只读取2字节长度内容 //但是可以在最后添加一个换行符方便查看 char buf[30] = "123456\n";
fda = open("./testA", O_RDWR | O_CREAT | O_TRUNC, 0777);
if ( fda < 0 ) { printf("error: A open\n"); return -1; }
if ( write(fda, buf, strlen(buf)) != strlen(buf) ) { //通过strlen计算buf的实际字节长度 printf("error: testA write\n"); close(fda); return -1; }
if ( lseek(fda, 3, SEEK_SET) < 0 ) { printf("error: testA lseek\n"); close(fda); return -1; }
if ( read(fda, msg, 2) < 0 ) { printf("error: testA read\n"); close(fda); return -1; }
msg[2] = '\n'; //为读取到的msg内容最后添加换行符
fdb = open("./testB", O_RDWR | O_CREAT, 0777);
if ( fdb < 0 ) { printf("error: testB open\n"); close(fda); return -1; }
if ( write(fdb, msg, 3) != 3 ) { printf("error: testB write\n"); close(fdb); return -1; }
close(fda); close(fdb); return 0; } 2.编译运行并查看测试结果 $ cat testA //cat查看文件testA的内容 123456 $ cat testB //cat查看文件testB的内容 45
|