473,597 Members | 2,749 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to write in a file

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

Apr 18 '07 #1
10 7619
On 18 Apr, 06:06, sheilly_2k7 <reply2shei...@ gmail.comwrote:
how can i write an output of a c prog in a file in plce of terminal
witout using redirection
fopen(), fwrite(), fflush().

http://c-faq.com/stdio/index.html

Apr 18 '07 #2

"sheilly_2k 7" <re***********@ gmail.comwrote in message
news:11******** **************@ y80g2000hsf.goo glegroups.com.. .
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.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Apr 18 '07 #3
Malcolm McLean wrote:
"sheilly_2k 7" <re***********@ gmail.comwrote in message
>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;
}
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.securityfoc us.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
--
Posted via a free Usenet account from http://www.teranews.com

Apr 18 '07 #4
On Wed, 18 Apr 2007 02:48:23 -0400, CBFalconer wrote:
>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')
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Apr 18 '07 #5
How? Movable yet? Click here to join!

http://www.9fy.cn/love/friends/

Apr 18 '07 #6
On Apr 18, 7:01 am, "Malcolm McLean" <regniz...@btin ternet.comwrote :
"sheilly_2k 7" <reply2shei...@ gmail.comwrote in message

news:11******** **************@ y80g2000hsf.goo glegroups.com.. .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;

}
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.... :)

--
Bill Pursell

Apr 18 '07 #7
On Wed, 18 Apr 2007 08:53:38 GMT, Roland Pibinger wrote:
>On Wed, 18 Apr 2007 02:48:23 -0400, CBFalconer wrote:
> 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')
I forgot that also the return value of fclose should be checked (for
the same reason).
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Apr 18 '07 #8
Bill Pursell wrote:
>
.... 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.securityfoc us.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

--
Posted via a free Usenet account from http://www.teranews.com

Apr 19 '07 #9
In article <11************ **********@l77g 2000hsb.googleg roups.com>
Bill Pursell <bi**********@g mail.comwrote (in part):
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
"interactiv e 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 "interactiv e 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.)
--
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.
Apr 22 '07 #10

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

Similar topics

1
7377
by: Ellixis | last post by:
Hello, How can I use fwrite() and fseek() in order to write data in the middle (or anywhere else) of a file without overwriting existing data ? People told me that I should load the file into memory (a variable) and use concatenation. But, according to me, It isn't clean to load an entire file into
5
2251
by: Just Me | last post by:
Using streams how do I write and then read a set of variables? For example, suppose I want to write into a text file: string1,string2,string3 Then read them later. Suppose I want to write and then read: string1, integer1, double1
6
9216
by: sambuela | last post by:
How can I write message to the file located in the wwwroot directory? It seems that IIS protect these files. Let make me cannot do the I/O writing sucessfully. I try to open file's write privileage by file manager and IIS manager. However, one PC is okay and another PC is not. Any help on this will be greatly appreciated. Regards, --sambuela
2
4899
by: ykgoh | last post by:
Hi. I've a problem of being able to create and remove a directory but unable to write a file inside the created directory for some strange reason. I suspect that this problem could be vaguely linked to Safe mode being set to On since my site is using shared server hosting and probably insufficient/incorrect Unix file permission. Below is my test script that helps me narrow down the problem....
5
3652
by: philip | last post by:
Here is some lines of code than I wrote. You can copy/paste theis code as code of form1 in a new project. My problem is this one : I try to write in a file a serie of bytes. BUT some bytes written in file are not the sent bytes. Copy and paste the following lines to observe my problem. What can I do to resolve problem ? Only System.Text.Encoding.ASCII write the same number of bytes, but not the good bytes. Someone can help me. Thanks by...
1
8055
by: =?Utf-8?B?R2FuZXNoIE11dGh1dmVsdQ==?= | last post by:
Hello All, Our application write logs to a file in a folder. Before our application starts writing to that file, I want to check if the current user has write access to that file, for example, "c:\temp\LogFile.txt". I see several articles for setting file access permissions, getting file access permissions for a given user or current user - but the current user could also gain write access to the same file not just by explicit permssion...
0
789
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. Stack Trace at System.Net.Sockets.NetworkStream.Write(Byte buffer, Int32 offset, Int32
3
14046
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. Stack Trace at System.Net.Sockets.NetworkStream.Write(Byte buffer, Int32 offset, Int32
6
18292
by: globalrev | last post by:
i ahve a program that takes certain textsnippets out of one file and inserts them into another. problem is it jsut overwrites the first riow every time. i want to insert every new piece of text into the next row. so: 1. how do i write to a new line every time i write to the file? 2. if i dont want to write to a new line but just want to insert it
0
8272
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8258
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5847
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5431
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3886
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3927
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2404
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 we have to send another system
1
1494
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1238
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.