急求高手幫忙解決!!!
我寫了一個小程序,功能是在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
聶文龍 閱讀(1142)
評論(0) 編輯 收藏 引用