随笔 - 298  文章 - 377  trackbacks - 0
<2015年5月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(34)

随笔分类

随笔档案

文章档案

相册

收藏夹

搜索

  •  

最新评论

阅读排行榜

评论排行榜

急求高手帮忙解决!!!
我写了一个小程序,功能是在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 方式打开,写和读都成功,但是貌似数据没有真正写入,因为读出来的数据和写入的是一样的,我的硬件没问题,肯定应该有响应,有可能是写到缓存里了,读也是从缓存读的。请大家帮忙出谋划策,小弟万分感谢!!!
posted on 2015-05-03 23:46 聂文龙 阅读(1113) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理