473,467 Members | 1,860 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

print out a file?

Just been searching google, but havent come up with anything. Just
wondering, whats the best way to print say a file.txt or other format to the
screen? A link would be great and ill read up on it. Cheers
Nov 14 '05 #1
21 18146
Advocated <......@......com> spoke thus:
Just been searching google, but havent come up with anything. Just
wondering, whats the best way to print say a file.txt or other format to the


You could use the following C program...

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

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

if( argc != 2 ) {
fprintf( stderr, "Usage: %s <filename>\n", argv[0] );
return EXIT_FAILURE;
}
if( (fp=fopen(argv[1],"r")) == NULL ) {
fprintf( stderr, "Could not open file \"%s\"\n", argv[1] );
return EXIT_FAILURE;
}
while( fgets(buf,sizeof buf,fp) ) {
printf( "%s", buf );
}
printf( "\n" ); /* in case there were no newlines in the file */
fclose( fp );
return EXIT_SUCCESS;
}

(salient comments from the regulars appreciated)

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #2

On Wed, 24 Dec 2003, Christopher Benson-Manica wrote:

Advocated <......@......com> spoke thus:

Just been searching google, but havent come up with anything. Just
wondering, whats the best way to print say a file.txt or other format
to the [screen?]
You could use the following C program...

[snip 24 lines using fgets() somewhat inappropriately]
(salient comments from the regulars appreciated)


What if you get a line in "file.txt" longer than 255 characters?
Anyway, the simple solutions are best... Use 'cat file.txt',
'type file.txt', or, if your OS doesn't have either of those,
just write your own 'cat' clone... [UNTESTED]

/* A simple 'cat' utility */

#include <stdio.h>

void process(FILE *fp)
{
if (fp == NULL) return;
while ((c=getc(fp)) != EOF)
putchar(c);
putchar('\n');
}

int main(int argc, char **argv)
{
if (argc < 2) {
process(stdin);
}
else {
int i;
for (i=1; i < argc; ++i)
process(fopen(argv[i]));
}
return 0;
}

HTH,
-Arthur
Nov 14 '05 #3
Arthur J. O'Dwyer wrote:

What if you get a line in "file.txt" longer than 255 characters?
Anyway, the simple solutions are best... Use 'cat file.txt',
'type file.txt', or, if your OS doesn't have either of those,
just write your own 'cat' clone... [UNTESTED]

/* A simple 'cat' utility */

#include <stdio.h>

void process(FILE *fp)
{
if (fp == NULL) return;
while ((c=getc(fp)) != EOF)
putchar(c);
putchar('\n');
}

int main(int argc, char **argv)
{
if (argc < 2) {
process(stdin);
}
else {
int i;
for (i=1; i < argc; ++i)
process(fopen(argv[i]));
}
return 0;
}


You forgot to fclose() the files. It looks like doing so will require
some changes beyond just adding the call.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #4
Arthur J. O'Dwyer wrote:

[snip 24 lines using fgets() somewhat inappropriately]

What if you get a line in "file.txt" longer than 255 characters?


I don't see the problem. What do you have in mind?

--
Russell Hanneken
rg********@pobox.com
Remove the 'g' from my address to send me mail.
Nov 14 '05 #5
nrk
Arthur J. O'Dwyer wrote:

On Wed, 24 Dec 2003, Christopher Benson-Manica wrote:

Advocated <......@......com> spoke thus:
>
> Just been searching google, but havent come up with anything. Just
> wondering, whats the best way to print say a file.txt or other format
> to the [screen?]
You could use the following C program...

[snip 24 lines using fgets() somewhat inappropriately]

(salient comments from the regulars appreciated)


What if you get a line in "file.txt" longer than 255 characters?
Anyway, the simple solutions are best... Use 'cat file.txt',
'type file.txt', or, if your OS doesn't have either of those,
just write your own 'cat' clone... [UNTESTED]

/* A simple 'cat' utility */

#include <stdio.h>

void process(FILE *fp)
{
if (fp == NULL) return;
while ((c=getc(fp)) != EOF)
putchar(c);
putchar('\n');
}


Warning: implicit declaration of int variable :-)

-nrk.
int main(int argc, char **argv)
{
if (argc < 2) {
process(stdin);
}
else {
int i;
for (i=1; i < argc; ++i)
process(fopen(argv[i]));
}
return 0;
}

HTH,
-Arthur


Nov 14 '05 #6

On Wed, 24 Dec 2003, Kevin Goodsell wrote:

Arthur J. O'Dwyer wrote:

/* A simple 'cat' utility */

#include <stdio.h>

void process(FILE *fp)
{
if (fp == NULL) return;
while ((c=getc(fp)) != EOF)
putchar(c);
putchar('\n'); if (fp != stdin) fclose(fp); }

int main(int argc, char **argv)
{
if (argc < 2) {
process(stdin);
}
else {
int i;
for (i=1; i < argc; ++i)
process(fopen(argv[i]));
}
return 0;
}


You forgot to fclose() the files. It looks like doing so will require
some changes beyond just adding the call.


There. It's a hack, but I don't see anything technically wrong
with the program now. Good catch -- thanks.
BTW, is the 'if (fp != stdin)' required in the line I added? I
always have tried to avoid closing 'stdin' or 'stdout' as if they
were "regular" files, but is that something to worry about, or is it
guaranteed to work either way?

-Arthur

Nov 14 '05 #7

On Wed, 24 Dec 2003, Russell Hanneken wrote:

Arthur J. O'Dwyer wrote:

[snip 24 lines using fgets() somewhat inappropriately]

What if you get a line in "file.txt" longer than 255 characters?


I don't see the problem. What do you have in mind?


Three strikes in one post for me! :( You're right, in that
Chris' code does work as expected even with long lines, but
it *looks* like it shouldn't. ;) And I stand by my diagnosis
of "overly complicated," and that 'getc' is more appropriate
than 'fgets' for this application. And thus 'fgets' is
"somewhat inappropriate," right?

And as nrk points out, I was also missing the declaration of

int c;

inside function 'process'. I do that a lot in "real" code, too,
probably because the first time the variable is used is always
buried inside a bunch of parentheses.

-Arthur

Nov 14 '05 #8
The main idea is that the user gives a filename, i.e file.c

It will try and open this file.. if not show an error. If the file is there,
it will just print the contents of it to the screen, but the filename could
be anything at all

Nov 14 '05 #9
"Arthur J. O'Dwyer" <aj*@nospam.andrew.cmu.edu> writes:
[...]
/* A simple 'cat' utility */

#include <stdio.h>

void process(FILE *fp)
{
if (fp == NULL) return;
while ((c=getc(fp)) != EOF)
putchar(c);
putchar('\n');
}

int main(int argc, char **argv)
{
if (argc < 2) {
process(stdin);
}
else {
int i;
for (i=1; i < argc; ++i)
process(fopen(argv[i]));
}
return 0;
}


This unconditionally prints an extra '\n' after printing each file.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #10
Arthur J. O'Dwyer <aj*@nospam.andrew.cmu.edu> spoke thus:
What if you get a line in "file.txt" longer than 255 characters?
Um, well at least it isn't UB, right? ;)
Anyway, the simple solutions are best... Use 'cat file.txt',
'type file.txt', or, if your OS doesn't have either of those,
just write your own 'cat' clone... [UNTESTED]


Yeeeah, much better. Thanks.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #11
Arthur J. O'Dwyer <aj*@nospam.andrew.cmu.edu> spoke thus:
Chris' code does work as expected even with long lines,


Well, it "works" without UB, although I don't think one would "expect"
long lines to be truncated :) I probably should have made some note
of that behavior in my original post. I noted elsewhere that in any
case putc() is probably better regardless.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #12

On Fri, 26 Dec 2003, Christopher Benson-Manica wrote:

Arthur J. O'Dwyer <aj*@nospam.andrew.cmu.edu> spoke thus:
Chris' code does work as expected even with long lines,
Well, it "works" without UB, although I don't think one would "expect"
long lines to be truncated :) I probably should have made some note
of that behavior in my original post.


See, that's what I mean when I say it *looks* like it's wrong. :D
Take a much closer look, and you'll find that long lines are *not*
truncated -- they're just output "piecewise" in multiple calls to
fgets/fputs (or printf; I forget which you used). So the output is
absolutely correct w.r.t. long lines -- but it's weird enough code
to fool me, and then to fool you!
I noted elsewhere that in any
case putc() is probably better regardless.


Definitely. Though you'll note I didn't get my code quite right
either. ;-)

-Arthur
Nov 14 '05 #13
Arthur J. O'Dwyer <aj*@nospam.andrew.cmu.edu> spoke thus:
See, that's what I mean when I say it *looks* like it's wrong. :D
Take a much closer look, and you'll find that long lines are *not*
truncated -- they're just output "piecewise" in multiple calls to
fgets/fputs (or printf; I forget which you used). So the output is
absolutely correct w.r.t. long lines -- but it's weird enough code
to fool me, and then to fool you!


So it is, on all counts. Would have looked smarter if I'd just kept
my mouth shut ;) Goes for both of us, perhaps...

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #14
Christopher Benson-Manica wrote:
Arthur J. O'Dwyer <aj*@nospam.andrew.cmu.edu> spoke thus:
Chris' code does work as expected even with long lines,


Well, it "works" without UB, although I don't think one would
"expect" long lines to be truncated :) I probably should have
made some note of that behavior in my original post. I noted
elsewhere that in any case putc() is probably better regardless.


Look again. It doesn't even truncate long lines.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #15
On Wed, 24 Dec 2003 18:23:34 +0000 (UTC), Christopher Benson-Manica
<at***@nospam.cyberspace.org> wrote:
Advocated <......@......com> spoke thus:
Just been searching google, but havent come up with anything. Just
wondering, whats the best way to print say a file.txt or other format to the


You could use the following C program...

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

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

if( argc != 2 ) {
fprintf( stderr, "Usage: %s <filename>\n", argv[0] );
return EXIT_FAILURE;
}
if( (fp=fopen(argv[1],"r")) == NULL ) {
fprintf( stderr, "Could not open file \"%s\"\n", argv[1] );
return EXIT_FAILURE;
}
while( fgets(buf,sizeof buf,fp) ) {
printf( "%s", buf );
}
printf( "\n" ); /* in case there were no newlines in the file */
fclose( fp );
return EXIT_SUCCESS;
}

(salient comments from the regulars appreciated)


Where we have to use "clearerr()"?

#include <stdio.h>
#include <stdlib.h>
#if !defined(BUFSIZ)
#define BUFSIZ 256
#endif
/* here sizeof(buf)== BUFSIZ */
size_t rread(FILE* fp, char* buf, size_t* err)
{static size_t contar=0, re=0;
size_t con;

contar += (con=fread(buf, 1, BUFSIZ, fp));
if(ferror(fp))
{if(!re) {*err=contar; re=1;}
clearerr(fp);
}
return con;
}
/* here sizeof(buf)== BUFSIZ */
size_t wwrite(FILE* fp, char* buf, size_t* err, size_t num)
{static size_t contaw=0, wr=0;
size_t con;

contaw += (con=fwrite(buf, 1, num, fp));
fflush(fp);
if(!wr && con!=num)
{*err=contaw; wr=1;}
return con;
}
int read_write(FILE* fin, FILE* fout) /* fin and fout must be
opened first */
{char buf[BUFSIZ];
size_t yr=0, yw=0, num;
int c;

if(fin==stdout || fout==stdin || fin==0 || fout==0)
return -1;
if(ferror(fin))
clearerr(fin);
if(ferror(fout))
clearerr(fout);
if(feof(fin))
return 1; /* no errors */
do{num=rread(fin, buf, &yr);
if(num)
{wwrite(fout, buf, &yw, num); c=buf[--num]; }
}while(!feof(fin));
if(fout==stdout && c!='\n') c=fputc('\n', fout);
fflush(fout);
if(yr) fprintf( stderr, "Error in reading from %lu char\n",
(unsigned long) yr);
if(yw) fprintf( stderr, "Error in writing from %lu char\n",
(unsigned long) yw);
if(c==-1) fprintf( stderr, "Error in writing the last \\n ");
return c==-1 ? 0 : !(yr+yw) ;
}

void ricor(int c, char** a)
{FILE *fp;
if(a==0 || c<=0 || a[c]==0) return;
if( (fp=fopen(a[c],"r")) == NULL )
{fprintf( stderr, "I could not open file \"%s\"\n", a[c] );
ricor(++c, a);
return;
}
fprintf( stderr, "I writing the file \"%s\": \n", a[c] );
read_write(fp, stdout);
fclose(fp);
ricor(++c, a);
}
int main( int argc, char *argv[] )
{if( argc < 2 )
{fprintf(
stderr, "Usage: %s <filename_0> <filename_1> ... <filename_n>\n",
argv[0]!=NULL ? argv[0]: "This program "
);
return EXIT_FAILURE;
}

ricor(1, argv);
return EXIT_SUCCESS;
}

Nov 14 '05 #16
On Sat, 27 Dec 2003 12:06:19 GMT, no_name <no*@esist.eeee> wrote:
Where we have to use "clearerr()"? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_________________________#include <stdio.h>
#include <stdlib.h>
#if !defined(BUFSIZ)
#define BUFSIZ 256
#endif
/* here sizeof(buf)== BUFSIZ */
size_t rread(FILE* fp, char* buf, size_t* err)
{static size_t contar=0, re=0;
size_t con;

contar += (con=fread(buf, 1, BUFSIZ, fp));
if(ferror(fp))
{if(!re) {*err=contar; re=1;} if(!re) {*err=contar-con; re=1;}
clearerr(fp);
}
return con;
}
/* here sizeof(buf)== BUFSIZ */
size_t wwrite(FILE* fp, char* buf, size_t* err, size_t num)
{static size_t contaw=0, wr=0;
size_t con;

contaw += (con=fwrite(buf, 1, num, fp));
fflush(fp);
if(!wr && con!=num)
{*err=contaw; wr=1;} {*err=contaw-con; wr=1;}
return con;
}


Nov 14 '05 #17
Christopher Benson-Manica wrote:
if( argc != 2 ) {
fprintf( stderr, "Usage: %s <filename>\n", argv[0] );
If argc is 0 then argv[0] is a null pointer.
(salient comments from the regulars appreciated)


Do you mean "sapient"?

Jeremy.
Nov 14 '05 #18
Jeremy Yallop <je****@jdyallop.freeserve.co.uk> spoke thus:
If argc is 0 then argv[0] is a null pointer.


On common implementations (Unix, for example), this is never the case,
correct? Good call though.
(salient comments from the regulars appreciated)

Do you mean "sapient"?


A quick check of dictionary.com confirms that my vocabulary needs
work. I'm embarassed to say I've been misusing "salient" thus for
many years. ;(

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #19
begin followup to Christopher Benson-Manica:
Jeremy Yallop <je****@jdyallop.freeserve.co.uk> spoke thus:
If argc is 0 then argv[0] is a null pointer.


On common implementations (Unix, for example), this is never
the case, correct? Good call though.


It is very easy to set up.
Though only few programs can actually handle this.

#include <unistd.h>
int main(int argc, char** argv, char** env)
{
char* const arg[] = { 0 };
execve("/bin/sh", arg, env);
}

--
Für Google, Tux und GPL!
Nov 14 '05 #20
Christopher Benson-Manica wrote:
Jeremy Yallop <je****@jdyallop.freeserve.co.uk> spoke thus:
.... snip ...
(salient comments from the regulars appreciated)


Do you mean "sapient"?


A quick check of dictionary.com confirms that my vocabulary
needs work. I'm embarassed to say I've been misusing "salient"
thus for many years. ;(


Relax. I find (Websters Encyclopedic Unabridged):

salient 1. prominent or conspicuous: /salient traits/
....
SYN: 1. important, striking, remarkable.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #21
CBFalconer <cb********@yahoo.com> spoke thus:
Relax. I find (Websters Encyclopedic Unabridged): salient 1. prominent or conspicuous: /salient traits/
...
SYN: 1. important, striking, remarkable.


Yeah, it kind of fits, but I always thought it meant something closer
to "germane." Maybe "germane" wasn't the connotation I wanted anyway
;)

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #22

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

Similar topics

1
by: Manfred Schwab | last post by:
Recording messages and print statements in a textfile during program execution. Is there a similar command to redirect errormessages or print statements into a standart asciifile during...
1
by: hamil | last post by:
I am trying to print a graphic file (tif) and also use the PrintPreview control, the PageSetup control, and the Print dialog control. The code attached is a concatination of two examples taken out...
7
by: Ron | last post by:
Hi All, Is it possible to have Access print a report, identical to one that would print to a printer, only print to a "standard" text file? I can't find it in help and when I try to just print...
3
by: Max58kl | last post by:
Trying to access data and print it to the screen using Perl Builders I/O Window -------------------------------------------------------------------------------- Hi I am using a program called...
3
by: itdaddy | last post by:
hey perl gurus! i am new to this forum cause i need help. I have done many scripts. but i want to use perl to do this: What I want to do is this. I have a QRP file that I can convert to a txt...
2
by: alivip | last post by:
when I wont to inser (anyting I print) to the textbox it will not inser it just print then hanging # a look at the Tkinter Text widget # use ctrl+c to copy, ctrl+x to cut selected text, #...
12
by: Studiotyphoon | last post by:
Hi, I have report which I need to print 3 times, but would like to have the following headings Customer Copy - Print 1 Accounts Copy - Print 2 File Copy -Print 3 I created a macro to...
5
by: prakashturkar | last post by:
Hi, I am Prakash.... I have tried to print an MS Word file using the basic print utilities provided in JAVA.But while asking for printing through my own code i am getting proble for example..."The...
2
by: dmorand | last post by:
When I try to print a 'print version' of my page it looks fine in IE 7, but when I print in IE 6 the margins are all screwed up. The page itself looks the same in both browsers, it's just when I...
11
by: JWest46088 | last post by:
I'm having difficulty trying to figure out how to print a text file from a hash table one line at a time. I have the text file read into the hash table and can print the text file all at once, but I...
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
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...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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
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: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.