Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Can python take in a C array (from a file) and does some processing on it? For example, say I have a C header containing:

static char bin[] = {...}; // whole bunch of hex values

Can I write a python script to count how many bytes are there in the array? The reason I want to do this is I have about ~100 of these headers and some of them have the same array names, so I can't include all of these and sizeof each one.
Any suggestion on what should I look into? Doesn't have to be python but I feel like this is the right tool.

Thanks!

share|improve this question

2 Answers 2

This Perl one-liner may help, if array initializers do not span multi-lines:

perl -lne '($p)=($_=~/static char bin\[\] = \{([^}]*)\}/) and
      $p=~s/[^,]*//g; print length($p)' input.h
share|improve this answer
    
unfortunately they do.. they're about several hundreds lines each, but thanks anyways I could try to tweak this a little bit –  lzt May 31 '13 at 17:01

Here's an attempt at a python version:

If the values in each array are comma separated, you could try the following:

import glob

#get all the headers in the current directory
headers = glob.glob("*.h")

for header in headers:
    fp = open(header, "r")
    for line in fp.readlines():
        if line.startswith("static char"):
            bits = line.split(",")
            count = len(bits)-1
            print "Found array starting %s"%bits[0]
            print "containing %d bytes"%count
            print "in file %s"%header

This makes a few assumptions like the comma separation, and just prints out what it finds - what you do with the information is up to you - this wasn't clear in the question

share|improve this answer
    
I guess, regular expression will be better here. Your solution will fail for static char function(), static char b[] = {1, 2, 3} /* , , */ and multiline definitions. Also your solution gives incorrect output for static char b[] = {1, 2, 3}; - containing 2 bytes. –  soon May 31 '13 at 2:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.