473,387 Members | 1,512 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Help regarding Programming Style

Hi all,

I have implemented a timing out version of fgets function call. I am
pasting the entire code below. I have following doubts:

1. The code which I have written does it follow standard C programming
conventions. ( I am pretty familar with java styles but not with c :-(
).

2. In order to read character by character from stdin , I have made use
of termios.h function calls is it as standard portable way of doing it
or is there any other better way. I have tested it with freebsd 6.0 it
seems to work fine. Btw I got the code to do it from net
(http://www.macdonald.egate.net/CompSci/hkeyinp3.html)

3. Now is my code thread-safe?

Thanks for being so patient and please help me inorder to be a
efficient/better c-programmer.

----

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <setjmp.h>
#include <string.h>
#include <termios.h>
jmp_buf mybuf;
static void
sig_alrm(int signo)
{
longjmp(mybuf, 1);
return;
}

static struct termios stored_settings;

void
set_keypress(void)
{
struct termios new_settings;
tcgetattr(0, &stored_settings);
new_settings = stored_settings;
//setting buffer to 1 byte
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW, &new_settings);
return;
}

void
reset_keypress(void)
{
tcsetattr(0, TCSANOW, &stored_settings);
return;
}

char *
tgets(char *str, int size, FILE * stream, int nsec)
{
char *mytempchar;
int i = 0;
int ch;

mytempchar = (char *)malloc(sizeof(char) * size);
if (fileno(stream) == fileno(stdin))
set_keypress();

if (setjmp(mybuf) == 1)
goto done;
signal(SIGALRM,sig_alrm);
alarm(nsec);
while (i <= size - 1) {
ch = getc(stream);
if (ch != EOF) {
if (ch != '\n') {
mytempchar[i] = (char)ch;
i = i + 1;
} else
break;
}
}
done:
if (i == 0)
mytempchar = NULL;
else
mytempchar[i] = 0;
//printf("The gotten string is %s\n", mytempchar);
str = mytempchar;
reset_keypress();
return mytempchar;

}

int
main(void)
{
char *mystring;
int maxlen = 256;
FILE *myfile;
myfile = fopen("gen.txt","r");
mystring = (char *)malloc(sizeof(char) * maxlen);
//printf("Enter the Input String :::: ");
//mystring = tgets(mystring,maxlen,stdin,5);
mystring = tgets(mystring, maxlen,myfile , 5);
printf("%s\n", mystring);
return 0;
}
----

Regards
Sreekanth Ramakrishnan

Apr 17 '06 #1
4 2118
On 17 Apr 2006 15:55:05 -0700, "Sreekanth"
<sr********************@gmail.com> wrote in comp.lang.c:
Hi all,

I have implemented a timing out version of fgets function call. I am
pasting the entire code below. I have following doubts:

1. The code which I have written does it follow standard C programming
conventions. ( I am pretty familar with java styles but not with c :-(
).
There are no "standard C programming conventions", although this group
has a convention, namely that it discusses the standard C language, as
defined by any version of the ANSI/ISO C language standard, or by the
original de facto standard, the first edition of Kernighan & Richie's
"The C programming Language".
2. In order to read character by character from stdin , I have made use
of termios.h function calls is it as standard portable way of doing it
or is there any other better way. I have tested it with freebsd 6.0 it
seems to work fine. Btw I got the code to do it from net
(http://www.macdonald.egate.net/CompSci/hkeyinp3.html)
"termios" is not part of the standard C language, instead it is a non
standard extension provided by your compiler and operating system
combination, that makes it off-topic here. It needs to be discussed
in a group that supports that combination, in your case I would
suggest news:comp.unix.programmer.

Even though it is off-topic here, you are completely wrong about
termios reading from stdin. It does no such thing. Instead it uses
platform-specific methods to read from a hardware device that need not
have any connection at all to stdin or any other C stream.
3. Now is my code thread-safe?
That's another off-topic question here, because the C language does
not define nor support multiple threads of execution. Even if your
program used absolutely nothing but completely standard C, the
language does not specify whether it is thread safe or not.

Again you need to ask about this in a group like
news:comp.unix.programmer.
Thanks for being so patient and please help me inorder to be a
efficient/better c-programmer.

----

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <setjmp.h>
#include <string.h>
#include <termios.h>
The fcntrl.h and termios.h are not part of standard C.
jmp_buf mybuf;
static void
sig_alrm(int signo)
{
longjmp(mybuf, 1);
return;
}
According to the C standard, your program above has undefined
behavior. C does not define the results of calling longjmp(), or
indeed most other library functions, in a signal handler.

Also, your signal handling function is not invoked by a call to
raise() in your program. If you expect some mechanism outside your
program, such as your OS, to invoke the signal handler, that is
something else C does not define.
static struct termios stored_settings;

void
set_keypress(void)
{
struct termios new_settings;
tcgetattr(0, &stored_settings);
new_settings = stored_settings;
//setting buffer to 1 byte
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW, &new_settings);
return;
}
Every single line of the function above is off-topic here, exec pt for
the final return statement, which is not needed.
void
reset_keypress(void)
{
tcsetattr(0, TCSANOW, &stored_settings);
return;
}

char *
tgets(char *str, int size, FILE * stream, int nsec)
{
char *mytempchar;
int i = 0;
int ch;

mytempchar = (char *)malloc(sizeof(char) * size);
Don't cast the return value of malloc() in C.
if (fileno(stream) == fileno(stdin))
set_keypress();
There is no fileno() function in the standard C library, that is
another one of your platform's non-standard extensions.
if (setjmp(mybuf) == 1)
goto done;
signal(SIGALRM,sig_alrm);
alarm(nsec);
while (i <= size - 1) {
ch = getc(stream);
if (ch != EOF) {
if (ch != '\n') {
mytempchar[i] = (char)ch;
i = i + 1;
} else
break;
}
}
done:
if (i == 0)
mytempchar = NULL;
else
mytempchar[i] = 0;
//printf("The gotten string is %s\n", mytempchar);
str = mytempchar;
reset_keypress();
return mytempchar;

}

int
main(void)
{
char *mystring;
int maxlen = 256;
FILE *myfile;
myfile = fopen("gen.txt","r");
mystring = (char *)malloc(sizeof(char) * maxlen);
//printf("Enter the Input String :::: ");
//mystring = tgets(mystring,maxlen,stdin,5);
mystring = tgets(mystring, maxlen,myfile , 5);
printf("%s\n", mystring);
return 0;
}


You need to take this question to news:comp.unix.programmer, there is
far too much non-standard stuff and undefined behavior for standard C>

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Apr 18 '06 #2
Sreekanth wrote:
1. The code which I have written does it follow standard C programming
conventions. ( I am pretty familar with java styles but not with c :-(
).
I'd suggest you read the file Documentation/CodingStyle in the Linux kernel
sources, and also take a quick look at
<http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/>.

In all fairness, there is no defined standard style. I use the Linux Kernel
style because it looks sane to me, and I find it easy to read. Everyone has
their own preference. Just be consistent in whatever style you choose to use.

If you use the Linux kernel coding style, there's a script in scripts/Lindent
that calls GNU Indent to automatically indent your source code for you (this
goes back to 'consistency'.
2. In order to read character by character from stdin , I have made use
of termios.h function calls is it as standard portable way of doing it
or is there any other better way. I have tested it with freebsd 6.0 it
seems to work fine. Btw I got the code to do it from net
(http://www.macdonald.egate.net/CompSci/hkeyinp3.html)
I'm not 100% sure about this, but I think termios is POSIX-specific. You can
use 'getc' and 'putc', which are in stdio.h and are defined by the ANSI C
standard (and have been part of C since the pre-ANSI days of K&R standard C).
3. Now is my code thread-safe?


I have absolutely no idea - I've never done multi-threaded development.

--
Phil. | Kitsune: Acorn RiscPC SA202 64M+6G ViewFinder
ph*****@despammed.com (valid!)| Cheetah: Athlon64 3200+ A8VDeluxeV2 512M+100G
http://www.philpem.me.uk/ | Tiger: Toshiba SatPro4600 Celeron700 256M+40G
No software patents! <http://www.eff.org/> / <http://www.ffii.org/>
Apr 20 '06 #3
> I'm not 100% sure about this, but I think termios is POSIX-specific. You can
use 'getc' and 'putc', which are in stdio.h and are defined by the ANSI C
standard (and have been part of C since the pre-ANSI days of K&R standard C).
Yes, termios.h is required by 2001 POSIX.1 version, and so it's
portable across POSIX operating systems.
3. Now is my code thread-safe?


Well, at first one should always assume that in general a source is
_not_ thread safe. Thre's a preprocessor directive, namely #define
_REENTRANT that flags the proprocessor to use reentrant versions of
the functions if they are available (a reentrant function, for
instance, may be called multiple times overlaping in time and in an
asynchrounous fashion, like threads do often). Look that this is not a
warranty of reentrance, and so a judicious check of _each_ function
call is needed to place this statement safely.

Apr 20 '06 #4
In article <kh********************************@4ax.com>, Jack Klein
<ja*******@spamcop.net> writes
On 17 Apr 2006 15:55:05 -0700, "Sreekanth"
<sr********************@gmail.com> wrote in comp.lang.c:
Hi all,

I have implemented a timing out version of fgets function call. I am
pasting the entire code below. I have following doubts:

1. The code which I have written does it follow standard C programming
conventions. ( I am pretty familar with java styles but not with c :-(
).


There are no "standard C programming conventions",


Yes there are...... dozens of them. Virtually every company has a C
coding standard to a style guide or a mixture of the two.

Interestingly the MISRA C++ team grabbed every C++ guide it could find
for a quick comparison and found that the virtually all of them had a
large part that was common.

I expect the same is true of C coding standards.

However as Les Hatton pointed out recently there is a lot of received
wisdom in these things with no empirical evidence to support them.
--
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills Staffs England /\/\/\/\/
/\/\/ ch***@phaedsys.org www.phaedsys.org \/\/\
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

Apr 21 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Ann Duguay | last post by:
Hi there! Newbie here... :-) I'm trying to validate a form but can't seem to get it to work... Here's a copy of the code: The user has to select a color for every select box. How is this...
2
by: Jackson Yap | last post by:
can someone kind enough to help me look at the attached html and js file? Why is it that the javascript menu could not work at www.apchosting.net but could work at...
77
by: M.B | last post by:
Guys, Need some of your opinion on an oft beaten track We have an option of using "goto" in C language, but most testbooks (even K&R) advice against use of it. My personal experience was that...
17
by: Student | last post by:
Hi All, I have an assignment for my Programming language project to create a compiler that takes a C++ file as input and translate it into the C file. Here I have to take care of inheritance and...
38
by: edu.mvk | last post by:
Hi I am using strcpy() in my code for copying a string to another string. i am using static char arrays. for the first time it is exected correctly but the second time the control reaches...
23
by: casper christensen | last post by:
Hi I run a directory, where programs are listed based on the number of clicks they have recieved. The program with most clicks are placed on top and so on. Now I would like people to be apple to...
0
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted...
5
by: dannynnad | last post by:
Hi, SuperAdministrator when trying to edit the frontend content the following error is comingup: "You are not authorized to view this resource." I checked from the backend whether the...
4
omerbutt
by: omerbutt | last post by:
hi there i am amking an inventory application with php,ajax,javascript,html,dhtml,sql the problem is that i have hidden the input fields regarding the replace no's of the parts with this line of...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.