I'm try to use system("echo 1 > /sys/class/afile") to set a file to 1.
If I use it on console it works well, but if I run my C program it shows me:
sh: echo: I/O error
I already try to set it with following code:
char i[1];
i[0]=1;
int fd1 = open("/sys/class/afile",O_CREAT | O_WRONLY);
int ret = write(fd1,i,strlen(i));
if(ret > 0)
printf("Ok\n");
else
printf("nOk\n");
close(fd1);
The result is "Ok" but the file didn't change.
strlen(i)
yields undefined behavior because i
is not a string; the array lacks room for null termination. Also, i[0]=1;
does not put a '1'
character in the array, but rather puts a byte with value 1, which is a "^A
character".
Instead try write(fd, "1", 1)
- no need for any variables or strlen
.