how to write in a file

S

sheilly_2k7

how can i write an output of a c prog in a file in plce of terminal
witout using redirection
 
M

Malcolm McLean

sheilly_2k7 said:
how can i write an output of a c prog in a file in plce of terminal
witout using redirection
#include <stdio.h>

int main(void)
{
FILE *fp;

fp = fopen("temp.txt", "w");
if(!fp)
fprintf(stderr, "Can't open file\n");
else
fprintf(fp, "Hello file world\n");
fclose(fp);
return 0;
}

Untested but should be OK.
 
C

CBFalconer

Malcolm said:
#include <stdio.h>

int main(void)
{
FILE *fp;

fp = fopen("temp.txt", "w");
if(!fp)
fprintf(stderr, "Can't open file\n");
else
fprintf(fp, "Hello file world\n");
fclose(fp);
return 0;
}

That may close an unopened file. Instead, try:

#include <stdio.h>

int main(void) {
FILE *fp;

if (!(fp = fopen("temp.txt", "w")))
fprintf(stderr, "Can't open file\n");
else {
fprintf(fp, "Hello file world\n");
fclose(fp);
}
return 0;
}

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
 
R

Roland Pibinger

Instead, try:

#include <stdio.h>

int main(void) {
FILE *fp;

if (!(fp = fopen("temp.txt", "w")))
fprintf(stderr, "Can't open file\n");
else {
fprintf(fp, "Hello file world\n");
fclose(fp);
}
return 0;
}

and check the return value of fprintf (otherwise you will not detect a
write error, eg. 'disk full')
 
B

Bill Pursell

#include <stdio.h>

int main(void)
{
FILE *fp;

fp = fopen("temp.txt", "w");
if(!fp)
fprintf(stderr, "Can't open file\n");
else
fprintf(fp, "Hello file world\n");
fclose(fp);
return 0;

}

Perhaps this is just my personal pet peeve, but
messages like "Can't open file" are NOT enough
information. Granted, this is a toy program,
but consider a better error message. eg:

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

int
main( int argc, char **argv )
{
FILE *fp;
char *filename;
int status;

filename = argc < 2 ? "foo" : argv[1];

fp = fopen( filename , "w" );

if( fp == NULL ) {
fprintf( stderr, "Error opening %s. ",
filename );
perror( "Most recent system error" );
status = EXIT_FAILURE;
}
else {
fputs( "Hello file world!\n", fp );
fclose( fp );
status = EXIT_SUCCESS;
}
return status;
}

Note that one definitely ought to check the
return values of fputs and fclose for errors. I'm
merely demonstrating how to access the system
error message. (Also note that I've internalized
Keith's criticism about relying on perror to
generate useful messages in the event that
the implementation fails to set errno rationally,
and incorporated Chris's suggested solution.
(I think it was Chris Dollin who suggested the
"most recent system error" type message.)

Thanks, Keith and Chris.... :)
 
R

Roland Pibinger

and check the return value of fprintf (otherwise you will not detect a
write error, eg. 'disk full')

I forgot that also the return value of fclose should be checked (for
the same reason).
 
C

CBFalconer

Bill said:
.... snip ...

Perhaps this is just my personal pet peeve, but messages like
"Can't open file" are NOT enough information. Granted, this is
a toy program, but consider a better error message. eg:

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

int main( int argc, char **argv )
{
FILE *fp;
char *filename;
int status;

filename = argc < 2 ? "foo" : argv[1];
fp = fopen( filename , "w" );
if( fp == NULL ) {
fprintf( stderr, "Error opening %s. ",
filename );
perror( "Most recent system error" );
status = EXIT_FAILURE;
}
else {
fputs( "Hello file world!\n", fp );
fclose( fp );
status = EXIT_SUCCESS;
}
return status;
}

(slight code editing). Still insufficient. Try:

int main( int argc, char **argv ) {
FILE *fp;
char *filename;
int status;

status = EXIT_FAILURE;
filename = argc < 2 ? "foo" : argv[1];
if (!(fp = fopen(filename , "w"))) {
fprintf(stderr, "Error opening %s.\n", filename);
perror("Most recent system error");
}
else {
fputs("Hello file world!\n", fp);
if (fclose(fp)) status = EXIT_SUCCESS;
else fprintf(stderr, "Error closing %s.\n", filename);
}
return status;
}

and we are still assuming fputs succeeds. Haven't even mentioned
the success of fprintf();

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
 
C

Chris Torek

fp = fopen( filename , "w" );

if( fp == NULL ) {
fprintf( stderr, "Error opening %s. ",
filename );
perror( "Most recent system error" ); ...
(I think it was Chris Dollin who suggested the
"most recent system error" type message.)

Actually, it was probably me.

There is a danger in the above code: the call to fprintf() may
change errno, and in fact, on at least one common system (4.2BSD
Unix), it *did* do so. If you have ever had email returned with
the error string "Not a typewriter" included, this is exactly why:
the mail delivery agent attempted some operation that failed and
set errno appropriately; then it printed something to stderr, which
changed errno to ENOTTY; then it called perror(), which printed
"Not a typewriter".

The trick is to capture the "errno" "global variable" before it
can change. The easiest way to do that is to use strerror(errno)
in the fprintf() call, so that the string for fprintf() is computed
before fprintf() has a chance to overwrite errno.

(You can of course save and restore errno around the fprintf().
In fact, this is how I fixed the problem in the C library in 4.4BSD:
the setup routine that fprintf() calls, which modifies errno, saves
and restores errno so as to prevent this kind of disturbance. This
fix went in some time before 4.3-net-2, so it is in all modern BSD
systems. Older systems, including at least some Solaris systems,
however, have the "fprintf overwrites errno" bug. Note that only
the *first* fprintf to any particular stream does this -- if you
print something to stderr early on, a later fprintf(stderr) leaves
errno unchanged.)

(For the especially-curious: the reason for this is that stdio must
determine, at runtime, whether a given stream is talking to an
"interactive device", in which case the output is to be line buffered
rather than fully buffered. To find out, stdio executes an ioctl()
operation that fails with ENOTTY if the output stream is connected
to a "non-tty" device. If the ioctl succeeds, the stream's "line
buffered mode" flag is set. In this case, the ioctl() call does
not change errno. This means the errno disturbance never actually
happens when running a program "interactively", making it even more
interesting to debug. "./prog >& errs" produces the problem, but
"./prog" does not.

It would be possible to avoid the "interactive device" test on
stderr, which is never fully-buffered in the first place, but for
various reasons I, and presumably whoever had a hand in the earlier,
4.2BSD stdio as well, did the test anyway. In my case, I wanted
to obtain other information at the same time.)
 

Ask a Question

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

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

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top