Just a Computer Graphics Studio & My Life

先前介紹讀取檔案 (Read File),是以一行一行逐步讀取,現在我們想要一次讀取整個檔案為字串,再來做其它處理,這樣可以怎麼實作呢?

Happy Face JSON.png

這個檔案內容是關於人臉資訊的JSON檔,包含年齡、性別、姿勢、種族、微笑等等量化資訊。

想要讀取整個檔案為字串就靠內建函式,幾行程式碼就能實現!

將檔案放置到專案可以讀取到的位址,在程式碼中設定該檔名:

/**
 Theme: Read Whole File to String
 IDE: Xcode 7
 Language: C++
 Date: 105/04/04
 Author: HappyMan
 Blog: https://cg2010studio.wordpress.com/
 */
#include <iostream>
#include <fstream>

using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
   ifstream inFile;
    inFile.open("HappyFace.json");// Open the input file

    stringstream strStream;
    strStream << inFile.rdbuf();// Read the file
    string string = strStream.str();// string holds the content of the file

    cout << string << endl;// You can do anything with the string
    return 0;
}

編譯執行後列印:

{
  "face": [
    {
      "attribute": {
        "age": {
          "range": 5,
          "value": 29
        },
        "gender": {
          "confidence": 99.9984,
          "value": "Female"
        },
        "glass": {
          "confidence": 99.9052,
          "value": "None"
        },
        "pose": {
          "pitch_angle": {
            "value": 0.000004
          },
          "roll_angle": {
            "value": -6.40648
          },
          "yaw_angle": {
            "value": -0.188313
          }
        },
        "race": {
          "confidence": 99.1486,
          "value": "Asian"
        },
        "smiling": {
          "value": 96.3368
        }
      },
      "face_id": "8afb059d5b0d9defb366432bb34134ea",
      "position": {
        "center": {
          "x": 48.170732,
          "y": 53.536585
        },
        "eye_left": {
          "x": 38.587805,
          "y": 46.830488
        },
        "eye_right": {
          "x": 57.097317,
          "y": 44.752195
        },
        "height": 37.804878,
        "mouth_left": {
          "x": 41.124878,
          "y": 63.946829
        },
        "mouth_right": {
          "x": 59.078293,
          "y": 61.30439
        },
        "nose": {
          "x": 48.540488,
          "y": 56.718049
        },
        "width": 37.804878
      },
      "tag": ""
    }
  ],
  "img_height": 410,
  "img_id": "e42b1354574fe1b52234fb0f88a6edfc",
  "img_width": 410,
  "session_id": "a8b79da2383a45b4a4b08251bd3645ef",
}

接著就可以拿string來做後續處理,比如來剖析(parse)JSON檔,讓我們可以輕易取得內容中的某個key-value

參考:Read whole ASCII file into C++ std::string

廣告

Comments on: "[C++] 讀取整個檔案為字串 (Read Whole File to String)" (1)

  1. […] 接續上一篇文章:讀取整個檔案為字串 (Read Whole File to String),接著我們要將它解析JSON (Parse JSON)。 […]

    按讚數

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: