hi all,
how do i list the contents of a file and calculate the string length (strlen) with it?
thanks!
hi all,
how do i list the contents of a file and calculate the string length (strlen) with it?
thanks!
u can look into the implementation of the wc command in unix . say cat <filename>|wc-l. or equivalently to count the number of characters in it. Then u can use the same in your C code for achieving the same
hi,
thanks for your tips. i know cat <filename> is to display contents of file in Unix, but what is the equivalent code in C?
Do i have to open the file first fopen() before displaying the contents? thanks!
of course dear, you will have to open the file, without bringing the file into the RAM how can you work on that?
yes
u have to open the file. u can look for the implementation of the cat command as it is open source then go ahead with your program you will get it
Use the cat command?? When did this become a Unix OS Command board? Sheesh!
Open the file.Originally posted by zagelle
hi all,
how do i list the contents of a file and calculate the string length (strlen) with it?
thanks!
Read each line.
Add the number of characters read to a counter for the file length
Output the line to list the contents
When done, close the file.
This will work even in Windows and DOS too, whereas the other suggestion is only Unix/Linux.
Definition: Politics -- Latin, from
poly meaning many and
tics meaning blood sucking parasites
-- Tom Smothers
Quick code
[EDIT] Hoping this is not your homework.Code:#include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]) { char c; FILE *fp; if (argc!=2) { puts("wrong command.\n"); exit(1); } else if ((fp=fopen(argv[1],"r"))!=NULL) { while ((c=(char)getc(fp))!=EOF) putc(c,stdout); fclose(fp); } else { puts("file not found.\n"); exit(1); } return 0; }
>And I only intend to cast it to be printable to stdout.
Besides being incorrect for the comparison with EOF, it is also unnecessary -- putc is already performing this conversion.#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
fputc() writes the character c, cast to an unsigned char, to stream.
putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
If you are concerned about someone's ability to learn, as you implied, it's best to refrain from posting code that answers the question no matter how easy the solution. I know how it's a kick to be able to answer someone's question, but hold back on the solution so they can learn by solving it.Originally posted by Jaguar
Quick code
...
[EDIT] Hoping this is not your homework.
Definition: Politics -- Latin, from
poly meaning many and
tics meaning blood sucking parasites
-- Tom Smothers