S
sheilly_2k7
how can i write an output of a c prog in a file in plce of terminal
witout using redirection
witout using redirection
how can i write an output of a c prog in a file in plce of terminal
witout using redirection
#include <stdio.h>sheilly_2k7 said:how can i write an output of a c prog in a file in plce of terminal
witout using redirection
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;
}
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;
}
#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;
}
and check the return value of fprintf (otherwise you will not detect a
write error, eg. 'disk full')
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;
}
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.)
Chris said:Actually, it was probably me.
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.