1

I am trying to read following file from C code.

file: /sys/bus/iio/devices/iio\:device0/in_voltage7_raw

but file pointer I am getting is -1.

Using cat command it is able to read the file.

But I am trying to read the same from my code as follows:

nos_int32 nos_adc_read_port (ADC_PORT_DB *p_port, nos_int32 *data)
{

    char file_name[VALUE_MAX];
    int value;
    char buffer[BUFFER_LENGTH];
    char intBuffer[INT_BUFFER_LENGTH];
    int fd;

    sprintf(file_name, "/sys/bus/iio/devices/iio\\:device0/in_voltage7_raw");

    fd = open(file_name, O_RDONLY);

    if (fd == -1) {
        return(-1);
    }
    if (read(fd, buffer, BUFFER_LENGTH) == -1) {
        return(-1);
    }
    close(fd);
    memcpy(intBuffer, buffer, BUFFER_LENGTH);
    intBuffer[INT_BUFFER_LENGTH-1] = '\0';
    value = atoi(intBuffer);
    *data = value;
    return(0);
}

After the line: fd = open(file_name, O_RDONLY);

value of fd is -1. How can it be solved?

Paul R
  • 208,748
  • 37
  • 389
  • 560

1 Answers1

3

Most command line shells use some characters for special actions and if you're trying to use them as their actual character, you need to prefix them with a backslash to escape them. In this case, your shell needs you to escape the colon when accessing that filename.

In C you don't have this issue so you can put in your code the filename as it truly is, such as:

"/sys/bus/iio/devices/iio:device0/in_voltage7_raw"

Chris Turner
  • 8,082
  • 1
  • 14
  • 18
  • Backslash is included to escape the backslash in the file name. Actual file name is: /sys/bus/iio/devices/iio\:device0/in_voltage7_raw – Aneeshya Rose Dec 09 '17 at 07:15
  • No, the actual file name is `/sys/bus/iio/devices/iio:device0/in_voltage7_raw`, as pointed out in this answer; there is no backslash in the file name, so you don't have to escape anything in your C string. – Francesco Lavra Oct 30 '18 at 16:01