How to automatically remove certain preprocessors directives and comments from a C header-file?

2024/9/20 10:38:52

What's a good way to remove all text from a file which lies between /* */ and #if 0 and corresponding #endif? I want to strip these parts from C headers. This is the code I have so far:

For line in file:if def0Encountered == 0:  if Line.strip().startswith('#if 0') == True:  Def0StartsAt = Line.find('#if 0')  def0Encountered = 1  if Line.find('#endif')!= -1:  def0Encountered = 0  Def0EndsAt = Line.find('endif')  Line = Line[0:Def0StartsAt] + Line[Def0EndsAt + 2 : ]  List = Line.split()  
Answer

You could use a regular expression to replace the parts of the file you don't want with the empty string (Note, this is very basic, it won't work e.g. for nested macros):

#!/usr/bin/env pythonimport re# uncomment/comment for test with a real file ...
# header = open('mycfile.c', 'r').read()
header = """#if 0whatever(necessary)and maybe more#endif/* * This is an original style comment**/int main (int argc, char const *argv[])
{/* code */return 0;
}"""p_macro = re.compile("#if.*?#endif", re.DOTALL)
p_comment = re.compile("/\*.*?\*/", re.DOTALL)# Example ...
# print re.sub(p_macro, '', header)
# print re.sub(p_comment, '', header)
https://en.xdnf.cn/q/119777.html

Related Q&A

Get all pairs from elements in sublists

I have a list of sublists. I need all possible pairs between the elements in the sublists. For example, for a list like this: a=[[1,2,3],[4,5],[6]]The result should be: result=[[1,4], [1,5], [1,6], [2,…

Extracting variables from Javascript inside HTML

I need all the lines which contains the text .mp4. The Html file has no tag!My code:import urllib.request import demjson url = (https://myurl) content = urllib.request.urlopen(url).read()<script typ…

Pygame, self is not defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Python 3- assigns grades [duplicate]

This question already has answers here:Python 3- Assign grade(2 answers)Closed 8 years ago.• Define a function to prompt the user to enter valid scores until they enter a sentinel value -999. Have …

how to read video data from memory use pyqt5

i have an encrypted video file, i want to decrypt this file into memory and then use this data play video. but qt mediaplayer class is to pass a file name in, i need to have any good way?this is my co…

Pandas apply custom function to DF

I would like to create a brand new data frame by replacing values of a DF using a custom function. I keep getting the following error "ValueError: The truth value of a Series is ambiguous. Use a.e…

Economy Bot Daily Streak

I have a Discord.py economy bot that includes a daily command It gives everyone each day $50, but there is also a streak system. The first time they claim their daily, the bot gives them $50, day 2 is …

Normalise JSON with Python

Prompt me, please, how to normalize this JSON file using Python? This question is related to the previous The current JSON contains: {"total_stats": [{"domain": "domain.com&qu…

How to change decimal separator?

I have an Excel spreadsheet (an extract from SAP). I turn this into a DataFrame, do calculations and save it to an SQLite database. The Excel spreadsheet has comma as decimal separator. The SQLite data…

Unable to scrape the name from the inner page of each result using requests

Ive created a script in python making use of post http requests to get the search results from a webpage. To populate the results, it is necessary to click on the fields sequentially shown here. Now a …