473,794 Members | 2,765 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does this not work?

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

int main (void)
{
static char * contents = "Line1\nLine2\n Line3\nLine4";
FILE * tmp;
char readbuf[256];
size_t len, n = 0;

puts (contents);
len = strlen (contents);

tmp = tmpfile ();

if (fwrite (contents, 1, len, tmp) != len)
puts ("Write failed.");
else if ((n = fread (readbuf, 1, len, tmp)) != len)
puts ("Read failed.");

fclose (tmp);

readbuf[n] = '\0';
puts (readbuf);

return EXIT_SUCCESS;
}
Nov 14 '05 #1
5 1436

"Stephen Mayes" <oo******@hotma il.com> wrote in message
news:l1******** ************@bi gnews6.bellsout h.net...
if (fwrite (contents, 1, len, tmp) != len)
puts ("Write failed.");
fseek (tmp, 0, SEEK_SET);
if ((n = fread (readbuf, 1, len, tmp)) != len)
puts ("Read failed.");


As soon as I hit the send button, the light came on.

I'll be taking a nap now.
Nov 14 '05 #2
On Sun, 12 Jun 2005 18:56:00 -0400, "Stephen Mayes"
<oo******@hotma il.com> wrote in comp.lang.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
static char * contents = "Line1\nLine2\n Line3\nLine4";
FILE * tmp;
char readbuf[256];
size_t len, n = 0;

puts (contents);
len = strlen (contents);

tmp = tmpfile ();

if (fwrite (contents, 1, len, tmp) != len)
puts ("Write failed.");
else if ((n = fread (readbuf, 1, len, tmp)) != len)
puts ("Read failed.");

fclose (tmp);

readbuf[n] = '\0';
puts (readbuf);

return EXIT_SUCCESS;
}


What part of it does not work?

You don't check the value returned by tmpfile() for NULL, which it
could return. In that case, you invoke undefined behavior by calling
fwrite() on a null FILE *.

On the other hand, you need to look up the proper handling of files
opened for update, which is what tmpfile() does, if it succeeds.
There is no reason to expect a read directly following a write to such
a file will work, since it breaks the rules specified by the C
standard.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #3

"Jack Klein" <ja*******@spam cop.net> wrote in message
news:2t******** *************** *********@4ax.c om...
On Sun, 12 Jun 2005 18:56:00 -0400, "Stephen Mayes"
<oo******@hotma il.com> wrote in comp.lang.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
static char * contents = "Line1\nLine2\n Line3\nLine4";
FILE * tmp;
char readbuf[256];
size_t len, n = 0;

puts (contents);
len = strlen (contents);

tmp = tmpfile ();

if (fwrite (contents, 1, len, tmp) != len)
puts ("Write failed.");
else if ((n = fread (readbuf, 1, len, tmp)) != len)
puts ("Read failed.");

fclose (tmp);

readbuf[n] = '\0';
puts (readbuf);

return EXIT_SUCCESS;
}
What part of it does not work?

I expected it to print the contents of contents twice. I fixed it with the
fseek. (See me talking to myself.)

You don't check the value returned by tmpfile() for NULL, which it
could return. In that case, you invoke undefined behavior by calling
fwrite() on a null FILE *.
Your right. Thank you.
On the other hand, you need to look up the proper handling of files
opened for update, which is what tmpfile() does, if it succeeds.
There is no reason to expect a read directly following a write to such
a file will work, since it breaks the rules specified by the C
standard. Would that result in UB?
With the original code on gcc I got the "ReadError. " That's what I should
have expected without reseeking the pointer, but a couple of other compilers
seemed to read zeroes or junk from somewhere.
Where IS the file pointer and EOF immediately after the write?
Where do I look this up?

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html

Nov 14 '05 #4
On Sun, 12 Jun 2005 20:43:35 -0400, Stephen Mayes wrote:

....
On the other hand, you need to look up the proper handling of files
opened for update, which is what tmpfile() does, if it succeeds.
There is no reason to expect a read directly following a write to such
a file will work, since it breaks the rules specified by the C
standard. Would that result in UB?


Yes.

"When a file is opened with update mode ('+' as the second or third
character in the above list of mode argument values), both input and
output may be performed on the associated stream. However, output shall
not be directly followed by input without an intervening call to the
fflush function or to a file positioning function (fseek, fsetpos, or
rewind), and input shall not be directly followed by output without an
intervening call to a file positioning function, unless the input
operation encounters end-of-file."

Violation of a "shall" requirement as above results in undefined
behaviour. Note that tmpfile() opens the file in "wb+" mode i.e. an update
mode.
With the original code on gcc I got the "ReadError. " That's what I should
have expected without reseeking the pointer, but a couple of other compilers
seemed to read zeroes or junk from somewhere.
With undefined behaviour anything the compiler does is correct.
Where IS the file pointer and EOF immediately after the write?
After the write the file pointer is just after the data written which also
happens to be the end of the file. Your fseek() call resolves 2 problems,
the file position the data is read from subsequently and the requirement
above.
Where do I look this up?


A good C book or the standard.

Lawrence
Nov 14 '05 #5

In article <pa************ *************** *@netactive.co. uk>,
Lawrence Kirby <lk****@netacti ve.co.uk> wrote:
Violation of a "shall" requirement as above results in undefined
behaviour. Note that tmpfile() opens the file in "wb+" mode i.e. an update
mode.
All quite correct, of course. One side note, though, the "shall ...
as above" refers to an occurrence of the word "shall" that is *not*
in a "constraint s" section of the C standard. If the "shall-violation"
refers to a word that *is* in a "constraint s" section, the standard
requires the compiler to produce "at least one diagnostic" as
well.

In other words, something like:

fwrite(...);
fread(...);

does not require the compiler to warn you that you did something wrong.
Other ("more obvious") mistakes require a warning or error (or any
form of diagnostic, however the compiler defines its "diagnostic ").
On Sun, 12 Jun 2005 20:43:35 -0400, Stephen Mayes wrote:
With the original code on gcc I got the "ReadError. " That's what I
should have expected without reseeking the pointer, but a couple of
other compilers seemed to read zeroes or junk from somewhere.
With undefined behaviour anything the compiler does is correct.
Indeed.
Where IS the file pointer and EOF immediately after the write?

After the write the file pointer is just after the data written which also
happens to be the end of the file. Your fseek() call resolves 2 problems,
the file position the data is read from subsequently and the requirement
above.


Also all quite correct -- but I suspect Stephen Mayes was wondering
instead why he got the actual behavior (out of the infinite possible
undefined behaviors) that he saw on the "couple of other compilers".

This is not a compiler issue so much as a library issue, although the
C standard does not distinguish between these. In particular, if you
were to obtain a GCC binary for one of those "other" systems, and
compiled your code with GCC there, it would probably still have the
same odd behavior. The behavior itself arises from what I consider
a "penny-wise, pound-foolish" optimization in a lot of <stdio.h>
implementations .

The Standard's constraints on you (the programmer) allow me (the
implementor) to get away with something like this:

/* I am the implementor so I use __-prefixed names that you,
the user, must avoid. This way I avoid your names and you
avoid mine, and we never step on each other's toes. */
typedef struct __sFILE FILE;
struct __sFILE {
... various fields ...
unsigned char *__buf; /* the stdio buffer */
unsigned char *__p; /* a pointer into the buffer */
int __n; /* a buffer counter */
... more fields ...
};

#define getc(fp) \
(--(fp)->__n >= 0 ? *(fp)->__p++ : __sreadc(fp))
#define putc(c, fp) \
(--(fp)->__n >= 0 ? *(fp)->__p++ = (c) : __swritec(fp, c))

Note how I have "cleverly" used the same two fields, __n and __p,
to count the number of characters I can stick into the buffer (if
the file is being written) or read out of the buffer (if the file
is being read). I can do this because when you call fseek() or
rewind() (or hit EOF or do any of the other things that reset the
file from "read mode" or "write mode" to "ready to use either mode"),
I can zero out fp->__n. Then only my __sreadc() and __swritec()
functions have to check whether to put the file into "read mode"
(__sreadc()) or "write mode" (__swritec()).

The thing that is really dumb about this is that, for the price of
a single extra "int" per __sFILE structure, I could have put in
TWO counters:

unsigned char *__buf; /* the stdio buffer */
unsigned char *__p; /* a pointer into the buffer */
int __r; /* a "reading buffer" counter */
int __w; /* a "writing buffer" counter */

and now I can have getc() use --fp->__r, while putc() uses --fp->__w.
I simply guarantee that at least one of the two counters is always
zero, and suddenly my stdio can switch from read-mode to write-mode
"automatically" , and not return total garbage when you call getc()
on a file that is in write-mode.

And of course, this is just what I did in my stdio for 4.xBSD. The
system you were using that had gcc, and gave you a read error/EOF,
may have been using my stdio (or else whoever wrote the stdio for
that system saw the same obvious thing).

The C standard has the "seek between mode changes" requirement to
accomodate the obnoxious stdio versions that share a single counter.
--
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.
Nov 14 '05 #6

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

Similar topics

7
4862
by: Jonas | last post by:
This works fine in Win XP but does not work at all in Win 98. Private WithEvents objIExplorer As InternetExplorer I have to do it like this to get it to work in Win 98 Dim objIExplorer As InternetExplorer But then I cant see when a user exit my objIExplorer and than an error will show up when I try to open a link in the IE window that does not exist... What can I do about this and way does it not work in win 98?
3
3743
by: Julian | last post by:
Hi I am trying to update a date field in my table but some how this simple code does not work, I know the select work because if I write the fields, it will show the data from the table but why the update does not work? <% Set ConnGallery = Server.CreateObject("ADODB.Connection") ConnGallery.Open ConnectionString Set cmdTemp = Server.CreateObject("ADODB.Command")
5
3641
by: me | last post by:
I have a Class Library that contains a Form and several helper classes. A thread gets created that performs processing of data behind the scenes and the Form never gets displayed (it is for debug puposes only and is not normally visable to the user.) The Thread function is actually in the Form class. Now.. What I am seeing is that when I create an instance of this Class Library's Form, which starts the worker thread, it seems to hose up...
22
2624
by: Robert Bralic | last post by:
CAN anybody tell me any address where I can download some small(1000-2000) lines C++ proghram source. Or send me ,a small(1000-2000) lines C++ program source that I can compille with gpp under Linux Suse 7.1. I can't belive that C++ exists. Thanks in advance ! robert.bralic@si.htnet.hr
12
2953
by: Frank Hauptlorenz | last post by:
Hello Out there! I have a DB2 V7.2 Database (Fix11) on Win 2000 Professional. It was before a NT 4 based Domain - now it is a Win 2000 Domain. The database server is a domain member. Now sometimes Win 2000 Clients can't connect to the database. They connect over TCP/IP. The db2log says that the function getHostByName failed. It seems to be only on new installed win 2000 Workstations. Already installed WS have NOT this problem.
0
2370
by: Jarod_24 | last post by:
How does tabindex work in ASP .net pages I dosen't seem to work quite like in regular forms. and there isn't any TabStop property either. 1 .How do you prevent a control form beign "tabbed". (hidden textboxes ect.) 2. How do get a control to get focus when the page is loaded (think username textfield on a loginpage) 3. Does the tab-order work just like in regular forms (1 ->2 -> 3 and so on?) 4. How does tabindex work with datagrid...
14
4863
by: Anoop | last post by:
Hi, I am new to this newsgroup and need help in the following questions. 1. I am workin' on a GUI application. Does C# provides Layout Managers the way Java does to design GUI? I know that it can be done using the designer but I intentionally don't want to use that. The one reason is that you cannot change the code generated by the designer. The other could be that you have more free hand and control to design your GUI. 2....
89
6083
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be used." Could anybody tell me why gets() function is dangerous?? Thank you very much. Cuthbert
14
3496
by: webEater | last post by:
I have a problem, it's not browser specific, and I don't get a solution. I have an (X)HTML document, I show you a part of it: .... <!--<div class="pad">--> <div id="eventImages"><img src="" id="eventImage0" class="eventImage"><img src="" id="eventImage1" class="eventImage"></div>
1
7114
by: =?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= | last post by:
I get the above error in some of the ASP.NET web applications on a server, and I need some help figuring out how to deal with it. This is a rather long post, and I hope I have enough details that someone who bothers to read all of it have some pointers. Note, I have posted the stack trace and the code exhibiting the problem further down so if you want to start by reading that, search for +++ Also note that I am unable to reproduce...
0
10433
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
10212
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10000
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...
0
9035
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
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
6777
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
5560
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4112
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

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.