Reading GPIO value using ofstream

Feb 12, 2019 at 6:32pm
I would like to know if it is possible to read a GPIO value using ofstream. Or maybe I wouldn't have to use ofstream? I know how to set a GPIO value:

1
2
3
4
5
6
7
8
9
10
11
const char *const amplifierGPIO = "/sys/class/gpio/gpio107/value";

 void amplifierMute()
    {
      std::ofstream amp(amplifierGPIO);
      if (amp.is_open())
      {
        amp << "0";
        amp.close();
      }
    }


However, what if I want to read the GPIO's value and say use it as the argument to an if statement or more simply, just print it.
Last edited on Feb 12, 2019 at 6:33pm
Feb 12, 2019 at 6:38pm
If you want to read a file, use std::ifstream amp(amplifierGPIO);

1
2
3
4
5
6
7
8
9
10
{
    std::ifstream amp(amplifierGPIO);
    if (amp.is_open())
    {
        int data; // or perhaps a string?
        amp >> data;
        // use data
    }
}
// C++ streams close automatically when destroyed 
Last edited on Feb 12, 2019 at 6:39pm
Feb 12, 2019 at 6:49pm
@Ganado Ah I see, awesome thank you!
Topic archived. No new replies allowed.