IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Linux下读写usb设备的问题

    聂文龙发表于 2015-05-03 15:46:00
    love 0
    急求高手帮忙解决!!!
    我写了一个小程序,功能是在Linux(fedora 7)操作系统下,通过USB读卡器,读、写SD卡某个sector上的512字节的数据,如果能正确写入,会有相应的响应数据,程序如下:

    #define _GNU_SOURCE
    #include
    <stdio.h>
    #include
    <unistd.h>
    #include
    <sys/types.h>
    #include
    <sys/stat.h>
    #include
    <fcntl.h>
    #include
    <stdlib.h>
    #include
    <string.h>

    int main(void)
    {
    int fd,num,loop,tt,i;
    unsigned
    char writeBuf[512] = {0};
    int offset = 0x50000;

    //打开
    fd = open("/dev/sda1",O_RDWR | O_DIRECT);
    //fd = open("/media/SD CARD/system.txt",O_RDWR);

    if(fd==-1)
    {
    printf(
    "can't open the device by device mode !\n");
    return -1;
    }

    //设置
    //fcntl(fd,F_SETFL,O_DIRECT);


    //写入数据内容
    memcpy(writeBuf,"\x55\xAA\xAA\x55",4);

    //写
    tt = lseek(fd,offset,SEEK_SET);
    printf(
    "\n Write lseek %#x\n",tt);
    num
    = write(fd,writeBuf,512);

    if(num==512)
    {
    printf(
    "\n write success!\n");
    num
    = 0;
    }
    if(num==-1)
    {
    printf(
    "write failed!\n");
    close(fd);
    return -1;
    }

    //同步,等待
    sync();
    sleep(
    1);
    memset(writeBuf,
    0x00,512);

    //读
    tt = lseek(fd,offset,SEEK_SET);
    printf(
    "\n Read lseek %#x \n",tt);
    num
    = read(fd,writeBuf,512);

    if(num==512)
    {
    printf(
    "\n read success!\n");
    }
    else
    {
    printf(
    "read failed!\n");
    close(fd);
    return -1;
    }

    //打印响应数据
    for(i = 0; i < 512; i++)
    {
    if((i % 32) == 0)
    printf(
    "\r\n");
    printf(
    "%3x ", writeBuf);
    if(i == 512)
    printf(
    "\r\n\n");
    }

    close(fd);

    return 0;
    }


    目前问题是这样的:如果以O_RDWR | O_DIRECT方式打开设备,则无法写入。如果只以O_RDWR 方式打开,写和读都成功,但是貌似数据没有真正写入,因为读出来的数据和写入的是一样的,我的硬件没问题,肯定应该有响应,有可能是写到缓存里了,读也是从缓存读的。请大家帮忙出谋划策,小弟万分感谢!!!


    聂文龙 2015-05-03 23:46 发表评论


沪ICP备19023445号-2号
友情链接