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]);
		exit(1);
	}

	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));
		print_error;
        }

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

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

#if 0
	printf("bufferlen is %d\n", strlen(buf));
#endif
        
	close(fd);
	return 0;
}
 $ vim Makefile 
CC=gcc
#CC=arm-linux-gcc
CFLAGS=-Wall -g

main: sysfsread

clean:
        rm -f *.o *~
 $ make 

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

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply