473,770 Members | 1,778 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(vo id)
{
struct termios new_settings;
tcgetattr(0, &stored_setting s);
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_setting s);
return;
}

void
reset_keypress( void)
{
tcsetattr(0, TCSANOW, &stored_setting s);
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 2140
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(vo id)
{
struct termios new_settings;
tcgetattr(0, &stored_setting s);
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_setting s);
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_setting s);
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.l earn.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_ta lk/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*****@despamm ed.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*******@spam cop.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
1398
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 done??? Many thanks Ann Ottawa Canada **************** <HTML>
2
3895
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 http://home.pacific.net.sg/~jacksony ? (the drop down bar could not work at www.apchosting.net but can drop at home.pacific.net.sg. I suspect it is a server problem but was told it is not possible, therefore assuming it is a client script problem? the script works last time...
77
4039
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 goto sometimes makes program some more cleaner and easy to understand and also quite useful (in error handling cases). So why goto is outlawed from civilized c programmers community. is there any technical inefficiency in that.
17
2540
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 operator overloading and virtual functions. I mean it should not hamper the C++ meaning. In frank and simple terms i need to implement a small C++ compiler in C++, and i want the intermediate representation to be C. Please help me in this....
38
2734
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 then the SEGMENTATION FAULT is occuring. Please tell me what are all the cases this problem may occur if we use strcpy().
23
2803
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 place a link on there site so people can vote for their program, "ad a click". eg someone clicks the link on some page and it counts +1 click on my page. if some one clicks the link below it will count a click on my page.
0
5576
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 ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
5
1813
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 section, category n content is public. All of them are public and published. No clue why super admin can't edit the frontend content.
4
2028
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 code document.getElementById('bgrp1').style.visibility='hidden'; document.getElementById('lable_rp_no1').style.display='none'; document.getElementById('rp_no1').style.display='hidden'; the code for the html part is here
0
10257
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10099
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8931
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.