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

No. of 'a' in a text file

/* I wrote the following program to calculate no. of 'a' in the file
c:/1.txt but it fails to give appropriate result. What is wrong with
it? */

#include"stdio.h"
int main(void)
{
FILE *f;
char ch;
long int a=0;
f=fopen("c:/1.txt","r");
while(ch=getc(f)!=EOF)
{
switch(ch)
{
case 'a': a++;break;
}
}
printf("No. of 'a' = %d\n",a);
fclose(f);
return 0;
}

Apr 21 '07
77 2535
On Apr 22, 10:13 pm, Keith Thompson <k...@mib.orgwrote:
"Alf P. Steinbach" <a...@start.nowrites:
[...]
And when you're not doing that ungood thing, writing FILE* f makes sense.
There I disagree. If you're going to have declarations of any
significant complexity, you need to understand why C declaration are
the way they are (declaration follows use).
Except that declaration follows use went out of C the day
typedef's were introduced. And struct's, and all the rest. C's
declaration syntax is an experiment which failed. The basic
idea, applied to the very earliest C, seems interesting (and as
an experiment, was certainly worth doing), but it doesn't scale
properly once users start defining types.
With that understanding,
"FILE *f" just makes more sense.
FILE *f; /* *f is a FILE */
int a[10] /* a[10] is an int (or would be if it existed */
And what do you do once typedefs and user defined struct's enter
into the picture:

typedef int* Toto ;
Toto t ;
struct MyStruct s ;

or from an actual program I wrote (about 20 years ago):

struct T
{
// ...
struct V* (*f[ 8 ])( struct V* ) ;
} ;
struct T a[] = {...} ;
, use:
s = (*p[i]->f[j])( s ) ;

Any relationship between use and definition seems very tenuous,
at best.

There is an argument based on grouping: at the very highest
level, a declaration breaks down into a declaration specifier
and a declarator; the * is part of the declarator. But on the
whole, I think it's just a lot cleaner to think in terms of the
resulting types: conceptually, I'm not declaring *p to be an
int, I'm declaring p to be an int*.
But in simple cases like "FILE *f" / "FILE* f", it isn't all that big
a deal. Declaring it as "FILE* f" implies that f is a FILE* -- which
happens to be true in this case, but the principle doens't extend to
other forms of declarations. As long as you can keep it straight,
I'll still *prefer* to keep the "*" next to the identifier, but I can
cope with other styles.
You have to, if you're going to work in C or in C++:-). The
declaration syntax is a disaster, but it has to be learned and
lived with. I use Type*, rather than Type *, because that's
what is most frequent in C++, but I don't have any illusions
that one or the other miraculously make the declaration syntax
readable to a beginner.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 23 '07 #51
On Apr 22, 4:26 pm, Richard Heathfield <r...@see.sig.invalidwrote:
Gianni Mariani said:
Richard Heathfield wrote:
Nor, alas, did gcc like it very much:
...
Try naming the file with a .cpp (C++ extension) and compiling it with
a C++ compiler.
No, thank you. If I want C++, I know where to find it - but I don't
expect to find it in comp.lang.c.
The original posting (and all of the follow-ups) have been cross
posted to both comp.lang.c and comp.lang.c++. So it's hard to
know what sort of solution the original poster wanted: C or C++.
I know that I'd use different solutions in the two languages.

Anyway, Gianni cross-posted a C++ solution to comp.lang.c,
probably unintentionally, and now you're bitching that it isn't
C in comp.lang.c++, probably unintentionally as well.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 23 '07 #52
On Apr 23, 6:58 am, "Default User" <defaultuse...@yahoo.comwrote:
Francine.Ne...@googlemail.com wrote:
What on earth possessed you to send this to comp.lang.c? Do you
realize that C != C++?
See what I said to Richard. It's wildly unfair to expect other people
to anticipate what's topical regarding other groups in a cross-posted
message, or to refrain from giving replies that are perfectly correct
and topical for their group.
It's also very unrealistic to expect other people to notice the
cross-posting.
It's the fault of the OP, but that doesn't matter. It would have been
helpful for the clc++ people to cut clc out the their replies, but none
of the clc did that either, so there's plenty of blame to go around.
I suspect that many people would have done so if they'd have
noticed. I only noticed the cross-posting by chance; the
original code seems somewhat more idiomatic for C than for C++,
so I responded in that vein (although I believe I did mention
that in C++, better solutions were available). But I'm reading
this in clc++, and had I not noticed the cross-posting, I'd
probably have posted much more C++'ish.

And of course, I'm old enough that it is fun to go back to the
more primitive days of my youth. To the good old days, when men
were men, women were women, and pointers were ints:-).

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 23 '07 #53
On Apr 22, 6:00 pm, "Army1987" <please....@for.itwrote:
"Bruce !C!+" <aaniao...@163.comha scritto nel messaggionews:11**********************@e65g2000hsc .googlegroups.com...
my be it will like this,
while(ch=getc(f)!=EOF)-----------while(ch=getc(f)&&ch!=EOF)
{ //do something
It'll stop if it hits a null character.
Try while((ch = getc(f) != EOF)
Why not:

int ch,count=0;
while((ch=getc(f))=='a'?++count:ch!=EOF);

Since the goal seems to be as unreadable as possible.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 23 '07 #54
Default User wrote, On 22/04/07 22:35:
Richard Heathfield wrote:
>Gianni Mariani said:
>>Richard Heathfield wrote:
Gianni Mariani said:

Richard Heathfield wrote:
>Nor, alas, did gcc like it very much:
...
>
Try naming the file with a .cpp (C++ extension) and compiling it
with a C++ compiler.
No, thank you. If I want C++, I know where to find it - but I don't
expect to find it in comp.lang.c.

Then stop posting to comp.lang.c++
I'm reading this in comp.lang.c, where you posted off-topic C++ code.
Please don't do that again. Thank you.

I'm sorry Richard, but you're just way off-base here. When messages are
cross-posted like that, you can't use your own group's topicality to
override the other's.
Nor can others use their topicality to override that of comp.lang.c.
When it is cross posted, if posting something not topical in all the
groups then at least followups (if not the entire message) should be
redirected to the subset of groups where the post is topical.

This, of course, is also an example of why cross-posting between
comp.lang.c and comp.lang.c++ is rarely a good thing, since the best C++
solution is often not valid C.
--
Flash Gordon
Apr 23 '07 #55
Flash Gordon wrote:
....
>
Nor can others use their topicality to override that of comp.lang.c.
When it is cross posted, if posting something not topical in all the
groups then at least followups (if not the entire message) should be
redirected to the subset of groups where the post is topical.

This, of course, is also an example of why cross-posting between
comp.lang.c and comp.lang.c++ is rarely a good thing, since the best C++
solution is often not valid C.
Not all valid C is valid C++ either.
Apr 23 '07 #56
Gianni Mariani said:
Flash Gordon wrote:
...
>>
Nor can others use their topicality to override that of comp.lang.c.
When it is cross posted, if posting something not topical in all the
groups then at least followups (if not the entire message) should be
redirected to the subset of groups where the post is topical.

This, of course, is also an example of why cross-posting between
comp.lang.c and comp.lang.c++ is rarely a good thing, since the best
C++ solution is often not valid C.

Not all valid C is valid C++ either.
Quite so. In fact, a surprisingly small amount of good C is valid C++.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 23 '07 #57
Umesh wrote:
>
/*Calculate the no. of occurance of 'ab'. But is this one OK/
EFFICIENT?*/
#include<stdio.h>
int main(void)
{
FILE *f;
long int c,c1,ab=1;
f=fopen("c:/1.txt","r");
while ((c=getc(f))!=EOF && (c1=getc(f))!=EOF) {
if(c=='a' && c1=='b') ab++;}
fclose(f);
printf("No. of 'ab' = %ld\n",ab);
return 0;
}
In addition to the other comments, consider what happens if the
file contains:

abababababab
or
xabababababab

What will your code give as the count for each of the above?

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>
Apr 23 '07 #58
Richard Heathfield wrote:
Default User said:
He complained about your posts being off-topic?

No, he used the topicality of C++ in comp.lang.c++ to override
comp.lang.c's topic, which is C, not C++.
He answered in a way that was topical for his group. Very likely he
didn't notice that it was even cross-posted. However, he didn't take
that extra step to chastise someone else for "off-topic" posting for
something that was perfectly topical where another was reading and
responding.

If you failed to notice that it was cross-posted when you complained
about the topicality, then that's certainly understandable. If not,
then as I said you're out of line.
I must have missed that.

I must have missed the point where this discussion got very dull, but
I'm sure we have passed it by now.
Well, I'm done with it from this point. If you feel like a last
thought, I'll read it with interest but won't be responding (outside of
a direct question or change of direction).

Brian
Apr 23 '07 #59
On Apr 23, 5:04 pm, "Default User" <defaultuse...@yahoo.comwrote:
Richard Heathfield wrote:
Default User said:
He complained about your posts being off-topic?
No, he used the topicality of C++ in comp.lang.c++ to override
comp.lang.c's topic, which is C, not C++.

He answered in a way that was topical for his group. Very likely he
didn't notice that it was even cross-posted. However, he didn't take
that extra step to chastise someone else for "off-topic" posting for
something that was perfectly topical where another was reading and
responding.

If you failed to notice that it was cross-posted when you complained
about the topicality, then that's certainly understandable. If not,
then as I said you're out of line.
It seems to me that there's this difference: although the OP
crossposted, every reply up to that point had included only C code.
When there was a post full of C++, it jumped out immediately reading
it in clc. So I'd assume that if I'd been reading it in clc++ then all
the posts full of C would similarly have jumped out at me, and I'd
either have killed the thread (if my newsreader had that function) or
been alerted to the fact that it had probably been crossposted.
I must have missed that.
I must have missed the point where this discussion got very dull, but
I'm sure we have passed it by now.

Well, I'm done with it from this point. If you feel like a last
thought, I'll read it with interest but won't be responding (outside of
a direct question or change of direction).

Brian

Apr 23 '07 #60
James Kanze <ja*********@gmail.comwrites:
On Apr 22, 5:58 pm, "Army1987" <please....@for.itwrote:
[...]
>Anyhow, I'd write FILE *f rather than FILE* f, or else when you
write FILE* f, g you'll be surprised by results.

Every coding guideline I've ever seen has forbidden defining
more than one variable per statement. It's just bad programming
practice. Other than that, it's mostly a matter of taste. I
find it cleaner to separate the type from what is being defined.
How do you manage that for arrays?

[...]
>On the DS9K,
exit(2) makes the program securely erase the whole disk on exit.
The standard way to do that is exit(EXIT_FAILURE);

And the Unix way is exit(2).
It is?

<OT>
On Unix-like systems, EXIT_FAILURE is typically defined as 1. exit(0)
denotes success, and exit(1) commonly indicates some generic failure.
I know of no widespread convention for exit codes other than 0 and 1;
they tend to be defined individually for each command. One command,
curl, documents 76 distinct error codes.
</OT>

The C standard's exit(0), exit(EXIT_SUCCESS), and exit(EXIT_FAILURE)
are quite compatible with Unix conventions.

--
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"
Apr 23 '07 #61
James Kanze <ja*********@gmail.comwrites:
On Apr 22, 10:13 pm, Keith Thompson <k...@mib.orgwrote:
>"Alf P. Steinbach" <a...@start.nowrites:

[...]
And when you're not doing that ungood thing, writing FILE* f makes sense.
>There I disagree. If you're going to have declarations of any
significant complexity, you need to understand why C declaration are
the way they are (declaration follows use).

Except that declaration follows use went out of C the day
typedef's were introduced. And struct's, and all the rest. C's
declaration syntax is an experiment which failed. The basic
idea, applied to the very earliest C, seems interesting (and as
an experiment, was certainly worth doing), but it doesn't scale
properly once users start defining types.
>With that understanding,
"FILE *f" just makes more sense.
> FILE *f; /* *f is a FILE */
int a[10] /* a[10] is an int (or would be if it existed */

And what do you do once typedefs and user defined struct's enter
into the picture:
FILE is a typedef.
typedef int* Toto ;
I wouldn't declare a typedef for a pointer type unless I wanted to
make it opaque (so code using the type doesn't know it's a pointer).
Toto t ;
But if I did, the above would still ollow the declaration-follows-use
model: t is a Toto.
struct MyStruct s ;
And s is a "struct Mystruct".
or from an actual program I wrote (about 20 years ago):

struct T
{
// ...
struct V* (*f[ 8 ])( struct V* ) ;
} ;
struct T a[] = {...} ;
, use:
s = (*p[i]->f[j])( s ) ;

Any relationship between use and definition seems very tenuous,
at best.
Perhaps, but I think the underlying principle is still there. I'm too
lazy to wade through that declaration -- and I'm not *really* trying
to defend C's declaration syntax.
There is an argument based on grouping: at the very highest
level, a declaration breaks down into a declaration specifier
and a declarator; the * is part of the declarator. But on the
whole, I think it's just a lot cleaner to think in terms of the
resulting types: conceptually, I'm not declaring *p to be an
int, I'm declaring p to be an int*.
Which breaks down for

int a[10];

which, if C *didn't* use declaration-follows-use, would probably be:

int[10] a; /* not C 8/
>But in simple cases like "FILE *f" / "FILE* f", it isn't all that big
a deal. Declaring it as "FILE* f" implies that f is a FILE* -- which
happens to be true in this case, but the principle doens't extend to
other forms of declarations. As long as you can keep it straight,
I'll still *prefer* to keep the "*" next to the identifier, but I can
cope with other styles.

You have to, if you're going to work in C or in C++:-). The
declaration syntax is a disaster, but it has to be learned and
lived with. I use Type*, rather than Type *, because that's
what is most frequent in C++, but I don't have any illusions
that one or the other miraculously make the declaration syntax
readable to a beginner.
My preference for "type *obj" rather than "type* obj" is probably
largely based on the fact that that's what I've always been exposed
to. If I had been exposed to "type* obj", I'd likely be making the
same arguments you are. But my preference is also based in part on
having the spacing reflect the way it's actually defined by the syntax
and parsed by the compiler. De gustibus yadda yadda.

--
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"
Apr 23 '07 #62
Keith Thompson wrote:
James Kanze <ja*********@gmail.comwrites:
On Apr 22, 10:13 pm, Keith Thompson <k...@mib.orgwrote:
"Alf P. Steinbach" <a...@start.nowrites:
[...]
And when you're not doing that ungood thing, writing
FILE* f makes sense.
There I disagree. If you're going to have declarations of any
significant complexity, you need to understand why C declaration are
the way they are (declaration follows use).
Except that declaration follows use went out of C the day
typedef's were introduced. And struct's, and all the rest.
[...]
or from an actual program I wrote (about 20 years ago):
struct T
{
// ...
struct V* (*f[ 8 ])( struct V* ) ;
} ;
struct T a[] = {...} ;
, use:
s = (*p[i]->f[j])( s ) ;
Any relationship between use and definition seems very tenuous,
at best.
Perhaps, but I think the underlying principle is still there.
The underlying principle remains at the base of the original
concept. The problem is that as the type system has become more
complex, the underlying principle simply doesn't work any more.
It was an interesting experiment, one definitly worth doing, if
only to see what the repercussions were, but it turns out that
what the experiment proved was that it wasn't a good idea.
I'm too
lazy to wade through that declaration -- and I'm not *really* trying
to defend C's declaration syntax.
My only point is that the use doesn't look anything like the
declaration. As long as you stick to the basic types, pointers
and arrays (which is all there was in the earliest versions of
C), it does, and the declaration syntax actually works fairly
well. As soon as you start throwing in typedef's, struct's and
what have you, it stops working. And the declaration doesn't
follow use.
There is an argument based on grouping: at the very highest
level, a declaration breaks down into a declaration specifier
and a declarator; the * is part of the declarator. But on the
whole, I think it's just a lot cleaner to think in terms of the
resulting types: conceptually, I'm not declaring *p to be an
int, I'm declaring p to be an int*.
Which breaks down for
int a[10];
And for a lot of other cases. I know.
which, if C *didn't* use declaration-follows-use, would probably be:
int[10] a; /* not C 8/
Java went that way. It turns out (based on my experience with
Java), that it doesn't really work much better.

If C hadn't started with declaration-follows-use, the syntax
might have been something like:

array [10] int : a ;

or even:

var a: array[10] of int ;

[...]
My preference for "type *obj" rather than "type* obj" is probably
largely based on the fact that that's what I've always been exposed
to. If I had been exposed to "type* obj", I'd likely be making the
same arguments you are.
Probably. I know that I was exposed to the "type* obj" format
very early in my days of C---I forget from where---and have used
it ever since, even before learning C++. (I remember at the
time that there was some discussion about the issue, and that
one collegue adopted the solution "type * obj"; no need to take
sides.) But typically, C programmers use "type *obj", and C++
programmers "type* obj", because Kernighan and Richie use "type
*obj" and Stroustrup uses "type* obj".

Logically, I think that there is a valid argument for separating
the type from the name of what is being declared. But it is
very much weakened, in the case of C/C++, by the fact that you
can't do it systematically; you can't do it for arrays, for
example (and what makes a function declaration a function, and
not a scalar, is the (), which also follows). So it's really
six of one, and half dozen of another. I've gotten very much
into the habit of "type* obj", but it's something where I'll
conform to whatever the local conventions are; the difference
isn't important enough to warrent trying to change them.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 24 '07 #63
On Apr 23, 10:13 pm, Keith Thompson <k...@mib.orgwrote:
James Kanze <james.ka...@gmail.comwrites:
On Apr 22, 5:58 pm, "Army1987" <please....@for.itwrote:
[...]
Anyhow, I'd write FILE *f rather than FILE* f, or else when you
write FILE* f, g you'll be surprised by results.
Every coding guideline I've ever seen has forbidden defining
more than one variable per statement. It's just bad programming
practice. Other than that, it's mostly a matter of taste. I
find it cleaner to separate the type from what is being defined.
How do you manage that for arrays?
std::vector< int v ; // :-)

Seriously, I do it when I can, but when the language doesn't
allow it, obviously, I do have to write code which the compiler
can understand. As a general rule, I like to keep the type
separate from the name of what is being defined. As a general
rule, I like to make declarations distinctive from expression
statements. Neither are always possible.
[...]
On the DS9K,
exit(2) makes the program securely erase the whole disk on exit.
The standard way to do that is exit(EXIT_FAILURE);
And the Unix way is exit(2).
It is?
<OT>
On Unix-like systems, EXIT_FAILURE is typically defined as 1. exit(0)
denotes success, and exit(1) commonly indicates some generic failure.
I know of no widespread convention for exit codes other than 0 and 1;
they tend to be defined individually for each command. One command,
curl, documents 76 distinct error codes.
</OT>
Try "man grep":-).
The C standard's exit(0), exit(EXIT_SUCCESS), and exit(EXIT_FAILURE)
are quite compatible with Unix conventions.
With one of the Unix conventions:-). Back when I was regularly
implementing such things, I got in the habit of using 2 for real
errors, because a certain number of programs (e.g. grep) used 1
for special non-error conditions. So I've gradually developped
the habit of using 2 for most errors.

The only more or less enforced convention is, of course, 0 if
there is no error. A number of programs do use 1 for special
non-error or half-error conditions (grep not finding anything),
and 2 for real errors. And of course, anything greater than 127
should be avoided, as it normally indicates that the program was
killed from the outside. I've gotten into the habit of
distinguishing even more: 1 is a "half-error", 2 a real error, 3
a fatal error (the program stopped immediately on detecting it);
internally, I also use 4, but that will trigger a call to abort,
so the invoking code won't see it. In my production code, these
are mapped to the system defined error return codes, with all
but 0 mapping to EXIT_FAILURE by default, but with the Unix and
Windows mappings just passing them through. It allows
propagating extra information on systems which support it.

Still, 99% of my programming is under Unix, so I sometimes slip,
and just write the error codes directly. Even though I know
that they don't work everywhere.

--
James Kanze (GABI Software) mailto:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 24 '07 #64
On Apr 23, 6:17 pm, Francine.Ne...@googlemail.com wrote:
On Apr 23, 5:04 pm, "Default User" <defaultuse...@yahoo.comwrote:
[...]
It seems to me that there's this difference: although the OP
crossposted, every reply up to that point had included only C code.
When there was a post full of C++, it jumped out immediately reading
it in clc. So I'd assume that if I'd been reading it in clc++ then all
the posts full of C would similarly have jumped out at me, and I'd
either have killed the thread (if my newsreader had that function) or
been alerted to the fact that it had probably been crossposted.
All of the postings up to that point had also been legal C++.
Most well written C is. Not idiomatic, of course, but legal, so
it jumps out less.

--
James Kanze (GABI Software) mailto:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 24 '07 #65
Groovy hepcat ume$h <fr****************@gmail.comwas jivin' on Sat, 21
Apr 2007 13:43:29 -0700. It's a cool scene! Dig it.
/* I wrote the following program to calculate no. of 'a' in the file
c:/1.txt but it fails to give appropriate result. What is wrong with
it? */
Several things.
#include"stdio.h"
That's wrong. It should be:

#include <stdio.h>

I usually include the following too, so I can use the macro EXIT_FAILURE
where needed:

#include <stdlib.h>
int main(void)
{
FILE *f;
Very poor style, lack of indentation.
char ch;
I smell a problem here. No doubt you will need an int instead of a char.
long int a=0;
f=fopen("c:/1.txt","r");
Always test the return value of fopen, ALWAYS! Since you have not done
so, you have no way of knowing whether the file could be successfully
opened or not and whether you have a valid FILE pointer or not.

if(!f)
{
fprintf(stderr, "Error opening file: \"%s\"\n", "c:/1.txt");
return EXIT_FAILURE;
}
while(ch=getc(f)!=EOF)
Here you have a couple of problems. One of them is the one I sniffed out
above. Since ch is a char, it may not be able to represent EOF (a negative
integer) or may produce a false EOF equality. As I said, ch should be an
int.
The second problem is that != has higher precedence than =, so the
expression is evaluated as ch = (getc(f) != EOF). Thus ch gets set to 0 if
getc(f) returns EOF and 1 otherwise. You need to parenthesise the ch =
getc(f) subexpression.

while((ch = getc(f)) != EOF)
{
switch(ch)
{
case 'a': a++;break;
}
}
Inconsistant indentation.
printf("No. of 'a' = %d\n",a);
And here we have another serious problem. a is a long, but you are
telling printf() to expect an int. You need to look up the printf()
function in your C manual. The conversion specifier for a long is %ld.

printf("No. of 'a' = %ld\n",a);
fclose(f);
return 0;
}
Apr 24 '07 #66
James Kanze wrote:
On Apr 23, 10:13 pm, Keith Thompson <k...@mib.orgwrote:
.... snip ...
>
>How do you manage that for arrays?

std::vector< int v ; // :-)
This is NOT C. Please control your cross-posts. F'ups set.

--
<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.net
--
Posted via a free Usenet account from http://www.teranews.com

Apr 24 '07 #67
Peter 'Shaggy' Haywood <ph******@alphalink.com.auwrites:
Groovy hepcat ume$h <fr****************@gmail.comwas jivin' on Sat, 21
Apr 2007 13:43:29 -0700. It's a cool scene! Dig it.
>/* I wrote the following program to calculate no. of 'a' in the file
c:/1.txt but it fails to give appropriate result. What is wrong with
it? */
#include <stdio.h>
#include <stdlib.h>
>int main(void)
{
FILE *f;
char ch;

I smell a problem here. No doubt you will need an int instead of a char.
>long int a=0;
You can also assume that there will be non-negative number of letters
'a' in the file, so instead of 'long int' one can use:

unsigned long a = 0;
>f=fopen("c:/1.txt","r");

if(!f)
{
fprintf(stderr, "Error opening file: \"%s\"\n", "c:/1.txt");
return EXIT_FAILURE;
}

while((ch = getc(f)) != EOF)
>{
switch(ch)
{
case 'a': a++;break;
}
}

printf("No. of 'a' = %ld\n",a);
And here call would change to:

printf("No. of 'a' = %lu\n",a);
>fclose(f);
return 0;
}
--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>---<jid:mina86*chrome.pl>--ooO--(_)--Ooo--
Apr 24 '07 #68
"Bill Pursell" <bi**********@gmail.comha scritto nel messaggio
news:11**********************@b75g2000hsg.googlegr oups.com...
In the following, "that ungood thing" refers to multiple
declarations in a single line:

Keith Thompson wrote:
>"Alf P. Steinbach" <a...@start.nowrites:
And when you're not doing that ungood thing, writing FILE* f makes
sense.

There I disagree. If you're going to have declarations of any
significant complexity, you need to understand why C declaration are
the way they are (declaration follows use). With that understanding,
"FILE *f" just makes more sense.

FILE *f; /* *f is a FILE */
int a[10] /* a[10] is an int (or would be if it existed */

When I look to the declaration section of a block to see
what type f is, I'm interested in seeing what type f is. I don't
want to see what *f is. In other words, I'd rather derive
information about *f from information about f rather
than the other way around.
>But in simple cases like "FILE *f" / "FILE* f", it isn't all that big
a deal. Declaring it as "FILE* f" implies that f is a FILE* -- which
happens to be true in this case, but the principle doens't extend to
other forms of declarations. As long as you can keep it straight,
I'll still *prefer* to keep the "*" next to the identifier, but I can
cope with other styles.

In working code, what percentage of declarations are not the
"simple case"? Declarations of function pointers obviously
require special treatment, as do
complex array types, but "T * x" is probably valid 95% of the time.
And the non-simple cases could perhaps be made clearer: eg

typedef int (*int_int_fcn)(int);

int_int_fcn * h;
int (**f)(int);
....hmmm, perhaps this is a bad example...or perhaps you are,
as usual, correct. The declaration of h was supposed to be
clearer than the declaration of f, but I would argue that this is
not the case.
Agreed, but C declarations work assuming the other way round.
According to Wikipedia, "Ritchie's idea was to declare identifiers in
contexts resembling their use".

If I had written C, maybe I would have done something such as
&FILE f;
#define NULL (&void)0;
or similar. (Just an idea, I've not thought about how I would have made more
complex declarations.
Apr 24 '07 #69
<Fr************@googlemail.comha scritto nel messaggio
news:11**********************@o5g2000hsb.googlegro ups.com...
What on earth possessed you to send this to comp.lang.c? Do you
realize that C != C++?
Increment is performed after comparison... :-)
Apr 24 '07 #70
Army1987 wrote:
<Fr************@googlemail.comha scritto nel messaggio
news:11**********************@o5g2000hsb.googlegro ups.com...
>What on earth possessed you to send this to comp.lang.c? Do you
realize that C != C++?

Increment is performed after comparison... :-)
Maybe there's a custom operator!=()?
Apr 24 '07 #71
red floyd wrote:
Army1987 wrote:
><Fr************@googlemail.comha scritto nel messaggio

>>What on earth possessed you to send this to comp.lang.c? Do you
realize that C != C++?

Increment is performed after comparison... :-)

Maybe there's a custom operator!=()?
For heavens sake, just set the follow-ups.

--
<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.net

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

Apr 24 '07 #72
On Apr 24, 1:12 pm, CBFalconer <cbfalco...@yahoo.comwrote:
James Kanze wrote:
On Apr 23, 10:13 pm, Keith Thompson <k...@mib.orgwrote:
... snip ...
How do you manage that for arrays?
std::vector< int v ; // :-)
This is NOT C.
And why do you think I put the :-) at the end?

--
James Kanze (GABI Software) mailto:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Apr 25 '07 #73
James Kanze wrote:
On Apr 24, 1:12 pm, CBFalconer <cbfalco...@yahoo.comwrote:
>James Kanze wrote:
>>On Apr 23, 10:13 pm, Keith Thompson <k...@mib.orgwrote:
>... snip ...
>>>How do you manage that for arrays?
>> std::vector< int v ; // :-)
>This is NOT C.

And why do you think I put the :-) at the end?
But you didn't set follow-ups.

--
<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.net

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

Apr 26 '07 #74
In comp.lang.c++ James Kanze <ja*********@gmail.comwrote:
Keith Thompson wrote:
>My preference for "type *obj" rather than "type* obj" is probably
largely based on the fact that that's what I've always been exposed
to. If I had been exposed to "type* obj", I'd likely be making the
same arguments you are.

Probably. I know that I was exposed to the "type* obj" format
very early in my days of C---I forget from where---and have used
it ever since, even before learning C++. (I remember at the
time that there was some discussion about the issue, and that
one collegue adopted the solution "type * obj"; no need to take
sides.) But typically, C programmers use "type *obj", and C++
programmers "type* obj", because Kernighan and Richie use "type
*obj" and Stroustrup uses "type* obj".
This whole subthread can be summarized by this entry in Stroustrup's
FAQ:

Is "int* p;" right or is "int *p;" right?
http://www.research.att.com/~bs/bs_faq2.html#whitespace

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Apr 26 '07 #75
Marcus Kwok said:

<snip>
This whole subthread can be summarized by this entry in Stroustrup's
FAQ:

Is "int* p;" right or is "int *p;" right?
http://www.research.att.com/~bs/bs_faq2.html#whitespace
I note in passing that Stroustrup recommends in his discourse that we
should "always initialize variables". Perhaps he isn't such a bad chap
after all. :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 26 '07 #76
Richard Heathfield <rj*@see.sig.invalidwrites:
Marcus Kwok said:

<snip>
>This whole subthread can be summarized by this entry in Stroustrup's
FAQ:

Is "int* p;" right or is "int *p;" right?
http://www.research.att.com/~bs/bs_faq2.html#whitespace

I note in passing that Stroustrup recommends in his discourse that we
should "always initialize variables". Perhaps he isn't such a bad chap
after all. :-)
I also note that he refers to C in the past tense.

I'd probably ignite a whole new flame war if I tried to make some
point about "a*b + c" vs. "a * b+c", so I won't. 8-)}

--
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"
Apr 26 '07 #77
[followups set to clc]

Keith Thompson said:
Richard Heathfield <rj*@see.sig.invalidwrites:
>Marcus Kwok said:

<snip>
>>This whole subthread can be summarized by this entry in Stroustrup's
FAQ:

Is "int* p;" right or is "int *p;" right?
http://www.research.att.com/~bs/bs_faq2.html#whitespace

I note in passing that Stroustrup recommends in his discourse that we
should "always initialize variables". Perhaps he isn't such a bad
chap
after all. :-)

I also note that he refers to C in the past tense.
Well, that's just holy-warring - what else would you expect? But his
comment on initialisation is presumably his considered technical
opinion as an accomplished programmer. I'm not saying he's /right/ -
any more than he's right about C. I'm just saying that, far more than
any of us here, he has earned the right for his opinions to be given
serious consideration.
I'd probably ignite a whole new flame war if I tried to make some
point about "a*b + c" vs. "a * b+c", so I won't. 8-)}
If you want significant whitespace, you may find that this meets your
needs: <http://compsoc.dur.ac.uk/whitespace/:-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 27 '07 #78

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

Similar topics

22
by: Ling Lee | last post by:
Hi all. I'm trying to write a program that: 1) Ask me what file I want to count number of lines in, and then counts the lines and writes the answear out. 2) I made the first part like this: ...
1
by: Rigga | last post by:
Hi, I am new to Python and need to parse a text file and cut parts out i.e. say the text file contained 5 rows of text: line 1 of the text file line 2 of the text file line 3 of the text...
27
by: Eric | last post by:
Assume that disk space is not an issue (the files will be small < 5k in general for the purpose of storing preferences) Assume that transportation to another OS may never occur. Are there...
16
by: thenightfly | last post by:
Ok, I know all about how binary numbers translate into text characters. My question is what exactly IS a text character? Is it a bitmap?
7
by: Chris | last post by:
Hi I can use a text file as a datasource but am unable to get the datatable to see the text file as having multiple columns. Everything gets put into the first column in the datatable. Sample of...
3
by: bbepristis | last post by:
Hey all I have this code that reads from one text file writes to another unless im on a certian line then it writes the new data however it only seems to do about 40 lines then quits and I cant...
1
by: Osoccer | last post by:
...to a different folder and in the relocated file concatenates all of the lines in one long string with a space between each line element. Here is a fuller statement of the problem: I need a...
10
by: bluemountain | last post by:
Hi there, Iam new to python forms and programming too I had a text file where i need to extract few words of data from the header(which is of 3 lines) and search for the keyword TEXT1, TEXT2,...
0
Debadatta Mishra
by: Debadatta Mishra | last post by:
Introduction In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.