0

I am running this command

cat /proc/devices/memory/events/pcie0_read

in my code (c application). This is my code

#include<stdio.h>
#include<stdlib.h>

void main()

{

system(" cat /proc/devices/memory/events/pcie0_read ");

}

and the output of this command is

fidt=0x12,dtw=0x33,id=0x67

I want to extract only values from the command output using same c application.

I want to extract only 0x336712 only and save this value in an variable from the above command output.

for ex:

char var[100] or unsigned int var;

After extracting from command output I should get it,

var=0x336712

How do I do that???

5
  • 3
    On a POSIX system (such as linux) use popen() instead of system(). Commented Apr 28, 2021 at 7:11
  • use strtok(), first with , as delimiter, then =. Commented Apr 28, 2021 at 7:12
  • According to the tags you seem to think of a solution based on running awk and/or sed. Of course it is possible to extract values this way, but this can be easily implemented in C without running external programs. The declaration of the variable var as a char array doesn't match the assignment of a hexadecimal integer value. Please edit your question and add more details what you want to do with the values. Do you need at the end a string "0xff2006" or an (unsigned) int value 0xff2006 or individual values 0x06, 0x02, 0xff? Commented Apr 28, 2021 at 7:23
  • Not necessary char array.I just need to extract 0xff2006 from the command output and store it in an variable and variable can be unsigned int.....whatever you said is correct ...I need unsigned int value 0xff2006 Commented Apr 28, 2021 at 7:29
  • Please edit your question and add all requested information or clarification to the question. Don't use comments for this purpose. Explaining some background about what you want to do with the resulting value might help us to suggest the best solution. Commented Apr 28, 2021 at 11:14

1 Answer 1

1

Unless you really need to run external commands, you may want to read the /proc/... directly just like any ordinary files. Also, fscanf function is quite versatile enough to avoid complicated string parsing.

#include <stdio.h>
int main() {
        unsigned int fidt, dtw,id;

        FILE *f = fopen("/proc/devices/memory/events/pcie0_read", "r");
        fscanf(f, "fidt=%x,dtw=%x,id=%x", &fidt, &dtw, &id);
        fclose(f);

        printf("output: 0x%x\n", (id << 32) | (dtw << 16) | fidt);
        return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

printf("output: 0x%02x%02x%02x\n", portid&0xFF, evtype&0xFF, event&0xFF);
The file name and the resulting data has been changed in the question, so the answer should be adapted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.