I'm going to read "comm" file in each directory of /proc . My program can see list of directory, but when I try to open folder in this directory I get an error. My system is Debian Linux hardware Beaglebone Black. I'm learning programming under linux so I have a lot of questions (stupid sometimes).
list of code:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
int main()
{
char path[50] = {0};
register struct dirent *dirbuf;
char* dirname = "/proc";
DIR *fdir;
fdir = opendir(dirname);
if (NULL == fdir)
{
printf("Can't open %s\n", dirname);
return;
}
while(( dirbuf = readdir(fdir)) != NULL)
{
if ((strcmp(dirbuf->d_name, ".") == 0)||(strcmp(dirbuf->d_name, "..") == 0))
{
continue;
}
printf("folder name: %s\n", dirbuf->d_name);
strcat(path, dirbuf->d_name);
strcat(path, "/comm");
printf("path: %s\n", path);
int fd = open(path, O_RDONLY);
if ( -1 == fd)
{
printf("Can't open file %s\n", path);
}
else
{
//read file
close(fd);
}
memset(path, 0, strlen(path) + 1); //clear path buffer
}
closedir(fdir);
return 0;
}
Log from linux console:
You need to use the full path to open the file. ie: /proc/PID/comm
instead of PID/comm
.
You can use something like this to format the path:
char* path[PATH_MAX];
snprintf(path, PATH_MAX, "/proc/%s/comm", dirbuf->d_name);
To format the path appropriately.