slurping in binary data

G

George

Right. It's not exactly difficult to take a char ** and a size_t *.

It's difficult enough for me, who is having quite a time disambiguating all
the terms here. Chuck does have a link to your treatment of this material,
right at the bottom of readme.txt.

pg. 263, unleashed
The gets() function takes as its sole arguments a pointer to char.
Starting at that char, it will probably fill memory with data from stdin
until anewline is encountered, at which point gets90 will probably
null-terminate the string and probably return control to its caller. If,
by some miracle, STDIN contains a newline character within the first N
characters, where N is the supplied buffer, you can take the "probably"
from that sentence--for that one call. If there isn't a newline early
enough, gets() will start to trample over memory that it shouldn't be
touching, with undefined results.


If our way to slurp in these data followed roughly the declarations in
Nick's version:

gets (char data[], FILE *in)
{
char buffer [40];
int line_num;


, you wouldn't need the file *in part, because that's stdin. Are you
saying that:

14  100000111011011110000000000000111111111111111111111111111

would screw it up?

--
George

Leadership to me means duty, honor, country. It means character, and it
means listening from time to time.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
G

George

I suspect George is referring to my ggets.c package. This is
available in public domain source form at:

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


#include <stdio.h>
#include <stdlib.h>
#include "ggets.h"

#define INITSIZE 112 /* power of 2 minus 16, helps malloc */
#define DELTASIZE (INITSIZE + 16)

enum {OK = 0, NOMEM};

int fggets(char* *ln, FILE *f)

! end abridged source of ggets.c

If this is to replace the use of gets, what need have you of that file
pointer? The only use of f is in getc(f).
--
George

I believe that God has planted in every heart the desire to live in
freedom.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
G

George

George said:
George wrote:
assuming you mean the twenty lines at the beginning. Would fgets()
followed by

int line_num;
char data[32];

fscanf (line, "%d %32s", &line_num, data);

do the job?
Why fgets before scanf?

Key point to keep in mind here: I was thinking of sscanf(), not fscanf()
(or scanf()). The fgets()/sscanf() combo is the best way I know of to
read most text-format files.

I hadn't even disambiguated these. Am I correct that

scanf
sscanf
fscanf

are the only ones that look like another?
It stops at the first newline or when the buffer you've provided it is
full, or at the end of the file, whichever comes first. The key point is
the "newline" - that's what makes this approach more robust when reading
line-oriented files.

ok

If your input file is perfectly formatted, and your program is correctly
written, there's no need. However, I think it's poor design to write
code that fails catastrophically when given incorrect inputs. I believe
in designing programs so they fail gracefully when given bad input. That
means that they fail without undefined behavior, and with an informative
error message, if possible. It's a lot harder to achieve that goal with
fscanf() than it is with fgets()/sscanf().

What happens if the line number is missing from, for example, line 11?
With fscanf(), it will try to interpret 100000001111100 as a decimal
integer, and store it into the line number (with undefined behavior
unless INT_MAX is larger than that value), and then put "12" into the
data buffer. fscanf() will return a value of 2, indicating a successful
read, because it has no way of noticing that anything went wrong. With
fgets()/sscanf(), you can check whether sscanf()==2; if it does not, you
immediately know there's a problem with the line.

Continuing processing despite a problem like that can be pointless, or
mandatory, or anywhere in between those two extremes, depending upon
your application. If you keep using fscanf(), it would attempt to read
100000001111100 as the line number and put "13" into the data buffer; it
will stay out of sync with the actual lines until the end of the file,
or the next incorrectly formatted line, whichever comes first.

With fgets()/sscanf(), fgets() will start cleanly at the next line, so
sscanf() can do exactly what you need it to do; the combination of those
two functions won't stay out of sync with the data, the way fscanf() would.

#include <stdio.h>
#include <stdlib.h>

#define PATH "george.txt"
#define NUMBER 100
#define BIN 1000
#define MAXFMTLEN 2000

int main(void)
{
FILE *fp;
char pattern[MAXFMTLEN];
char lnumber[NUMBER];
char lbin[BIN];
char line[MAXFMTLEN];

if ((fp = fopen(PATH, "r")) == NULL ) {
fprintf(stderr, "can't open file\n");
exit(1);
}

sprintf(pattern, "%%%ds %%%ds", BIN-1, NUMBER-1);

while ((fgets(line, MAXFMTLEN, fp)) != NULL ) {
sscanf(line, pattern , lnumber, lbin);
/*fscanf (fp, "%d %32s", &lnumber, lbin);*/
printf("%s\n", lbin);
}


Q1) Does the while control satisfy your critism above?

Q2) Why doesn't the sprintf have to *follow* the while?

whitespace crlf
whitespace crlf
1 0001000000000000001
2 0001000000000000001
3 10000011001000000000000001
4 10000011001000000000000001
--
George

If you're sick and tired of the politics of cynicism and polls and
principles, come and join this campaign.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
G

George

Chad said:
But he would would fgets() followed by fscanf(), wouldn't that just
suck in one line at a time vs all 20 lines at once? Here is what I
mean. BTW, I used sscanf() and not fscanf().
[85 lines deleted]


Yikes! I forgot that using internet slang is a no no here. BTW = by
the way.

I don't think BTW is a problem; it's common enough that I think almost
everyone understands it. Silly abbreviations like "u" for "you"
are frowned upon.

But you really didn't need to quote the *entire* previous article to
add a one-line comment.

Chad's fine.

#include <stdio.h>
#include <stdlib.h>

#define PATH "george.txt"
#define NUMBER 100
#define BIN 1000
#define MAXFMTLEN 2000

int main(void)
{
FILE *fp;
char pattern[MAXFMTLEN];
char lnumber[NUMBER];
char lbin[BIN];
char line[MAXFMTLEN];

/*int line_num;
char data[32];*/
// was this an earlier version?

if ((fp = fopen(PATH, "r")) == NULL ) {
fprintf(stderr, "can't open file\n");
exit(1);
}

sprintf(pattern, "%%%ds %%%ds", BIN-1, NUMBER-1);

while ((fgets(line, MAXFMTLEN, fp)) != NULL ) {
sscanf(line, pattern , lnumber, lbin);
/*fscanf (fp, "%d %32s", &lnumber, lbin);*/
printf("%s\n", lbin);
}

fclose(fp);
return 0;
}

// gcc -o x.exe chad1.c

I see no useful distinction between

#define NUMBER 100
#define BIN 1000
, if there were to be meaningful line numbers. The next part of the
process is that I strip away anything that isn't a one or a zero in a range
of columns, so it's no big deal.

I'm a little sketchy about this line,
sscanf(line, pattern , lnumber, lbin);
in particular the meaning of pattern, when there's already a line, an
lnumber and an lbin.

BTW, everyone has equal editorial priveleges. As OP, I'm just more
equal.:)
--
George

Saddam Hussein is a homicidal dictator who is addicted to weapons of mass
destruction.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
G

George

I'll put in a plug for something like the getline() function from glibc.

ssize_t getline (char **LINEPTR, size_t *N, FILE *STREAM);

*LINEPTR should be a pointer to a buffer of size *N obtained from
malloc. If it is not large enough, it's expanded with realloc, and
*LINEPTR and *N are updated appropriately.

It's very easy to write your own version in standard C, of course.
Unfortunately glibc's code is tightly wound in with the rest of their
stdio library, otherwise it could be swiped and used verbatim in a GPL
program.

Are you on gcc's mailing list? How would you do that without having 20
emails a day in a mailbox that gets 2 personal and important emails a week?

gmane?
--
George

Now, there are some who would like to rewrite history - revisionist
historians is what I like to call them.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
N

Nate Eldredge

George said:
Are you on gcc's mailing list? How would you do that without having 20
emails a day in a mailbox that gets 2 personal and important emails a week?

I don't see what that has to do with my post. gcc != glibc. But since
you ask:

- I'm not on the gcc mailing list.
- 20 emails per day is not very many at all, to me.
- A decent mail client will be able to direct those messages to a
separate mailbox.
- The subscription page at http://gcc.gnu.org/lists.html has a "digest"
option, which will bundle everything into one email per day.

That would also work.
 
P

Phil Carmody

George said:
It's difficult enough for me, who is having quite a time disambiguating all
the terms here. Chuck does have a link to your treatment of this material,
right at the bottom of readme.txt.

pg. 263, unleashed
The gets() function takes as its sole arguments a pointer to char.
Starting at that char, it will probably fill memory with data from stdin
until anewline is encountered, at which point gets90 will probably
null-terminate the string and probably return control to its caller. If,
by some miracle, STDIN contains a newline character within the first N
characters, where N is the supplied buffer, you can take the "probably"
from that sentence--for that one call. If there isn't a newline early
enough, gets() will start to trample over memory that it shouldn't be
touching, with undefined results.

Is that a 99.8% verbatim quote, because it looks horrifically mangled?
(I subtract .2%, as I presume 90 was really () sans shift key, and your
whitespace is a bit dodgy.)

Phil
 
C

CBFalconer

George said:
#include <stdio.h>
#include <stdlib.h>
#include "ggets.h"

#define INITSIZE 112 /* power of 2 minus 16, helps malloc */
#define DELTASIZE (INITSIZE + 16)

enum {OK = 0, NOMEM};

int fggets(char* *ln, FILE *f)

! end abridged source of ggets.c

That is YOUR abridgement, not mine.
If this is to replace the use of gets, what need have you of
that file pointer? The only use of f is in getc(f).

Because fggets can read text lines from any file. ggets is a
macro, that supplies stdin as the source file id.
 
N

Nick Keighley

It's difficult enough for me, who is having quite a time disambiguating all
the terms here.  Chuck does have a link to your treatment of this material,
right at the bottom of readme.txt.

Which terms that heve been used in this thread are ambiguous.
ggets() is function written by Chuck. It attempts to "fix"
fgets() (a standard library function). fgets() can only read
up to the specified number of characters. ggets() widens the
buffer used to store the line in as necessary. Richard thinks
that ggets() habbit of allocating a new buffer for every line
is a poor idea and it would be better if the caller passed
a buffer which could be re-sized (hence char**), it would also
return the current size of the buffer (hence the size_t*).

pg. 263, unleashed
The gets() function takes as its sole arguments a pointer to char.
Starting at that char, it will probably fill memory with data from stdin
until anewline is encountered, at which point gets90 will probably
null-terminate the string and probably return control to its caller.  If,
by some miracle, STDIN contains a newline character within the first N
characters, where N is the supplied buffer, you can take the "probably"
from that sentence--for that one call.   If there isn't a newline early
enough, gets() will start to trample over memory that it shouldn't be
touching, with undefined results.

and you problem with that is?
If our way to slurp in these data followed roughly the declarations in
Nick's version:

gets (char data[], FILE *in)
{
    char buffer [40];
    int line_num;

I *never* suggested using gets()! This is not the correct
prototype for gets() only takes one argument (the buffer).
What is buffer for?
, you wouldn't need the file *in part, because that's stdin.

so why did you add it?
Are you saying that:

14  100000111011011110000000000000111111111111111111111111111

would screw it up?

screw what up? This will screw up

char buffer [10];
gets(buffer);

if you type more than 40 characters.

I'm sorry if I haven't given a very clear answer, but you didn't
ask a very clear question!

Are you asking a question about fgets(), gets() (the standard library
one!), ggets(), some version of gets() you made up, the enhanced
version
of ggets() specified by Richard, or something else entirely?
 
J

James Kuyper

George said:
George said:
On Tue, 18 Nov 2008 12:26:05 GMT, James Kuyper wrote:

George wrote:
assuming you mean the twenty lines at the beginning. Would fgets()
followed by

int line_num;
char data[32];

fscanf (line, "%d %32s", &line_num, data);

do the job?
Why fgets before scanf?
Key point to keep in mind here: I was thinking of sscanf(), not fscanf()
(or scanf()). The fgets()/sscanf() combo is the best way I know of to
read most text-format files.

I hadn't even disambiguated these. Am I correct that

scanf
sscanf
fscanf

are the only ones that look like another?

vfscanf
vscanf
vsscanf
swscanf
fwscanf
vfwscanf
vswscanf
vwscanf
wscanf

To decode those names: a prefix of 'f' means that it reads from a
specified file, 's' reads from a character string, and if neither is
present it reads from stdin. A prefix of 'v' means that takes a va_list
argument instead of a variable argument list, and a 'w' means that it
reads from a wchar_t source instead of a char source.

The list of printf() variants is even longer, since it includes things
like snprintf, for which there's no scanf() equivalent.

The math library has a similarly dizzying array of similar names, since
it uses a suffix of 'f' for functions that take float arguments and
produce float results, a suffix of 'l' indicates the use of 'long
double', and a prefix of 'c' indicates a function that works with
complex numbers.

In addition, there's a very confusing array of choices for rounding
numbers <math.h>, which are NOT all named with similar names.

Enjoy!

....
#include <stdio.h>
#include <stdlib.h>

#define PATH "george.txt"
#define NUMBER 100
#define BIN 1000
#define MAXFMTLEN 2000

int main(void)
{
FILE *fp;
char pattern[MAXFMTLEN];
char lnumber[NUMBER];
char lbin[BIN];
char line[MAXFMTLEN];

if ((fp = fopen(PATH, "r")) == NULL ) {
fprintf(stderr, "can't open file\n");
exit(1);

It's more portable to use EXIT_FAILURE. The standard defines what it
means when you use 0, EXIT_SUCCESS, or EXIT_FAILURE; it does not specify
say what an exit status of 1 means.
}

sprintf(pattern, "%%%ds %%%ds", BIN-1, NUMBER-1);

while ((fgets(line, MAXFMTLEN, fp)) != NULL ) {
sscanf(line, pattern , lnumber, lbin);
/*fscanf (fp, "%d %32s", &lnumber, lbin);*/
printf("%s\n", lbin);
}

I would add the following after the loop:

if(ferror(fp))
perror(PATH);
Q1) Does the while control satisfy your critism above?

I prefer

while(fgets(line, MAXFMTLEN, fp) == line)

If fgets() is functioning properly, !=NULL and ==line will produce the
exact same results. However, what if fgets() malfunctions and returns a
value that is neither equal to line nor a null pointer? Your version
treats a fgets() malfunction as a successful return; my version
terminates the loop. The chance that fgets() will malfunction should be
negligible, but so is the cost of using ==line rather than !=NULL.

I apply this logic to any function call that legally can produce only
two different values: I treat anything other than the value that
indicates success as a failure indicator.
Q2) Why doesn't the sprintf have to *follow* the while?

The pattern needs to be created only once, and it needs to be created
before it is used by sscanf(). Putting it inside the while loop would
pointlessly re-execute it during every pass through the loop.
 
G

George


[re-ordered and proofread]
Is that a 99.8% verbatim quote, because it looks horrifically mangled?
(I subtract .2%, as I presume 90 was really () sans shift key, and your
whitespace is a bit dodgy.)

Phil

Yeah, but those mistakes are very much in keeping with the spirit of
unleashed. With dodgy whitespace is the way I've read Richard for years
now. I think the lack of polish comes from the question, "who's going to
proofread it?"

Will such a person know that a (12,4) Hamming code reverses the role of
data bits and parity bits from (12,8)?

When you bring 20 guys together to write a book where each covers his
specialty, are you going to have them do the hardest thing about writing:
heeling to an editor who doesn't really know the subject?

With that Han from China dumbass spouting off on the deficiencies of clc,
unleashed, and the queen of england, I don't feel that right now is the
time for negative criticism.

BTW, I get a pass for my lack of exact typing: there's a piece of metal
strapped into my left palm, and my third and fourth fingers on my right
hand funtion as one.

I think this sentence were better:

"If, by happenstance or assiduous data preparation, ... ."

That my data set was readable by gets didn't seem like a miracle to me.
Some would say that my surviving being run over by a car two weeks ago were
a miracle. I was wearing two layers of clothing, brightly colored, gloves,
and a helmet, that I still wear now that I'm a pedestrian with a cane.
(Same drivers out there.) Preparation counts.

I still say my hail marys though.
--
George

I will never relent in defending America - whatever it takes.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
P

Phil Carmody

George said:

[re-ordered and proofread]

What needed re-ordering? Not my response; my response was correctly
ordered, being after that to which it was a response.

"that" - demonstrative pronoun, refers to something prior.

Your exchange of the two parts of my post has turned me into an
apparent drooling top-poster. Please don't do that.

And I don't think much of your proofreading, you left my post completely
untouched! (Yes, I know what you meant, just disagree where you stuck
the labels.)
Yeah, but those mistakes are very much in keeping with the spirit of
unleashed. With dodgy whitespace is the way I've read Richard for years
now. I think the lack of polish comes from the question, "who's going to
proofread it?"

It's very rare for anything not vanity-press to not get any proof-reading.
Simple bribes of copies of the book to people who proof 1 chapter is
normally enough to get volunteers.
Will such a person know that a (12,4) Hamming code reverses the role of
data bits and parity bits from (12,8)?

When you bring 20 guys together to write a book where each covers his
specialty, are you going to have them do the hardest thing about writing:
heeling to an editor who doesn't really know the subject?

With that Han from China dumbass spouting off on the deficiencies of clc,
unleashed, and the queen of england, I don't feel that right now is the
time for negative criticism.

True, but it's always a good time for precision.
BTW, I get a pass for my lack of exact typing: there's a piece of metal
strapped into my left palm, and my third and fourth fingers on my right
hand funtion as one.

The funky spacing wasn't what I was complaining about. A missing
space is not a horrific mangling, 3 missing words that change the
meaning of the sentence is.
I think this sentence were better:

"If, by happenstance or assiduous data preparation, ... ."

Whilst I agree, I think "where N is the length of the supplied buffer"
is a far better improvement. I like my char*'s to be char*'s, and my
size_t's to be size_t's, and to not combine the two.
That my data set was readable by gets didn't seem like a miracle to me.
Some would say that my surviving being run over by a car two weeks ago were
a miracle. I was wearing two layers of clothing, brightly colored, gloves,
and a helmet, that I still wear now that I'm a pedestrian with a cane.
(Same drivers out there.) Preparation counts.

Sounds like a SMIDSY? Had one of those myself on a bright summer
day too, and my mum was nearly killed by one too a few years back.
One thing that's practically universal here in Finland is wearing
not just bright clothing, but actual reflectors. Having said that,
I've seen 2 cars go past with no lights on in the last few days,
so reflectors would be useless.

Get well and stay well, and don't worry about typos in prose.
Phil
 
C

CBFalconer

Nick said:
Which terms that heve been used in this thread are ambiguous.
ggets() is function written by Chuck. It attempts to "fix"
fgets() (a standard library function). fgets() can only read
up to the specified number of characters. ggets() widens the
buffer used to store the line in as necessary. Richard thinks
that ggets() habbit of allocating a new buffer for every line
is a poor idea and it would be better if the caller passed
a buffer which could be re-sized (hence char**), it would also
return the current size of the buffer (hence the size_t*).

I disapprove of the "fix" description for ggets. It is an
available replacement for fgets and other string input mechanisms,
and should be selected when its characteristics are suitable.

My primary objectives were to make it dead safe, and to simplify
the parameter list as far as possible. It is hard to forget
anything. Yes, you can use it to foul the system. What useful C
routines are proof against that?
 
G

George

[snipped and re-proofread]
And I don't think much of your proofreading, you left my post completely
untouched! (Yes, I know what you meant, just disagree where you stuck
the labels.)

That would be a miracle by american diplomatic standards. I didn't mean
for my posting proclivities to lead anyone to believe you were a drooling
top-poster. I reordered for thematic reasons.

pg. 263, unleashed
The gets() function takes as its sole arguments a pointer to char.
Starting at that char, it will probably fill memory with data from stdin
until a newline is encountered, at which point gets() will probably
null-terminate the string and probably return control to its caller. If,
by some miracle, STDIN contains a newline character within the first N
characters, where N is the [size of the] supplied buffer, you can
take the "probably"
from that sentence--for that one call. If there isn't a newline early
enough, gets() will start to trample over memory that it shouldn't be
touching, with undefined results.

Yeah, but those mistakes are very much in keeping with the spirit of
unleashed. With dodgy whitespace is the way I've read Richard for years
now. I think the lack of polish comes from the question, "who's going to
proofread it?"

It's very rare for anything not vanity-press to not get any proof-reading.
Simple bribes of copies of the book to people who proof 1 chapter is
normally enough to get volunteers.


Then I would have to accuse Heathfield et ali of a lack of sufficient
corruption.
True, but it's always a good time for precision.


The funky spacing wasn't what I was complaining about. A missing
space is not a horrific mangling, 3 missing words that change the
meaning of the sentence is.


Whilst I agree, I think "where N is the length of the supplied buffer"
is a far better improvement. I like my char*'s to be char*'s, and my
size_t's to be size_t's, and to not combine the two.


Sounds like a SMIDSY? Had one of those myself on a bright summer
day too, and my mum was nearly killed by one too a few years back.
One thing that's practically universal here in Finland is wearing
not just bright clothing, but actual reflectors. Having said that,
I've seen 2 cars go past with no lights on in the last few days,
so reflectors would be useless.

Not only was she not looking right while turning right, our coincident four
vectors did not motivate her to reverse her acceleration. Since F=ma and
F* delta time = energy, the only means I had to expend the energy she gave
me while adding injury to insult was by punishing the avenue with it. You
know you're in for something when you have time enough to think, "oh shit,
this is gonna be real."
Get well and stay well, and don't worry about typos in prose.
Phil

Thanks. I've never met a Finn I didn't like. I think the first was at
Brigham Young with the basketball sensation Timo Saarelainen. He was their
best player but no small scandal as he knocked up a cheerleader. He could
jump three feet off the floor.

--
George

It's going to be the year of the sharp elbow and the quick tongue.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
N

Nick Keighley

George said:
On Tue, 18 Nov 2008 00:59:20 -0800 (PST), Nick Keighley wrote:
assuming you mean the twenty lines at the beginning. Would fgets()
followed by
   int line_num;
   char data[32];
   fscanf (line, "%d %32s", &line_num, data);
do the job?
Why fgets before scanf?
Key point to keep in mind here: I was thinking of sscanf(), not fscanf()
(or scanf()). The fgets()/sscanf() combo is the best way I know of to
read most text-format files.

I hadn't even disambiguated these.  

I'm not sure you're using "disambiguate" in a standard fashion
Am I correct that

scanf
sscanf
fscanf

are the only ones that look like another?

as another poster pointed out, no. Though I'd argue they don't "look
like each other". You just have to get used to the fact that (partly
for
historical reasons) the C standard library names are short to the
point
of terse.

Get yourself a good reference to find out what the various function
do.
Try K&R or Harbison and Steele are slightly better (IMHO) on the
standard library. This on-line reference isn't bad
http://www.dinkumware.com/manuals/

<snip>
 
G

George

George wrote:

vfscanf
vscanf
vsscanf
swscanf
fwscanf
vfwscanf
vswscanf
vwscanf
wscanf

To decode those names: a prefix of 'f' means that it reads from a
specified file, 's' reads from a character string, and if neither is
present it reads from stdin. A prefix of 'v' means that takes a va_list
argument instead of a variable argument list, and a 'w' means that it
reads from a wchar_t source instead of a char source.

Yikes. My references appear to be outdated here. I haveno reason to go
with something other than fgets/sscanf for this little project, but since
you've created this list, maybe you could comment on a couple questions.

I'm very interested in c/fortran interop, and one of the things that you
can't call as per F03 is a C function that is variadic.

q1) Which of the above are variadic?

q2) What can a variadic function do that a garden-variety function can't?

Fortran just had its sacred convocation to decide on f08. A report from
this conference reads so:

The Further Interoperability TR is nearly fixed,
with the only controversial question being whether
to include optional value arguments.

q3) Fortran's interop with any other syntax is defined in terms of its
interop with C. Would you guess that the above has to do with variadic
functions?

The list of printf() variants is even longer, since it includes things
like snprintf, for which there's no scanf() equivalent.

The math library has a similarly dizzying array of similar names, since
it uses a suffix of 'f' for functions that take float arguments and
produce float results, a suffix of 'l' indicates the use of 'long
double', and a prefix of 'c' indicates a function that works with
complex numbers.

I'm trying to read similar tea leaves with the slatec library for linear
algebra. They're written in fortran but very callable by C.

I would add the following after the loop:

if(ferror(fp))
perror(PATH);
ok

I prefer

while(fgets(line, MAXFMTLEN, fp) == line)

If fgets() is functioning properly, !=NULL and ==line will produce the
exact same results. However, what if fgets() malfunctions and returns a
value that is neither equal to line nor a null pointer? Your version
treats a fgets() malfunction as a successful return; my version
terminates the loop. The chance that fgets() will malfunction should be
negligible, but so is the cost of using ==line rather than !=NULL.

I apply this logic to any function call that legally can produce only
two different values: I treat anything other than the value that
indicates success as a failure indicator.
ok

The pattern needs to be created only once, and it needs to be created
before it is used by sscanf(). Putting it inside the while loop would
pointlessly re-execute it during every pass through the loop.

I see. In fortran we call this an internal write.

--
George

Do I think faith will be an important part of being a good president? Yes,
I do.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
G

George

George wrote:
On Tue, 18 Nov 2008 00:59:20 -0800 (PST), Nick Keighley wrote:
assuming you mean the twenty lines at the beginning. Would fgets()
followed by
   int line_num;
   char data[32];
   fscanf (line, "%d %32s", &line_num, data);
do the job?
Why fgets before scanf?
Key point to keep in mind here: I was thinking of sscanf(), not fscanf()
(or scanf()). The fgets()/sscanf() combo is the best way I know of to
read most text-format files.

I hadn't even disambiguated these.  

I'm not sure you're using "disambiguate" in a standard fashion

Disambiguate: to establish a single semantic or grammatical interpretation
for.
as another poster pointed out, no. Though I'd argue they don't "look
like each other". You just have to get used to the fact that (partly
for
historical reasons) the C standard library names are short to the
point
of terse.

Get yourself a good reference to find out what the various function
do.
Try K&R or Harbison and Steele are slightly better (IMHO) on the
standard library. This on-line reference isn't bad
http://www.dinkumware.com/manuals/

<snip>

I think Harbison and Steele will be my next C book purchase. (I might
already have it. Makes for a good reason to go through my books.) I wish
I had a nonzero book budget.:-( When Suzy Chang turned my bike and me into
a pretzel, she deprived me of my only licensed means to move my token
forward. With my foot in anatomical position, wedged under her car, my
body was 180 degrees opposite, kissing the asphalt. Go back to go, wait a
year to collect $200.
--
George

You can't put democracy and freedom back into a box.
George W. Bush

Picture of the Day http://apod.nasa.gov/apod/
 
N

Nick Keighley

Yikes.  My references appear to be outdated here.  I haveno reason to go
with something other than fgets/sscanf for this little project, but since
you've created this list, maybe you could comment on a couple questions.

I'm very interested in c/fortran interop, and one of the things that you
can't call as per F03 is a C function that is variadic.  

q1) Which of the above are variadic?

all the ones that don't start with v
q2)  What can a variadic function do that a garden-variety function can't?

take a varible number of arguments
Fortran just had its sacred convocation to decide on f08.  A report from
this conference reads so:

The Further Interoperability TR is nearly fixed,
with the only controversial question being whether
to include optional value arguments.

I've no idea what "optional value arguments" are
q3)  Fortran's interop with any other syntax is defined in terms of its
interop with C.  Would you guess that the above has to do with variadic
functions?

line 42 reverses the polarity of the rabbit
I'm trying to read similar tea leaves with the slatec library for linear
algebra.  They're written in fortran but very callable by C.
what?




I see.  In fortran we call this an internal write.

I don't see why it needs a funny name it same like basic
good programming practice that applies to any programming
language.

<snip>
 
N

Nick Keighley

On Tue, 18 Nov 2008 00:59:20 -0800 (PST), Nick Keighley wrote:
assuming you mean the twenty lines at the beginning. Would fgets()
followed by
   int line_num;
   char data[32];
   fscanf (line, "%d %32s", &line_num, data);
do the job?
Why fgets before scanf?
Key point to keep in mind here: I was thinking of sscanf(), not fscanf()
(or scanf()). The fgets()/sscanf() combo is the best way I know of to
read most text-format files.
I hadn't even disambiguated these.  
I'm not sure you're using "disambiguate" in a standard fashion

Disambiguate: to establish a single semantic or grammatical interpretation
for.

and it what way are the definitions of the scanf() functions
"ambiguous"? I don't think they are ambiguous therefore I don't
think they need disambiguating. Do you simply mean you don't
know what scanf/sscanf/fscanf do?

as a Fortran user I'd thought you'd be used to this!


<snip>
 
J

James Kuyper

You're using "syntax" when the correct term would be "language". I've
seen this in other people's messages too. Is this a dialect issue?
line 42 reverses the polarity of the rabbit

Translation for the OP: you haven't provided Nick with enough
information for him to make an intelligible answer.
I don't see why it needs a funny name it same like basic
good programming practice that applies to any programming
language.

The term "internal write" is used for the Fortran equivalent of
sprintf(), because it writes to a variable internal to a program, rather
than to a file which is external to the program. That term has nothing
directly to do with the fact that the sprintf() call should be placed
prior to the loop instead of being done inside the loop.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,588
Members
45,100
Latest member
MelodeeFaj
Top