ansi c - auto clean up ugly code - c

I'm dealing with some code written in manner that is really, honestly, ugly. Is there a way to auto enforce proper tabs and remove all of the random multi-line white space entries?

Old Unix people have a solution for everything, including lazy programmers. Enter GNU indent.

You can use any editor but I would prefer using Vim, with vim you can actually give proper tabs by selecting all the code in visual mode and then '='.
You will also have to set sw=3 for only 3 space equal tab - preferred spacing in most of the code. Also set expandtabs this will ensure the code will look the same as it will replace '\t' with 3 space

Related

Why use `code' for embracing code in a comment?

I just read some glibc 2.22 source code (the source file at /sysdeps/posix/readdir.c) and came across this comment:
/* The only version of `struct dirent*' that lacks `d_reclen' is fixed-size. */
(Newline removed.)
The weird emphasis of the type and identifier bugs me. Why not use just single-quotes or des accents graves? Is there some specific reason behind this? Might it be some character set conversion mistake?
I also searched the glibc style guide but didn't found anything concerning code formatting in comments.
Convention.
As you no doubt know, comments are ignored by the C compiler. They make no difference, but the developer who wrote that comment probably preferred their appearance to plain single quotes.
ASCII
Using non-ASCII characters (unicode) in source code is a relatively new practice (moreso when English-authored source code is concerned), and there are still compatibility issues remaining in many programming language implementations. Unicode in program input/output is a different thing entirely (and that isn't perfect either). In program source code, unicode characters are still quite uncommon, and I doubt we'll see them make much of an appearance in older code like the POSIX header files for some time, yet.
Source code filters
There are some source code filters, such as document generation packages like the the well-known Javadoc, that look for specific comment strings, such as /** to open a comment. Some of these programs may treat your `quoted strings' specially, but that quoting convention is older than most (all?) of the source code filters that might give them special treatment, so that's probably not it.
Backticks for command substutution
There is a strong convention in many scripting languages (as well as StackExchange markdown!) to use backticks (``) to execute commands and include the output, such as in shell scripts:
echo "The current directory is `pwd`"
Which would output something like:
The current directory is /home/type_outcast
This may be part of the reason behind the convention, however I believe Cristoph has a point as well, about the quotes being balanced, similar to properly typeset opening and closing quotation marks.
So, again, and in a word: `convention'.
This goes back to early computer fonts, where backtick and apostrophe were displayed as mirror images. In fact, early versions of the ASCII standard blessed this usage.
Paraphrased from RFC 20, which is easier to get at than the actual standards like USAS X3.4-1968:
Column/Row Symbol Name
2/7 ' Apostrophe (Closing Single Quotation Mark Acute Accent)
6/0 ` Grave Accent (Opening Single Quotation Mark)
This heritage can also be seen in tools like troff, m4 and TeX, which also used this quoting style originally.
Note that syntactically, there is a benefit to having different opening and closing marks: they can be nested properly.

Print Unicode characters in C, using ncurses

I have to draw a box in C, using ncurses;
First, I have defined some values for simplicity:
#define RB "\e(0\x6a\e(B" (ASCII 188,Right bottom, for example)
I have compiled with gcc, over Ubuntu, with -finput-charset=UTF-8 flag.
But, if I try to print with addstr or printw, I get the hexa code.
What I`m doing wrong?
ncurses defines the values ACS_HLINE, ACS_VLINE, ACS_ULCORNER, ACS_URCORNER, ACS_LLCORNER and ACS_LRCORNER. You can use those constants in addch and friends, which should result in your seeing the expected box characters. (There's lots more ACS characters; you'll find a complete list in man addch.)
ncurses needs to know what it is drawing because it needs to know exactly where the cursor is all the time. Outputting console control sequences is not a good idea; if ncurses knows how to handle the sequence, it has its own abstraction for the feature and you should use that abstraction. The ACS ("alternate character set") defines are one of those abstractions.
A few issues:
if your program writes something like "\e(0\x6a\e(B" using addstr, then ncurses (any curses implementation) will translate the individual characters to printable form as described in the addch manual page.
ncurses supports line-drawing for commonly-used pseudo-graphics using symbols (such as ACS_HLINE) which are predefined characters with the A_ALTCHARSET attribute combined. You can read about those in the Line Graphics section of the addch manual page.
the code 0x6a is ASCII j, which (given a VT100-style mapping) would be the lower left corner. The curses symbol for that is ACS_LRCORNER.
you cannot write the line-drawing characters with addstr; instead addch, addchstr are useful. There are also functions oriented to line-drawing (see box and friends).
running in Ubuntu, your locale encoding is probably UTF-8. To make your program work properly, it should initialize the locale as described in the Initialization section of the ncurses manual page. In particular:
setlocale(LC_ALL, "");
Also, your program should link against the ncursesw library (-lncursesw) to use UTF-8, rather than just ncurses (-lncurses).
when compiling on Ubuntu, to use the proper header definitions, you should define _GNU_SOURCE.
BTW, maybe I'm probably arriving somewhat late to the party but I'll give you some insight that might or not shed some light and skills for your "box drawing" needs.
As of 2020 I'm involved in a funny project on my own mixing Swift + Ncurses (under OSX for now, but thinking about mixing it with linux). Apparently it works flawlessly.
The thing is, as I'm using Swift, internally it all reduces to "importing .h and .c" files from some Darwin.ncurses library the MacOS Xcode/runtime offers.
That means (I hope) my newly acquired skills might be useful for you because apparently we're using the very same .h and .c files for our ncurses needs. (or at least they should be really similar)
Said that:
As of now, I "ignored" ACS_corner chars (I can't find them under swift/Xcode/Darwin.ncurses runtime !!!) in favour of pure UTF "corner chars", which also exist in the unicode pointspace, look:
https://en.wikipedia.org/wiki/Box-drawing_character
What does it mean? Whenever I want to use some drawing box chars around I just copy&paste pure UTF-8 chars into my strings, and I send these very strings onto addstr.
Why does it work? Because as someone also answered above, before initializing ncurses with initscr(), I just claimed "I want a proper locale support" in the form of a setlocale(LC_ALL, ""); line.
What did I achieve? Apparently pure magic. And very comfortable one, as I just copy paste box chars inside my normal strings. At least under Darwin.ncurses/OSX Mojave I'm getting, not only "bounding box chars", but also full UTF8 support.
Try the "setlocale(LC_ALL, ""); initscr();" approach and tell us if "drawing boxes" works also for you under a pure C environment just using UTF8 bounding box chars.
Greetings and happy ncursing!

preventing arrow keys's outputing raw characters like ^[[A when making a shell in C

I am implementing a shell-like program where user types command (defined by me). Just like this.
>cmd
result blah blah blah
>
When I use arrow keys it outputs raw characters like ^[[A.
>^[[A
I also notice sqlite3 behaves like this at least in the version I compiled on my computer.
How to prevent this and let <- and -> keys move cursor left and right?
GNU Readline is a library specifically designed for this task (that is, allowing the user to edit commands typed at an interactive command-driven program). Note that this library is distributed under the GPL (not the LGPL); if that won't work for you, editline is a similar library with a BSD-style license.
I note that you say this is homework, so you might want to ask your instructor whether you are expected to implement cursor motion and line editing yourself. If so, ncurses (as mentioned by jDourlens) is the next step down in terms of abstraction, and if you really want to do everything yourself, read up on termios and the VT-220 control sequences (nearly all terminal emulators used nowadays emulate the VT220 or one of its descendants).
I have found a slightly simpler way to do that. Run rlwrap [your program] instead of [your program].
For example, it works fine with sqlite3 as rlwrap sqlite3
To let the user navigate in cmd with the keyboards arrows you may have to use termcaps.
http://www.gnu.org/software/termutils/manual/termcap-1.3/html_chapter/termcap_2.html
If you want to be easier to deal with termcaps that are a bit complex you shoul use Ncurses.
http://www.gnu.org/software/ncurses/ncurses.html
Good luck to deal with termcaps if you chosse this solution, it's some pain in the ass!
You may take a look to Ncurses. It's a library that let you control almost everything in terminals. The specific function you want is noecho(), which stops terminals from showing users' input.

coding style checker for c (variable names, not indentation)

This question asks about a coding style checker, but the focus seems to be on indentation and brace placement. GNU indent deals with indentation (which isn't a problem in this code base, amazingly enough).
I'm working with a pile of code that is full of various naming schemes: camelCase, everythingruntogetherinlowercase, underscores_as_separators, SomeStructsEndWithT, etc.
I'd like to be able to pick a convention and at least have an automatic check that new changes are in line with the convention.
Is there a good tool for checking naming in C? Something like Python's pep8 checker tool, I don't want a beautifier.
Thanks.
It looks like Google's cpplint (a C++ style checker) can be hacked into submission for checking C like I want.
(I'm still interested in knowing if there are any better checkers out there.)
It is an unorthodox choice, but I'd go with cxref, if you are willing to put in half a days work. It is a cross referencer, comes with the source code, it has a clean parser and doesn't build a parse tree. Yet, with a few lines of code you can dump all the variables to examine them, or rewrite them to your favoured style (or if you are as lazy as I am instead of rewriting you could generate replace commands for emacs/sed). I only managed to build it for Mac.
This one has a number of answers already in this thread Coding style checker for C
from which Vera++ might be the most promising, since most of the other suggestions are formatters not validators. There's a webpage about running vera++ at
https://bitbucket.org/verateam/vera/wiki/Running.
There's a download from https://bitbucket.org/verateam/vera/downloads/vera++-1.1.1.tar.gz
Compiling presents a few issues:
sudo apt-get install libboost-dev tcl-dev
An include of tcl.h that should have been tcl/tcl.h
Need a full boost src tree, like that from http://sourceforge.net/projects/boost/files/boost/1.53.0/boost_1_53_0.tar.gz/download
The build command becomes something like: make BOOST_DIR=/home/fluffy/tmp/boost_1_53_0
vera++ needs a ~/.vera++/profiles/ but doesn't autocreate a default (it can be copied from the one in the distribution, however)
Finally, running it on a C++ file produced output like (with duplicate errors omitted for brevity):
../dllist.c:1: no copyright notice found
../dllist.c:4: horizontal tab used
../dllist.c:10: horizontal tab used
../dllist.c:10: closing curly bracket not in the same line or column
../dllist.c:29: horizontal tab used
../dllist.c:38: keyword 'if' not followed by a single space
../dllist.c:38: negation operator used in its short form
../dllist.c:40: horizontal tab used
../dllist.c:40: full block {} expected in the control structure
../dllist.c:42: horizontal tab used
../dllist.c:71: keyword 'if' not followed by a single space
../dllist.c:71: negation operator used in its short form
../dllist.c:72: horizontal tab used
../dllist.c:72: full block {} expected in the control structure
../dllist.c:73: horizontal tab used

More Control Over C Standard Output

I can't seem to find the right way to ask the almighty google...
In such programs as a command-line progress bar, the output buffer seems to be directly manipulated. It can't print a character to a terminal in any place it wants. How is such control over a program's output controlled in standard C? Is there a special library that I can look up?
look at curses
it`s a lib for unix/linux
If you just want a progress bar, you can just print a single 'X' for every 2% completion. This should fill 50 characters on a line.
If you want something more fancy, on Linux you can try the classic "curses" library, or if you just want a dialog box, you could try the library that the Debian install utilities use, but I forget its name.
you can do the progress bar with \r check this
for doing more advanced stuff you can use ncurses
It's not part of standard C. These things work by writing some special character sequences that are recognized by the terminal emulator which takes care of the cursor positioning and stuff.
The big gorilla here is the ncurses library, but you can do a lot of cool stuff with less learning curve. Try using \r to move to beginning of line and using simple control sequences to clear to end of line, turn bold on and off, etcetera. The tput(1) command is invaluable. For example, I wrote a simple application the does highlighted text, and to turn highlighting on and off I just called the commands tput smso and tput rmso. You can capture the results using C with popen(3); using a shell it is even easier.
You could use ANSI escape coding to control the termincal output. This is how a lot of MUD games do their output.

Resources