Show HN: I always wanted to learn C and make some app in “C”
I always wanted to learn "C" but never found an real-world application of what I cound make. On last Sunday, I needed to measure time of some tasks. So I wrote an terminal "Stopwatch" app.
It's my first application in C programming language, probably it is stupid and not efficient. If you mind, let me know, so I can learn more about C in real world.
https://github.com/ggtd/cstopwatch
3 comments
[ 2.9 ms ] story [ 18.0 ms ] thread- use the _s variants of the string manipulations, since they are safer and protect against buffer overflows, e.g sprintf_s
- perhaps poll more often, but only print when there is a change in the output, e.g. maybe poll every 10 ms and print whenever it passes 1 second
If you want to try to sleep for the exact right amount of time, this is a great opportunity to learn about some more system calls because that's something you often come in contact with when programming in C. Here is an example of how it can be done on Linux...
Before the loop, get the current time in nanosecond precision by using `clock_gettime(CLOCK_REALTIME, &t)`, where t is a `struct timespec` that needs to be declared before the call. Then in the loop (in the end), increment t.tv_sec by one and sleep until that new absolute time by calling `clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &t, NULL)`.
Another thing you can try is to print the exact time at sub-second precision when the user presses ctrl+c. Here you can use clock_gettime again to get the exact time, and to catch the ctrl+c you need to use the `signal(SIGINT, your_ctrl_c_handler_function)` system call.
The point is not in having the completed projects but in learning how to overcome the roadblocks you strike while building those projects to completion.
Your stopwatch isn't accurate? Find out why and fix it.
Your project needs to read and write files in certain directories? Find out about absolute and relative path filenames and how to produce the code for that.
Your project needs to convert between integers, floats, currency values, numbers written in text strings? Find out how that is done.
Your project needs a GUI or a database? Learn about (examples) GTK+ and MYSQL and how to interface your project to those.
You want to make your own computer language interpreter? You can do that in C too.
And many, many more.
The world is your oyster with C. It's only limitations are yours.