473,320 Members | 1,854 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,320 software developers and data experts.

Return type of "readin" and correct error handling

Greetings, I know it's usually a bad habit to include several questions in a
single message, but they are quite related.

I have declared and defined a function named readin, whose purpose is to get
input from stdin and save the result in a character array (provided the
input does not exceed the maximum limit). Somehow it feels natural that
readin will then have the type "char *" and return the obtained input to
whoever calls it (or rather, the address of the first element?). Such as
this:

char *readin();

However, in case anything goes wrong readin should be able to return an
error code to the function that called it.

I "solved" the problem with the following declaration of readin:

int readin (char *);

Which makes it possible to return -1, and the function that calls readin
always tests the return value in an if-clause. From my brief and
incomprehensible explanation, does this look like an acceptable solution -
or are there better, standardized ways to perform error testing? I'm new to
C and am therefore trying to pick up as few bad habits as possible.
Jun 17 '07 #1
11 1849
On Sun, 17 Jun 2007 10:02:18 GMT, Victor Lagerkvist wrote:
>However, in case anything goes wrong readin should be able to return an
error code to the function that called it.

I "solved" the problem with the following declaration of readin:

int readin (char *);

Which makes it possible to return -1, and the function that calls readin
always tests the return value in an if-clause. From my brief and
incomprehensible explanation, does this look like an acceptable solution -
or are there better, standardized ways to perform error testing? I'm new to
C and am therefore trying to pick up as few bad habits as possible.
Compare your solution to Microsoft's (it's just a comparison of
interfaces, not the off-topic discussion of a non C-Standard library):
BOOL ReadFile(
HANDLE hFile,
LPVOID lpBuffer,
DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead,
LPOVERLAPPED lpOverlapped
);

http://msdn2.microsoft.com/en-us/library/aa365467.aspx
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Jun 17 '07 #2
Victor Lagerkvist said:

<snip>
>
char *readin();

However, in case anything goes wrong readin should be able to return
an error code to the function that called it.

I "solved" the problem with the following declaration of readin:

int readin (char *);

Which makes it possible to return -1, and the function that calls
readin always tests the return value in an if-clause.
How does readin() know how much data it can safely store in the buffer
whose first byte is pointed to by its parameter?
From my brief
and incomprehensible explanation, does this look like an acceptable
solution - or are there better, standardized ways to perform error
testing? I'm new to C and am therefore trying to pick up as few bad
habits as possible.
My own strategy is much like yours - I generally return an int error
code from my functions, unless they are object-creating functions, in
which case I return either a pointer to the new object or NULL if the
object could not be created.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 17 '07 #3
Victor Lagerkvist wrote:
>
.... snip ...
>
I "solved" the problem with the following declaration of readin:

int readin (char *);

Which makes it possible to return -1, and the function that calls
readin always tests the return value in an if-clause. From my
brief and incomprehensible explanation, does this look like an
acceptable solution - or are there better, standardized ways to
perform error testing? I'm new to C and am therefore trying to
pick up as few bad habits as possible.
Sounds good. In fact, it is almost exactly what ggets does, which
returns EOF for EOF, 0 for good operation, and something positive
for i/o error. See:

<http://cbfalconer.home.att.net/download/>

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Jun 17 '07 #4
Richard Heathfield wrote:
How does readin() know how much data it can safely store in the buffer
whose first byte is pointed to by its parameter?
I currently use #define to specify the largest amount of allowed characters.
Jun 17 '07 #5
Victor Lagerkvist wrote:
>
Richard Heathfield wrote:
How does readin() know how much data it can
safely store in the buffer
whose first byte is pointed to by its parameter?

I currently use #define to specify
the largest amount of allowed characters.
In that case, you can use fscanf.
/* BEGIN fscanf_input.c */
/*
** There are only three different values
** that can be assigned to the int variable rc
** from the fscanf calls in this program;
** They are:
** EOF
** 0
** 1
** If rc equals EOF, then the end of file was reached,
** or there is some other input problem;
** ferror and feof can be used to distinguish which.
** If rc equals 0, then an empty line
** (a line consisting only of one newline character)
** was entered, and the array contains garbage values.
** If rc equals 1, then there is a string in the array.
** Up to LENGTH number of characters are read
** from a line of a text stream
** and written to a string in an array.
** The newline character in the text line is replaced
** by a null character in the array.
** If the line is longer than LENGTH,
** then the extra characters are discarded.
*/
#include <stdio.h>

#define LENGTH 40
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
int rc;
char array[LENGTH + 1];

puts("The LENGTH macro is " xstr(LENGTH) ".");
do {
fputs("Enter any line of text to continue,\n"
"or just hit the Enter key to quit:", stdout);
fflush(stdout);
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
if (rc == 0) {
array[0] = '\0';
}
if (rc == EOF) {
puts("rc equals EOF");
} else {
printf("rc is %d. Your string is:%s\n\n", rc, array);
}
} while (rc == 1);
return 0;
}

/* END fscanf_input.c */

--
pete
Jun 17 '07 #6
Victor Lagerkvist <pl*******@gmail.comwrites:
Richard Heathfield wrote:
>How does readin() know how much data it can safely store in the
buffer whose first byte is pointed to by its parameter?

I currently use #define to specify the largest amount of allowed
characters.
Ok.

You said "currently". Does that imply that you might later want it to
be more flexible, allowing the maximum size to vary for each call? If
so, you should consider allowing for that in the interface now.

On the other hand, perhaps the size will always be fixed, or perhaps
you'll want to allocate the space dynamically.

There are lots of possibilities. It can be helpful to anticipate any
changes and nail down the interface early, but that's not always
possible.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 17 '07 #7
Keith Thompson wrote:
Victor Lagerkvist <pl*******@gmail.comwrites:
>Richard Heathfield wrote:
>>How does readin() know how much data it can safely store in the
buffer whose first byte is pointed to by its parameter?

I currently use #define to specify the largest amount of allowed
characters.

Ok.

You said "currently". Does that imply that you might later want it to
be more flexible, allowing the maximum size to vary for each call? If
so, you should consider allowing for that in the interface now.
Yes... I'm pondering whether or not it is a good idea to save all user input
in an array for future references. In that case it would be neat if the
stored arrays weren't larger than the sentences they hold (currently every
array have place for the largest amount of allowed characters, which might
be wasteful if the backlog is big). Would it suffice to first get the user
input and save it in a "big" array and then copy it's content in a smaller
one of the same size as the number of characters the user entered? It
doesn't seem perfect, but I can't think of anything else since it's
impossible to tell how huge the input is beforehand.
Jun 19 '07 #8
Victor Lagerkvist said:
It doesn't seem perfect, but I can't
think of anything else since it's impossible to tell how huge the
input is beforehand.
The trick is to resize as you go.

How you do this is up to you - you can go for simple, or flexible, or
anything in between.

Here are four quite different approaches to the problem, all with full C
source code.

My own fgetline() - borders on the flexible:
http://www.cpax.org.uk/prg/writings/fgetdata.php

Chuck Falconer's ggets() - simple but unbending:
http://cbfalconer.home.att.net/download/ggets.zip

Morris Dovey's rather strangely recursive gline():
http://www.iedu.com/mrd/c/getsm.c

Eric Sosman's hide-it-all-away getline() function:
http://www.cpax.org.uk/prg/portable/...sman/index.php

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 19 '07 #9
Richard Heathfield wrote:
>
Victor Lagerkvist said:
It doesn't seem perfect, but I can't
think of anything else since it's impossible to tell how huge the
input is beforehand.

The trick is to resize as you go.

How you do this is up to you - you can go for simple, or flexible, or
anything in between.

Here are four quite different approaches to the problem, all with full C
source code.

My own fgetline() - borders on the flexible:
http://www.cpax.org.uk/prg/writings/fgetdata.php

Chuck Falconer's ggets() - simple but unbending:
http://cbfalconer.home.att.net/download/ggets.zip

Morris Dovey's rather strangely recursive gline():
http://www.iedu.com/mrd/c/getsm.c

Eric Sosman's hide-it-all-away getline() function:
http://www.cpax.org.uk/prg/portable/...sman/index.php
Hey, I've got one too!

http://www.mindspring.com/~pfilandr/...ine/get_line.c

.... and, it has 2 siblings:

http://www.mindspring.com/~pfilandr/...ne/get_delim.c
http://www.mindspring.com/~pfilandr/...t_delimeters.c

--
pete
Jun 23 '07 #10
pete said:
Richard Heathfield wrote:
>>
<snip>
>>
Here are four quite different approaches to the problem, all with
full C source code.
<snip>
Hey, I've got one too!
Added to:

http://www.cpax.org.uk/prg/writings/...ta.php#related

if that's okay with you. (If not, I can always rip it out again.)

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 23 '07 #11
Richard Heathfield wrote:
>
pete said:
Richard Heathfield wrote:
>
<snip>
>
Here are four quite different approaches to the problem, all with
full C source code.
<snip>
Hey, I've got one too!

Added to:

http://www.cpax.org.uk/prg/writings/...ta.php#related

if that's okay with you. (If not, I can always rip it out again.)
It's very OK.
Thank you.

--
pete
Jun 23 '07 #12

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

Similar topics

13
by: Dave Smithz | last post by:
Hi there, I have a php script that does some form input validation. As it verifies each field if the field has incorrect data, it appends an error message to an $error array. E.g. if...
2
by: Luis | last post by:
the assignment is to count the number of words in a txt file here is my code #include <iostream> #include <fstream> #include <cassert> using namespace std; int main () {
15
by: Matthew Jakeman | last post by:
can anyone tell me why the following piece of code causes a segmentation fault please ?? char *getFNFromIden(char *ident) { int i = 0 ; printf("identifier %s\n", allMenus.identifier) ;...
2
by: Fatih BOY | last post by:
Hi, I want to send a report from a windows application to a web page like 'report.asp' Currently i can send it via post method with a context like local=En&Username=fatih&UserId=45&Firm=none...
3
by: zhi lin | last post by:
hi, guys I am doing a c program which need me to print out the error message during the file input, suppose we need to read in a struct { int pid; char *name; char *skill; }
2
by: gj_williams2000 | last post by:
Not sure if this is the right board but it is in c... I've got a console program written in c which receives key presses and gets a Windows Virtual key code. I am trying to convert it to the...
7
by: Mark Waser | last post by:
Hi all, I'm trying to post multipart/form-data to a web page but seem to have run into a wall. I'm familiar with RFC 1867 and have done this before (with AOLServer and Tcl) but just can't seem...
6
by: Rylios | last post by:
I am trying to make a very basic text editor using a linked list, fstream, sorting... This is what i have so far...
3
by: George Orwell | last post by:
hay, Han frm china heer again... ben readin sum more c unleashed book dick heathfields book... still readin dick heathfields data structs cht but jumped ahead to chad dixons cgi proggraming cht...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.