急求高手幫忙解決!!!
我寫了一個(gè)小程序,功能是在Linux(fedora 7)操作系統(tǒng)下,通過(guò)USB讀卡器,讀、寫SD卡某個(gè)sector上的512字節(jié)的數(shù)據(jù),如果能正確寫入,會(huì)有相應(yīng)的響應(yīng)數(shù)據(jù),程序如下:
#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;
//打開(kāi)
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;
}
//設(shè)置
//fcntl(fd,F_SETFL,O_DIRECT);
//寫入數(shù)據(jù)內(nèi)容
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;
}
//打印響應(yīng)數(shù)據(jù)
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;
}
目前問(wèn)題是這樣的:如果以O(shè)_RDWR | O_DIRECT方式打開(kāi)設(shè)備,則無(wú)法寫入。如果只以O(shè)_RDWR 方式打開(kāi),寫和讀都成功,但是貌似數(shù)據(jù)沒(méi)有真正寫入,因?yàn)樽x出來(lái)的數(shù)據(jù)和寫入的是一樣的,我的硬件沒(méi)問(wèn)題,肯定應(yīng)該有響應(yīng),有可能是寫到緩存里了,讀也是從緩存讀的。請(qǐng)大家?guī)兔Τ鲋\劃策,小弟萬(wàn)分感謝!!!
posted on 2015-05-03 23:46
聶文龍 閱讀(1142)
評(píng)論(0) 編輯 收藏 引用