• 正文
  • 相关推荐
申请入驻 产业图谱

飞凌嵌入式ElfBoard-系统IO接口之练习

11/04 15:00
251
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

通过前面的简单概念和基本系统IO接口的介绍,可以尝试写一个简单程序,需求如下:

创建文件testA,向testA写入123456,创建文件testB,将testA中3后面的2字节长度内容拷贝到文件B中。

1.示例

#include <stdio.h>

#include <stdlib.h>

#include <string.h>            //strlen的头文件

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <unistd.h>

int main()

{

int fda, fdb;

char msg[3];      //虽然只读取2字节长度内容

//但是可以在最后添加一个换行符方便查看

char buf[30] = "123456n";

fda = open("./testA", O_RDWR | O_CREAT | O_TRUNC, 0777);

if ( fda < 0 ) {

printf("error: A openn");

return -1;

}

if ( write(fda, buf, strlen(buf)) != strlen(buf) ) {  //通过strlen计算buf的实际字节长度

printf("error: testA writen");

close(fda);

return -1;

}

if ( lseek(fda, 3, SEEK_SET) < 0 ) {

printf("error: testA lseekn");

close(fda);

return -1;

}

if ( read(fda, msg, 2) < 0 ) {

printf("error: testA readn");

close(fda);

return -1;

}

msg[2] = 'n';                     //为读取到的msg内容最后添加换行符

fdb = open("./testB", O_RDWR | O_CREAT, 0777);

if ( fdb < 0 ) {

printf("error: testB openn");

close(fda);

return -1;

}

if ( write(fdb, msg, 3) != 3 ) {

printf("error: testB writen");

close(fdb);

return -1;

}

close(fda);

close(fdb);

return 0;

}

2.编译运行并查看测试结果

$ cat testA                 //cat查看文件testA的内容

123456

$ cat testB                 //cat查看文件testB的内容

45

相关推荐