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

How to get the total row number of a text file

Hi,
I have a text file abc.txt and it looks like:
12 34 56
23 45 56
33 56 78
... .. ..
... .. ..

I want to get how many rows totally in the text file, how to do this?
Thanks.

Nov 15 '05 #1
36 3541

Wei Su schreef:
Hi,
I have a text file abc.txt and it looks like:
12 34 56
23 45 56
33 56 78
.. .. ..
.. .. ..

I want to get how many rows totally in the text file, how to do this?
Thanks.


You could count the numbers of linebreaks.

Nov 15 '05 #2
please show some details. thanks

Nov 15 '05 #3
ThunderBird wrote:
please show some details. thanks


Please show some context so people have a clue as to what you are
balking about.

Robert Gamble.

Nov 15 '05 #4
it mentioned "You could count the numbers of linebreaks. ". My question
is how to count the numbers of linebreaks?
TB

Nov 15 '05 #5
----- Original Message -----
From: "ThunderBird" <th*********@gmail.com>
Newsgroups: comp.lang.c
Sent: Thursday, August 11, 2005 1:14 PM
Subject: Re: How to get the total row number of a text file

it mentioned "You could count the numbers of linebreaks. ". My question
is how to count the numbers of linebreaks?
TB


This works for me...

cmreinke@hologram>cat lines.c
/* lines.c */
#include <stdio.h>

int main(int argc, char **argv) {
long lines=0;
FILE *fp;

if(argc>1) {
if((fp=fopen(argv[1], "r"))) {
while(fscanf(fp, "%*[^\n]\n")!=EOF) lines++;
printf("Number of lines in file \"%s\": %ld\n", argv[1], lines);
} /* if */
else printf("ERROR: could not open file \"%s\"\n", argv[1]);
} /* if */
else printf("ERROR: no input file specified\n");

return 0;
} /* main */
/* lines.c */

cmreinke@hologram>gcc -Wall -ansi -pedantic -o lines.exe lines.c
cmreinke@hologram>lines.exe output2
Number of lines in file "output2": 270

-Charles
Nov 15 '05 #6
This is a kind of tricky question, different os use different
combinations to get the newline.
Windows: \r\n
Unix: \n
Mac: \r . it said to be, I have never used a Mac machine. However, the
text file transfered between M$'s os and Unix, I dit get some trouble
with the carriage return and line feed.

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

static const char *prog_name="wcn";

int
main(int argc, char *argv[]) {
FILE *fp;
int i;

if (argc == 1) {
printf("Usage: %s [files]\n", prog_name);
exit(EXIT_FAILURE);
}

for (i=1; i<argc; ++i) {
unsigned int r_c=0, n_c=0, rn_c=0;
int c, last=0;
if (! (fp=fopen(argv[i], "rb"))) {
printf("%s: %s: %s\n", prog_name, argv[i], strerror(errno));
continue;
}
while ((c=fgetc(fp)) != EOF) {
if (c == '\n') {
++n_c;
if (last == '\r')
++rn_c;
} else if (last == '\r')
++r_c;
last = c;
}
r_c += last=='\r'; /* In case the last char is '\r' */

if (ferror(fp)) {
printf("%s: %s: %s\n", prog_name, argv[i], strerror(errno));
if (fclose(fp) == EOF)
perror(prog_name);
continue;
}
if (fclose(fp) == EOF)
printf("%s: %s: %s\n", prog_name, argv[i], strerror(errno));
printf("%s:\t \\n: %u\t \\r: %u\t \\r\\n: %u\n", argv[i], n_c, r_c,
rn_c);
}
exit(EXIT_SUCCESS);
}

Nov 15 '05 #7
In article <11**********************@g44g2000cwa.googlegroups .com>,
moxm <mo********@yahoo.com> wrote:
This is a kind of tricky question, different os use different
combinations to get the newline.
Windows: \r\n
Unix: \n
Mac: \r . it said to be, I have never used a Mac machine. However, the
text file transfered between M$'s os and Unix, I dit get some trouble
with the carriage return and line feed. if (! (fp=fopen(argv[i], "rb"))) {


If you do not open in binary mode, then the local OS's internal convention
will be transformed into \n when the data is read.

If you are trying to deal with files that have been copied from other
OS's then the first line of defence is to copy them in text mode instead
of binary mode.
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers
Nov 15 '05 #8
Charles' code is very clean and elegant, I think it works well in
windows and unix , but what if the newline character is just '\r' at a
Mac machine.

Nov 15 '05 #9
Sorry! I am idiot, just open the file in text mode is okay like Walter
Roberson said.

Nov 15 '05 #10
"Charles M. Reinke" <cm******@ece.gatech.edu> writes:
"ThunderBird" <th*********@gmail.com> writes:
it mentioned "You could count the numbers of linebreaks. ". My question
is how to count the numbers of linebreaks?


This works for me...

cmreinke@hologram>cat lines.c
/* lines.c */
#include <stdio.h>

int main(int argc, char **argv) {
long lines=0;
FILE *fp;

if(argc>1) {
if((fp=fopen(argv[1], "r"))) {
while(fscanf(fp, "%*[^\n]\n")!=EOF) lines++;
printf("Number of lines in file \"%s\": %ld\n", argv[1], lines);
} /* if */
else printf("ERROR: could not open file \"%s\"\n", argv[1]);
} /* if */
else printf("ERROR: no input file specified\n");

return 0;
} /* main */
/* lines.c */


Why bother with fscanf()?

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

int main(int argc, char **argv)
{
long lines = 0;
FILE *fp;

if (argc>1) {
if((fp = fopen(argv[1], "r"))) {
int c;
while ((c = getc(fp)) != EOF) {
if (c == '\n') {
lines ++;
}
}
fclose(fp);
printf("Number of lines in file \"%s\": %ld\n", argv[1], lines);
}
else {
fprintf(stderr, "ERROR: could not open file \"%s\"\n", argv[1]);
exit(EXIT_FAILURE);
}
}
else {
fprintf(stderr, "ERROR: no input file specified\n");
exit(EXIT_FAILURE);
}
return 0;
}

I've also added a call to fclose(), improved error handling, and
(IMHO) improved code layout.

--
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.
Nov 15 '05 #11
Do we have any ways to tell the newline character in our os? If it is
not '\n', then Charles' fscanf statement have to be changed.

I mean if I have a text file which is gotten from other os in binary
mode, and I want a general program to deal with it, what should I do?

Nov 15 '05 #12
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...

Why bother with fscanf()?
I thought about using something like fgetc(), but preferred to consuming the
whole line at a time. Although fscanf() is still probably not the *best*
way to do this. :-)

[code snipped] I've also added a call to fclose(), improved error handling, and
(IMHO) improved code layout.

I completely forgot to fclose(), thanx! And I agree that your error
handling is superior. Alas, I am not a l33t haxor.

-Charles
Nov 15 '05 #13
"moxm" <mo********@yahoo.com> writes:
Do we have any ways to tell the newline character in our os? If it is
not '\n', then Charles' fscanf statement have to be changed.

I mean if I have a text file which is gotten from other os in binary
mode, and I want a general program to deal with it, what should I do?


In the article to which you replied, Walter Roberson wrote:

If you do not open in binary mode, then the local OS's internal
convention will be transformed into \n when the data is read.

As long as you open the file in text mode, and as long as the input
file is a valid text file for the OS, you don't need to know how the
OS represents an end-of-line.

And please provide some context when you post a followup. Search for
"google broken reply link" in this newsgroup for many many copies of
the same explanation.

--
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.
Nov 15 '05 #14
ThunderBird wrote:

it mentioned "You could count the numbers of linebreaks. ". My question
is how to count the numbers of linebreaks?


This is meaningless. See my sig below for a means of quoting on
the foul google usenet interface. Without context you might as
well not write anything.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson

Nov 15 '05 #15
"Charles M. Reinke" <cm******@ece.gatech.edu> writes:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...

Why bother with fscanf()?

I thought about using something like fgetc(), but preferred to consuming the
whole line at a time. Although fscanf() is still probably not the *best*
way to do this. :-)


I think fscanf() is defined to do the equivalent of calling fgetc()
anyway. It may do some optimizations to avoid reading a single
character at a time, but fgetc() can use the same optimizations
(reading from an in-memory buffer whenever possible, for example).
There may be some overhead from the function calls, but using getc()
(which is typically a macro) avoids that, and in any case function
call overhead is probably insignificant.

--
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.
Nov 15 '05 #16
On 11 Aug 2005 10:14:41 -0700, in comp.lang.c , "ThunderBird"
<th*********@gmail.com> wrote:
it mentioned "You could count the numbers of linebreaks. ". My question
is how to count the numbers of linebreaks?


walk through the file byte by byte, counting linefeed characters.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 15 '05 #17
"Charles M. Reinke" wrote:
From: "ThunderBird" <th*********@gmail.com>
it mentioned "You could count the numbers of linebreaks. ".
My question is how to count the numbers of linebreaks?


This works for me...

cmreinke@hologram>cat lines.c
/* lines.c */
#include <stdio.h>

int main(int argc, char **argv) {
long lines=0;
FILE *fp;

if(argc>1) {
if((fp=fopen(argv[1], "r"))) {
while(fscanf(fp, "%*[^\n]\n")!=EOF) lines++;
printf("Number of lines in file \"%s\": %ld\n", argv[1], lines);
} /* if */
else printf("ERROR: could not open file \"%s\"\n", argv[1]);
} /* if */
else printf("ERROR: no input file specified\n");

return 0;
} /* main */
/* lines.c */


Why so complex? Use stdin. :-)

[1] c:\c\wc>cat lc.c
#include <stdio.h>

int main(void)
{
unsigned long chars, lines;
int ch;

chars = lines = 0;
while (EOF != (ch = getchar())) {
chars++;
if ('\n' == ch) lines++;
}
printf("%lu chars in %lu lines\n", chars, lines);
return 0;
} /* main lines */

[1] c:\c\wc>cc lc.c -o lc.exe

[1] c:\c\wc>.\lc < lc.c
285 chars in 15 lines

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 15 '05 #18

"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"moxm" <mo********@yahoo.com> writes:
Do we have any ways to tell the newline character in our os? If it is
not '\n', then Charles' fscanf statement have to be changed.

I mean if I have a text file which is gotten from other os in binary
mode, and I want a general program to deal with it, what should I do?
In the article to which you replied, Walter Roberson wrote:

If you do not open in binary mode, then the local OS's internal
convention will be transformed into \n when the data is read.

I don't understand how... what magic causes this to happen?
The local OS wouldn't know what character(s) to 'transform'.
As long as you open the file in text mode, and as long as the input
file is a valid text file for the OS, you don't need to know how the
OS represents an end-of-line.


He has already stated that it may not be a valid text file for the current
system ...
text file which is gotten from other os in binary mode


Obviously, when transferring 'text' files between different operating
systems
they should be transferred in 'text' mode to make the appropriate
conversions.
When a text file is transferred in binary mode, these conversions do NOT
take
place.

Mark
Nov 15 '05 #19
CBFalconer wrote:
"Charles M. Reinke" wrote:
From: "ThunderBird" <th*********@gmail.com>
it mentioned "You could count the numbers of linebreaks. ".
My question is how to count the numbers of linebreaks?


This works for me...

cmreinke@hologram>cat lines.c
/* lines.c */
#include <stdio.h>

int main(int argc, char **argv) {
long lines=0;
FILE *fp;

if(argc>1) {
if((fp=fopen(argv[1], "r"))) {
while(fscanf(fp, "%*[^\n]\n")!=EOF) lines++;
printf("Number of lines in file \"%s\": %ld\n", argv[1], lines);
} /* if */
else printf("ERROR: could not open file \"%s\"\n", argv[1]);
} /* if */
else printf("ERROR: no input file specified\n");

return 0;
} /* main */
/* lines.c */

Why so complex? Use stdin. :-)

[1] c:\c\wc>cat lc.c
#include <stdio.h>

int main(void)
{
unsigned long chars, lines;
int ch;

chars = lines = 0;
while (EOF != (ch = getchar())) {
chars++;
if ('\n' == ch) lines++;
}
printf("%lu chars in %lu lines\n", chars, lines);
return 0;
} /* main lines */

[1] c:\c\wc>cc lc.c -o lc.exe

[1] c:\c\wc>.\lc < lc.c
285 chars in 15 lines


WOW! Although not the original poster, I tried that. It works sweet. Thnx.
Nov 15 '05 #20
In article <11**********************@g14g2000cwa.googlegroups .com>,
moxm <mo********@yahoo.com> wrote:
Do we have any ways to tell the newline character in our os? If it is
not '\n', then Charles' fscanf statement have to be changed. I mean if I have a text file which is gotten from other os in binary
mode, and I want a general program to deal with it, what should I do?


In such a case, you would need to probe the newline conventions of
the -other- OS, not of your own OS ;-)

Actually it's worse than that: you need to know how the file
gets transformed during the transfer. For example, the original
text file might happen to be stored in a format that is not
stream-oriented. such as fixed recordlength, or counted-length, or
using lineprinter encoding (e.g., one particular character in
the first column might indicate overstrike on the same line,
whereas a different one might indicate end-of-page with an implication
that all remaining lines on the page "exist" but read as empty).
Or the file might be stored in a semi-database format with a series
of descriptors of the individual lines, followed by the data -- but
the data in binary format will not necessarily be in-order compared
to the line sequence imposed by the header (e.g., because the
file was editted or 'patched'.)

One system's internal format might not be easily representable as
a binary stream during file transfer -- some of the crucial parameters
might have been stored as meta-data for example... Hence one must know
how the binary transfer process reshaped the data. What got to the
other side might not be the same thing as the way the same file would
have read out in "binary mode" on the original OS. C doesn't promise
that "binary" files will contain only exactly the bytes one writes out:
C's promise is that if one writes in binary mode, that the byte stream
read back in will exactly match what was written out. There could
be an intermediate representation layer [as long as that layer supports
seeking and writing at arbitrary positions.]

--
"I will speculate that [...] applications [...] could actually see a
performance boost for most users by going dual-core [...] because it
is running the adware and spyware that [...] are otherwise slowing
down the single CPU that user has today" -- Herb Sutter
Nov 15 '05 #21
On 11 Aug 2005 12:25:40 -0700, moxm
<mo********@yahoo.com> wrote:
Do we have any ways to tell the newline character in our os? If it is
not '\n', then Charles' fscanf statement have to be changed.
fscanf is for use with text mode streams, so the C library should do any
conversion required for files correct for that OS. But...
I mean if I have a text file which is gotten from other os in binary
mode, and I want a general program to deal with it, what should I do?


.... you are now talking about files from a foreign OS. If the file has
been imported as a binary copy, the C library on your machine has no
idea how to handle it. For the most common ones these days, you can
faitly easily write your own code to read a line, though. Mine uses an
algorithm something like:

if the character is CR
get the next character.
if that is not LF, unget it (push it back so it's got next time).
return end of line
else if the character is LF
get the next character.
if that is not CR, unget it (push it back so it's got next time).
return end of line
end if

That copes with lines ending with CR, LF, CRLF and LFCR, as long as
there are no stray CR or LF characters which are supposed to be part of
the data (which is silly but occasionally happens).

Of course, your foreign file might have come from a system where each
like is represented as a 2 byte count followed by that many characters
in the line, or where all files are kept in a compressed form, or text
files have a header stating the line width and all lines are constant
width, or something more strange, and there is no way that you can
automatically detect all of the possibilities...

Chris C
Nov 15 '05 #22
CBFalconer wrote:
"Charles M. Reinke" wrote:
From: "ThunderBird" <th*********@gmail.com>
it mentioned "You could count the numbers of linebreaks. ".
My question is how to count the numbers of linebreaks?


This works for me...

cmreinke@hologram>cat lines.c
/* lines.c */
#include <stdio.h>

int main(int argc, char **argv) {
long lines=0;
FILE *fp;

if(argc>1) {
if((fp=fopen(argv[1], "r"))) {
while(fscanf(fp, "%*[^\n]\n")!=EOF) lines++;
printf("Number of lines in file \"%s\": %ld\n", argv[1], lines);
} /* if */
else printf("ERROR: could not open file \"%s\"\n", argv[1]);
} /* if */
else printf("ERROR: no input file specified\n");

return 0;
} /* main */
/* lines.c */

Why so complex? Use stdin. :-)

[1] c:\c\wc>cat lc.c
#include <stdio.h>

int main(void)
{
unsigned long chars, lines;
int ch;

chars = lines = 0;
while (EOF != (ch = getchar())) {
chars++;
if ('\n' == ch) lines++;
}
printf("%lu chars in %lu lines\n", chars, lines);
return 0;
} /* main lines */


Well, we can still make it terser ;-)

#include <stdio.h>

int main(void)
{
int count = 0, c;

while (((c = getchar()) != EOF) && ((count += (c == '\n')), 1));
printf("%i\n", count);
return 0;
}
August
Nov 15 '05 #23
"akarl" <fu********@comhem.se> wrote in message
news:fo*********************@newsc.telia.net...
Well, we can still make it terser ;-)

#include <stdio.h>

int main(void)
{
int count = 0, c;

while (((c = getchar()) != EOF) && ((count += (c == '\n')), 1));
printf("%i\n", count);
return 0;
}
August


Wow, not bad at all...thatz kinda cute.

Thus, it would appear that I've initiated some sort of contest: write a
program to count the number of lines in a file and output the result to
stdout, using the least number of characters for the source code. Of
course, the usual caveats apply, i.e. must use portable Standard C, must
compile without errors and not dump core during *normal* operation, etc.
Any challengers? :-p

-Charles
Nov 15 '05 #24

akarl wrote:
CBFalconer wrote:
"Charles M. Reinke" wrote:
From: "ThunderBird" <th*********@gmail.com>

it mentioned "You could count the numbers of linebreaks. ".
My question is how to count the numbers of linebreaks?

This works for me...

cmreinke@hologram>cat lines.c
/* lines.c */
#include <stdio.h>

int main(int argc, char **argv) {
long lines=0;
FILE *fp;

if(argc>1) {
if((fp=fopen(argv[1], "r"))) {
while(fscanf(fp, "%*[^\n]\n")!=EOF) lines++;
printf("Number of lines in file \"%s\": %ld\n", argv[1], lines);
} /* if */
else printf("ERROR: could not open file \"%s\"\n", argv[1]);
} /* if */
else printf("ERROR: no input file specified\n");

return 0;
} /* main */
/* lines.c */

Why so complex? Use stdin. :-)

[1] c:\c\wc>cat lc.c
#include <stdio.h>

int main(void)
{
unsigned long chars, lines;
int ch;

chars = lines = 0;
while (EOF != (ch = getchar())) {
chars++;
if ('\n' == ch) lines++;
}
printf("%lu chars in %lu lines\n", chars, lines);
return 0;
} /* main lines */


Well, we can still make it terser ;-)

#include <stdio.h>

int main(void)
{
int count = 0, c;

while (((c = getchar()) != EOF) && ((count += (c == '\n')), 1));


I'd prefer:
while ((c = getchar()) != EOF) count += (c =='\n');
saves a few precious chars, makes the intent clear etc etc...
printf("%i\n", count);
return 0;
}
August


Nov 15 '05 #25
Charles M. Reinke wrote:
"akarl" <fu********@comhem.se> wrote in message
news:fo*********************@newsc.telia.net...
Well, we can still make it terser ;-)

#include <stdio.h>

int main(void)
{
int count = 0, c;

while (((c = getchar()) != EOF) && ((count += (c == '\n')), 1));
printf("%i\n", count);
return 0;
}


Wow, not bad at all...thatz kinda cute.

Thus, it would appear that I've initiated some sort of contest: write a
program to count the number of lines in a file and output the result to
stdout, using the least number of characters for the source code. Of
course, the usual caveats apply, i.e. must use portable Standard C, must
compile without errors and not dump core during *normal* operation, etc.


My code sure does.

(In practice we should strive for clarity and maintainability rather
than to write terse and obscure code such as the one I presented.
....still, C makes you want to do the opposite ;-)
August
Nov 15 '05 #26
Suman wrote:
akarl wrote:
while (((c = getchar()) != EOF) && ((count += (c == '\n')), 1));


I'd prefer:
while ((c = getchar()) != EOF) count += (c =='\n');
saves a few precious chars, makes the intent clear etc etc...


Yes, of course. That's shorter *and* clearer. (Stupid me)

August
Nov 15 '05 #27
In article <dd**********@news-int2.gatech.edu>,
Charles M. Reinke <cm******@ece.gatech.edu> wrote:

Thus, it would appear that I've initiated some sort of contest: write a
program to count the number of lines in a file and output the result to
stdout, using the least number of characters for the source code. Of
course, the usual caveats apply, i.e. must use portable Standard C, must
compile without errors and not dump core during *normal* operation, etc.
Any challengers? :-p


Well, here's the impertinent solution...

#include <stdlib.h>
int main(void)
{
system("wc -l");
exit(0);
}
Nov 15 '05 #28
In article <V%4Le.367$uO2.258@fed1read07>,
Anonymous 7843 <an******@example.com> wrote:
In article <dd**********@news-int2.gatech.edu>,
Charles M. Reinke <cm******@ece.gatech.edu> wrote:

using the least number of characters for the source code.


Well, here's the impertinent solution...

#include <stdlib.h>
int main(void)
{
system("wc -l");
exit(0);
}


I might as well make a two-liner out of that.
Leave off out the #include and it could be a one-liner if you don't
mind a few warnings from the compiler.

#include <stdlib.h>
int main(void) { exit(system("wc -l")); }
Nov 15 '05 #29
In article <w95Le.369$uO2.15@fed1read07>,
Anonymous 7843 <an******@example.com> wrote:
I might as well make a two-liner out of that.
Leave off out the #include and it could be a one-liner if you don't
mind a few warnings from the compiler. #include <stdlib.h>
int main(void) { exit(system("wc -l")); }


int system(const char*); int main(void){return system("wc -l");}

You can probably remove the 'const'. I would need to dig through
the standards to determine whether it is safe to use

int system(); main(void){return system("wc -l");}

K&R C pretty much had to guarantee that char* was promoted to long
safely. If I recall correctly, K&R2 promises that a pointer
can be converted to long and back again safely, but that C89's
wording is different enough to make this technically unsafe.
--
Any sufficiently old bug becomes a feature.
Nov 15 '05 #30
In article <dd**********@canopus.cc.umanitoba.ca>,
Walter Roberson <ro******@ibd.nrc-cnrc.gc.ca> wrote:

In article <w95Le.369$uO2.15@fed1read07>,
Anonymous 7843 <an******@example.com> wrote:
#include <stdlib.h>
int main(void) { exit(system("wc -l")); }


int system(const char*); int main(void){return system("wc -l");}

You can probably remove the 'const'. I would need to dig through
the standards to determine whether it is safe to use

int system(); main(void){return system("wc -l");}

K&R C pretty much had to guarantee that char* was promoted to long
safely. If I recall correctly, K&R2 promises that a pointer
can be converted to long and back again safely, but that C89's
wording is different enough to make this technically unsafe.


I was a bit surprised that "gcc -ansi" (3.3) quietly compiles this:

main(){return system("wc -l");}
Nov 15 '05 #31
Anonymous 7843 wrote:
In article <dd**********@canopus.cc.umanitoba.ca>,
Walter Roberson <ro******@ibd.nrc-cnrc.gc.ca> wrote:
In article <w95Le.369$uO2.15@fed1read07>,
Anonymous 7843 <an******@example.com> wrote:

#include <stdlib.h>
int main(void) { exit(system("wc -l")); }
int system(const char*); int main(void){return system("wc -l");}

You can probably remove the 'const'. I would need to dig through
the standards to determine whether it is safe to use

int system(); main(void){return system("wc -l");}

K&R C pretty much had to guarantee that char* was promoted to long
safely. If I recall correctly, K&R2 promises that a pointer
can be converted to long and back again safely, but that C89's
wording is different enough to make this technically unsafe.


As I understand it pointers don't undergo any conversion when passed as
parameters to a function without a prototype, so as long as you are
passing the correct type of pointer (or a compatible one) they it is
safe. Not something I would ever choose to do, but safe.
I was a bit surprised that "gcc -ansi" (3.3) quietly compiles this:

main(){return system("wc -l");}


I'm not. It is perfectly valid on a machine where passing "wc -l" to
system is valid.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #32

Anonymous 7843 wrote:
In article <V%4Le.367$uO2.258@fed1read07>,
Anonymous 7843 <an******@example.com> wrote:
In article <dd**********@news-int2.gatech.edu>,
Charles M. Reinke <cm******@ece.gatech.edu> wrote:

using the least number of characters for the source code.


Well, here's the impertinent solution...

#include <stdlib.h>
int main(void)
{
system("wc -l");
exit(0);
}


I might as well make a two-liner out of that.
Leave off out the #include and it could be a one-liner if you don't
mind a few warnings from the compiler.

#include <stdlib.h>
int main(void) { exit(system("wc -l")); }


1. Relying on the system function is not portable at all, as I found
out the hard way. It is one of the few things that is implementation
defined, and I can gie you right now an example -- CodeWarrior on
Macintosh systems, where though the `wc' command is available,
system() is a do nothing.

2. `wc' itself is not portable.

3. And int main() will do just as fine as int main(void),
when you don't mind not including libraries ;-)

Nov 15 '05 #33
Flash Gordon wrote:
Anonymous 7843 wrote:
I was a bit surprised that "gcc -ansi" (3.3) quietly compiles this:

main(){return system("wc -l");}


I'm not. It is perfectly valid on a machine where passing "wc -l" to
system is valid.


It is perfectly valid (for the purpose of compilation) even on a machine
where it is not. I believe that Anonymous' surprise originated from gcc
not objecting to a missing prototype for system().

Peter

Nov 15 '05 #34
In article <42********@mk-nntp-2.news.uk.tiscali.com>,
Peter Pichler <pi*****@pobox.sk> wrote:
Flash Gordon wrote:
Anonymous 7843 wrote:
I was a bit surprised that "gcc -ansi" (3.3) quietly compiles this: main(){return system("wc -l");}
I'm not. It is perfectly valid on a machine where passing "wc -l" to
system is valid.
It is perfectly valid (for the purpose of compilation) even on a machine
where it is not. I believe that Anonymous' surprise originated from gcc
not objecting to a missing prototype for system().


That part is well defined by C89: if a previously-undefined
identifier is found in a function-call position, then the identifier
is implicitly defined as an unprototyped function returning int.

The part that I'm pondering is why the main() did not generate a
warning or diagnostic. C89 says that the implementation does not
define any prototype for main, but it appears to list only two forms
as being valid, with the simpler of the two having (void) .

I have not been able to find anything in C89 that would explicitly
allow the prototypeless main(), so it seems to me that using
the prototypeless version would be a system extension
(just like the 3-parameter version that includes an environment
pointer), and I would have expected -pedantic to give a murmur
about it.
--
Look out, there are llamas!
Nov 15 '05 #35
In article <dd**********@news-int2.gatech.edu>
Charles M. Reinke <cm******@ece.gatech.edu> wrote:
cmreinke@hologram>cat lines.c
/* lines.c */
#include <stdio.h>

int main(int argc, char **argv) {
long lines=0;
FILE *fp;

if(argc>1) {
if((fp=fopen(argv[1], "r"))) {
while(fscanf(fp, "%*[^\n]\n")!=EOF) lines++;
printf("Number of lines in file \"%s\": %ld\n", argv[1], lines);
} /* if */
else printf("ERROR: could not open file \"%s\"\n", argv[1]);
} /* if */
else printf("ERROR: no input file specified\n");

return 0;
} /* main */
/* lines.c */


This program has what might be a flaw (given that, as far as I
know, no one has ever defined "total row number" in this thread,
so it is hard to say how to count "number of rows").

The program *does* compile and run, but:

% cat in
line 1
line 4
line 5
% wc -l in
5 in
% ./lines in
Number of lines in file "in": 3
%

The exercise for the reader is to figure out why these numbers
are different. (I know why, so you do not need to tell me.)

Note that the program gives the same result if I change the
fscanf() call to use "%*[^\n] " or even "%*[^\n]\f".
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 15 '05 #36
On Thu, 11 Aug 2005 23:10:31 +0100, Chris Croughton
<ch***@keristor.net> wrote:
On 11 Aug 2005 12:25:40 -0700, moxm
<mo********@yahoo.com> wrote:
Do we have any ways to tell the newline character in our os? If it is
not '\n', then Charles' fscanf statement have to be changed.
fscanf is for use with text mode streams, so the C library should do any
conversion required for files correct for that OS. But...

Yes and no. All of the stdio routines (*get/putc/char, *printf/scanf,
fread/fwrite) are defined to work on both text and binary streams.

It is rare but does sometimes happen that actual binary files contain
data that can usefully be processed by *printf or even *scanf. There
are also situations where it makes sense to access as binary an actual
text file, or mostly text file (e.g. a tar or ar of texts).
I mean if I have a text file which is gotten from other os in binary
mode, and I want a general program to deal with it, what should I do?


... you are now talking about files from a foreign OS. If the file has
been imported as a binary copy, the C library on your machine has no
idea how to handle it. For the most common ones these days, you can
faitly easily write your own code to read a line, though. Mine uses an
algorithm something like: <snip>
That copes with lines ending with CR, LF, CRLF and LFCR, as long as
there are no stray CR or LF characters which are supposed to be part of
the data (which is silly but occasionally happens).

This is certainly most cases. Historically there have been systems (or
formats) where FF and maybe VT was also treated as line terminator,
sometimes with CR and sometimes not (as you have for LF). And I've
heard rumors someone actually used RS (and maybe GS) as intended.
Of course, your foreign file might have come from a system where each
like is represented as a 2 byte count followed by that many characters
in the line, or where all files are kept in a compressed form, or text
files have a header stating the line width and all lines are constant
width, or something more strange, and there is no way that you can
automatically detect all of the possibilities...

Or a 4-byte count (or two of them) as in OS/360 et seq V[b]. I don't
know if there is an FTP for those systems that will transmit that
format in binary, but it's certainly possible to find on tape or disk.

Or, as you say, even more strange. I use one that does 2K blocks, in
arbitrary order with an index, each containing a 2-byte header then a
series of lines each with a 5-byte header and compressed data, and
_usually_ a 1-byte block trailer but not if the block is exactly full.
And I wrote a utility to fix files that were mistakenly transferred
binary and couldn't easily be retransferred correctly.

- David.Thompson1 at worldnet.att.net
Nov 15 '05 #37

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

Similar topics

3
by: T-Narg | last post by:
I would like to produce the following output based on my XML file: My Album (2005) Elapsed Time (hh:mm:ss): 00:07:00 Song 1: title1 Length (hh:mm:ss): 00:02:30 Song 2: title2 Length...
1
by: beavenour | last post by:
I am looking for some help creating a more universal function out of this lame attempt at javascript. I have little experience with javascript and want to be able to universalize this function. ...
10
by: giancarlodirisioster | last post by:
Can someone help me modify this for future Usenet archival and to help me solve what I don't know? <form name="addform" method="POST" action="./submit.php"> <input type="text" name="Box 1"...
5
by: RC | last post by:
I have a form with three text boxes on it. I want the third text box to show the total of the values in the other two text boxes. The first box is named: BoxOne and I type the number 2 into it...
7
by: RC | last post by:
I have a form with five text boxes on it. The format for all the boxes is set as General Number. In four of the boxes the user can enter a number, the fifth box totals up the values in the other...
8
by: W. eWatson | last post by:
I have an ordinary text file with a CR at the end of a line, and two numbers in each line. Is there some way to determine the number of lines (records) in the file before I begin reading it? --...
3
by: =?Utf-8?B?UGF1bA==?= | last post by:
Hi I have a webform with several entry boxes and the user enters numbers in each box. I keep a running total (just adds all of the entries together) but am posting back to the server to do this. ...
1
by: deshaipet | last post by:
Hi friends - I created a automatic storage tablespace with a pagesize of 16 K and initial size of 64 MB. create large tablespace test_tbsp1 pagesize 16k managed by automatic storage autoresize...
2
by: alwaali | last post by:
Hi I need help please This is my project and i need a help to solve it with you A page of text is to be read and analyzed to determine number of occurrences and locations of different words. The...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...

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.