1. 程式人生 > >讀寫sd卡代碼分析(vivado sdk c++)

讀寫sd卡代碼分析(vivado sdk c++)

adf obj 基本數據 rect 原型 love you 直接 lseek ace

void ReadFloatsFromSDFile(float *weightsFromFile, const std::string file_name) 
{
    FIL fil;        /* File object */
    FATFS fatfs;
    FILINFO file_info;
    char *SD_File;
    FRESULT Res;
    UINT NumBytesRead;

    Res = f_mount(&fatfs, "0:/", 0);
    if (Res != FR_OK) printf( "Could not mount SD card.");

    //printf("SD Card Mounted successfully\n");
    SD_File = (char *)file_name.c_str();

    Res = f_open(&fil, SD_File, FA_READ | FA_OPEN_EXISTING);
    if (Res) throw Res;
    //printf("FILE Opened successfully\n");

    Res = f_lseek(&fil, 0);
    if (Res) throw "Failed to seek opened file.";



    Res = f_stat(SD_File, &file_info);
    //DWORD fil_size = file_info.fsize+1;

    //printf("Size: %u\n",file_info.fsize);
    Res = f_stat(SD_File, &file_info);
    //DWORD fil_size = file_info.fsize+1;
    for(int i = 0; i < 51902; i++) {

        float number;
        Res = f_read(&fil, &number, sizeof(number), &NumBytesRead);
        if (Res) throw "Failed to read file.";
        //if(i==49154)printf("the first weight value is %.2f\n", number);
        weightsFromFile[i] = number;
        //weightsFromFile[i+1] = number[2];


    }
  1. const: const 類型的對象在程序執行期間不能被修改改變。
  2. 這個函數需要weightsFromFile和存在sd卡中的file_name。
  3. 命名空間
    這裏std::string file_name前面的std是為了指明命名空間,因為很多函數可能在很多的庫中出現,指明了之後就不會引起混亂。
    簡單的說,命名空間是為了防止沖突而建立的。比如你在命名空間a聲明一個方法c,在命名空間b也聲明一個方法c,那麽在使用的時候就可以通過a::c和b::c來分別調用兩個方法。
    使用命名空間的語句是:using namespace [命名空間的名稱]
    一旦使用了這個語句,你就可以直接寫該命名空間的方法名,比如:
    using namespace std; // 使用std命名空間
    cout << "xxx" << endl; // 你還是可以寫成std::cout << "xxx" << std::endl;的
    延伸幾點:
  • 這裏還有一點,使用標準函數庫
  • endl為換行符,‘‘std::cout<<"love you"<<endl;``
    "endl"與"\n"的區別是"endl"還調用輸出流的flush函數,刷新緩沖區,讓數據直接寫在文件或者屏幕上。
  1. std:string
    之所以拋棄char*的字符串而選用C++標準程序庫中的string類,是因為他和前者比較起來,不必擔心內存是否足夠、字符串長度等等,而且作為一個類出現,他集成的操作函數足以完成我們大多數情況下(甚至是100%)的需要。我們可以用 = 進行賦值操作,== 進行比較,+ 做串聯(是不是很簡單?)。我們盡可以把它看成是C++的基本數據類型。
    詳情:http://blog.csdn.net/debugconsole/article/details/8677313

main.cc

float *weightsFromFile = (float *) malloc(numOfParameters*sizeof(float));
int *test_labels = (int *) malloc(10000 * sizeof(int));
std::vector<std::vector<float> > test_images;
int correctPrediction;
  1. malloc
    float *weightsFromFile = (float *) malloc(numOfParameters*sizeof(float));
    此句為分配numOfParameters個float型變量。
    函數原型是void *malloc(unsigned int num_bytes);
    但是void型不能賦值給float/int,因此要用(float *)強制轉換。
    sizeof(float)為float型變量的字節。

  2. std::vector<std::vector<float> > test_images;

讀寫sd卡代碼分析(vivado sdk c++)