从gpio0/direction正确读取文本的C语言函数demo
时间: 2024-02-20 10:58:48 浏览: 65
C语言实现读取文件 demo
以下是一个从gpio0/direction正确读取文本的C语言函数demo:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
char *read_gpio_direction() {
FILE *fp;
char *buffer = NULL;
char *result = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/sys/class/gpio/gpio0/direction", "r");
if (fp == NULL) {
printf("Failed to open gpio direction file.\n");
return NULL;
}
read = getline(&buffer, &len, fp);
if (read == -1) {
printf("Failed to read gpio direction file.\n");
fclose(fp);
return NULL;
}
result = (char *) malloc(strlen(buffer) + 1);
if (result == NULL) {
printf("Failed to allocate memory.\n");
fclose(fp);
return NULL;
}
strcpy(result, buffer);
free(buffer);
fclose(fp);
return result;
}
int main() {
char *direction = read_gpio_direction();
printf("GPIO direction: %s\n", direction);
free(direction);
return 0;
}
```
这个函数通过打开gpio0/direction文件并使用getline函数读取文件内容,然后使用malloc函数来分配内存并复制读取到的文本。最后关闭文件并返回结果。在主函数中调用这个函数并打印结果。
阅读全文