C application test code for reading any Sysfs file in Linux

 $ vim readsysfs.c 
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define print_error \
	do { \
		fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
		__LINE__, __FILE__, errno, strerror(errno)); exit(1); \
	} while(0)

int main(int argc, char **argv)
        char buf[1024];
        ssize_t len;
        int fd;
	char *filename;

	if(argc < 2) {
		fprintf(stderr, "\nUsage:\t%s { sysfs file }\n", argv[0]);

	filename = argv[1]; /* accept argument 1 as filename */

        fd = open(filename, O_RDONLY);
        if (fd < 0) {
		fprintf(stderr, "open %s: %s\n", filename, strerror(errno));

        len = read(fd, buf, sizeof(buf)-1);
        if (len < 0) {
                fprintf(stderr, "read %s: %s", filename, strerror(errno));

        buf[len] = 0;
	printf("%s : %s\n", filename, buf);

#if 0
	printf("bufferlen is %d\n", strlen(buf));
	return 0;
 $ vim Makefile 
CFLAGS=-Wall -g

main: sysfsread

        rm -f *.o *~
 $ make 

$ ./sysfsread /sys/bus/usb/devices/usb1/manufacturer

Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question